Index: branches/HTM-6.2-dev1-Samsung/.cproject
===================================================================
--- branches/HTM-6.2-dev1-Samsung/.cproject	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/.cproject	(revision 341)
@@ -0,0 +1,883 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?>
+
+<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>
+</cproject>
Index: branches/HTM-6.2-dev1-Samsung/.project
===================================================================
--- branches/HTM-6.2-dev1-Samsung/.project	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/.project	(revision 341)
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>HM</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+			<triggers>clean,full,incremental,</triggers>
+			<arguments>
+				<dictionary>
+					<key>?name?</key>
+					<value></value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.append_environment</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.autoBuildTarget</key>
+					<value>all</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildArguments</key>
+					<value></value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildCommand</key>
+					<value>make</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildLocation</key>
+					<value>${workspace_loc:}/${ProjName}/build/linux</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
+					<value>clean</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.contents</key>
+					<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
+					<value>false</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableFullBuild</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.fullBuildTarget</key>
+					<value>all</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.stopOnError</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
+					<value>true</value>
+				</dictionary>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.cdt.core.cnature</nature>
+		<nature>org.eclipse.cdt.core.ccnature</nature>
+		<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+		<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+	</natures>
+</projectDescription>
Index: branches/HTM-6.2-dev1-Samsung/.settings/org.eclipse.cdt.core.prefs
===================================================================
--- branches/HTM-6.2-dev1-Samsung/.settings/org.eclipse.cdt.core.prefs	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/.settings/org.eclipse.cdt.core.prefs	(revision 341)
@@ -0,0 +1,152 @@
+#Fri Nov 12 15:27:20 CET 2010
+eclipse.preferences.version=1
+org.eclipse.cdt.core.formatter.alignment_for_arguments_in_method_invocation=16
+org.eclipse.cdt.core.formatter.alignment_for_base_clause_in_type_declaration=80
+org.eclipse.cdt.core.formatter.alignment_for_compact_if=0
+org.eclipse.cdt.core.formatter.alignment_for_conditional_expression=80
+org.eclipse.cdt.core.formatter.alignment_for_declarator_list=16
+org.eclipse.cdt.core.formatter.alignment_for_enumerator_list=48
+org.eclipse.cdt.core.formatter.alignment_for_expression_list=0
+org.eclipse.cdt.core.formatter.alignment_for_expressions_in_array_initializer=16
+org.eclipse.cdt.core.formatter.alignment_for_parameters_in_method_declaration=16
+org.eclipse.cdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
+org.eclipse.cdt.core.formatter.brace_position_for_array_initializer=end_of_line
+org.eclipse.cdt.core.formatter.brace_position_for_block=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_block_in_case=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_method_declaration=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_namespace_declaration=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_switch=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_type_declaration=next_line
+org.eclipse.cdt.core.formatter.compact_else_if=false
+org.eclipse.cdt.core.formatter.continuation_indentation=2
+org.eclipse.cdt.core.formatter.continuation_indentation_for_array_initializer=2
+org.eclipse.cdt.core.formatter.format_guardian_clause_on_one_line=false
+org.eclipse.cdt.core.formatter.indent_access_specifier_compare_to_type_header=false
+org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_access_specifier=true
+org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_namespace_header=false
+org.eclipse.cdt.core.formatter.indent_breaks_compare_to_cases=true
+org.eclipse.cdt.core.formatter.indent_declaration_compare_to_template_header=false
+org.eclipse.cdt.core.formatter.indent_empty_lines=false
+org.eclipse.cdt.core.formatter.indent_statements_compare_to_block=true
+org.eclipse.cdt.core.formatter.indent_statements_compare_to_body=true
+org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_cases=true
+org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_switch=false
+org.eclipse.cdt.core.formatter.indentation.size=2
+org.eclipse.cdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_after_template_declaration=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_else_in_if_statement=insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_identifier_in_function_declaration=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_in_empty_block=insert
+org.eclipse.cdt.core.formatter.insert_space_after_assignment_operator=insert
+org.eclipse.cdt.core.formatter.insert_space_after_binary_operator=insert
+org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_arguments=insert
+org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_parameters=insert
+org.eclipse.cdt.core.formatter.insert_space_after_closing_brace_in_block=insert
+org.eclipse.cdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
+org.eclipse.cdt.core.formatter.insert_space_after_colon_in_base_clause=insert
+org.eclipse.cdt.core.formatter.insert_space_after_colon_in_case=insert
+org.eclipse.cdt.core.formatter.insert_space_after_colon_in_conditional=insert
+org.eclipse.cdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_base_types=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_declarator_list=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_expression_list=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_arguments=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_parameters=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_bracket=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_catch=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_exception_specification=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_for=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_if=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_switch=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_while=insert
+org.eclipse.cdt.core.formatter.insert_space_after_postfix_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_prefix_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_question_in_conditional=insert
+org.eclipse.cdt.core.formatter.insert_space_after_semicolon_in_for=insert
+org.eclipse.cdt.core.formatter.insert_space_after_unary_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_assignment_operator=insert
+org.eclipse.cdt.core.formatter.insert_space_before_binary_operator=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_bracket=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_catch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_exception_specification=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_for=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_if=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_switch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_while=insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_base_clause=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_case=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_conditional=insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_default=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_base_types=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_declarator_list=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_expression_list=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_block=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_namespace_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_bracket=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_exception_specification=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_for=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_if=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_while=insert
+org.eclipse.cdt.core.formatter.insert_space_before_postfix_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_prefix_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_question_in_conditional=insert
+org.eclipse.cdt.core.formatter.insert_space_before_semicolon=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_unary_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_brackets=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_exception_specification=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
+org.eclipse.cdt.core.formatter.keep_else_statement_on_same_line=false
+org.eclipse.cdt.core.formatter.keep_empty_array_initializer_on_one_line=false
+org.eclipse.cdt.core.formatter.keep_imple_if_on_one_line=true
+org.eclipse.cdt.core.formatter.keep_then_statement_on_same_line=false
+org.eclipse.cdt.core.formatter.lineSplit=100
+org.eclipse.cdt.core.formatter.number_of_empty_lines_to_preserve=1
+org.eclipse.cdt.core.formatter.put_empty_statement_on_new_line=true
+org.eclipse.cdt.core.formatter.tabulation.char=space
+org.eclipse.cdt.core.formatter.tabulation.size=2
+org.eclipse.cdt.core.formatter.use_tabs_only_for_leading_indentations=false
Index: branches/HTM-6.2-dev1-Samsung/.settings/org.eclipse.cdt.ui.prefs
===================================================================
--- branches/HTM-6.2-dev1-Samsung/.settings/org.eclipse.cdt.ui.prefs	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/.settings/org.eclipse.cdt.ui.prefs	(revision 341)
@@ -0,0 +1,4 @@
+#Fri Nov 12 14:22:53 CET 2010
+eclipse.preferences.version=1
+formatter_profile=_TM
+formatter_settings_version=1
Index: branches/HTM-6.2-dev1-Samsung/COPYING
===================================================================
--- branches/HTM-6.2-dev1-Samsung/COPYING	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/COPYING	(revision 341)
@@ -0,0 +1,31 @@
+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-2012, 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.
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/_README.txt
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/_README.txt	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/_README.txt	(revision 341)
@@ -0,0 +1,61 @@
+
+#########################################
+###
+###  encoding
+###
+#########################################
+
+An encoder configuration file can be generated by
+concatenating three of the given configuration files,
+one for the base configuration, one for sequence
+parameters, and one for QP settings.
+
+For example, in order to obtain the encoder configuration
+file for coding the sequence Balloons with 3 views including
+depth and a base QP of 30, the encoder configuration file
+can be created under Linux using:
+
+cat baseCfg_3view+depth.cfg  >  encoder.cfg
+cat seqCfg_Balloons.cfg      >> encoder.cfg
+cat qpCfg_QP30.cfg           >> encoder.cfg
+
+For Windows, the command "cat" can by replaced with "type".
+As another example (for Windows), the encoder configuration
+file for coding the sequence Kendo with 2 views without
+depth and a base QP of 40, the encoder configuration file
+can be created using:
+
+type baseCfg_2view.cfg  >  encoder.cfg
+type seqCfg_Kendo.cfg   >> encoder.cfg
+type qpCfg_QP40.cfg     >> encoder.cfg
+
+
+
+
+
+#########################################
+###
+###  rendering
+###
+#########################################
+
+The folder contain four examples for renderer configuration files:
+
+rendering_2view_orgData.cfg : 2 view case with original data
+rendering_3view_orgData.cfg : 3 view case with original data
+rendering_2view_decData.cfg : 2 view case with decoded data
+rendering_3view_decData.cfg : 3 view case with decoded data
+
+The following parameters in these configuraton files have to be
+replaced with the actual parameters:
+
+FramesToBeRendered    : number of frames
+
+SourceWidth           : frame width
+
+SourceHeight          : frame height
+
+BaseViewCameraNumbers : base view camera numbers 
+
+
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_2view+depth.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_2view+depth.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_2view+depth.cfg	(revision 341)
@@ -0,0 +1,222 @@
+
+#========== file i/o ==========
+InputFile_0               : org_0.yuv                              # video input file for view 0
+InputFile_1               : org_1.yuv                              # video input file for view 1
+
+DepthInputFile_0          : org_depth_0.yuv                        # depth input file for view 0
+DepthInputFile_1          : org_depth_1.yuv                        # depth input file for view 1
+
+ReconFile_0               : rec_0.yuv                              # video output file for view 0
+ReconFile_1               : rec_1.yuv                              # video output file for view 1
+
+DepthReconFile_0          : rec_depth_0.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_1.yuv                        # depth output file for view 1
+
+BitstreamFile             : stream.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 2                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_pars.txt                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : P    0   3        0.442    0           1                1       0                            0                                                      1             -2                 1                  0  
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -2                 2                  0  
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -2                 2                  0  
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -2                 2                  0  
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -2                 2                  0  
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -2                 3                  0  
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -2                 3                  0  
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1 1                               # illumination compensation (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                     # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1T1                              # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) I(s0.25 s0.5 s0.75)]  # VSO configuration string
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) I(s0.25 s0.5 s0.75)]  # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_2view.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_2view.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_2view.cfg	(revision 341)
@@ -0,0 +1,207 @@
+
+#========== file i/o ==========
+InputFile_0               : org_0.yuv                              # video input file for view 0
+InputFile_1               : org_1.yuv                              # video input file for view 1
+
+ReconFile_0               : rec_0.yuv                              # video output file for view 0
+ReconFile_1               : rec_1.yuv                              # video output file for view 1
+
+BitstreamFile             : stream.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 2                                      # number of views to be coded
+CodeDepthMaps             : 0                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_pars.txt                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : P    0   3        0.442    0           1                1       0                            0                                                      1             -2                 1                  0  
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -2                 2                  0  
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -2                 2                  0  
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -2                 2                  0  
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -2                 2                  0  
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -2                 3                  0  
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -2                 3                  0  
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                                 # illumination compensation (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 0                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 0.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+
+#========== depth coding tools ==========
+DMM                       : 0                                      # use depth intra modes (wedgelets)
+MVI                       : 0                                      # motion parameter inheritance
+VSO                       : 0                                      # use of view synthesis optimization for depth coding
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 :                                        # VSO configuration string
+
+
+#============ Misc. ================
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_3view+depth.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_3view+depth.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_3view+depth.cfg	(revision 341)
@@ -0,0 +1,226 @@
+
+#========== file i/o ==========
+InputFile_0               : org_0.yuv                              # video input file for view 0
+InputFile_1               : org_1.yuv                              # video input file for view 1
+InputFile_2               : org_2.yuv                              # video input file for view 2
+
+DepthInputFile_0          : org_depth_0.yuv                        # depth input file for view 0
+DepthInputFile_1          : org_depth_1.yuv                        # depth input file for view 1
+DepthInputFile_2          : org_depth_2.yuv                        # depth input file for view 2
+
+ReconFile_0               : rec_0.yuv                              # video output file for view 0
+ReconFile_1               : rec_1.yuv                              # video output file for view 1
+ReconFile_2               : rec_2.yuv                              # video output file for view 2
+
+DepthReconFile_0          : rec_depth_0.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_1.yuv                        # depth output file for view 1
+DepthReconFile_2          : rec_depth_2.yuv                        # depth output file for view 2
+
+BitstreamFile             : stream.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_pars.txt                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : P    0   3        0.442    0           1                1       0                            0                                                      1             -2                 1                  0  
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -2                 2                  0  
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -2                 2                  0  
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -2                 2                  0  
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -2                 2                  0  
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -2                 3                  0  
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -2                 3                  0  
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1 1                               # illumination compensation (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                      # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1D2T1T2                           # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][ox2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string for FCO = 1
+WVSO                       : 1                                     # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                  : 10                                    # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                  : 1                                     # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                    : 1                                     # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_3view.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_3view.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/baseCfg_3view.cfg	(revision 341)
@@ -0,0 +1,210 @@
+
+#========== file i/o ==========
+InputFile_0               : org_0.yuv                              # video input file for view 0
+InputFile_1               : org_1.yuv                              # video input file for view 1
+InputFile_2               : org_2.yuv                              # video input file for view 2
+
+ReconFile_0               : rec_0.yuv                              # video output file for view 0
+ReconFile_1               : rec_1.yuv                              # video output file for view 1
+ReconFile_2               : rec_2.yuv                              # video output file for view 2
+
+BitstreamFile             : stream.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 0                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_pars.txt                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : P    0   3        0.442    0           1                1       0                            0                                                      1             -2                 1                  0  
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -2                 2                  0  
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -2                 2                  0  
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -2                 2                  0  
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -2                 2                  0  
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -2                 3                  0  
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -2                 3                  0  
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                                 # illumination compensation (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 0                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 0.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+
+
+#========== depth coding tools ==========
+DMM                       : 0                                      # use depth intra modes (wedgelets)
+MVI                       : 0                                      # motion parameter inheritance
+VSO                       : 0                                      # use of view synthesis optimization for depth coding
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 :                                        # VSO configuration string
+
+
+#============ Misc. ================
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP25.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP25.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP25.cfg	(revision 341)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25 34                                  # quantization parameter (view depth)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP30.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP30.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP30.cfg	(revision 341)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30 39                                  # quantization parameter (view depth)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP35.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP35.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP35.cfg	(revision 341)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35 42                                  # quantization parameter (view depth)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP40.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP40.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP40.cfg	(revision 341)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40 45                                  # quantization parameter (view depth)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP45.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP45.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/qpCfg_QP45.cfg	(revision 341)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45 48                                  # quantization parameter (view depth)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_2view_decData.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_2view_decData.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_2view_decData.cfg	(revision 341)
@@ -0,0 +1,27 @@
+# renderer config file for decoded data
+
+FramesToBeRendered : 300         # !!! replace with actual number of frames
+SourceWidth : 1024               # !!! replace with actual frame width
+SourceHeight : 768               # !!! replace with actual frame height
+BaseViewCameraNumbers : 0 1
+
+VideoInputFile_0 : dec_0.yuv
+VideoInputFile_1 : dec_1.yuv
+DepthInputFile_0 : dec_depth_0.yuv
+DepthInputFile_1 : dec_depth_1.yuv
+SynthOutputFileBaseName : dec_synth_$.yuv
+ContOutputFileNumbering : 1
+FrameSkip : 0
+SynthViewCameraNumbers : 0 .25000 .50000 .75000 1
+CameraParameterFile : dec_cam_pars.txt
+RenderDirection : 0
+RenderMode : 0
+TemporalDepthFilter : 0
+SimEnhance : 1
+ShiftPrecision : 2
+HoleFillingMode : 1
+BlendMode : 0
+BlendZThresPerc : 30
+BlendUseDistWeight : 1
+BlendHoleMargin : 6
+Sweep : 0
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_2view_orgData.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_2view_orgData.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_2view_orgData.cfg	(revision 341)
@@ -0,0 +1,27 @@
+# renderer config file for original data
+
+FramesToBeRendered : 300         # !!! replace with actual number of frames
+SourceWidth : 1024               # !!! replace with actual frame width
+SourceHeight : 768               # !!! replace with actual frame height
+BaseViewCameraNumbers : 3 1      # !!! replace with actual camera numbers
+
+VideoInputFile_0 : org_0.yuv
+VideoInputFile_1 : org_1.yuv
+DepthInputFile_0 : org_depth_0.yuv
+DepthInputFile_1 : org_depth_1.yuv
+SynthOutputFileBaseName : org_synth_$.yuv
+ContOutputFileNumbering : 1
+FrameSkip : 0
+SynthViewCameraNumbers : 0 .25000 .50000 .75000 1
+CameraParameterFile : org_cam_pars.txt
+RenderDirection : 0
+RenderMode : 0
+TemporalDepthFilter : 0
+SimEnhance : 1
+ShiftPrecision : 2
+HoleFillingMode : 1
+BlendMode : 0
+BlendZThresPerc : 30
+BlendUseDistWeight : 1
+BlendHoleMargin : 6
+Sweep : 0
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_3view_decData.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_3view_decData.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_3view_decData.cfg	(revision 341)
@@ -0,0 +1,29 @@
+# renderer config file for decoded data
+
+FramesToBeRendered : 300         # !!! replace with actual number of frames
+SourceWidth : 1024               # !!! replace with actual frame width
+SourceHeight : 768               # !!! replace with actual frame height
+BaseViewCameraNumbers : 0 1 2
+
+VideoInputFile_0 : dec_0.yuv
+VideoInputFile_1 : dec_1.yuv
+VideoInputFile_2 : dec_2.yuv
+DepthInputFile_0 : dec_depth_0.yuv
+DepthInputFile_1 : dec_depth_1.yuv
+DepthInputFile_2 : dec_depth_2.yuv
+SynthOutputFileBaseName : dec_synth_$.yuv
+ContOutputFileNumbering : 1
+FrameSkip : 0
+SynthViewCameraNumbers : 0 .25000 .50000 .75000 1 1.25000 1.50000 1.75000 2
+CameraParameterFile : dec_cam_pars.txt
+RenderDirection : 0
+RenderMode : 0
+TemporalDepthFilter : 0
+SimEnhance : 1
+ShiftPrecision : 2
+HoleFillingMode : 1
+BlendMode : 0
+BlendZThresPerc : 30
+BlendUseDistWeight : 1
+BlendHoleMargin : 6
+Sweep : 0
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_3view_orgData.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_3view_orgData.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/rendering_3view_orgData.cfg	(revision 341)
@@ -0,0 +1,29 @@
+# renderer config file for original data
+
+FramesToBeRendered : 300         # !!! replace with actual number of frames
+SourceWidth : 1024               # !!! replace with actual frame width
+SourceHeight : 768               # !!! replace with actual frame height
+BaseViewCameraNumbers : 3 1 5    # !!! replace with actual camera numbers
+
+VideoInputFile_0 : org_0.yuv
+VideoInputFile_1 : org_1.yuv
+VideoInputFile_2 : org_2.yuv
+DepthInputFile_0 : org_depth_0.yuv
+DepthInputFile_1 : org_depth_1.yuv
+DepthInputFile_2 : org_depth_2.yuv
+SynthOutputFileBaseName : org_synth_$.yuv
+ContOutputFileNumbering : 1
+FrameSkip : 0
+SynthViewCameraNumbers : 0 .25000 .50000 .75000 1 1.25000 1.50000 1.75000 2
+CameraParameterFile : org_cam_pars.txt
+RenderDirection : 0
+RenderMode : 0
+TemporalDepthFilter : 0
+SimEnhance : 1
+ShiftPrecision : 2
+HoleFillingMode : 1
+BlendMode : 0
+BlendZThresPerc : 30
+BlendUseDistWeight : 1
+BlendHoleMargin : 6
+Sweep : 0
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Balloons.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Balloons.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Balloons.cfg	(revision 341)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 3 1 5                                  # camera numbers of coded views (in coding order)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_GhostTownFly.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_GhostTownFly.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_GhostTownFly.cfg	(revision 341)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 5 9 1                                  # camera numbers of coded views (in coding order)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Kendo.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Kendo.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Kendo.cfg	(revision 341)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 3 1 5                                  # camera numbers of coded views (in coding order)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Newspaper.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Newspaper.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_Newspaper.cfg	(revision 341)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 4 2 6                                  # camera numbers of coded views (in coding order)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_PoznanHall2.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_PoznanHall2.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_PoznanHall2.cfg	(revision 341)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 200                                    # number of frames to be coded
+BaseViewCameraNumbers     : 6 7 5                                  # camera numbers of coded views (in coding order)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_PoznanStreet.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_PoznanStreet.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_PoznanStreet.cfg	(revision 341)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 4 5 3                                  # camera numbers of coded views (in coding order)
+
Index: branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_UndoDancer.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_UndoDancer.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/CommonTestConditionsCfgs/seqCfg_UndoDancer.cfg	(revision 341)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 5 1 9                                  # camera numbers of coded views (in coding order)
+
Index: branches/HTM-6.2-dev1-Samsung/HTM.xcodeproj/project.pbxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/HTM.xcodeproj/project.pbxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/HTM.xcodeproj/project.pbxproj	(revision 341)
@@ -0,0 +1,1839 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 46;
+	objects = {
+
+/* Begin PBXAggregateTarget section */
+		78C9B17C14DAD3E800989162 /* Package */ = {
+			isa = PBXAggregateTarget;
+			buildConfigurationList = 78C9B17F14DAD3E800989162 /* Build configuration list for PBXAggregateTarget "Package" */;
+			buildPhases = (
+			);
+			dependencies = (
+				7885899D15664EAA00982C12 /* PBXTargetDependency */,
+				78C9B18214DAD3F100989162 /* PBXTargetDependency */,
+				78C9B18414DAD3F100989162 /* PBXTargetDependency */,
+				78C9B18614DAD3F100989162 /* PBXTargetDependency */,
+			);
+			name = Package;
+			productName = Package;
+		};
+/* End PBXAggregateTarget section */
+
+/* Begin PBXBuildFile section */
+		78C593B5158721A1004401C5 /* ContextModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5931D158720BB004401C5 /* ContextModel.cpp */; };
+		78C593B6158721A1004401C5 /* ContextModel3DBuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5931F158720BB004401C5 /* ContextModel3DBuffer.cpp */; };
+		78C593B7158721A1004401C5 /* TComAdaptiveLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59324158720BB004401C5 /* TComAdaptiveLoopFilter.cpp */; };
+		78C593B8158721A1004401C5 /* TComBitStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59327158720BB004401C5 /* TComBitStream.cpp */; };
+		78C593B9158721A1004401C5 /* TComCABACTables.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59329158720BB004401C5 /* TComCABACTables.cpp */; };
+		78C593BA158721A1004401C5 /* TComDataCU.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5932B158720BB004401C5 /* TComDataCU.cpp */; };
+		78C593BB158721A1004401C5 /* TComDepthMapGenerator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5932D158720BB004401C5 /* TComDepthMapGenerator.cpp */; };
+		78C593BC158721A1004401C5 /* TComInterpolationFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5932F158720BB004401C5 /* TComInterpolationFilter.cpp */; };
+		78C593BD158721A1004401C5 /* TComLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59332158720BB004401C5 /* TComLoopFilter.cpp */; };
+		78C593BE158721A1004401C5 /* TComMotionInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59334158720BB004401C5 /* TComMotionInfo.cpp */; };
+		78C593BF158721A1004401C5 /* TComPattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59337158720BB004401C5 /* TComPattern.cpp */; };
+		78C593C0158721A1004401C5 /* TComPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59339158720BB004401C5 /* TComPic.cpp */; };
+		78C593C1158721A1004401C5 /* TComPicSym.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5933B158720BB004401C5 /* TComPicSym.cpp */; };
+		78C593C2158721A1004401C5 /* TComPicYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5933D158720BB004401C5 /* TComPicYuv.cpp */; };
+		78C593C3158721A1004401C5 /* TComPicYuvMD5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5933F158720BB004401C5 /* TComPicYuvMD5.cpp */; };
+		78C593C4158721A1004401C5 /* TComPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59340158720BB004401C5 /* TComPrediction.cpp */; };
+		78C593C5158721A1004401C5 /* TComRdCost.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59342158720BB004401C5 /* TComRdCost.cpp */; };
+		78C593C6158721A1004401C5 /* TComRdCostWeightPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59344158720BB004401C5 /* TComRdCostWeightPrediction.cpp */; };
+		78C593C7158721A1004401C5 /* TComResidualGenerator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59346158720BB004401C5 /* TComResidualGenerator.cpp */; };
+		78C593C8158721A1004401C5 /* TComRom.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59348158720BB004401C5 /* TComRom.cpp */; };
+		78C593C9158721A1004401C5 /* TComSampleAdaptiveOffset.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5934A158720BB004401C5 /* TComSampleAdaptiveOffset.cpp */; };
+		78C593CA158721A1004401C5 /* TComSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5934C158720BB004401C5 /* TComSlice.cpp */; };
+		78C593CB158721A1004401C5 /* TComTrQuant.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5934E158720BB004401C5 /* TComTrQuant.cpp */; };
+		78C593CC158721A1004401C5 /* TComWedgelet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59350158720BB004401C5 /* TComWedgelet.cpp */; };
+		78C593CD158721A1004401C5 /* TComWeightPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59352158720BB004401C5 /* TComWeightPrediction.cpp */; };
+		78C593CE158721A1004401C5 /* TComYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59354158720BB004401C5 /* TComYuv.cpp */; };
+		78C593CF158721AD004401C5 /* program_options_lite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59316158720BB004401C5 /* program_options_lite.cpp */; };
+		78C593D0158721AD004401C5 /* TAppComCamPara.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59318158720BB004401C5 /* TAppComCamPara.cpp */; };
+		78C593D1158721BB004401C5 /* AnnexBread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59358158720BB004401C5 /* AnnexBread.cpp */; };
+		78C593D2158721BB004401C5 /* NALread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5935A158720BB004401C5 /* NALread.cpp */; };
+		78C593D3158721BB004401C5 /* SEIread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5935C158720BB004401C5 /* SEIread.cpp */; };
+		78C593D4158721BB004401C5 /* TDecBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5935F158720BB004401C5 /* TDecBinCoderCABAC.cpp */; };
+		78C593D5158721BB004401C5 /* TDecCAVLC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59361158720BB004401C5 /* TDecCAVLC.cpp */; };
+		78C593D6158721BB004401C5 /* TDecCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59363158720BB004401C5 /* TDecCu.cpp */; };
+		78C593D7158721BB004401C5 /* TDecEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59365158720BB004401C5 /* TDecEntropy.cpp */; };
+		78C593D8158721BB004401C5 /* TDecGop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59367158720BB004401C5 /* TDecGop.cpp */; };
+		78C593D9158721BB004401C5 /* TDecSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59369158720BB004401C5 /* TDecSbac.cpp */; };
+		78C593DA158721BB004401C5 /* TDecSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5936B158720BB004401C5 /* TDecSlice.cpp */; };
+		78C593DB158721BB004401C5 /* TDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5936D158720BB004401C5 /* TDecTop.cpp */; };
+		78C593DC158721CE004401C5 /* NALwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59371158720BB004401C5 /* NALwrite.cpp */; };
+		78C593DD158721CE004401C5 /* SEIwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59373158720BB004401C5 /* SEIwrite.cpp */; };
+		78C593DE158721CE004401C5 /* TEncAdaptiveLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59375158720BB004401C5 /* TEncAdaptiveLoopFilter.cpp */; };
+		78C593DF158721CE004401C5 /* TEncBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59379158720BB004401C5 /* TEncBinCoderCABAC.cpp */; };
+		78C593E0158721CE004401C5 /* TEncBinCoderCABACCounter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5937B158720BB004401C5 /* TEncBinCoderCABACCounter.cpp */; };
+		78C593E1158721CE004401C5 /* TEncCavlc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5937D158720BB004401C5 /* TEncCavlc.cpp */; };
+		78C593E2158721CE004401C5 /* TEncCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59380158720BB004401C5 /* TEncCu.cpp */; };
+		78C593E3158721CE004401C5 /* TEncEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59382158720BB004401C5 /* TEncEntropy.cpp */; };
+		78C593E4158721CE004401C5 /* TEncGOP.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59384158720BB004401C5 /* TEncGOP.cpp */; };
+		78C593E5158721CE004401C5 /* TEncPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59386158720BB004401C5 /* TEncPic.cpp */; };
+		78C593E6158721CE004401C5 /* TEncPreanalyzer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59388158720BB004401C5 /* TEncPreanalyzer.cpp */; };
+		78C593E7158721CE004401C5 /* TEncSampleAdaptiveOffset.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5938A158720BB004401C5 /* TEncSampleAdaptiveOffset.cpp */; };
+		78C593E8158721CE004401C5 /* TEncSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5938C158720BB004401C5 /* TEncSbac.cpp */; };
+		78C593E9158721CE004401C5 /* TEncSearch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5938E158720BB004401C5 /* TEncSearch.cpp */; };
+		78C593EA158721CE004401C5 /* TEncSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59390158720BB004401C5 /* TEncSlice.cpp */; };
+		78C593EB158721CE004401C5 /* TEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59392158720BB004401C5 /* TEncTop.cpp */; };
+		78C593EC158721CE004401C5 /* WeightPredAnalysis.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59394158720BB004401C5 /* WeightPredAnalysis.cpp */; };
+		78C593ED158721D7004401C5 /* TExtrTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59397158720BB004401C5 /* TExtrTop.cpp */; };
+		78C593EE158721E2004401C5 /* TRenFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5939A158720BB004401C5 /* TRenFilter.cpp */; };
+		78C593EF158721E2004401C5 /* TRenImage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5939C158720BB004401C5 /* TRenImage.cpp */; };
+		78C593F0158721E2004401C5 /* TRenImagePlane.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5939E158720BB004401C5 /* TRenImagePlane.cpp */; };
+		78C593F1158721E2004401C5 /* TRenInterpFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A0158720BB004401C5 /* TRenInterpFilter.cpp */; };
+		78C593F2158721E2004401C5 /* TRenModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A2158720BB004401C5 /* TRenModel.cpp */; };
+		78C593F3158721E2004401C5 /* TRenModSetupStrParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A4158720BB004401C5 /* TRenModSetupStrParser.cpp */; };
+		78C593F4158721E2004401C5 /* TRenSingleModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A6158720BB004401C5 /* TRenSingleModel.cpp */; };
+		78C593F5158721E2004401C5 /* TRenTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A8158720BB004401C5 /* TRenTop.cpp */; };
+		78C593F6158721E9004401C5 /* TVideoIOYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593AB158720BB004401C5 /* TVideoIOYuv.cpp */; };
+		78C593F7158721F1004401C5 /* encmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592EF158720BB004401C5 /* encmain.cpp */; };
+		78C593F8158721F1004401C5 /* TAppEncCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F0158720BB004401C5 /* TAppEncCfg.cpp */; };
+		78C593F9158721F1004401C5 /* TAppEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F2158720BB004401C5 /* TAppEncTop.cpp */; };
+		78C593FA158721F6004401C5 /* decmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592E9158720BB004401C5 /* decmain.cpp */; };
+		78C593FB158721F6004401C5 /* TAppDecCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592EA158720BB004401C5 /* TAppDecCfg.cpp */; };
+		78C593FC158721F6004401C5 /* TAppDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592EC158720BB004401C5 /* TAppDecTop.cpp */; };
+		78C593FD158721FC004401C5 /* extrmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F5158720BB004401C5 /* extrmain.cpp */; };
+		78C593FE158721FC004401C5 /* TAppExtrCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F6158720BB004401C5 /* TAppExtrCfg.cpp */; };
+		78C593FF158721FC004401C5 /* TAppExtrTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F8158720BB004401C5 /* TAppExtrTop.cpp */; };
+		78C5940015872201004401C5 /* RendererMain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592FB158720BB004401C5 /* RendererMain.cpp */; };
+		78C5940115872201004401C5 /* TAppRendererCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592FC158720BB004401C5 /* TAppRendererCfg.cpp */; };
+		78C5940215872201004401C5 /* TAppRendererTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592FE158720BB004401C5 /* TAppRendererTop.cpp */; };
+		78C5940D15872233004401C5 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		78C5940E15872233004401C5 /* libTLibEncoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767961911AD626F00421804 /* libTLibEncoder.a */; };
+		78C5940F15872233004401C5 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		78C5941015872233004401C5 /* libTLibRenderer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7894E36714890D9A009259F4 /* libTLibRenderer.a */; };
+		78C5941115872233004401C5 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C593B415872152004401C5 /* libTAppCommon.a */; };
+		78C594121587228A004401C5 /* libmd5.c in Sources */ = {isa = PBXBuildFile; fileRef = 78C59312158720BB004401C5 /* libmd5.c */; };
+		78C5941B158722B7004401C5 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		78C5941C158722BA004401C5 /* libTLibDecoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 676795F411AD621A00421804 /* libTLibDecoder.a */; };
+		78C5941D158722BC004401C5 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		78C5941E158722C0004401C5 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C593B415872152004401C5 /* libTAppCommon.a */; };
+		78C5941F158722D4004401C5 /* libmd5.c in Sources */ = {isa = PBXBuildFile; fileRef = 78C59312158720BB004401C5 /* libmd5.c */; };
+		78C59428158722F2004401C5 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		78C59429158722F6004401C5 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		78C5942A158722FA004401C5 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C593B415872152004401C5 /* libTAppCommon.a */; };
+		78C5942B15872300004401C5 /* libTLibRenderer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7894E36714890D9A009259F4 /* libTLibRenderer.a */; };
+		78C5943A1587234F004401C5 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		78C5943B15872352004401C5 /* libTLibDecoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 676795F411AD621A00421804 /* libTLibDecoder.a */; };
+		78C5943C15872356004401C5 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		78C5943D1587235B004401C5 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C593B415872152004401C5 /* libTAppCommon.a */; };
+		78C5943E1587235E004401C5 /* libTLibExtractor.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7885897D15664E3D00982C12 /* libTLibExtractor.a */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXContainerItemProxy section */
+		7885899C15664EAA00982C12 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7885897F15664E6A00982C12;
+			remoteInfo = TAppExtractor;
+		};
+		78C5940315872220004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		78C5940515872221004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767961811AD626F00421804;
+			remoteInfo = TLibEncoder;
+		};
+		78C5940715872222004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		78C5940915872226004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7894E34D14890D9A009259F4;
+			remoteInfo = TLibRenderer;
+		};
+		78C5940B15872228004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 78C593AD15872152004401C5;
+			remoteInfo = TAppCommon;
+		};
+		78C59413158722AE004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		78C59415158722AF004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 676795F311AD621A00421804;
+			remoteInfo = TLibDecoder;
+		};
+		78C59417158722B1004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		78C59419158722B3004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 78C593AD15872152004401C5;
+			remoteInfo = TAppCommon;
+		};
+		78C59420158722E9004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		78C59422158722EB004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7894E34D14890D9A009259F4;
+			remoteInfo = TLibRenderer;
+		};
+		78C59424158722ED004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 78C593AD15872152004401C5;
+			remoteInfo = TAppCommon;
+		};
+		78C59426158722EF004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		78C5943015872345004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7885896E15664E3D00982C12;
+			remoteInfo = TLibExtractor;
+		};
+		78C5943215872347004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		78C5943415872348004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 676795F311AD621A00421804;
+			remoteInfo = TLibDecoder;
+		};
+		78C594361587234A004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		78C594381587234B004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 78C593AD15872152004401C5;
+			remoteInfo = TAppCommon;
+		};
+		78C9B18114DAD3F100989162 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767966911AD635600421804;
+			remoteInfo = TAppEncoder;
+		};
+		78C9B18314DAD3F100989162 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6782E0DD11AD691A00E8FFB8;
+			remoteInfo = TAppDecoder;
+		};
+		78C9B18514DAD3F100989162 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7894E37514890DD2009259F4;
+			remoteInfo = TAppRenderer;
+		};
+/* End PBXContainerItemProxy section */
+
+/* Begin PBXFileReference section */
+		6767959411AD61BB00421804 /* libTLibCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibCommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		676795F411AD621A00421804 /* libTLibDecoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibDecoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767961911AD626F00421804 /* libTLibEncoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibEncoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767964B11AD629200421804 /* libTLibVideoIO.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibVideoIO.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767966A11AD635600421804 /* TAppEncoder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppEncoder; sourceTree = BUILT_PRODUCTS_DIR; };
+		6782E0DE11AD691A00E8FFB8 /* TAppDecoder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppDecoder; sourceTree = BUILT_PRODUCTS_DIR; };
+		7885897D15664E3D00982C12 /* libTLibExtractor.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibExtractor.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		7885899415664E6A00982C12 /* TAppExtractor */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppExtractor; sourceTree = BUILT_PRODUCTS_DIR; };
+		7894E36714890D9A009259F4 /* libTLibRenderer.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibRenderer.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		7894E38A14890DD2009259F4 /* TAppRenderer */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppRenderer; sourceTree = BUILT_PRODUCTS_DIR; };
+		78C592E9158720BB004401C5 /* decmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = decmain.cpp; sourceTree = "<group>"; };
+		78C592EA158720BB004401C5 /* TAppDecCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppDecCfg.cpp; sourceTree = "<group>"; };
+		78C592EB158720BB004401C5 /* TAppDecCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppDecCfg.h; sourceTree = "<group>"; };
+		78C592EC158720BB004401C5 /* TAppDecTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppDecTop.cpp; sourceTree = "<group>"; };
+		78C592ED158720BB004401C5 /* TAppDecTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppDecTop.h; sourceTree = "<group>"; };
+		78C592EF158720BB004401C5 /* encmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = encmain.cpp; sourceTree = "<group>"; };
+		78C592F0158720BB004401C5 /* TAppEncCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppEncCfg.cpp; sourceTree = "<group>"; };
+		78C592F1158720BB004401C5 /* TAppEncCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppEncCfg.h; sourceTree = "<group>"; };
+		78C592F2158720BB004401C5 /* TAppEncTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppEncTop.cpp; sourceTree = "<group>"; };
+		78C592F3158720BB004401C5 /* TAppEncTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppEncTop.h; sourceTree = "<group>"; };
+		78C592F5158720BB004401C5 /* extrmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = extrmain.cpp; sourceTree = "<group>"; };
+		78C592F6158720BB004401C5 /* TAppExtrCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppExtrCfg.cpp; sourceTree = "<group>"; };
+		78C592F7158720BB004401C5 /* TAppExtrCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppExtrCfg.h; sourceTree = "<group>"; };
+		78C592F8158720BB004401C5 /* TAppExtrTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppExtrTop.cpp; sourceTree = "<group>"; };
+		78C592F9158720BB004401C5 /* TAppExtrTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppExtrTop.h; sourceTree = "<group>"; };
+		78C592FB158720BB004401C5 /* RendererMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = RendererMain.cpp; sourceTree = "<group>"; };
+		78C592FC158720BB004401C5 /* TAppRendererCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppRendererCfg.cpp; sourceTree = "<group>"; };
+		78C592FD158720BB004401C5 /* TAppRendererCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppRendererCfg.h; sourceTree = "<group>"; };
+		78C592FE158720BB004401C5 /* TAppRendererTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppRendererTop.cpp; sourceTree = "<group>"; };
+		78C592FF158720BB004401C5 /* TAppRendererTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppRendererTop.h; sourceTree = "<group>"; };
+		78C59301158720BB004401C5 /* annexBbytecount.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = annexBbytecount.cpp; sourceTree = "<group>"; };
+		78C59303158720BB004401C5 /* encode.shl */ = {isa = PBXFileReference; lastKnownFileType = text; path = encode.shl; sourceTree = "<group>"; };
+		78C59304158720BB004401C5 /* encodeCommand.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = encodeCommand.sh; sourceTree = "<group>"; };
+		78C59305158720BB004401C5 /* ExtractBitrates.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ExtractBitrates.cpp; sourceTree = "<group>"; };
+		78C59306158720BB004401C5 /* ExtractBitrates.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ExtractBitrates.h; sourceTree = "<group>"; };
+		78C59307158720BB004401C5 /* ExtractBitratesMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ExtractBitratesMain.cpp; sourceTree = "<group>"; };
+		78C59308158720BB004401C5 /* GuessLambdaModifiers.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = GuessLambdaModifiers.cpp; sourceTree = "<group>"; };
+		78C59309158720BB004401C5 /* GuessLambdaModifiers.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GuessLambdaModifiers.h; sourceTree = "<group>"; };
+		78C5930A158720BB004401C5 /* GuessLambdaModifiersMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = GuessLambdaModifiersMain.cpp; sourceTree = "<group>"; };
+		78C5930B158720BB004401C5 /* makefile */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.make; path = makefile; sourceTree = "<group>"; };
+		78C5930C158720BB004401C5 /* QuickStartGuide.pdf */ = {isa = PBXFileReference; lastKnownFileType = image.pdf; path = QuickStartGuide.pdf; sourceTree = "<group>"; };
+		78C5930D158720BB004401C5 /* RuntimeError.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RuntimeError.h; sourceTree = "<group>"; };
+		78C5930E158720BB004401C5 /* targetBitrates.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = targetBitrates.sh; sourceTree = "<group>"; };
+		78C5930F158720BB004401C5 /* convert_NtoMbit_YCbCr.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = convert_NtoMbit_YCbCr.cpp; sourceTree = "<group>"; };
+		78C59312158720BB004401C5 /* libmd5.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = libmd5.c; sourceTree = "<group>"; };
+		78C59313158720BB004401C5 /* libmd5.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = libmd5.h; sourceTree = "<group>"; };
+		78C59314158720BB004401C5 /* MD5.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MD5.h; sourceTree = "<group>"; };
+		78C59316158720BB004401C5 /* program_options_lite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = program_options_lite.cpp; sourceTree = "<group>"; };
+		78C59317158720BB004401C5 /* program_options_lite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = program_options_lite.h; sourceTree = "<group>"; };
+		78C59318158720BB004401C5 /* TAppComCamPara.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppComCamPara.cpp; sourceTree = "<group>"; };
+		78C59319158720BB004401C5 /* TAppComCamPara.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppComCamPara.h; sourceTree = "<group>"; };
+		78C5931B158720BB004401C5 /* AccessUnit.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AccessUnit.h; sourceTree = "<group>"; };
+		78C5931C158720BB004401C5 /* CommonDef.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CommonDef.h; sourceTree = "<group>"; };
+		78C5931D158720BB004401C5 /* ContextModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ContextModel.cpp; sourceTree = "<group>"; };
+		78C5931E158720BB004401C5 /* ContextModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextModel.h; sourceTree = "<group>"; };
+		78C5931F158720BB004401C5 /* ContextModel3DBuffer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ContextModel3DBuffer.cpp; sourceTree = "<group>"; };
+		78C59320158720BB004401C5 /* ContextModel3DBuffer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextModel3DBuffer.h; sourceTree = "<group>"; };
+		78C59321158720BB004401C5 /* ContextTables.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextTables.h; sourceTree = "<group>"; };
+		78C59322158720BB004401C5 /* NAL.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NAL.h; sourceTree = "<group>"; };
+		78C59323158720BB004401C5 /* SEI.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEI.h; sourceTree = "<group>"; };
+		78C59324158720BB004401C5 /* TComAdaptiveLoopFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComAdaptiveLoopFilter.cpp; sourceTree = "<group>"; };
+		78C59325158720BB004401C5 /* TComAdaptiveLoopFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComAdaptiveLoopFilter.h; sourceTree = "<group>"; };
+		78C59326158720BB004401C5 /* TComBitCounter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComBitCounter.h; sourceTree = "<group>"; };
+		78C59327158720BB004401C5 /* TComBitStream.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComBitStream.cpp; sourceTree = "<group>"; };
+		78C59328158720BB004401C5 /* TComBitStream.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComBitStream.h; sourceTree = "<group>"; };
+		78C59329158720BB004401C5 /* TComCABACTables.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComCABACTables.cpp; sourceTree = "<group>"; };
+		78C5932A158720BB004401C5 /* TComCABACTables.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComCABACTables.h; sourceTree = "<group>"; };
+		78C5932B158720BB004401C5 /* TComDataCU.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComDataCU.cpp; sourceTree = "<group>"; };
+		78C5932C158720BB004401C5 /* TComDataCU.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComDataCU.h; sourceTree = "<group>"; };
+		78C5932D158720BB004401C5 /* TComDepthMapGenerator.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComDepthMapGenerator.cpp; sourceTree = "<group>"; };
+		78C5932E158720BB004401C5 /* TComDepthMapGenerator.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComDepthMapGenerator.h; sourceTree = "<group>"; };
+		78C5932F158720BB004401C5 /* TComInterpolationFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComInterpolationFilter.cpp; sourceTree = "<group>"; };
+		78C59330158720BB004401C5 /* TComInterpolationFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComInterpolationFilter.h; sourceTree = "<group>"; };
+		78C59331158720BB004401C5 /* TComList.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComList.h; sourceTree = "<group>"; };
+		78C59332158720BB004401C5 /* TComLoopFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComLoopFilter.cpp; sourceTree = "<group>"; };
+		78C59333158720BB004401C5 /* TComLoopFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComLoopFilter.h; sourceTree = "<group>"; };
+		78C59334158720BB004401C5 /* TComMotionInfo.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComMotionInfo.cpp; sourceTree = "<group>"; };
+		78C59335158720BB004401C5 /* TComMotionInfo.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComMotionInfo.h; sourceTree = "<group>"; };
+		78C59336158720BB004401C5 /* TComMv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComMv.h; sourceTree = "<group>"; };
+		78C59337158720BB004401C5 /* TComPattern.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPattern.cpp; sourceTree = "<group>"; };
+		78C59338158720BB004401C5 /* TComPattern.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPattern.h; sourceTree = "<group>"; };
+		78C59339158720BB004401C5 /* TComPic.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPic.cpp; sourceTree = "<group>"; };
+		78C5933A158720BB004401C5 /* TComPic.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPic.h; sourceTree = "<group>"; };
+		78C5933B158720BB004401C5 /* TComPicSym.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicSym.cpp; sourceTree = "<group>"; };
+		78C5933C158720BB004401C5 /* TComPicSym.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPicSym.h; sourceTree = "<group>"; };
+		78C5933D158720BB004401C5 /* TComPicYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicYuv.cpp; sourceTree = "<group>"; };
+		78C5933E158720BB004401C5 /* TComPicYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPicYuv.h; sourceTree = "<group>"; };
+		78C5933F158720BB004401C5 /* TComPicYuvMD5.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicYuvMD5.cpp; sourceTree = "<group>"; };
+		78C59340158720BB004401C5 /* TComPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPrediction.cpp; sourceTree = "<group>"; };
+		78C59341158720BB004401C5 /* TComPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPrediction.h; sourceTree = "<group>"; };
+		78C59342158720BB004401C5 /* TComRdCost.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRdCost.cpp; sourceTree = "<group>"; };
+		78C59343158720BB004401C5 /* TComRdCost.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRdCost.h; sourceTree = "<group>"; };
+		78C59344158720BB004401C5 /* TComRdCostWeightPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRdCostWeightPrediction.cpp; sourceTree = "<group>"; };
+		78C59345158720BB004401C5 /* TComRdCostWeightPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRdCostWeightPrediction.h; sourceTree = "<group>"; };
+		78C59346158720BB004401C5 /* TComResidualGenerator.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComResidualGenerator.cpp; sourceTree = "<group>"; };
+		78C59347158720BB004401C5 /* TComResidualGenerator.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComResidualGenerator.h; sourceTree = "<group>"; };
+		78C59348158720BB004401C5 /* TComRom.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRom.cpp; sourceTree = "<group>"; };
+		78C59349158720BB004401C5 /* TComRom.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRom.h; sourceTree = "<group>"; };
+		78C5934A158720BB004401C5 /* TComSampleAdaptiveOffset.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComSampleAdaptiveOffset.cpp; sourceTree = "<group>"; };
+		78C5934B158720BB004401C5 /* TComSampleAdaptiveOffset.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComSampleAdaptiveOffset.h; sourceTree = "<group>"; };
+		78C5934C158720BB004401C5 /* TComSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComSlice.cpp; sourceTree = "<group>"; };
+		78C5934D158720BB004401C5 /* TComSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComSlice.h; sourceTree = "<group>"; };
+		78C5934E158720BB004401C5 /* TComTrQuant.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComTrQuant.cpp; sourceTree = "<group>"; };
+		78C5934F158720BB004401C5 /* TComTrQuant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComTrQuant.h; sourceTree = "<group>"; };
+		78C59350158720BB004401C5 /* TComWedgelet.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComWedgelet.cpp; sourceTree = "<group>"; };
+		78C59351158720BB004401C5 /* TComWedgelet.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComWedgelet.h; sourceTree = "<group>"; };
+		78C59352158720BB004401C5 /* TComWeightPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComWeightPrediction.cpp; sourceTree = "<group>"; };
+		78C59353158720BB004401C5 /* TComWeightPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComWeightPrediction.h; sourceTree = "<group>"; };
+		78C59354158720BB004401C5 /* TComYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComYuv.cpp; sourceTree = "<group>"; };
+		78C59355158720BB004401C5 /* TComYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComYuv.h; sourceTree = "<group>"; };
+		78C59356158720BB004401C5 /* TypeDef.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TypeDef.h; sourceTree = "<group>"; };
+		78C59358158720BB004401C5 /* AnnexBread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = AnnexBread.cpp; sourceTree = "<group>"; };
+		78C59359158720BB004401C5 /* AnnexBread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AnnexBread.h; sourceTree = "<group>"; };
+		78C5935A158720BB004401C5 /* NALread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = NALread.cpp; sourceTree = "<group>"; };
+		78C5935B158720BB004401C5 /* NALread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NALread.h; sourceTree = "<group>"; };
+		78C5935C158720BB004401C5 /* SEIread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SEIread.cpp; sourceTree = "<group>"; };
+		78C5935D158720BB004401C5 /* SEIread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEIread.h; sourceTree = "<group>"; };
+		78C5935E158720BB004401C5 /* TDecBinCoder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecBinCoder.h; sourceTree = "<group>"; };
+		78C5935F158720BB004401C5 /* TDecBinCoderCABAC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		78C59360158720BB004401C5 /* TDecBinCoderCABAC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecBinCoderCABAC.h; sourceTree = "<group>"; };
+		78C59361158720BB004401C5 /* TDecCAVLC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecCAVLC.cpp; sourceTree = "<group>"; };
+		78C59362158720BB004401C5 /* TDecCAVLC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecCAVLC.h; sourceTree = "<group>"; };
+		78C59363158720BB004401C5 /* TDecCu.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecCu.cpp; sourceTree = "<group>"; };
+		78C59364158720BB004401C5 /* TDecCu.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecCu.h; sourceTree = "<group>"; };
+		78C59365158720BB004401C5 /* TDecEntropy.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecEntropy.cpp; sourceTree = "<group>"; };
+		78C59366158720BB004401C5 /* TDecEntropy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecEntropy.h; sourceTree = "<group>"; };
+		78C59367158720BB004401C5 /* TDecGop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecGop.cpp; sourceTree = "<group>"; };
+		78C59368158720BB004401C5 /* TDecGop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecGop.h; sourceTree = "<group>"; };
+		78C59369158720BB004401C5 /* TDecSbac.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecSbac.cpp; sourceTree = "<group>"; };
+		78C5936A158720BB004401C5 /* TDecSbac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecSbac.h; sourceTree = "<group>"; };
+		78C5936B158720BB004401C5 /* TDecSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecSlice.cpp; sourceTree = "<group>"; };
+		78C5936C158720BB004401C5 /* TDecSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecSlice.h; sourceTree = "<group>"; };
+		78C5936D158720BB004401C5 /* TDecTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecTop.cpp; sourceTree = "<group>"; };
+		78C5936E158720BB004401C5 /* TDecTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecTop.h; sourceTree = "<group>"; };
+		78C59370158720BB004401C5 /* AnnexBwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AnnexBwrite.h; sourceTree = "<group>"; };
+		78C59371158720BB004401C5 /* NALwrite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = NALwrite.cpp; sourceTree = "<group>"; };
+		78C59372158720BB004401C5 /* NALwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NALwrite.h; sourceTree = "<group>"; };
+		78C59373158720BB004401C5 /* SEIwrite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SEIwrite.cpp; sourceTree = "<group>"; };
+		78C59374158720BB004401C5 /* SEIwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEIwrite.h; sourceTree = "<group>"; };
+		78C59375158720BB004401C5 /* TEncAdaptiveLoopFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncAdaptiveLoopFilter.cpp; sourceTree = "<group>"; };
+		78C59376158720BB004401C5 /* TEncAdaptiveLoopFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncAdaptiveLoopFilter.h; sourceTree = "<group>"; };
+		78C59377158720BB004401C5 /* TEncAnalyze.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncAnalyze.h; sourceTree = "<group>"; };
+		78C59378158720BB004401C5 /* TEncBinCoder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoder.h; sourceTree = "<group>"; };
+		78C59379158720BB004401C5 /* TEncBinCoderCABAC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		78C5937A158720BB004401C5 /* TEncBinCoderCABAC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoderCABAC.h; sourceTree = "<group>"; };
+		78C5937B158720BB004401C5 /* TEncBinCoderCABACCounter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncBinCoderCABACCounter.cpp; sourceTree = "<group>"; };
+		78C5937C158720BB004401C5 /* TEncBinCoderCABACCounter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoderCABACCounter.h; sourceTree = "<group>"; };
+		78C5937D158720BB004401C5 /* TEncCavlc.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncCavlc.cpp; sourceTree = "<group>"; };
+		78C5937E158720BB004401C5 /* TEncCavlc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCavlc.h; sourceTree = "<group>"; };
+		78C5937F158720BB004401C5 /* TEncCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCfg.h; sourceTree = "<group>"; };
+		78C59380158720BB004401C5 /* TEncCu.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncCu.cpp; sourceTree = "<group>"; };
+		78C59381158720BB004401C5 /* TEncCu.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCu.h; sourceTree = "<group>"; };
+		78C59382158720BB004401C5 /* TEncEntropy.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncEntropy.cpp; sourceTree = "<group>"; };
+		78C59383158720BB004401C5 /* TEncEntropy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncEntropy.h; sourceTree = "<group>"; };
+		78C59384158720BB004401C5 /* TEncGOP.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncGOP.cpp; sourceTree = "<group>"; };
+		78C59385158720BB004401C5 /* TEncGOP.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncGOP.h; sourceTree = "<group>"; };
+		78C59386158720BB004401C5 /* TEncPic.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncPic.cpp; sourceTree = "<group>"; };
+		78C59387158720BB004401C5 /* TEncPic.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncPic.h; sourceTree = "<group>"; };
+		78C59388158720BB004401C5 /* TEncPreanalyzer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncPreanalyzer.cpp; sourceTree = "<group>"; };
+		78C59389158720BB004401C5 /* TEncPreanalyzer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncPreanalyzer.h; sourceTree = "<group>"; };
+		78C5938A158720BB004401C5 /* TEncSampleAdaptiveOffset.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSampleAdaptiveOffset.cpp; sourceTree = "<group>"; };
+		78C5938B158720BB004401C5 /* TEncSampleAdaptiveOffset.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSampleAdaptiveOffset.h; sourceTree = "<group>"; };
+		78C5938C158720BB004401C5 /* TEncSbac.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSbac.cpp; sourceTree = "<group>"; };
+		78C5938D158720BB004401C5 /* TEncSbac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSbac.h; sourceTree = "<group>"; };
+		78C5938E158720BB004401C5 /* TEncSearch.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSearch.cpp; sourceTree = "<group>"; };
+		78C5938F158720BB004401C5 /* TEncSearch.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSearch.h; sourceTree = "<group>"; };
+		78C59390158720BB004401C5 /* TEncSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSlice.cpp; sourceTree = "<group>"; };
+		78C59391158720BB004401C5 /* TEncSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSlice.h; sourceTree = "<group>"; };
+		78C59392158720BB004401C5 /* TEncTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncTop.cpp; sourceTree = "<group>"; };
+		78C59393158720BB004401C5 /* TEncTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncTop.h; sourceTree = "<group>"; };
+		78C59394158720BB004401C5 /* WeightPredAnalysis.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WeightPredAnalysis.cpp; sourceTree = "<group>"; };
+		78C59395158720BB004401C5 /* WeightPredAnalysis.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WeightPredAnalysis.h; sourceTree = "<group>"; };
+		78C59397158720BB004401C5 /* TExtrTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TExtrTop.cpp; sourceTree = "<group>"; };
+		78C59398158720BB004401C5 /* TExtrTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TExtrTop.h; sourceTree = "<group>"; };
+		78C5939A158720BB004401C5 /* TRenFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenFilter.cpp; sourceTree = "<group>"; };
+		78C5939B158720BB004401C5 /* TRenFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenFilter.h; sourceTree = "<group>"; };
+		78C5939C158720BB004401C5 /* TRenImage.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenImage.cpp; sourceTree = "<group>"; };
+		78C5939D158720BB004401C5 /* TRenImage.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenImage.h; sourceTree = "<group>"; };
+		78C5939E158720BB004401C5 /* TRenImagePlane.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenImagePlane.cpp; sourceTree = "<group>"; };
+		78C5939F158720BB004401C5 /* TRenImagePlane.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenImagePlane.h; sourceTree = "<group>"; };
+		78C593A0158720BB004401C5 /* TRenInterpFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenInterpFilter.cpp; sourceTree = "<group>"; };
+		78C593A1158720BB004401C5 /* TRenInterpFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenInterpFilter.h; sourceTree = "<group>"; };
+		78C593A2158720BB004401C5 /* TRenModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenModel.cpp; sourceTree = "<group>"; };
+		78C593A3158720BB004401C5 /* TRenModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenModel.h; sourceTree = "<group>"; };
+		78C593A4158720BB004401C5 /* TRenModSetupStrParser.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenModSetupStrParser.cpp; sourceTree = "<group>"; };
+		78C593A5158720BB004401C5 /* TRenModSetupStrParser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenModSetupStrParser.h; sourceTree = "<group>"; };
+		78C593A6158720BB004401C5 /* TRenSingleModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenSingleModel.cpp; sourceTree = "<group>"; };
+		78C593A7158720BB004401C5 /* TRenSingleModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenSingleModel.h; sourceTree = "<group>"; };
+		78C593A8158720BB004401C5 /* TRenTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenTop.cpp; sourceTree = "<group>"; };
+		78C593A9158720BB004401C5 /* TRenTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenTop.h; sourceTree = "<group>"; };
+		78C593AB158720BB004401C5 /* TVideoIOYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TVideoIOYuv.cpp; sourceTree = "<group>"; };
+		78C593AC158720BB004401C5 /* TVideoIOYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TVideoIOYuv.h; sourceTree = "<group>"; };
+		78C593B415872152004401C5 /* libTAppCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTAppCommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		6767959211AD61BB00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F211AD621A00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961711AD626F00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964911AD629200421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767966811AD635600421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C5940D15872233004401C5 /* libTLibCommon.a in Frameworks */,
+				78C5940E15872233004401C5 /* libTLibEncoder.a in Frameworks */,
+				78C5940F15872233004401C5 /* libTLibVideoIO.a in Frameworks */,
+				78C5941015872233004401C5 /* libTLibRenderer.a in Frameworks */,
+				78C5941115872233004401C5 /* libTAppCommon.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DC11AD691A00E8FFB8 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C5941B158722B7004401C5 /* libTLibCommon.a in Frameworks */,
+				78C5941C158722BA004401C5 /* libTLibDecoder.a in Frameworks */,
+				78C5941E158722C0004401C5 /* libTAppCommon.a in Frameworks */,
+				78C5941D158722BC004401C5 /* libTLibVideoIO.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885897915664E3D00982C12 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885898C15664E6A00982C12 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C5943A1587234F004401C5 /* libTLibCommon.a in Frameworks */,
+				78C5943B15872352004401C5 /* libTLibDecoder.a in Frameworks */,
+				78C5943C15872356004401C5 /* libTLibVideoIO.a in Frameworks */,
+				78C5943D1587235B004401C5 /* libTAppCommon.a in Frameworks */,
+				78C5943E1587235E004401C5 /* libTLibExtractor.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E36314890D9A009259F4 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E38214890DD2009259F4 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C59428158722F2004401C5 /* libTLibCommon.a in Frameworks */,
+				78C59429158722F6004401C5 /* libTLibVideoIO.a in Frameworks */,
+				78C5942A158722FA004401C5 /* libTAppCommon.a in Frameworks */,
+				78C5942B15872300004401C5 /* libTLibRenderer.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		78C593B015872152004401C5 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		08FB7794FE84155DC02AAC07 /* Trinity */ = {
+			isa = PBXGroup;
+			children = (
+				08FB7795FE84155DC02AAC07 /* Source */,
+				1AB674ADFE9D54B511CA2CBB /* Products */,
+			);
+			name = Trinity;
+			sourceTree = "<group>";
+		};
+		08FB7795FE84155DC02AAC07 /* Source */ = {
+			isa = PBXGroup;
+			children = (
+				78C592E7158720BB004401C5 /* App */,
+				78C59310158720BB004401C5 /* Lib */,
+			);
+			indentWidth = 2;
+			name = Source;
+			sourceTree = "<group>";
+			tabWidth = 2;
+		};
+		1AB674ADFE9D54B511CA2CBB /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				6767959411AD61BB00421804 /* libTLibCommon.a */,
+				676795F411AD621A00421804 /* libTLibDecoder.a */,
+				6767961911AD626F00421804 /* libTLibEncoder.a */,
+				6767964B11AD629200421804 /* libTLibVideoIO.a */,
+				6767966A11AD635600421804 /* TAppEncoder */,
+				6782E0DE11AD691A00E8FFB8 /* TAppDecoder */,
+				7894E36714890D9A009259F4 /* libTLibRenderer.a */,
+				7894E38A14890DD2009259F4 /* TAppRenderer */,
+				7885897D15664E3D00982C12 /* libTLibExtractor.a */,
+				7885899415664E6A00982C12 /* TAppExtractor */,
+				78C593B415872152004401C5 /* libTAppCommon.a */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+		78C592E7158720BB004401C5 /* App */ = {
+			isa = PBXGroup;
+			children = (
+				78C592E8158720BB004401C5 /* TAppDecoder */,
+				78C592EE158720BB004401C5 /* TAppEncoder */,
+				78C592F4158720BB004401C5 /* TAppExtractor */,
+				78C592FA158720BB004401C5 /* TAppRenderer */,
+				78C59300158720BB004401C5 /* utils */,
+			);
+			name = App;
+			path = source/App;
+			sourceTree = "<group>";
+		};
+		78C592E8158720BB004401C5 /* TAppDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				78C592E9158720BB004401C5 /* decmain.cpp */,
+				78C592EA158720BB004401C5 /* TAppDecCfg.cpp */,
+				78C592EB158720BB004401C5 /* TAppDecCfg.h */,
+				78C592EC158720BB004401C5 /* TAppDecTop.cpp */,
+				78C592ED158720BB004401C5 /* TAppDecTop.h */,
+			);
+			path = TAppDecoder;
+			sourceTree = "<group>";
+		};
+		78C592EE158720BB004401C5 /* TAppEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				78C592EF158720BB004401C5 /* encmain.cpp */,
+				78C592F0158720BB004401C5 /* TAppEncCfg.cpp */,
+				78C592F1158720BB004401C5 /* TAppEncCfg.h */,
+				78C592F2158720BB004401C5 /* TAppEncTop.cpp */,
+				78C592F3158720BB004401C5 /* TAppEncTop.h */,
+			);
+			path = TAppEncoder;
+			sourceTree = "<group>";
+		};
+		78C592F4158720BB004401C5 /* TAppExtractor */ = {
+			isa = PBXGroup;
+			children = (
+				78C592F5158720BB004401C5 /* extrmain.cpp */,
+				78C592F6158720BB004401C5 /* TAppExtrCfg.cpp */,
+				78C592F7158720BB004401C5 /* TAppExtrCfg.h */,
+				78C592F8158720BB004401C5 /* TAppExtrTop.cpp */,
+				78C592F9158720BB004401C5 /* TAppExtrTop.h */,
+			);
+			path = TAppExtractor;
+			sourceTree = "<group>";
+		};
+		78C592FA158720BB004401C5 /* TAppRenderer */ = {
+			isa = PBXGroup;
+			children = (
+				78C592FB158720BB004401C5 /* RendererMain.cpp */,
+				78C592FC158720BB004401C5 /* TAppRendererCfg.cpp */,
+				78C592FD158720BB004401C5 /* TAppRendererCfg.h */,
+				78C592FE158720BB004401C5 /* TAppRendererTop.cpp */,
+				78C592FF158720BB004401C5 /* TAppRendererTop.h */,
+			);
+			path = TAppRenderer;
+			sourceTree = "<group>";
+		};
+		78C59300158720BB004401C5 /* utils */ = {
+			isa = PBXGroup;
+			children = (
+				78C59301158720BB004401C5 /* annexBbytecount.cpp */,
+				78C59302158720BB004401C5 /* BitrateTargeting */,
+				78C5930F158720BB004401C5 /* convert_NtoMbit_YCbCr.cpp */,
+			);
+			path = utils;
+			sourceTree = "<group>";
+		};
+		78C59302158720BB004401C5 /* BitrateTargeting */ = {
+			isa = PBXGroup;
+			children = (
+				78C59303158720BB004401C5 /* encode.shl */,
+				78C59304158720BB004401C5 /* encodeCommand.sh */,
+				78C59305158720BB004401C5 /* ExtractBitrates.cpp */,
+				78C59306158720BB004401C5 /* ExtractBitrates.h */,
+				78C59307158720BB004401C5 /* ExtractBitratesMain.cpp */,
+				78C59308158720BB004401C5 /* GuessLambdaModifiers.cpp */,
+				78C59309158720BB004401C5 /* GuessLambdaModifiers.h */,
+				78C5930A158720BB004401C5 /* GuessLambdaModifiersMain.cpp */,
+				78C5930B158720BB004401C5 /* makefile */,
+				78C5930C158720BB004401C5 /* QuickStartGuide.pdf */,
+				78C5930D158720BB004401C5 /* RuntimeError.h */,
+				78C5930E158720BB004401C5 /* targetBitrates.sh */,
+			);
+			path = BitrateTargeting;
+			sourceTree = "<group>";
+		};
+		78C59310158720BB004401C5 /* Lib */ = {
+			isa = PBXGroup;
+			children = (
+				78C59311158720BB004401C5 /* libmd5 */,
+				78C59315158720BB004401C5 /* TAppCommon */,
+				78C5931A158720BB004401C5 /* TLibCommon */,
+				78C59357158720BB004401C5 /* TLibDecoder */,
+				78C5936F158720BB004401C5 /* TLibEncoder */,
+				78C59396158720BB004401C5 /* TLibExtractor */,
+				78C59399158720BB004401C5 /* TLibRenderer */,
+				78C593AA158720BB004401C5 /* TLibVideoIO */,
+			);
+			name = Lib;
+			path = source/Lib;
+			sourceTree = "<group>";
+		};
+		78C59311158720BB004401C5 /* libmd5 */ = {
+			isa = PBXGroup;
+			children = (
+				78C59312158720BB004401C5 /* libmd5.c */,
+				78C59313158720BB004401C5 /* libmd5.h */,
+				78C59314158720BB004401C5 /* MD5.h */,
+			);
+			path = libmd5;
+			sourceTree = "<group>";
+		};
+		78C59315158720BB004401C5 /* TAppCommon */ = {
+			isa = PBXGroup;
+			children = (
+				78C59316158720BB004401C5 /* program_options_lite.cpp */,
+				78C59317158720BB004401C5 /* program_options_lite.h */,
+				78C59318158720BB004401C5 /* TAppComCamPara.cpp */,
+				78C59319158720BB004401C5 /* TAppComCamPara.h */,
+			);
+			path = TAppCommon;
+			sourceTree = "<group>";
+		};
+		78C5931A158720BB004401C5 /* TLibCommon */ = {
+			isa = PBXGroup;
+			children = (
+				78C5931B158720BB004401C5 /* AccessUnit.h */,
+				78C5931C158720BB004401C5 /* CommonDef.h */,
+				78C5931D158720BB004401C5 /* ContextModel.cpp */,
+				78C5931E158720BB004401C5 /* ContextModel.h */,
+				78C5931F158720BB004401C5 /* ContextModel3DBuffer.cpp */,
+				78C59320158720BB004401C5 /* ContextModel3DBuffer.h */,
+				78C59321158720BB004401C5 /* ContextTables.h */,
+				78C59322158720BB004401C5 /* NAL.h */,
+				78C59323158720BB004401C5 /* SEI.h */,
+				78C59324158720BB004401C5 /* TComAdaptiveLoopFilter.cpp */,
+				78C59325158720BB004401C5 /* TComAdaptiveLoopFilter.h */,
+				78C59326158720BB004401C5 /* TComBitCounter.h */,
+				78C59327158720BB004401C5 /* TComBitStream.cpp */,
+				78C59328158720BB004401C5 /* TComBitStream.h */,
+				78C59329158720BB004401C5 /* TComCABACTables.cpp */,
+				78C5932A158720BB004401C5 /* TComCABACTables.h */,
+				78C5932B158720BB004401C5 /* TComDataCU.cpp */,
+				78C5932C158720BB004401C5 /* TComDataCU.h */,
+				78C5932D158720BB004401C5 /* TComDepthMapGenerator.cpp */,
+				78C5932E158720BB004401C5 /* TComDepthMapGenerator.h */,
+				78C5932F158720BB004401C5 /* TComInterpolationFilter.cpp */,
+				78C59330158720BB004401C5 /* TComInterpolationFilter.h */,
+				78C59331158720BB004401C5 /* TComList.h */,
+				78C59332158720BB004401C5 /* TComLoopFilter.cpp */,
+				78C59333158720BB004401C5 /* TComLoopFilter.h */,
+				78C59334158720BB004401C5 /* TComMotionInfo.cpp */,
+				78C59335158720BB004401C5 /* TComMotionInfo.h */,
+				78C59336158720BB004401C5 /* TComMv.h */,
+				78C59337158720BB004401C5 /* TComPattern.cpp */,
+				78C59338158720BB004401C5 /* TComPattern.h */,
+				78C59339158720BB004401C5 /* TComPic.cpp */,
+				78C5933A158720BB004401C5 /* TComPic.h */,
+				78C5933B158720BB004401C5 /* TComPicSym.cpp */,
+				78C5933C158720BB004401C5 /* TComPicSym.h */,
+				78C5933D158720BB004401C5 /* TComPicYuv.cpp */,
+				78C5933E158720BB004401C5 /* TComPicYuv.h */,
+				78C5933F158720BB004401C5 /* TComPicYuvMD5.cpp */,
+				78C59340158720BB004401C5 /* TComPrediction.cpp */,
+				78C59341158720BB004401C5 /* TComPrediction.h */,
+				78C59342158720BB004401C5 /* TComRdCost.cpp */,
+				78C59343158720BB004401C5 /* TComRdCost.h */,
+				78C59344158720BB004401C5 /* TComRdCostWeightPrediction.cpp */,
+				78C59345158720BB004401C5 /* TComRdCostWeightPrediction.h */,
+				78C59346158720BB004401C5 /* TComResidualGenerator.cpp */,
+				78C59347158720BB004401C5 /* TComResidualGenerator.h */,
+				78C59348158720BB004401C5 /* TComRom.cpp */,
+				78C59349158720BB004401C5 /* TComRom.h */,
+				78C5934A158720BB004401C5 /* TComSampleAdaptiveOffset.cpp */,
+				78C5934B158720BB004401C5 /* TComSampleAdaptiveOffset.h */,
+				78C5934C158720BB004401C5 /* TComSlice.cpp */,
+				78C5934D158720BB004401C5 /* TComSlice.h */,
+				78C5934E158720BB004401C5 /* TComTrQuant.cpp */,
+				78C5934F158720BB004401C5 /* TComTrQuant.h */,
+				78C59350158720BB004401C5 /* TComWedgelet.cpp */,
+				78C59351158720BB004401C5 /* TComWedgelet.h */,
+				78C59352158720BB004401C5 /* TComWeightPrediction.cpp */,
+				78C59353158720BB004401C5 /* TComWeightPrediction.h */,
+				78C59354158720BB004401C5 /* TComYuv.cpp */,
+				78C59355158720BB004401C5 /* TComYuv.h */,
+				78C59356158720BB004401C5 /* TypeDef.h */,
+			);
+			path = TLibCommon;
+			sourceTree = "<group>";
+		};
+		78C59357158720BB004401C5 /* TLibDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				78C59358158720BB004401C5 /* AnnexBread.cpp */,
+				78C59359158720BB004401C5 /* AnnexBread.h */,
+				78C5935A158720BB004401C5 /* NALread.cpp */,
+				78C5935B158720BB004401C5 /* NALread.h */,
+				78C5935C158720BB004401C5 /* SEIread.cpp */,
+				78C5935D158720BB004401C5 /* SEIread.h */,
+				78C5935E158720BB004401C5 /* TDecBinCoder.h */,
+				78C5935F158720BB004401C5 /* TDecBinCoderCABAC.cpp */,
+				78C59360158720BB004401C5 /* TDecBinCoderCABAC.h */,
+				78C59361158720BB004401C5 /* TDecCAVLC.cpp */,
+				78C59362158720BB004401C5 /* TDecCAVLC.h */,
+				78C59363158720BB004401C5 /* TDecCu.cpp */,
+				78C59364158720BB004401C5 /* TDecCu.h */,
+				78C59365158720BB004401C5 /* TDecEntropy.cpp */,
+				78C59366158720BB004401C5 /* TDecEntropy.h */,
+				78C59367158720BB004401C5 /* TDecGop.cpp */,
+				78C59368158720BB004401C5 /* TDecGop.h */,
+				78C59369158720BB004401C5 /* TDecSbac.cpp */,
+				78C5936A158720BB004401C5 /* TDecSbac.h */,
+				78C5936B158720BB004401C5 /* TDecSlice.cpp */,
+				78C5936C158720BB004401C5 /* TDecSlice.h */,
+				78C5936D158720BB004401C5 /* TDecTop.cpp */,
+				78C5936E158720BB004401C5 /* TDecTop.h */,
+			);
+			path = TLibDecoder;
+			sourceTree = "<group>";
+		};
+		78C5936F158720BB004401C5 /* TLibEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				78C59370158720BB004401C5 /* AnnexBwrite.h */,
+				78C59371158720BB004401C5 /* NALwrite.cpp */,
+				78C59372158720BB004401C5 /* NALwrite.h */,
+				78C59373158720BB004401C5 /* SEIwrite.cpp */,
+				78C59374158720BB004401C5 /* SEIwrite.h */,
+				78C59375158720BB004401C5 /* TEncAdaptiveLoopFilter.cpp */,
+				78C59376158720BB004401C5 /* TEncAdaptiveLoopFilter.h */,
+				78C59377158720BB004401C5 /* TEncAnalyze.h */,
+				78C59378158720BB004401C5 /* TEncBinCoder.h */,
+				78C59379158720BB004401C5 /* TEncBinCoderCABAC.cpp */,
+				78C5937A158720BB004401C5 /* TEncBinCoderCABAC.h */,
+				78C5937B158720BB004401C5 /* TEncBinCoderCABACCounter.cpp */,
+				78C5937C158720BB004401C5 /* TEncBinCoderCABACCounter.h */,
+				78C5937D158720BB004401C5 /* TEncCavlc.cpp */,
+				78C5937E158720BB004401C5 /* TEncCavlc.h */,
+				78C5937F158720BB004401C5 /* TEncCfg.h */,
+				78C59380158720BB004401C5 /* TEncCu.cpp */,
+				78C59381158720BB004401C5 /* TEncCu.h */,
+				78C59382158720BB004401C5 /* TEncEntropy.cpp */,
+				78C59383158720BB004401C5 /* TEncEntropy.h */,
+				78C59384158720BB004401C5 /* TEncGOP.cpp */,
+				78C59385158720BB004401C5 /* TEncGOP.h */,
+				78C59386158720BB004401C5 /* TEncPic.cpp */,
+				78C59387158720BB004401C5 /* TEncPic.h */,
+				78C59388158720BB004401C5 /* TEncPreanalyzer.cpp */,
+				78C59389158720BB004401C5 /* TEncPreanalyzer.h */,
+				78C5938A158720BB004401C5 /* TEncSampleAdaptiveOffset.cpp */,
+				78C5938B158720BB004401C5 /* TEncSampleAdaptiveOffset.h */,
+				78C5938C158720BB004401C5 /* TEncSbac.cpp */,
+				78C5938D158720BB004401C5 /* TEncSbac.h */,
+				78C5938E158720BB004401C5 /* TEncSearch.cpp */,
+				78C5938F158720BB004401C5 /* TEncSearch.h */,
+				78C59390158720BB004401C5 /* TEncSlice.cpp */,
+				78C59391158720BB004401C5 /* TEncSlice.h */,
+				78C59392158720BB004401C5 /* TEncTop.cpp */,
+				78C59393158720BB004401C5 /* TEncTop.h */,
+				78C59394158720BB004401C5 /* WeightPredAnalysis.cpp */,
+				78C59395158720BB004401C5 /* WeightPredAnalysis.h */,
+			);
+			path = TLibEncoder;
+			sourceTree = "<group>";
+		};
+		78C59396158720BB004401C5 /* TLibExtractor */ = {
+			isa = PBXGroup;
+			children = (
+				78C59397158720BB004401C5 /* TExtrTop.cpp */,
+				78C59398158720BB004401C5 /* TExtrTop.h */,
+			);
+			path = TLibExtractor;
+			sourceTree = "<group>";
+		};
+		78C59399158720BB004401C5 /* TLibRenderer */ = {
+			isa = PBXGroup;
+			children = (
+				78C5939A158720BB004401C5 /* TRenFilter.cpp */,
+				78C5939B158720BB004401C5 /* TRenFilter.h */,
+				78C5939C158720BB004401C5 /* TRenImage.cpp */,
+				78C5939D158720BB004401C5 /* TRenImage.h */,
+				78C5939E158720BB004401C5 /* TRenImagePlane.cpp */,
+				78C5939F158720BB004401C5 /* TRenImagePlane.h */,
+				78C593A0158720BB004401C5 /* TRenInterpFilter.cpp */,
+				78C593A1158720BB004401C5 /* TRenInterpFilter.h */,
+				78C593A2158720BB004401C5 /* TRenModel.cpp */,
+				78C593A3158720BB004401C5 /* TRenModel.h */,
+				78C593A4158720BB004401C5 /* TRenModSetupStrParser.cpp */,
+				78C593A5158720BB004401C5 /* TRenModSetupStrParser.h */,
+				78C593A6158720BB004401C5 /* TRenSingleModel.cpp */,
+				78C593A7158720BB004401C5 /* TRenSingleModel.h */,
+				78C593A8158720BB004401C5 /* TRenTop.cpp */,
+				78C593A9158720BB004401C5 /* TRenTop.h */,
+			);
+			path = TLibRenderer;
+			sourceTree = "<group>";
+		};
+		78C593AA158720BB004401C5 /* TLibVideoIO */ = {
+			isa = PBXGroup;
+			children = (
+				78C593AB158720BB004401C5 /* TVideoIOYuv.cpp */,
+				78C593AC158720BB004401C5 /* TVideoIOYuv.h */,
+			);
+			path = TLibVideoIO;
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXHeadersBuildPhase section */
+		6767959011AD61BB00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F011AD621A00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961511AD626F00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964711AD629200421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885896F15664E3D00982C12 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E34E14890D9A009259F4 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		78C593AE15872152004401C5 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXHeadersBuildPhase section */
+
+/* Begin PBXNativeTarget section */
+		6767959311AD61BB00421804 /* TLibCommon */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767959811AD61D700421804 /* Build configuration list for PBXNativeTarget "TLibCommon" */;
+			buildPhases = (
+				6767959011AD61BB00421804 /* Headers */,
+				6767959111AD61BB00421804 /* Sources */,
+				6767959211AD61BB00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibCommon;
+			productName = TLibCommon;
+			productReference = 6767959411AD61BB00421804 /* libTLibCommon.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		676795F311AD621A00421804 /* TLibDecoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 676795F711AD623800421804 /* Build configuration list for PBXNativeTarget "TLibDecoder" */;
+			buildPhases = (
+				676795F011AD621A00421804 /* Headers */,
+				676795F111AD621A00421804 /* Sources */,
+				676795F211AD621A00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibDecoder;
+			productName = TLibDecoder;
+			productReference = 676795F411AD621A00421804 /* libTLibDecoder.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767961811AD626F00421804 /* TLibEncoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767964611AD628100421804 /* Build configuration list for PBXNativeTarget "TLibEncoder" */;
+			buildPhases = (
+				6767961511AD626F00421804 /* Headers */,
+				6767961611AD626F00421804 /* Sources */,
+				6767961711AD626F00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibEncoder;
+			productName = TLibEncoder;
+			productReference = 6767961911AD626F00421804 /* libTLibEncoder.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767964A11AD629200421804 /* TLibVideoIO */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767964F11AD629700421804 /* Build configuration list for PBXNativeTarget "TLibVideoIO" */;
+			buildPhases = (
+				6767964711AD629200421804 /* Headers */,
+				6767964811AD629200421804 /* Sources */,
+				6767964911AD629200421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibVideoIO;
+			productName = TLibVideoIO;
+			productReference = 6767964B11AD629200421804 /* libTLibVideoIO.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767966911AD635600421804 /* TAppEncoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767966E11AD637400421804 /* Build configuration list for PBXNativeTarget "TAppEncoder" */;
+			buildPhases = (
+				6767966711AD635600421804 /* Sources */,
+				6767966811AD635600421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				78C5940415872220004401C5 /* PBXTargetDependency */,
+				78C5940615872221004401C5 /* PBXTargetDependency */,
+				78C5940815872222004401C5 /* PBXTargetDependency */,
+				78C5940A15872226004401C5 /* PBXTargetDependency */,
+				78C5940C15872228004401C5 /* PBXTargetDependency */,
+			);
+			name = TAppEncoder;
+			productName = TAppEncoder;
+			productReference = 6767966A11AD635600421804 /* TAppEncoder */;
+			productType = "com.apple.product-type.tool";
+		};
+		6782E0DD11AD691A00E8FFB8 /* TAppDecoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6782E0E611AD692F00E8FFB8 /* Build configuration list for PBXNativeTarget "TAppDecoder" */;
+			buildPhases = (
+				6782E0DB11AD691A00E8FFB8 /* Sources */,
+				6782E0DC11AD691A00E8FFB8 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				78C59414158722AE004401C5 /* PBXTargetDependency */,
+				78C59416158722AF004401C5 /* PBXTargetDependency */,
+				78C59418158722B1004401C5 /* PBXTargetDependency */,
+				78C5941A158722B3004401C5 /* PBXTargetDependency */,
+			);
+			name = TAppDecoder;
+			productName = TAppDecoder;
+			productReference = 6782E0DE11AD691A00E8FFB8 /* TAppDecoder */;
+			productType = "com.apple.product-type.tool";
+		};
+		7885896E15664E3D00982C12 /* TLibExtractor */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7885897A15664E3D00982C12 /* Build configuration list for PBXNativeTarget "TLibExtractor" */;
+			buildPhases = (
+				7885896F15664E3D00982C12 /* Headers */,
+				7885897015664E3D00982C12 /* Sources */,
+				7885897915664E3D00982C12 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibExtractor;
+			productName = TLibDecoder;
+			productReference = 7885897D15664E3D00982C12 /* libTLibExtractor.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		7885897F15664E6A00982C12 /* TAppExtractor */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7885899115664E6A00982C12 /* Build configuration list for PBXNativeTarget "TAppExtractor" */;
+			buildPhases = (
+				7885898815664E6A00982C12 /* Sources */,
+				7885898C15664E6A00982C12 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				78C5943115872345004401C5 /* PBXTargetDependency */,
+				78C5943315872347004401C5 /* PBXTargetDependency */,
+				78C594391587234B004401C5 /* PBXTargetDependency */,
+				78C594371587234A004401C5 /* PBXTargetDependency */,
+				78C5943515872348004401C5 /* PBXTargetDependency */,
+			);
+			name = TAppExtractor;
+			productName = TAppDecoder;
+			productReference = 7885899415664E6A00982C12 /* TAppExtractor */;
+			productType = "com.apple.product-type.tool";
+		};
+		7894E34D14890D9A009259F4 /* TLibRenderer */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7894E36414890D9A009259F4 /* Build configuration list for PBXNativeTarget "TLibRenderer" */;
+			buildPhases = (
+				7894E34E14890D9A009259F4 /* Headers */,
+				7894E35914890D9A009259F4 /* Sources */,
+				7894E36314890D9A009259F4 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibRenderer;
+			productName = TLibDecoder;
+			productReference = 7894E36714890D9A009259F4 /* libTLibRenderer.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		7894E37514890DD2009259F4 /* TAppRenderer */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7894E38714890DD2009259F4 /* Build configuration list for PBXNativeTarget "TAppRenderer" */;
+			buildPhases = (
+				7894E37E14890DD2009259F4 /* Sources */,
+				7894E38214890DD2009259F4 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				78C59421158722E9004401C5 /* PBXTargetDependency */,
+				78C59423158722EB004401C5 /* PBXTargetDependency */,
+				78C59425158722ED004401C5 /* PBXTargetDependency */,
+				78C59427158722EF004401C5 /* PBXTargetDependency */,
+			);
+			name = TAppRenderer;
+			productName = TAppDecoder;
+			productReference = 7894E38A14890DD2009259F4 /* TAppRenderer */;
+			productType = "com.apple.product-type.tool";
+		};
+		78C593AD15872152004401C5 /* TAppCommon */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 78C593B115872152004401C5 /* Build configuration list for PBXNativeTarget "TAppCommon" */;
+			buildPhases = (
+				78C593AE15872152004401C5 /* Headers */,
+				78C593AF15872152004401C5 /* Sources */,
+				78C593B015872152004401C5 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TAppCommon;
+			productName = TLibCommon;
+			productReference = 78C593B415872152004401C5 /* libTAppCommon.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		08FB7793FE84155DC02AAC07 /* Project object */ = {
+			isa = PBXProject;
+			attributes = {
+				BuildIndependentTargetsInParallel = YES;
+				LastUpgradeCheck = 0430;
+			};
+			buildConfigurationList = 1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "HTM" */;
+			compatibilityVersion = "Xcode 3.2";
+			developmentRegion = English;
+			hasScannedForEncodings = 1;
+			knownRegions = (
+				English,
+				Japanese,
+				French,
+				German,
+			);
+			mainGroup = 08FB7794FE84155DC02AAC07 /* Trinity */;
+			projectDirPath = "";
+			projectRoot = "";
+			targets = (
+				6767959311AD61BB00421804 /* TLibCommon */,
+				676795F311AD621A00421804 /* TLibDecoder */,
+				6767961811AD626F00421804 /* TLibEncoder */,
+				6767964A11AD629200421804 /* TLibVideoIO */,
+				7894E34D14890D9A009259F4 /* TLibRenderer */,
+				7885896E15664E3D00982C12 /* TLibExtractor */,
+				78C593AD15872152004401C5 /* TAppCommon */,
+				6767966911AD635600421804 /* TAppEncoder */,
+				6782E0DD11AD691A00E8FFB8 /* TAppDecoder */,
+				7894E37514890DD2009259F4 /* TAppRenderer */,
+				7885897F15664E6A00982C12 /* TAppExtractor */,
+				78C9B17C14DAD3E800989162 /* Package */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXSourcesBuildPhase section */
+		6767959111AD61BB00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593B5158721A1004401C5 /* ContextModel.cpp in Sources */,
+				78C593B6158721A1004401C5 /* ContextModel3DBuffer.cpp in Sources */,
+				78C593B7158721A1004401C5 /* TComAdaptiveLoopFilter.cpp in Sources */,
+				78C593B8158721A1004401C5 /* TComBitStream.cpp in Sources */,
+				78C593B9158721A1004401C5 /* TComCABACTables.cpp in Sources */,
+				78C593BA158721A1004401C5 /* TComDataCU.cpp in Sources */,
+				78C593BB158721A1004401C5 /* TComDepthMapGenerator.cpp in Sources */,
+				78C593BC158721A1004401C5 /* TComInterpolationFilter.cpp in Sources */,
+				78C593BD158721A1004401C5 /* TComLoopFilter.cpp in Sources */,
+				78C593BE158721A1004401C5 /* TComMotionInfo.cpp in Sources */,
+				78C593BF158721A1004401C5 /* TComPattern.cpp in Sources */,
+				78C593C0158721A1004401C5 /* TComPic.cpp in Sources */,
+				78C593C1158721A1004401C5 /* TComPicSym.cpp in Sources */,
+				78C593C2158721A1004401C5 /* TComPicYuv.cpp in Sources */,
+				78C593C3158721A1004401C5 /* TComPicYuvMD5.cpp in Sources */,
+				78C593C4158721A1004401C5 /* TComPrediction.cpp in Sources */,
+				78C593C5158721A1004401C5 /* TComRdCost.cpp in Sources */,
+				78C593C6158721A1004401C5 /* TComRdCostWeightPrediction.cpp in Sources */,
+				78C593C7158721A1004401C5 /* TComResidualGenerator.cpp in Sources */,
+				78C593C8158721A1004401C5 /* TComRom.cpp in Sources */,
+				78C593C9158721A1004401C5 /* TComSampleAdaptiveOffset.cpp in Sources */,
+				78C593CA158721A1004401C5 /* TComSlice.cpp in Sources */,
+				78C593CB158721A1004401C5 /* TComTrQuant.cpp in Sources */,
+				78C593CC158721A1004401C5 /* TComWedgelet.cpp in Sources */,
+				78C593CD158721A1004401C5 /* TComWeightPrediction.cpp in Sources */,
+				78C593CE158721A1004401C5 /* TComYuv.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F111AD621A00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593D1158721BB004401C5 /* AnnexBread.cpp in Sources */,
+				78C593D2158721BB004401C5 /* NALread.cpp in Sources */,
+				78C593D3158721BB004401C5 /* SEIread.cpp in Sources */,
+				78C593D4158721BB004401C5 /* TDecBinCoderCABAC.cpp in Sources */,
+				78C593D5158721BB004401C5 /* TDecCAVLC.cpp in Sources */,
+				78C593D6158721BB004401C5 /* TDecCu.cpp in Sources */,
+				78C593D7158721BB004401C5 /* TDecEntropy.cpp in Sources */,
+				78C593D8158721BB004401C5 /* TDecGop.cpp in Sources */,
+				78C593D9158721BB004401C5 /* TDecSbac.cpp in Sources */,
+				78C593DA158721BB004401C5 /* TDecSlice.cpp in Sources */,
+				78C593DB158721BB004401C5 /* TDecTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961611AD626F00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593DC158721CE004401C5 /* NALwrite.cpp in Sources */,
+				78C593DD158721CE004401C5 /* SEIwrite.cpp in Sources */,
+				78C593DE158721CE004401C5 /* TEncAdaptiveLoopFilter.cpp in Sources */,
+				78C593DF158721CE004401C5 /* TEncBinCoderCABAC.cpp in Sources */,
+				78C593E0158721CE004401C5 /* TEncBinCoderCABACCounter.cpp in Sources */,
+				78C593E1158721CE004401C5 /* TEncCavlc.cpp in Sources */,
+				78C593E2158721CE004401C5 /* TEncCu.cpp in Sources */,
+				78C593E3158721CE004401C5 /* TEncEntropy.cpp in Sources */,
+				78C593E4158721CE004401C5 /* TEncGOP.cpp in Sources */,
+				78C593E5158721CE004401C5 /* TEncPic.cpp in Sources */,
+				78C593E6158721CE004401C5 /* TEncPreanalyzer.cpp in Sources */,
+				78C593E7158721CE004401C5 /* TEncSampleAdaptiveOffset.cpp in Sources */,
+				78C593E8158721CE004401C5 /* TEncSbac.cpp in Sources */,
+				78C593E9158721CE004401C5 /* TEncSearch.cpp in Sources */,
+				78C593EA158721CE004401C5 /* TEncSlice.cpp in Sources */,
+				78C593EB158721CE004401C5 /* TEncTop.cpp in Sources */,
+				78C593EC158721CE004401C5 /* WeightPredAnalysis.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964811AD629200421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593F6158721E9004401C5 /* TVideoIOYuv.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767966711AD635600421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593F7158721F1004401C5 /* encmain.cpp in Sources */,
+				78C593F8158721F1004401C5 /* TAppEncCfg.cpp in Sources */,
+				78C593F9158721F1004401C5 /* TAppEncTop.cpp in Sources */,
+				78C594121587228A004401C5 /* libmd5.c in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DB11AD691A00E8FFB8 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593FA158721F6004401C5 /* decmain.cpp in Sources */,
+				78C593FB158721F6004401C5 /* TAppDecCfg.cpp in Sources */,
+				78C593FC158721F6004401C5 /* TAppDecTop.cpp in Sources */,
+				78C5941F158722D4004401C5 /* libmd5.c in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885897015664E3D00982C12 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593ED158721D7004401C5 /* TExtrTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885898815664E6A00982C12 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593FD158721FC004401C5 /* extrmain.cpp in Sources */,
+				78C593FE158721FC004401C5 /* TAppExtrCfg.cpp in Sources */,
+				78C593FF158721FC004401C5 /* TAppExtrTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E35914890D9A009259F4 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593EE158721E2004401C5 /* TRenFilter.cpp in Sources */,
+				78C593EF158721E2004401C5 /* TRenImage.cpp in Sources */,
+				78C593F0158721E2004401C5 /* TRenImagePlane.cpp in Sources */,
+				78C593F1158721E2004401C5 /* TRenInterpFilter.cpp in Sources */,
+				78C593F2158721E2004401C5 /* TRenModel.cpp in Sources */,
+				78C593F3158721E2004401C5 /* TRenModSetupStrParser.cpp in Sources */,
+				78C593F4158721E2004401C5 /* TRenSingleModel.cpp in Sources */,
+				78C593F5158721E2004401C5 /* TRenTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E37E14890DD2009259F4 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C5940015872201004401C5 /* RendererMain.cpp in Sources */,
+				78C5940115872201004401C5 /* TAppRendererCfg.cpp in Sources */,
+				78C5940215872201004401C5 /* TAppRendererTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		78C593AF15872152004401C5 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593CF158721AD004401C5 /* program_options_lite.cpp in Sources */,
+				78C593D0158721AD004401C5 /* TAppComCamPara.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXTargetDependency section */
+		7885899D15664EAA00982C12 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7885897F15664E6A00982C12 /* TAppExtractor */;
+			targetProxy = 7885899C15664EAA00982C12 /* PBXContainerItemProxy */;
+		};
+		78C5940415872220004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 78C5940315872220004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5940615872221004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767961811AD626F00421804 /* TLibEncoder */;
+			targetProxy = 78C5940515872221004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5940815872222004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 78C5940715872222004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5940A15872226004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7894E34D14890D9A009259F4 /* TLibRenderer */;
+			targetProxy = 78C5940915872226004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5940C15872228004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 78C593AD15872152004401C5 /* TAppCommon */;
+			targetProxy = 78C5940B15872228004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59414158722AE004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 78C59413158722AE004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59416158722AF004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 676795F311AD621A00421804 /* TLibDecoder */;
+			targetProxy = 78C59415158722AF004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59418158722B1004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 78C59417158722B1004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5941A158722B3004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 78C593AD15872152004401C5 /* TAppCommon */;
+			targetProxy = 78C59419158722B3004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59421158722E9004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 78C59420158722E9004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59423158722EB004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7894E34D14890D9A009259F4 /* TLibRenderer */;
+			targetProxy = 78C59422158722EB004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59425158722ED004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 78C593AD15872152004401C5 /* TAppCommon */;
+			targetProxy = 78C59424158722ED004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59427158722EF004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 78C59426158722EF004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5943115872345004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7885896E15664E3D00982C12 /* TLibExtractor */;
+			targetProxy = 78C5943015872345004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5943315872347004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 78C5943215872347004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5943515872348004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 676795F311AD621A00421804 /* TLibDecoder */;
+			targetProxy = 78C5943415872348004401C5 /* PBXContainerItemProxy */;
+		};
+		78C594371587234A004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 78C594361587234A004401C5 /* PBXContainerItemProxy */;
+		};
+		78C594391587234B004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 78C593AD15872152004401C5 /* TAppCommon */;
+			targetProxy = 78C594381587234B004401C5 /* PBXContainerItemProxy */;
+		};
+		78C9B18214DAD3F100989162 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767966911AD635600421804 /* TAppEncoder */;
+			targetProxy = 78C9B18114DAD3F100989162 /* PBXContainerItemProxy */;
+		};
+		78C9B18414DAD3F100989162 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6782E0DD11AD691A00E8FFB8 /* TAppDecoder */;
+			targetProxy = 78C9B18314DAD3F100989162 /* PBXContainerItemProxy */;
+		};
+		78C9B18614DAD3F100989162 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7894E37514890DD2009259F4 /* TAppRenderer */;
+			targetProxy = 78C9B18514DAD3F100989162 /* PBXContainerItemProxy */;
+		};
+/* End PBXTargetDependency section */
+
+/* Begin XCBuildConfiguration section */
+		1DEB923608733DC60010E9CD /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_VERSION = com.apple.compilers.llvmgcc42;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/source/Lib/";
+				MACOSX_DEPLOYMENT_TARGET = 10.7;
+				ONLY_ACTIVE_ARCH = YES;
+				SDKROOT = macosx;
+			};
+			name = Debug;
+		};
+		1DEB923708733DC60010E9CD /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+				GCC_OPTIMIZATION_LEVEL = s;
+				GCC_VERSION = com.apple.compilers.llvmgcc42;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES;
+				GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/source/Lib/";
+				MACOSX_DEPLOYMENT_TARGET = 10.7;
+				SDKROOT = macosx;
+			};
+			name = Release;
+		};
+		6767959511AD61BC00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibCommon;
+			};
+			name = Debug;
+		};
+		6767959611AD61BC00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibCommon;
+			};
+			name = Release;
+		};
+		676795F511AD621A00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibDecoder;
+			};
+			name = Debug;
+		};
+		676795F611AD621A00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibDecoder;
+			};
+			name = Release;
+		};
+		6767961A11AD626F00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibEncoder;
+			};
+			name = Debug;
+		};
+		6767961B11AD626F00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibEncoder;
+			};
+			name = Release;
+		};
+		6767964C11AD629200421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibVideoIO;
+			};
+			name = Debug;
+		};
+		6767964D11AD629200421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibVideoIO;
+			};
+			name = Release;
+		};
+		6767966C11AD635600421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppEncoder;
+			};
+			name = Debug;
+		};
+		6767966D11AD635600421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppEncoder;
+			};
+			name = Release;
+		};
+		6782E0E011AD691B00E8FFB8 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppDecoder;
+			};
+			name = Debug;
+		};
+		6782E0E111AD691B00E8FFB8 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppDecoder;
+			};
+			name = Release;
+		};
+		7885897B15664E3D00982C12 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibExtractor;
+			};
+			name = Debug;
+		};
+		7885897C15664E3D00982C12 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibExtractor;
+			};
+			name = Release;
+		};
+		7885899215664E6A00982C12 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppExtractor;
+			};
+			name = Debug;
+		};
+		7885899315664E6A00982C12 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppExtractor;
+			};
+			name = Release;
+		};
+		7894E36514890D9A009259F4 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibRenderer;
+			};
+			name = Debug;
+		};
+		7894E36614890D9A009259F4 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibRenderer;
+			};
+			name = Release;
+		};
+		7894E38814890DD2009259F4 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppRenderer;
+			};
+			name = Debug;
+		};
+		7894E38914890DD2009259F4 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppRenderer;
+			};
+			name = Release;
+		};
+		78C593B215872152004401C5 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TAppCommon;
+			};
+			name = Debug;
+		};
+		78C593B315872152004401C5 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TAppCommon;
+			};
+			name = Release;
+		};
+		78C9B17D14DAD3E800989162 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				PRODUCT_NAME = "$(TARGET_NAME)";
+			};
+			name = Debug;
+		};
+		78C9B17E14DAD3E800989162 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				PRODUCT_NAME = "$(TARGET_NAME)";
+			};
+			name = Release;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "HTM" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				1DEB923608733DC60010E9CD /* Debug */,
+				1DEB923708733DC60010E9CD /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767959811AD61D700421804 /* Build configuration list for PBXNativeTarget "TLibCommon" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767959511AD61BC00421804 /* Debug */,
+				6767959611AD61BC00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		676795F711AD623800421804 /* Build configuration list for PBXNativeTarget "TLibDecoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				676795F511AD621A00421804 /* Debug */,
+				676795F611AD621A00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767964611AD628100421804 /* Build configuration list for PBXNativeTarget "TLibEncoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767961A11AD626F00421804 /* Debug */,
+				6767961B11AD626F00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767964F11AD629700421804 /* Build configuration list for PBXNativeTarget "TLibVideoIO" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767964C11AD629200421804 /* Debug */,
+				6767964D11AD629200421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767966E11AD637400421804 /* Build configuration list for PBXNativeTarget "TAppEncoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767966C11AD635600421804 /* Debug */,
+				6767966D11AD635600421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6782E0E611AD692F00E8FFB8 /* Build configuration list for PBXNativeTarget "TAppDecoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6782E0E011AD691B00E8FFB8 /* Debug */,
+				6782E0E111AD691B00E8FFB8 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7885897A15664E3D00982C12 /* Build configuration list for PBXNativeTarget "TLibExtractor" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7885897B15664E3D00982C12 /* Debug */,
+				7885897C15664E3D00982C12 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7885899115664E6A00982C12 /* Build configuration list for PBXNativeTarget "TAppExtractor" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7885899215664E6A00982C12 /* Debug */,
+				7885899315664E6A00982C12 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7894E36414890D9A009259F4 /* Build configuration list for PBXNativeTarget "TLibRenderer" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7894E36514890D9A009259F4 /* Debug */,
+				7894E36614890D9A009259F4 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7894E38714890DD2009259F4 /* Build configuration list for PBXNativeTarget "TAppRenderer" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7894E38814890DD2009259F4 /* Debug */,
+				7894E38914890DD2009259F4 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		78C593B115872152004401C5 /* Build configuration list for PBXNativeTarget "TAppCommon" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				78C593B215872152004401C5 /* Debug */,
+				78C593B315872152004401C5 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		78C9B17F14DAD3E800989162 /* Build configuration list for PBXAggregateTarget "Package" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				78C9B17D14DAD3E800989162 /* Debug */,
+				78C9B17E14DAD3E800989162 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+/* End XCConfigurationList section */
+	};
+	rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
+}
Index: branches/HTM-6.2-dev1-Samsung/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata
===================================================================
--- branches/HTM-6.2-dev1-Samsung/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata	(revision 341)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+   version = "1.0">
+   <FileRef
+      location = "self:HTM.xcodeproj">
+   </FileRef>
+</Workspace>
Index: branches/HTM-6.2-dev1-Samsung/README-changes.txt
===================================================================
--- branches/HTM-6.2-dev1-Samsung/README-changes.txt	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/README-changes.txt	(revision 341)
@@ -0,0 +1,126 @@
+Changes from JCTVC-A124
+Contact: Woo-Jin Han, wjhan.han@samsung.com
+
+1. Removed tools
+
+  1.1 MVAC (motion vector accuracy control)
+      - Enables to limit the motion accuracy up to 1/2 accuracy in B-slices for complexity reductio
+			- Not used in CfP submission
+      - Command line option in A124: MVA
+  1.2 SHV (simultaneous H & V motion partition)
+      - Enables to use motion partition composed of quarter and remaining regions
+      - Not used in CfP submission
+      - Command line option in A124: SHV
+  1.3 RNG (random noise generation)
+      - Insert Gaussian noise into the reconstruction file to improve perceived quality in flat areas
+      - Not used in CfP submission
+      - Command line option in A124: RNG
+  1.4 LOT (logical transform)
+      - Perform 5-3 wavelet + DCT if physical transform size is smaller than requested transform size
+      - Used in CfP submission only for 128x128 block
+      - Command line option in A124: LOT
+  1.5 CADR (contents-adaptive dynamic range)
+      - Performance source scaling within bit-depth limit
+      - Used in CfP submission
+      - Command line option in A124: CAD
+  1.6 LCT (low-complexity transform)
+      - Low-complexity version of large integer transform
+      - Not used in CfP submission
+      - Command line option in A124: LCT
+  1.7 EXC (extreme correction) & BDC (band correction)
+      - In-loop post filters based on pixel statistics
+      - Used in CfP submission
+      - Command line option in A124: EXC
+  1.8 PTM (pattern matching intra)
+      - Pixel-based pattern matching technique for intra prediction
+      - Used in CfP submission
+      - Command line option in A124: TMI
+  1.9 MPI (multi-parametric intra)
+      - Multi-parametric post-processing of intra prediction
+      - Used in CfP submission
+      - Command line option in A124: MPI
+  1.A CCCP (color correlation based chroma prediction)
+      - Chroma intra prediction based on luma reconstruction
+      - Used in CfP submission
+      - Command line option in A124: CCP
+  1.B ACS (adaptive coefficient scanning)
+      - 3 scanning patterns are used selectively (zigzag, horiz, vert)
+      - Used in CfP submission
+      - Command line option in A124: ACS
+  1.C HAM (high accuracy motion)
+      - 1/12th accuracy motion vector for luma and chroma
+      - Used in CfP submission for both luma and chroma
+      - Command line option in A124: HME, HAP, HAB
+  1.D HME: high accuracy motion estimation
+      - HAP: HAM in P-slice
+      - HAB: HAM in B-slice
+
+2. Modified tools
+
+  2.1 DIF (DCT-based interpolation filter)
+      - A124 uses 6-tap DIF for chroma
+      - Replaced with AVC bi-linear (1/8th) since it uses HAM filters (1/12th), which are not included in TMuC.
+  2.2 GRF (generated reference frame)
+      - Weighted, weight + offset, offset, affine, isotropic and perspective are supported
+      - Not used in CfP submission
+      - Command line option in A124: -v <character>
+      - w: weighted, o: offset, r: refinement, a: affine, i: isotropic, p: perspective
+      - Affine, isotropic and perspective are removed but weighted prediction is remained due to simulate AVC WP
+      - To activate: ¡®-v w¡¯ in command line (scale+offset) or ¡®-v o¡¯ for offset-only
+  2.3 AMVP (advanced motion prediction)
+      - A124 software supports three AMVP modes
+      - AM_NONE	: use first candidate only (similar to AVC), no signaling
+      - AM_EXPL	: use explicit signaling (used in CfP submission)
+      - AM_IMPL	: use implicit signaling based on template matching
+      - TMuC only has both explicit signaling mode and non-AMVP method
+      - AM_IMPL is removed since it is not included in TMuC
+      - AM_NONE is maintained since it can be a place-holder for non-AMVP method
+  2.4 CIP (combined intra prediction)
+      - CIPflag is now coded only for intra blocks (bug-fix)
+      - A124 codes CIPflag even in inter blocks
+
+3. Option changes
+
+  3.1 JMQ (JM QP)
+      - JMQ = 1: use JM QP assignments, JMQ = 0: use JSVM QP assignments
+      - Option is removed and JMQ is always on
+      - Option fix: JML (JM Lambda)
+  3.2 JML = 1: use JM lambda strategy, JML = 0: use JSVM lambda strategy
+      - Option is removed and JML is always on
+  3.3 Option fix: ADI
+      - Option is removed and ADI is always turned on
+  3.4 Option fix: AMV (AMVP)
+      - Option is removed and AMVP is always turned on
+  3.5 Option fix: DIF
+      - Option is removed and DIF is always turned on
+  3.6 Option fix: AMP
+      - Option is removed and AMP is always turned on
+  3.7 Option fix: CIP
+      - Option is removed and CIP is always turned on
+  3.8 Option fix: ROT
+      - Option is removed and ROT is always turned on
+      - Note: set ROT_DICT = 1 to disable ROT
+  3.9 Option fix: ACC
+      - Try coefficient clearing in inter modes
+      - Option is removed and ACC is always turned on
+  3.A Profile option (-p)
+      - It was used to separate A124 and A125 coding tools
+      - Removed, now 
+
+4. Misc. changes
+
+  4.1 MAX value of IBDI is fixed (IBDI_NOCLIP_RANGE MACRO)
+      - Only allows possible values of bit-depth increased signal, not all possible values of inherent high bit-depth case
+  4.2 Encoder output is fixed
+      - Slice size bit (32) is now added to the encoder print-out
+	4.3 Source code improvements
+	    - Unused functions are removed
+			- Variable & function namings are changed to clarify its purpose
+	
+5. Known problems
+
+  5.1 POC coding
+	    - It's not implemented well. Currently, fixed 10-bit is used for POC coding.
+	5.2 ROT (rotational transform)
+	    - Inverse ROT code is not the best one on the aspects of the dynamic range although we already have better one.
+			- It'll be replaced later with much simpler implementation.
Index: branches/HTM-6.2-dev1-Samsung/README-newconfig.txt
===================================================================
--- branches/HTM-6.2-dev1-Samsung/README-newconfig.txt	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/README-newconfig.txt	(revision 341)
@@ -0,0 +1,103 @@
+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-6.2-dev1-Samsung/README-usage.txt
===================================================================
--- branches/HTM-6.2-dev1-Samsung/README-usage.txt	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/README-usage.txt	(revision 341)
@@ -0,0 +1,147 @@
+Software usage example
+Contact: Woo-Jin Han, wjhan.han@samsung.com
+
+1. Installation and compilation
+   1.1 Source tree
+       - Root
+         |--- bin
+         |--- build
+              |--- linux
+         |--- cfg
+              |--- cfp
+         |--- doc
+         |--- source
+              |--- App
+                   |--- TAppDecoder
+                   |--- TAppEncoder
+              |--- Lib
+                   |--- TLibCommon
+                   |--- TLibDecoder
+                   |--- TLibEncoder
+                   |--- TLibVideoIO
+                   
+   1.2 Windows using MS Visual Studio
+       - Workspaces of VC6 and VC2008 are included in Root/build directory
+   1.3 Linux
+       - Makefile is included in Root/build/linux directory
+
+2. Encoder option
+   2.1 Parameters
+        - TAppEncoder.exe -c config.cfg [options]
+        - Options
+            -c      configuration file name
+            -i      original YUV input file name
+            -o      decoded YUV output file name
+            -b      bitstream file name
+            -m      dQP file name
+            -f      number of frames to be encoded (default EOS)
+            -q      Qp value, if value is float, QP is switched once during encoding
+            -g      GOP size of temporal structure
+            -rg     GOP size of hierarchical QP assignment
+            -s      max CU size
+            -h      CU depth
+            -r      Number of reference (P)
+            -rb0    Number of reference (B_L0)
+            -rb1    Number of reference (B_L1)
+            -ip     intra period in frames, (-1: only first frame)
+            -ldm    recommended low-delay setting (with LDC), (0=slow sequence, 1=fast sequence)
+            -d      max dQp offset for block
+            -dqr    max dQp offset for slice
+            -t      max transform size
+            -ltd    min transform depth
+            -utd    max transform depth
+            -v      additional reference for weighted prediction (w: scale+offset, o: offset)
+            -tap    number of interpolation filter taps (luma)
+            -tq0    QP offset of temporal layer 0
+            -tq1    QP offset of temporal layer 1
+            -tq2    QP offset of temporal layer 2
+            -tq3    QP offset of temporal layer 3
+            -pdx    horizontal source padding size
+            -pdy    vertical source padding size
+            -1/0    <name>: turn on/off <name>
+                    <name> = ALF - adaptive loop filter
+                             IBD - bit-depth increasement
+                             GPB - generalized B instead of P in low-delay mode
+                             HAD - hadamard ME for fractional-pel
+                             SRD - SBAC based RD estimation
+                             RDQ - RDOQ
+                             LDC - low-delay mode
+                             NRF - non-reference frame marking in last layer
+                             BQP - hier-P style QP assignment in low-delay mode
+                             PAD - automatic source padding of multiple of 16
+                             QBO - skip refers highest quality picture
+                             ASR - adaptive motion search range
+   2.2 Config file (example)
+   
+      #======== File I/O ===============
+      InputFile                     : d:\test\origcfp\RaceHorses_416x240_30.yuv
+      BitstreamFile                 : RaceHorses.bin
+      ReconFile                     : RaceHorses_enc.yuv
+      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
+      FrameToBeEncoded              : 9           # Number of frames to be coded
+
+      #======== Coding Structure =======
+      IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+      GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+      NumOfReference                : 1           # Number of reference frames
+      NumOfReferenceB_L0            : 1           # Number of reference frames for L0 for B-slices
+      NumOfReferenceB_L1            : 1           # Number of reference frames for L1 for B-slices
+      QP                            : 32          # Quantization parameter(0-51)
+
+      #======== New Structure ===========
+      MaxCUWidth                    : 128         # Maximum Coding Unit size in width
+      MaxCUHeight                   : 128         # Maximum Coding Unit size in Height
+      MaxPartitionDepth             : 5           # Maximum partition depth. ( minimum width = MaxWidth >> (MaxPartitionDepth-1) )
+
+      #=========== B Slice ===================
+      HierarchicalCoding            : 1           # B hierarchical coding ON/OFF (if OFF, no reference B is used)
+
+      #=========== Entropy Coding ============
+      SymbolMode                    : 1           # CAVLC: 0, SBAC: 1, only 1 supported, CAVLC implementation is not completed
+
+      #=========== Loop/Deblock Filter =======
+      LoopFilterDisable             : 0           # Disable loop filter in slice header (0=Filter, 1=No Filter)
+      LoopFilterAlphaC0Offset       : 0           # Range: -26 ~ 26
+      LoopFilterBetaOffset          : 0           # Range: -26 ~ 26
+
+      #=========== Motion search =============
+      FastSearch                    : 1           # 0:Full search  1:Diamond  2:PMVFAST(not supported) 
+      SearchRange                   : 128         # (0: Search range is a Full frame)
+      MaxDeltaQP                    : 0           # Absolute delta QP (1:default)
+      
+   2.3 Typical example
+  
+      Example 1) TAppEncoder.exe -c test.cfg -q 32 -g 8 -f 9 -s 64 -h 4
+      (Hier-B)    -> QP 32, hierarchical-B GOP 8, 9 frames, 64x64-8x8 CU (~4x4 PU)
+
+      Example 2) TAppEncoder.exe -c test.cfg -q 32 -g 4 -f 9 -s 64 -h 4 -1 LDC
+      (Hier-P)    -> QP 32, hierarchical-P GOP 4, 9 frames, 64x64-8x8 CU (~4x4 PU)
+			
+      Example 3) TAppEncoder.exe -c test.cfg -q 32 -g 1 -f 9 -s 64 -h 4 -1 LDC
+      (IPPP)      -> QP 32, hierarchical-P GOP 4, 9 frames, 64x64-8x8 CU (~4x4 PU)
+      
+3. Decoder option
+   3.1 Parameters
+        - TAppDecoder.exe -b test.bin -o test.yuv
+          . Decode test.bin and make test.yuv as the reconstructed YUV
+        - TAppDecoder.exe -b test.bin
+          . Decode test.bin but YUV writing is skipped
+
+4. Contact point
+
+    =========================================================== 
+    Woo-Jin Han, Principal Engineer
+    (wjhan.han@samsung.com)
+
+    M/M Platform Lab 
+
+    Digital Media & Communications R&D Center 
+    Digital Media & Communications Business
+    Samsung Electronics Co. Ltd.
+
+    Korea phone) 
+    +82-31-279-8831 (office), +82-10-3329-6393 (cellular)
+    ===========================================================
Index: branches/HTM-6.2-dev1-Samsung/build/HM_vc10.sln
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/HM_vc10.sln	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/HM_vc10.sln	(revision 341)
@@ -0,0 +1,138 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc10\TAppDecoder_vc10.vcxproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc10\TAppEncoder_vc10.vcxproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	ProjectSection(ProjectDependencies) = postProject
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4} = {2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc10\TAppCommon_vc10.vcxproj", "{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc10\TLibCommon_vc10.vcxproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc10\TLibDecoder_vc10.vcxproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc10\TLibEncoder_vc10.vcxproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+	ProjectSection(ProjectDependencies) = postProject
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4} = {2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc10\TLibVideoIO_vc10.vcxproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppRenderer", "vc10\TAppRenderer_vc10.vcxproj", "{3A5A8B26-8CA4-4690-944E-AB78559DE848}"
+	ProjectSection(ProjectDependencies) = postProject
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4} = {2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibRenderer", "vc10\TLibRenderer_vc10.vcxproj", "{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}"
+	ProjectSection(ProjectDependencies) = postProject
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibExtractor", "vc10\TLibExtractor_vc10.vcxproj", "{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppExtractor", "vc10\TAppExtractor_vc10.vcxproj", "{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.Build.0 = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.ActiveCfg = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.Build.0 = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.ActiveCfg = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.Build.0 = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.ActiveCfg = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Debug|Win32.ActiveCfg = Debug|Win32
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Debug|Win32.Build.0 = Debug|Win32
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Debug|x64.ActiveCfg = Debug|x64
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Debug|x64.Build.0 = Debug|x64
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Release|Win32.ActiveCfg = Release|Win32
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Release|Win32.Build.0 = Release|Win32
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Release|x64.ActiveCfg = Release|x64
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Release|x64.Build.0 = Release|x64
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Debug|Win32.ActiveCfg = Debug|Win32
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Debug|Win32.Build.0 = Debug|Win32
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Debug|x64.ActiveCfg = Debug|x64
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Debug|x64.Build.0 = Debug|x64
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Release|Win32.ActiveCfg = Release|Win32
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Release|Win32.Build.0 = Release|Win32
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Release|x64.ActiveCfg = Release|x64
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Release|x64.Build.0 = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.ActiveCfg = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.Build.0 = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.ActiveCfg = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.Build.0 = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.ActiveCfg = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.Build.0 = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.ActiveCfg = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.Build.0 = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.Build.0 = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.ActiveCfg = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.Build.0 = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.ActiveCfg = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.Build.0 = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.ActiveCfg = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: branches/HTM-6.2-dev1-Samsung/build/HM_vc8.sln
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/HM_vc8.sln	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/HM_vc8.sln	(revision 341)
@@ -0,0 +1,155 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 9.00
+# Visual Studio 2005
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc8\TAppDecoder_vc8.vcproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	ProjectSection(ProjectDependencies) = postProject
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc8\TAppEncoder_vc8.vcproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A} = {5E87AD84-AC4F-4336-B4EE-549CA210EE4A}
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1} = {47E90995-1FC5-4EE4-A94D-AD474169F0E1}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc8\TAppCommon_vc8.vcproj", "{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc8\TLibCommon_vc8.vcproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc8\TLibDecoder_vc8.vcproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc8\TLibEncoder_vc8.vcproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc8\TLibVideoIO_vc8.vcproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibRenderer", "vc8\TLibRenderer_vc8.vcproj", "{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppRenderer", "vc8\TAppRenderer_vc8.vcproj", "{CE149235-A923-4BA7-B552-3A02287CD3E4}"
+	ProjectSection(ProjectDependencies) = postProject
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A} = {5E87AD84-AC4F-4336-B4EE-549CA210EE4A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibExtractor", "vc8\TLibExtractor_vc8.vcproj", "{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppExtractor", "vc8\TAppExtractor_vc8.vcproj", "{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{27E2C758-E3CE-44CA-A226-83491EC7F798} = {27E2C758-E3CE-44CA-A226-83491EC7F798}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|Win32.ActiveCfg = Debug|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|Win32.Build.0 = Debug|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|x64.ActiveCfg = Debug|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|x64.Build.0 = Debug|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|Win32.ActiveCfg = Release|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|Win32.Build.0 = Release|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|x64.ActiveCfg = Release|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Debug|Win32.Build.0 = Debug|Win32
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Debug|x64.ActiveCfg = Debug|x64
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Debug|x64.Build.0 = Debug|x64
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Release|Win32.ActiveCfg = Release|Win32
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Release|Win32.Build.0 = Release|Win32
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Release|x64.ActiveCfg = Release|x64
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Release|x64.Build.0 = Release|x64
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Debug|Win32.ActiveCfg = Debug|Win32
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Debug|Win32.Build.0 = Debug|Win32
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Debug|x64.ActiveCfg = Debug|x64
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Debug|x64.Build.0 = Debug|x64
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Release|Win32.ActiveCfg = Release|Win32
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Release|Win32.Build.0 = Release|Win32
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Release|x64.ActiveCfg = Release|x64
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Release|x64.Build.0 = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.ActiveCfg = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.Build.0 = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.ActiveCfg = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.Build.0 = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.ActiveCfg = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.Build.0 = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.ActiveCfg = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.Build.0 = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.Build.0 = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.ActiveCfg = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.Build.0 = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.ActiveCfg = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.Build.0 = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.ActiveCfg = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: branches/HTM-6.2-dev1-Samsung/build/HM_vc9.sln
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/HM_vc9.sln	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/HM_vc9.sln	(revision 341)
@@ -0,0 +1,155 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc9\TAppDecoder_vc9.vcproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc9\TAppEncoder_vc9.vcproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1} = {47E90995-1FC5-4EE4-A94D-AD474169F0E1}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9} = {457993C6-AE2C-4B9B-B5F9-71033279A0B9}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc9\TAppCommon_vc9.vcproj", "{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc9\TLibCommon_vc9.vcproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc9\TLibDecoder_vc9.vcproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc9\TLibEncoder_vc9.vcproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc9\TLibVideoIO_vc9.vcproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibRenderer", "vc9\TLibRenderer_vc9.vcproj", "{457993C6-AE2C-4B9B-B5F9-71033279A0B9}"
+	ProjectSection(ProjectDependencies) = postProject
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppRenderer", "vc9\TAppRenderer_vc9.vcproj", "{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9} = {457993C6-AE2C-4B9B-B5F9-71033279A0B9}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibExtractor", "vc9\TLibExtractor_vc9.vcproj", "{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppExtractor", "vc9\TAppExtractor_vc9.vcproj", "{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{27E2C758-E3CE-44CA-A226-83491EC7F798} = {27E2C758-E3CE-44CA-A226-83491EC7F798}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.Build.0 = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.ActiveCfg = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.Build.0 = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.ActiveCfg = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.Build.0 = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.ActiveCfg = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Debug|Win32.ActiveCfg = Debug|Win32
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Debug|Win32.Build.0 = Debug|Win32
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Debug|x64.ActiveCfg = Debug|x64
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Debug|x64.Build.0 = Debug|x64
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Release|Win32.ActiveCfg = Release|Win32
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Release|Win32.Build.0 = Release|Win32
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Release|x64.ActiveCfg = Release|x64
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Release|x64.Build.0 = Release|x64
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Debug|Win32.ActiveCfg = Debug|Win32
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Debug|Win32.Build.0 = Debug|Win32
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Debug|x64.ActiveCfg = Debug|x64
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Debug|x64.Build.0 = Debug|x64
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Release|Win32.ActiveCfg = Release|Win32
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Release|Win32.Build.0 = Release|Win32
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Release|x64.ActiveCfg = Release|x64
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Release|x64.Build.0 = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.ActiveCfg = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.Build.0 = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.ActiveCfg = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.Build.0 = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.ActiveCfg = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.Build.0 = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.ActiveCfg = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.Build.0 = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.Build.0 = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.ActiveCfg = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.Build.0 = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.ActiveCfg = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.Build.0 = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.ActiveCfg = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppDecoder/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppDecoder/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppDecoder/makefile	(revision 341)
@@ -0,0 +1,58 @@
+# 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	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppDecoder
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# 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		= -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_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
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppEncoder/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppEncoder/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppEncoder/makefile	(revision 341)
@@ -0,0 +1,58 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppEncoder
+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	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppEncoder
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/encmain.o \
+					$(OBJ_DIR)/TAppEncCfg.o \
+					$(OBJ_DIR)/TAppEncTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+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_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
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppExtractor/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppExtractor/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppExtractor/makefile	(revision 341)
@@ -0,0 +1,58 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppExtractor
+INC_DIR				= ../../../../source/App/TAppExtractor
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppExtractor
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/extrmain.o \
+					$(OBJ_DIR)/TAppExtrCfg.o \
+					$(OBJ_DIR)/TAppExtrTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+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_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
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppRenderer/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppRenderer/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/app/TAppRenderer/makefile	(revision 341)
@@ -0,0 +1,58 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppRenderer
+INC_DIR				= ../../../../source/App
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppRenderer
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/RendererMain.o \
+					$(OBJ_DIR)/TAppRendererCfg.o \
+					$(OBJ_DIR)/TAppRendererTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibRendererd -lTLibCommond -lTLibVideoIOd -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
+
+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
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: branches/HTM-6.2-dev1-Samsung/build/linux/common/makefile.base
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/common/makefile.base	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/common/makefile.base	(revision 341)
@@ -0,0 +1,471 @@
+#########################################################
+# check CONFIG parameter
+#########################################################
+
+ifneq ($(CONFIG), LIBRARY)
+ifneq ($(CONFIG), CONSOLE)
+CONFIG_ERR = TRUE
+endif
+endif
+
+#########################################################
+# executables used
+#########################################################
+
+CPP   	= g++
+AR    	= ar
+LD    	= $(CPP)
+ASM		= nasm
+
+#########################################################
+# output file names and version information
+#########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+# the libraries that can be created
+STAT_DEBUG_OUT    	= $(LIB_DIR)/lib$(PRJ_NAME)Staticd.a
+STAT_RELEASE_OUT  	= $(LIB_DIR)/lib$(PRJ_NAME)Static.a
+DYN_DEBUG_OUT     	= $(LIB_DIR)/lib$(PRJ_NAME)d.so
+DYN_RELEASE_OUT   	= $(LIB_DIR)/lib$(PRJ_NAME).so
+#
+else 
+ifeq ($(CONFIG), CONSOLE)
+# the executables that can be created
+STAT_DEBUG_OUT    = $(BIN_DIR)/$(PRJ_NAME)Staticd
+STAT_RELEASE_OUT  = $(BIN_DIR)/$(PRJ_NAME)Static
+DYN_DEBUG_OUT     = $(BIN_DIR)/$(PRJ_NAME)d
+DYN_RELEASE_OUT   = $(BIN_DIR)/$(PRJ_NAME)
+#
+endif
+endif
+
+
+#########################################################
+# c compiler flags
+#########################################################
+
+# default cpp flags for all configurations
+#CPPFLAGS          = -Wall -fPIC $(DEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS)
+CPPFLAGS          = -fPIC $(DEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS) -Wall -Wshadow -Wno-sign-compare -Werror
+
+########## 
+# enforce 32-bit build : 1=yes, 0=no
+##########
+M32?= 0
+ifeq ($(M32),1)
+CPPFLAGS+=-m32
+endif
+##########
+
+#
+# debug cpp flags
+DEBUG_CPPFLAGS    = -g  -D_DEBUG
+#
+# release cpp
+RELEASE_CPPFLAGS  =  -O3 -ffloat-store -Wuninitialized
+
+
+#########################################################
+# assembler compiler flags
+#########################################################
+
+# default asm flags for all configurations
+ASMFLAGS          = -f elf $(DEFS)
+#
+# debug asm flags
+DEBUG_ASMFLAGS    = -g
+#
+# release asm flags
+RELEASE_ASMFLAGS  =
+
+
+
+#########################################################
+# linker flags
+#########################################################
+
+# linker flags for all
+ALL_LDFLAGS       = -Wall
+
+########## 
+# enforce 32-bit build : 1=yes, 0=no
+##########
+ifeq ($(M32),1)
+ALL_LDFLAGS+=-m32
+endif
+##########
+
+
+ifeq ($(CONFIG), LIBRARY)
+# linker flags for library
+# LDFLAGS           = $(ALL_LDFLAGS) -shared -Wl,-Bsymbolic
+LDFLAGS           = $(ALL_LDFLAGS) -shared
+#
+# debug linker flags for library
+DEBUG_LDFLAGS     = -Wl,-soname,lib$(PRJ_NAME)d.so.$(VER)
+#
+# release linker flags for library
+RELEASE_LDFLAGS   = -Wl,-soname,lib$(PRJ_NAME).so.$(VER)
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+# linker flags for console
+LDFLAGS           = $(ALL_LDFLAGS)
+#
+# debug linker flags for console
+DEBUG_LDFLAGS     =
+#
+# release linker flags for console
+RELEASE_LDFLAGS   =
+#
+endif
+endif
+
+
+
+#########################################################
+# objects that have to be created
+#########################################################
+
+# the object types that have to be created      
+RELEASE_OBJS  = $(OBJS:.o=.r.o)
+DEBUG_OBJS    = $(OBJS:.o=.d.o)
+
+
+#########################################################
+# rules
+#########################################################
+
+# suffixes
+.SUFFIXES: .cpp .asm .r.o .d.o
+
+#########################################################
+# assembler rules
+#########################################################
+
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+
+
+#########################################################
+# c rules
+#########################################################
+
+# Generate dependency files during compilation
+# see also: http://make.paulandlesley.org/autodep.html
+#    2005-01-25 Steffen Kamp (kamp@ient.rwth-aachen.de), RWTH Aachen
+define COMPILE_AND_DEPEND_RELEASE
+        $(CPP) -c -MMD -MF $(OBJ_DIR)/$*.r.d -MT $(OBJ_DIR)/$*.r.o $(CPPFLAGS) $(RELEASE_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.r.d $(OBJ_DIR)/$*.r.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.r.d >> $(OBJ_DIR)/$*.r.P; \
+                rm -f $(OBJ_DIR)/$*.r.d
+endef
+define COMPILE_AND_DEPEND_DEBUG
+        $(CPP) -c -MMD -MF $(OBJ_DIR)/$*.d.d -MT $(OBJ_DIR)/$*.d.o $(CPPFLAGS) $(DEBUG_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.d.d $(OBJ_DIR)/$*.d.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.d.d >> $(OBJ_DIR)/$*.d.P; \
+                rm -f $(OBJ_DIR)/$*.d.d
+endef
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+
+#########################################################
+# directory settings
+#########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+# directories that have to be created for a library
+CHECK_DIRS = $(OBJ_DIR) $(LIB_DIR)
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+# directories that have to be created for console and MFC
+CHECK_DIRS = $(OBJ_DIR) $(BIN_DIR)
+#
+endif
+endif
+
+
+#########################################################
+# targets
+#########################################################
+
+all:              	check_errors debug release
+
+debug:            	check_errors \
+					$(CHECK_DIRS) \
+					$(STAT_DEBUG_OUT)
+
+release:          	check_errors \
+					$(CHECK_DIRS) \
+					$(STAT_RELEASE_OUT)
+
+
+#all:              	check_errors debug release
+#
+#debug:            	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_DEBUG_OUT) \
+#					$(STAT_DEBUG_OUT)
+#
+#release:          	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_RELEASE_OUT) \
+#					$(STAT_RELEASE_OUT)
+#
+#stat_debug:       	check_errors \
+#					$(CHECK_DIRS) \
+#					$(STAT_DEBUG_OUT)
+#          
+#dyn_debug:        	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_DEBUG_OUT)
+#
+#stat_release:     	check_errors \
+#					$(CHECK_DIRS) \
+#					$(STAT_RELEASE_OUT)
+#        
+#dyn_release:      	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_RELEASE_OUT)
+
+##########################################################
+# check for errors
+##########################################################
+check_errors:
+	@if [ "$(CONFIG_ERR)" = "TRUE" ]; then\
+		echo "Wrong CONFIG parameter specified: $(CONFIG)";\
+		false;\
+	fi
+
+
+##########################################################
+# create directories
+##########################################################
+
+$(OBJ_DIR):
+	@if [ ! -d $(OBJ_DIR) ]; then\
+		mkdir $(OBJ_DIR);\
+	fi
+
+$(LIB_DIR):
+	@if [ ! -d $(LIB_DIR) ]; then\
+		mkdir $(LIB_DIR);\
+	fi
+
+$(BIN_DIR):
+	@if [ ! -d $(BIN_DIR) ]; then\
+		mkdir $(BIN_DIR);\
+	fi
+
+
+
+##########################################################
+# create output files
+##########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+#
+# create static debug out
+$(STAT_DEBUG_OUT): $(DEBUG_OBJS)
+	$(AR) -crs $@ $(DEBUG_OBJS)
+#
+#
+# create release debug out
+$(STAT_RELEASE_OUT): $(RELEASE_OBJS)
+	$(AR) -crs $@ $(RELEASE_OBJS)
+#
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT): $(DYN_DEBUG_OUT).$(VER) 
+	ln -fs lib$(PRJ_NAME)d.so.$(VER) $@
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT).$(VER): $(DEBUG_OBJS) 
+	$(LD) $(LDFLAGS) $(DEBUG_LDFLAGS) -o $@ $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(DYN_LIBS) $(DYN_DEBUG_LIBS)
+#
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT): $(DYN_RELEASE_OUT).$(VER)
+	ln -fs lib$(PRJ_NAME).so.$(VER) $@
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT).$(VER): $(RELEASE_OBJS)
+	$(LD) $(LDFLAGS) $(RELEASE_LDFLAGS) -o $@ $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(DYN_LIBS) $(DYN_RELEASE_LIBS)
+#
+#
+#
+#
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+#
+# added linked libraries to target prerequisites - $(*_PREREQS) variables - to force relinking when libraries have been rebuilt
+#    2005-01-25 Steffen Kamp (kamp@ient.rwth-aachen.de), RWTH Aachen
+#
+# create static debug out
+$(STAT_DEBUG_OUT): $(DEBUG_OBJS) $(STAT_DEBUG_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(DEBUG_LDFLAGS) $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(STAT_LIBS) $(STAT_DEBUG_LIBS)
+#
+#
+# create static release out
+$(STAT_RELEASE_OUT): $(RELEASE_OBJS) $(STAT_RELEASE_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(RELEASE_LDFLAGS) $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(STAT_LIBS) $(STAT_RELEASE_LIBS)
+#
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT): $(DEBUG_OBJS) $(DYN_DEBUG_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(DEBUG_LDFLAGS) $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(DYN_LIBS) $(DYN_DEBUG_LIBS)
+#
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT): $(RELEASE_OBJS) $(DYN_RELEASE_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(RELEASE_LDFLAGS) $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(DYN_LIBS) $(DYN_RELEASE_LIBS)
+#
+#
+endif
+endif
+
+##########################################################
+# delete all produced files
+##########################################################
+
+clean:
+	/bin/rm -rf $(STAT_DEBUG_OUT)
+	/bin/rm -rf $(STAT_RELEASE_OUT)
+	/bin/rm -rf $(DYN_DEBUG_OUT)
+	/bin/rm -rf $(DYN_RELEASE_OUT)
+	/bin/rm -rf $(OBJ_DIR)
+
+ifeq ($(CONFIG), LIBRARY)
+	/bin/rm -rf $(DYN_DEBUG_OUT).$(VER)
+	/bin/rm -rf $(DYN_RELEASE_OUT).$(VER)
+endif
+
+
+##########################################################
+# include dependency files
+##########################################################
+
+-include $(OBJS:.o=.d.P)
+-include $(OBJS:.o=.r.P)
Index: branches/HTM-6.2-dev1-Samsung/build/linux/lib/TAppCommon/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/lib/TAppCommon/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/lib/TAppCommon/makefile	(revision 341)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TAppCommon
+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	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TAppCommon
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/program_options_lite.o \
+			$(OBJ_DIR)/TAppComCamPara.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-6.2-dev1-Samsung/build/linux/lib/TLibCommon/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibCommon/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibCommon/makefile	(revision 341)
@@ -0,0 +1,81 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibCommon
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		= ../../../../source/Lib/libmd5
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibCommon
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/ContextModel.o \
+			$(OBJ_DIR)/ContextModel3DBuffer.o \
+			$(OBJ_DIR)/TComCABACTables.o \
+			$(OBJ_DIR)/TComAdaptiveLoopFilter.o \
+			$(OBJ_DIR)/TComSampleAdaptiveOffset.o \
+			$(OBJ_DIR)/TComBitStream.o \
+			$(OBJ_DIR)/TComDataCU.o \
+			$(OBJ_DIR)/TComDepthMapGenerator.o \
+			$(OBJ_DIR)/TComLoopFilter.o \
+			$(OBJ_DIR)/TComMotionInfo.o \
+			$(OBJ_DIR)/TComPattern.o \
+			$(OBJ_DIR)/TComPic.o \
+			$(OBJ_DIR)/TComPicSym.o \
+			$(OBJ_DIR)/TComPicYuv.o \
+			$(OBJ_DIR)/TComPicYuvMD5.o \
+			$(OBJ_DIR)/TComPrediction.o \
+			$(OBJ_DIR)/TComRdCost.o \
+			$(OBJ_DIR)/TComResidualGenerator.o \
+			$(OBJ_DIR)/TComRom.o \
+			$(OBJ_DIR)/TComSlice.o \
+			$(OBJ_DIR)/TComTrQuant.o \
+			$(OBJ_DIR)/TComYuv.o \
+			$(OBJ_DIR)/TComInterpolationFilter.o \
+			$(OBJ_DIR)/libmd5.o \
+			$(OBJ_DIR)/TComWeightPrediction.o \
+			$(OBJ_DIR)/TComRdCostWeightPrediction.o \
+			$(OBJ_DIR)/TComWedgelet.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-6.2-dev1-Samsung/build/linux/lib/TLibDecoder/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibDecoder/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibDecoder/makefile	(revision 341)
@@ -0,0 +1,65 @@
+# 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	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibDecoder
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+				$(OBJ_DIR)/AnnexBread.o \
+				$(OBJ_DIR)/NALread.o \
+				$(OBJ_DIR)/SEIread.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-6.2-dev1-Samsung/build/linux/lib/TLibEncoder/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibEncoder/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibEncoder/makefile	(revision 341)
@@ -0,0 +1,71 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibEncoder
+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	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibEncoder
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/NALwrite.o \
+			$(OBJ_DIR)/SEIwrite.o \
+			$(OBJ_DIR)/TEncBinCoderCABAC.o \
+			$(OBJ_DIR)/TEncBinCoderCABACCounter.o \
+			$(OBJ_DIR)/TEncAdaptiveLoopFilter.o \
+			$(OBJ_DIR)/TEncSampleAdaptiveOffset.o \
+			$(OBJ_DIR)/TEncCavlc.o \
+			$(OBJ_DIR)/TEncCu.o \
+			$(OBJ_DIR)/TEncEntropy.o \
+			$(OBJ_DIR)/TEncGOP.o \
+			$(OBJ_DIR)/TEncSbac.o \
+			$(OBJ_DIR)/TEncSearch.o \
+			$(OBJ_DIR)/TEncSlice.o \
+			$(OBJ_DIR)/TEncTop.o \
+			$(OBJ_DIR)/TEncPic.o \
+			$(OBJ_DIR)/TEncPreanalyzer.o \
+			$(OBJ_DIR)/WeightPredAnalysis.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-6.2-dev1-Samsung/build/linux/lib/TLibExtractor/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibExtractor/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibExtractor/makefile	(revision 341)
@@ -0,0 +1,55 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibExtractor
+INC_DIR			= ../../../../source/Lib/TLibExtractor
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibExtractor
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+				$(OBJ_DIR)/TExtrTop.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-6.2-dev1-Samsung/build/linux/lib/TLibRenderer/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibRenderer/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibRenderer/makefile	(revision 341)
@@ -0,0 +1,62 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibRenderer
+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	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibRenderer
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/TRenFilter.o \
+			$(OBJ_DIR)/TRenInterpFilter.o \
+			$(OBJ_DIR)/TRenImage.o \
+			$(OBJ_DIR)/TRenImagePlane.o \
+			$(OBJ_DIR)/TRenTop.o \
+			$(OBJ_DIR)/TRenModel.o \
+                        $(OBJ_DIR)/TRenSingleModel.o \
+                        $(OBJ_DIR)/TRenModSetupStrParser.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-6.2-dev1-Samsung/build/linux/lib/TLibVideoIO/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibVideoIO/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/lib/TLibVideoIO/makefile	(revision 341)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibVideoIO
+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	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibVideoIO
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 28
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/TVideoIOYuv.o \
+						
+
+LIBS				= -lpthread 
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			=
+
+# 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-6.2-dev1-Samsung/build/linux/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/makefile	(revision 341)
@@ -0,0 +1,67 @@
+### enforce 32-bit build : 1=yes, 0=no
+M32?= 0
+ 
+export M32
+
+all:
+	$(MAKE) -C lib/TLibVideoIO 	MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	MM32=$(M32)
+	$(MAKE) -C lib/TLibRenderer  MM32=$(M32)
+	$(MAKE) -C lib/TLibExtractor  MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon   MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      MM32=$(M32)
+	$(MAKE) -C app/TAppRenderer     MM32=$(M32)
+	$(MAKE) -C app/TAppExtractor    MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr MM32=$(M32)
+
+
+debug:
+	$(MAKE) -C lib/TLibVideoIO 	debug	MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	debug	MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	debug MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	debug MM32=$(M32)
+	$(MAKE) -C lib/TLibRenderer  debug	MM32=$(M32)
+	$(MAKE) -C lib/TLibExtractor  debug	MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon   debug MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      debug MM32=$(M32)
+	$(MAKE) -C app/TAppRenderer     debug MM32=$(M32)
+	$(MAKE) -C app/TAppExtractor    debug MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       debug MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr debug MM32=$(M32)
+
+
+release:
+	$(MAKE) -C lib/TLibVideoIO 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibRenderer  release MM32=$(M32)
+	$(MAKE) -C lib/TLibExtractor  release MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon   release MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      release MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      release MM32=$(M32)
+	$(MAKE) -C app/TAppRenderer    release MM32=$(M32)	
+	$(MAKE) -C app/TAppExtractor    release MM32=$(M32)	
+	$(MAKE) -C utils/annexBbytecount       release MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr release MM32=$(M32)
+
+
+clean:
+	$(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/TAppCommon   clean MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      clean MM32=$(M32)
+	$(MAKE) -C app/TAppRenderer    clean MM32=$(M32)	
+	$(MAKE) -C app/TAppExtractor    clean MM32=$(M32)	
+	$(MAKE) -C utils/annexBbytecount       clean MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr clean MM32=$(M32)
Index: branches/HTM-6.2-dev1-Samsung/build/linux/utils/annexBbytecount/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/utils/annexBbytecount/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/utils/annexBbytecount/makefile	(revision 341)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/utils
+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	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= annexBbytecount
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/annexBbytecount.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+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_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
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: branches/HTM-6.2-dev1-Samsung/build/linux/utils/convert_NtoMbit_YCbCr/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 341)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/utils
+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	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= convert_NtoMbit_YCbCr
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/convert_NtoMbit_YCbCr.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+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_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
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: branches/HTM-6.2-dev1-Samsung/build/vc10/TAppCommon_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TAppCommon_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TAppCommon_vc10.vcxproj	(revision 341)
@@ -0,0 +1,156 @@
+﻿<?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>TAppCommon</ProjectName>
+    <ProjectGuid>{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}</ProjectGuid>
+    <RootNamespace>TAppCommon</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;%(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;%(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\TAppCommon\program_options_lite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TAppCommon\TAppComCamPara.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h" />
+    <ClInclude Include="..\..\source\Lib\TAppCommon\TAppComCamPara.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: branches/HTM-6.2-dev1-Samsung/build/vc10/TAppDecoder_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TAppDecoder_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TAppDecoder_vc10.vcxproj	(revision 341)
@@ -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>TAppDecoder</ProjectName>
+    <ProjectGuid>{A7A515D9-E917-4706-BD5B-57DC6C78D612}</ProjectGuid>
+    <RootNamespace>TAppDecoder</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;%(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;%(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="TLibDecoder_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-6.2-dev1-Samsung/build/vc10/TAppEncoder_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TAppEncoder_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TAppEncoder_vc10.vcxproj	(revision 341)
@@ -0,0 +1,207 @@
+﻿<?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>TAppEncoder</ProjectName>
+    <ProjectGuid>{D759E4E1-D33A-4483-B57B-0FD248E022FE}</ProjectGuid>
+    <RootNamespace>TAppEncoder</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;%(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;%(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\TAppEncoder\encmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.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="TLibEncoder_vc10.vcxproj">
+      <Project>{47e90995-1fc5-4ee4-a94d-ad474169f0e1}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <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">
+      <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-6.2-dev1-Samsung/build/vc10/TAppExtractor_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TAppExtractor_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TAppExtractor_vc10.vcxproj	(revision 341)
@@ -0,0 +1,201 @@
+﻿<?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>TAppExtractor</ProjectName>
+    <ProjectGuid>{F46F95E9-7174-4328-90DD-092450E4DCF6}</ProjectGuid>
+    <RootNamespace>TAppExtractor</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.30319.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)'=='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>
+    <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>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+      <AdditionalIncludeDirectories>..\..\compat\msvc</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>..\..\compat\msvc</AdditionalIncludeDirectories>
+    </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>
+      <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|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <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>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppExtractor\extrmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppExtractor\TAppExtrCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppExtractor\TAppExtrTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppExtractor\TAppExtrCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppExtractor\TAppExtrTop.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="TLibDecoder_vc10.vcxproj">
+      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibExtractor_vc10.vcxproj">
+      <Project>{27e2c758-e3ce-44ca-a226-83491ec7f798}</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-6.2-dev1-Samsung/build/vc10/TAppRenderer_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TAppRenderer_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TAppRenderer_vc10.vcxproj	(revision 341)
@@ -0,0 +1,203 @@
+﻿<?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>TAppRenderer</ProjectName>
+    <ProjectGuid>{3A5A8B26-8CA4-4690-944E-AB78559DE848}</ProjectGuid>
+    <RootNamespace>TAppRenderer</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.30319.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)'=='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>
+    <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>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <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>
+      <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>
+      <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>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</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>
+      <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>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppRenderer\RendererMain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppRenderer\TAppRendererCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppRenderer\TAppRendererTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppRenderer\TAppRendererCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppRenderer\TAppRendererTop.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="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">
+      <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-6.2-dev1-Samsung/build/vc10/TLibCommon_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TLibCommon_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TLibCommon_vc10.vcxproj	(revision 341)
@@ -0,0 +1,215 @@
+﻿<?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>TLibCommon</ProjectName>
+    <ProjectGuid>{78018D78-F890-47E3-A0B7-09D273F0B11D}</ProjectGuid>
+    <RootNamespace>TLibCommon</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;%(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;%(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\TLibCommon\ContextModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp" />
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDepthMapGenerator.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComResidualGenerator.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWedgelet.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h" />
+    <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\NAL.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDepthMapGenerator.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComResidualGenerator.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\TComWedgelet.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: branches/HTM-6.2-dev1-Samsung/build/vc10/TLibDecoder_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TLibDecoder_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TLibDecoder_vc10.vcxproj	(revision 341)
@@ -0,0 +1,175 @@
+﻿<?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>TLibDecoder</ProjectName>
+    <ProjectGuid>{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}</ProjectGuid>
+    <RootNamespace>TLibDecoder</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;%(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;%(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\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\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-6.2-dev1-Samsung/build/vc10/TLibEncoder_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TLibEncoder_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TLibEncoder_vc10.vcxproj	(revision 341)
@@ -0,0 +1,190 @@
+﻿<?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>TLibEncoder</ProjectName>
+    <ProjectGuid>{47E90995-1FC5-4EE4-A94D-AD474169F0E1}</ProjectGuid>
+    <RootNamespace>TLibEncoder</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;%(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;%(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\TLibEncoder\NALwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPic.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPic.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: branches/HTM-6.2-dev1-Samsung/build/vc10/TLibExtractor_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TLibExtractor_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TLibExtractor_vc10.vcxproj	(revision 341)
@@ -0,0 +1,152 @@
+﻿<?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>TLibExtractor</ProjectName>
+    <ProjectGuid>{27E2C758-E3CE-44CA-A226-83491EC7F798}</ProjectGuid>
+    <RootNamespace>TLibExtractor</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.30319.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)'=='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>
+    <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>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_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>
+    </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>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_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\TLibExtractor\TExtrTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibExtractor\TExtrTop.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: branches/HTM-6.2-dev1-Samsung/build/vc10/TLibRenderer_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TLibRenderer_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TLibRenderer_vc10.vcxproj	(revision 341)
@@ -0,0 +1,168 @@
+﻿<?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>TLibRenderer</ProjectName>
+    <ProjectGuid>{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}</ProjectGuid>
+    <RootNamespace>TLibRenderer</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.30319.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)'=='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>
+    <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>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_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>
+  </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>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_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>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenImagePlane.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenImage.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenInterpFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenSingleModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenImagePlane.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenImage.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenInterpFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenModel.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenSingleModel.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenTop.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: branches/HTM-6.2-dev1-Samsung/build/vc10/TLibVideoIO_vc10.vcxproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 341)
@@ -0,0 +1,154 @@
+﻿<?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>TLibVideoIO</ProjectName>
+    <ProjectGuid>{5280C25A-D316-4BE7-AE50-29D72108624F}</ProjectGuid>
+    <RootNamespace>TLibVideoIo</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;%(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;%(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\TLibVideoIO\TVideoIOYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TAppCommon_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TAppCommon_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TAppCommon_vc8.vcproj	(revision 341)
@@ -0,0 +1,306 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppCommon"
+	ProjectGUID="{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}"
+	RootNamespace="TAppCommon"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\TAppComCamPara.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\TAppComCamPara.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TAppDecoder_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TAppDecoder_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TAppDecoder_vc8.vcproj	(revision 341)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppDecoder"
+	ProjectGUID="{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	RootNamespace="TAppDecoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\decmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TAppEncoder_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TAppEncoder_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TAppEncoder_vc8.vcproj	(revision 341)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppEncoder"
+	ProjectGUID="{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	RootNamespace="TAppEncoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\encmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TAppExtractor_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TAppExtractor_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TAppExtractor_vc8.vcproj	(revision 341)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppExtractor"
+	ProjectGUID="{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+	RootNamespace="TAppExtractor"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\extrmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TAppRenderer_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TAppRenderer_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TAppRenderer_vc8.vcproj	(revision 341)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppRenderer"
+	ProjectGUID="{CE149235-A923-4BA7-B552-3A02287CD3E4}"
+	RootNamespace="TAppRenderer"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\RendererMain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TLibCommon_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TLibCommon_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TLibCommon_vc8.vcproj	(revision 341)
@@ -0,0 +1,544 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8.00"
+	Name="TLibCommon"
+	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+	RootNamespace="TLibCommon"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDepthMapGenerator.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComResidualGenerator.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWedgelet.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\AccessUnit.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\CommonDef.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\MD5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\NAL.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDepthMapGenerator.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComList.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComResidualGenerator.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWedgelet.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TypeDef.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TLibDecoder_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TLibDecoder_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TLibDecoder_vc8.vcproj	(revision 341)
@@ -0,0 +1,382 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibDecoder"
+	ProjectGUID="{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+	RootNamespace="TLibDecoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TLibEncoder_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TLibEncoder_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TLibEncoder_vc8.vcproj	(revision 341)
@@ -0,0 +1,442 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibEncoder"
+	ProjectGUID="{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+	RootNamespace="TLibEncoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\AnnexBwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TLibExtractor_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TLibExtractor_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TLibExtractor_vc8.vcproj	(revision 341)
@@ -0,0 +1,298 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibExtractor"
+	ProjectGUID="{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+	RootNamespace="TLibExtractor"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibExtractor\TExtrTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibExtractor\TExtrTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TLibRenderer_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TLibRenderer_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TLibRenderer_vc8.vcproj	(revision 341)
@@ -0,0 +1,354 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibRenderer"
+	ProjectGUID="{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}"
+	RootNamespace="TLibRenderer"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImage.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImagePlane.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenInterpFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenSingleModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImage.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImagePlane.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenInterpFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenSingleModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc8/TLibVideoIO_vc8.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc8/TLibVideoIO_vc8.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc8/TLibVideoIO_vc8.vcproj	(revision 341)
@@ -0,0 +1,298 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibVideoIO"
+	ProjectGUID="{5280C25A-D316-4BE7-AE50-29D72108624F}"
+	RootNamespace="TLibVideoIo"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TAppCommon_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TAppCommon_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TAppCommon_vc9.vcproj	(revision 341)
@@ -0,0 +1,309 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppCommon"
+	ProjectGUID="{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+	RootNamespace="TAppCommon"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\TAppComCamPara.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\TAppComCamPara.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TAppDecoder_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TAppDecoder_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TAppDecoder_vc9.vcproj	(revision 341)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppDecoder"
+	ProjectGUID="{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	RootNamespace="TAppDecoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\decmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TAppEncoder_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TAppEncoder_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TAppEncoder_vc9.vcproj	(revision 341)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppEncoder"
+	ProjectGUID="{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	RootNamespace="TAppEncoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\encmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TAppExtractor_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TAppExtractor_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TAppExtractor_vc9.vcproj	(revision 341)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppExtractor"
+	ProjectGUID="{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+	RootNamespace="TAppExtractor"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\extrmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TAppRenderer_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TAppRenderer_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TAppRenderer_vc9.vcproj	(revision 341)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppRenderer"
+	ProjectGUID="{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}"
+	RootNamespace="TAppRenderer"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\RendererMain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TLibCommon_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TLibCommon_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TLibCommon_vc9.vcproj	(revision 341)
@@ -0,0 +1,547 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibCommon"
+	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+	RootNamespace="TLibCommon"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDepthMapGenerator.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComResidualGenerator.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWedgelet.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\AccessUnit.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\CommonDef.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\MD5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\NAL.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDepthMapGenerator.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComList.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComResidualGenerator.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWedgelet.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TypeDef.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TLibDecoder_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TLibDecoder_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TLibDecoder_vc9.vcproj	(revision 341)
@@ -0,0 +1,385 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibDecoder"
+	ProjectGUID="{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+	RootNamespace="TLibDecoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TLibEncoder_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TLibEncoder_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TLibEncoder_vc9.vcproj	(revision 341)
@@ -0,0 +1,445 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibEncoder"
+	ProjectGUID="{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+	RootNamespace="TLibEncoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\AnnexBwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TLibExtractor_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TLibExtractor_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TLibExtractor_vc9.vcproj	(revision 341)
@@ -0,0 +1,301 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibExtractor"
+	ProjectGUID="{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+	RootNamespace="TLibExtractor"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibExtractor\TExtrTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibExtractor\TExtrTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TLibRenderer_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TLibRenderer_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TLibRenderer_vc9.vcproj	(revision 341)
@@ -0,0 +1,357 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibRenderer"
+	ProjectGUID="{457993C6-AE2C-4B9B-B5F9-71033279A0B9}"
+	RootNamespace="TLibRenderer"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImage.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImagePlane.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenInterpFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenSingleModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImage.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImagePlane.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenInterpFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenSingleModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/build/vc9/TLibVideoIO_vc9.vcproj
===================================================================
--- branches/HTM-6.2-dev1-Samsung/build/vc9/TLibVideoIO_vc9.vcproj	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/build/vc9/TLibVideoIO_vc9.vcproj	(revision 341)
@@ -0,0 +1,301 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibVideoIO"
+	ProjectGUID="{5280C25A-D316-4BE7-AE50-29D72108624F}"
+	RootNamespace="TLibVideoIo"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_balloons.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_balloons.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_balloons.cfg	(revision 341)
@@ -0,0 +1,236 @@
+
+#========== file i/o ==========
+InputFile_0               : balloons_1024x768_420_1.yuv                              # video input file for view 0
+InputFile_1               : balloons_1024x768_420_5.yuv                              # video input file for view 2
+InputFile_2               : balloons_1024x768_420_3.yuv                              # video input file for view 1
+
+DepthInputFile_0          : balloons_1024x768_420_depth_1.yuv                        # depth input file for view 0
+DepthInputFile_1          : balloons_1024x768_420_depth_5.yuv                        # depth input file for view 2
+DepthInputFile_2          : balloons_1024x768_420_depth_3.yuv                        # depth input file for view 1
+
+ReconFile_0               : rec_texture_1.yuv                              # video output file for view 0
+ReconFile_1               : rec_texture_5.yuv                              # video output file for view 2
+ReconFile_2               : rec_texture_3.yuv                              # video output file for view 1
+
+DepthReconFile_0          : rec_depth_1.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_5.yuv                        # depth output file for view 2
+DepthReconFile_2          : rec_depth_3.yuv                        # depth output file for view 1
+
+
+BitstreamFile             : str.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_balloons.cfg                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : B    0   3        0.442    0           1                1       0                            0                                                      2             -2 -1              1 0                0 1
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      2             -2 -1              2 0                0 2
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       2             -2 -1              2 0                0 2
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         2             -2 -1              2 0                0 2
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       2             -2 -1              2 0                0 2
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       2             -2 -1              3 0                0 3
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                            # illumination compensation (0: OFF, 1: ON)
+IVSEnable                      : 1                                 # inter-view vector scaling (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                      # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1D2T1T2                           # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(oo1) I(s0.25 s0.5 s0.75)][cx1 B(cc0) B(cc2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(oo1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+QP                        : 25 34        # Quantization parameter(0-51), second QP for Depth
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+SourceWidth               : 1024                                    # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 1 5 3                                 # camera numbers of coded views (in coding order)
+
+
Index: branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_gtfly.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_gtfly.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_gtfly.cfg	(revision 341)
@@ -0,0 +1,236 @@
+
+#========== file i/o ==========
+InputFile_0               : GT_Fly_1920x1088_420_9.yuv                              # video input file for view 0
+InputFile_1               : GT_Fly_1920x1088_420_1.yuv                              # video input file for view 2
+InputFile_2               : GT_Fly_1920x1088_420_5.yuv                              # video input file for view 1
+
+DepthInputFile_0          : GT_Fly_1920x1088_420_depth_9.yuv                        # depth input file for view 0
+DepthInputFile_1          : GT_Fly_1920x1088_420_depth_1.yuv                        # depth input file for view 2
+DepthInputFile_2          : GT_Fly_1920x1088_420_depth_5.yuv                        # depth input file for view 1
+
+ReconFile_0               : rec_texture_9.yuv                              # video output file for view 0
+ReconFile_1               : rec_texture_1.yuv                              # video output file for view 2
+ReconFile_2               : rec_texture_5.yuv                              # video output file for view 1
+
+DepthReconFile_0          : rec_depth_9.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_1.yuv                        # depth output file for view 2
+DepthReconFile_2          : rec_depth_5.yuv                        # depth output file for view 1
+
+
+BitstreamFile             : str.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_gtfly.cfg                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : B    0   3        0.442    0           1                1       0                            0                                                      2             -2 -1              1 0                0 1
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      2             -2 -1              2 0                0 2
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       2             -2 -1              2 0                0 2
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         2             -2 -1              2 0                0 2
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       2             -2 -1              2 0                0 2
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       2             -2 -1              3 0                0 3
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                            # illumination compensation (0: OFF, 1: ON)
+IVSEnable                      : 1                                 # inter-view vector scaling (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                      # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1D2T1T2                           # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(oo1) I(s0.25 s0.5 s0.75)][cx1 B(cc0) B(cc2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(oo1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+QP                        : 25 34        # Quantization parameter(0-51), second QP for Depth
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+SourceWidth               : 1920                                    # input frame width
+SourceHeight              : 1088                                    # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 9 1 5                                 # camera numbers of coded views (in coding order)
+
+
Index: branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_kendo.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_kendo.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_kendo.cfg	(revision 341)
@@ -0,0 +1,236 @@
+
+#========== file i/o ==========
+InputFile_0               : kendo_1024x768_420_1.yuv                              # video input file for view 0
+InputFile_1               : kendo_1024x768_420_5.yuv                              # video input file for view 2
+InputFile_2               : kendo_1024x768_420_3.yuv                              # video input file for view 1
+
+DepthInputFile_0          : kendo_1024x768_420_depth_1.yuv                        # depth input file for view 0
+DepthInputFile_1          : kendo_1024x768_420_depth_5.yuv                        # depth input file for view 2
+DepthInputFile_2          : kendo_1024x768_420_depth_3.yuv                        # depth input file for view 1
+
+ReconFile_0               : rec_texture_1.yuv                              # video output file for view 0
+ReconFile_1               : rec_texture_5.yuv                              # video output file for view 2
+ReconFile_2               : rec_texture_3.yuv                              # video output file for view 1
+
+DepthReconFile_0          : rec_depth_1.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_5.yuv                        # depth output file for view 2
+DepthReconFile_2          : rec_depth_3.yuv                        # depth output file for view 1
+
+
+BitstreamFile             : str.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_kendo.cfg                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : B    0   3        0.442    0           1                1       0                            0                                                      2             -2 -1              1 0                0 1
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      2             -2 -1              2 0                0 2
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       2             -2 -1              2 0                0 2
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         2             -2 -1              2 0                0 2
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       2             -2 -1              2 0                0 2
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       2             -2 -1              3 0                0 3
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                            # illumination compensation (0: OFF, 1: ON)
+IVSEnable                      : 1                                 # inter-view vector scaling (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                      # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1D2T1T2                           # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(oo1) I(s0.25 s0.5 s0.75)][cx1 B(cc0) B(cc2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(oo1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+QP                        : 25 34        # Quantization parameter(0-51), second QP for Depth
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+SourceWidth               : 1024                                    # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 1 5 3                                 # camera numbers of coded views (in coding order)
+
+
Index: branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_news.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_news.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_news.cfg	(revision 341)
@@ -0,0 +1,236 @@
+
+#========== file i/o ==========
+InputFile_0               : Newspaper_1024x768_420_2.yuv                              # video input file for view 0
+InputFile_1               : Newspaper_1024x768_420_6.yuv                              # video input file for view 2
+InputFile_2               : Newspaper_1024x768_420_4.yuv                              # video input file for view 1
+
+DepthInputFile_0          : Newspaper_1024x768_420_depth_2.yuv                        # depth input file for view 0
+DepthInputFile_1          : Newspaper_1024x768_420_depth_6.yuv                        # depth input file for view 2
+DepthInputFile_2          : Newspaper_1024x768_420_depth_4.yuv                        # depth input file for view 1
+
+ReconFile_0               : rec_texture_2.yuv                              # video output file for view 0
+ReconFile_1               : rec_texture_6.yuv                              # video output file for view 2
+ReconFile_2               : rec_texture_4.yuv                              # video output file for view 1
+
+DepthReconFile_0          : rec_depth_2.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_6.yuv                        # depth output file for view 2
+DepthReconFile_2          : rec_depth_4.yuv                        # depth output file for view 1
+
+
+BitstreamFile             : str.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_newspaper.cfg                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : B    0   3        0.442    0           1                1       0                            0                                                      2             -2 -1              1 0                0 1
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      2             -2 -1              2 0                0 2
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       2             -2 -1              2 0                0 2
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         2             -2 -1              2 0                0 2
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       2             -2 -1              2 0                0 2
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       2             -2 -1              3 0                0 3
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                            # illumination compensation (0: OFF, 1: ON)
+IVSEnable                      : 1                                 # inter-view vector scaling (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                      # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1D2T1T2                           # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(oo1) I(s0.25 s0.5 s0.75)][cx1 B(cc0) B(cc2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(oo1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+QP                        : 25 34        # Quantization parameter(0-51), second QP for Depth
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+SourceWidth               : 1024                                    # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 2 6 4                                 # camera numbers of coded views (in coding order)
+
+
Index: branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_poznanhall.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_poznanhall.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_poznanhall.cfg	(revision 341)
@@ -0,0 +1,236 @@
+
+#========== file i/o ==========
+InputFile_0               : Poznan_Hall2_00_1920x1088_420_7.yuv                              # video input file for view 0
+InputFile_1               : Poznan_Hall2_00_1920x1088_420_5.yuv                              # video input file for view 2
+InputFile_2               : Poznan_Hall2_00_1920x1088_420_6.yuv                              # video input file for view 1
+
+DepthInputFile_0          : Poznan_Hall2_00_1920x1088_420_depth_7.yuv                        # depth input file for view 0
+DepthInputFile_1          : Poznan_Hall2_00_1920x1088_420_depth_5.yuv                        # depth input file for view 2
+DepthInputFile_2          : Poznan_Hall2_00_1920x1088_420_depth_6.yuv                        # depth input file for view 1
+
+ReconFile_0               : rec_texture_7.yuv                              # video output file for view 0
+ReconFile_1               : rec_texture_5.yuv                              # video output file for view 2
+ReconFile_2               : rec_texture_6.yuv                              # video output file for view 1
+
+DepthReconFile_0          : rec_depth_7.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_5.yuv                        # depth output file for view 2
+DepthReconFile_2          : rec_depth_6.yuv                        # depth output file for view 1
+
+
+BitstreamFile             : str.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_poznanhall2.cfg                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : B    0   3        0.442    0           1                1       0                            0                                                      2             -2 -1              1 0                0 1
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      2             -2 -1              2 0                0 2
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       2             -2 -1              2 0                0 2
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         2             -2 -1              2 0                0 2
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       2             -2 -1              2 0                0 2
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       2             -2 -1              3 0                0 3
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                            # illumination compensation (0: OFF, 1: ON)
+IVSEnable                      : 1                                 # inter-view vector scaling (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                      # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1D2T1T2                           # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(oo1) I(s0.25 s0.5 s0.75)][cx1 B(cc0) B(cc2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(oo1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+QP                        : 25 34        # Quantization parameter(0-51), second QP for Depth
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+SourceWidth               : 1920                                    # input frame width
+SourceHeight              : 1088                                    # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 200                                    # number of frames to be coded
+BaseViewCameraNumbers     : 7 5 6                                 # camera numbers of coded views (in coding order)
+
+
Index: branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_poznanstreet.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_poznanstreet.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_poznanstreet.cfg	(revision 341)
@@ -0,0 +1,236 @@
+
+#========== file i/o ==========
+InputFile_0               : Poznan_Street_00_1920x1088_420_5.yuv                              # video input file for view 0
+InputFile_1               : Poznan_Street_00_1920x1088_420_3.yuv                              # video input file for view 2
+InputFile_2               : Poznan_Street_00_1920x1088_420_4.yuv                              # video input file for view 1
+
+DepthInputFile_0          : Poznan_Street_00_1920x1088_420_depth_5.yuv                        # depth input file for view 0
+DepthInputFile_1          : Poznan_Street_00_1920x1088_420_depth_3.yuv                        # depth input file for view 2
+DepthInputFile_2          : Poznan_Street_00_1920x1088_420_depth_4.yuv                        # depth input file for view 1
+
+ReconFile_0               : rec_texture_5.yuv                              # video output file for view 0
+ReconFile_1               : rec_texture_3.yuv                              # video output file for view 2
+ReconFile_2               : rec_texture_4.yuv                              # video output file for view 1
+
+DepthReconFile_0          : rec_depth_5.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_3.yuv                        # depth output file for view 2
+DepthReconFile_2          : rec_depth_4.yuv                        # depth output file for view 1
+
+
+BitstreamFile             : str.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_poznanstreet.cfg                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : B    0   3        0.442    0           1                1       0                            0                                                      2             -2 -1              1 0                0 1
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      2             -2 -1              2 0                0 2
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       2             -2 -1              2 0                0 2
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         2             -2 -1              2 0                0 2
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       2             -2 -1              2 0                0 2
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       2             -2 -1              3 0                0 3
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                            # illumination compensation (0: OFF, 1: ON)
+IVSEnable                      : 1                                 # inter-view vector scaling (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                      # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1D2T1T2                           # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(oo1) I(s0.25 s0.5 s0.75)][cx1 B(cc0) B(cc2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(oo1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+QP                        : 25 34        # Quantization parameter(0-51), second QP for Depth
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+SourceWidth               : 1920                                    # input frame width
+SourceHeight              : 1088                                    # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 5 3 4                                 # camera numbers of coded views (in coding order)
+
+
Index: branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_undodancer.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_undodancer.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/IBPsetting_undodancer.cfg	(revision 341)
@@ -0,0 +1,236 @@
+
+#========== file i/o ==========
+InputFile_0               : Dancer_1920x1088_420_1.yuv                              # video input file for view 0
+InputFile_1               : Dancer_1920x1088_420_9.yuv                              # video input file for view 2
+InputFile_2               : Dancer_1920x1088_420_5.yuv                              # video input file for view 1
+
+DepthInputFile_0          : Dancer_1920x1088_420_depth_1.yuv                        # depth input file for view 0
+DepthInputFile_1          : Dancer_1920x1088_420_depth_9.yuv                        # depth input file for view 2
+DepthInputFile_2          : Dancer_1920x1088_420_depth_5.yuv                        # depth input file for view 1
+
+ReconFile_0               : rec_texture_1.yuv                              # video output file for view 0
+ReconFile_1               : rec_texture_9.yuv                              # video output file for view 2
+ReconFile_2               : rec_texture_5.yuv                              # video output file for view 1
+
+DepthReconFile_0          : rec_depth_1.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_9.yuv                        # depth output file for view 2
+DepthReconFile_2          : rec_depth_5.yuv                        # depth output file for view 1
+
+
+BitstreamFile             : str.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_undodancer.cfg                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod               : 24                                     # Period of I-Frame ( -1 = only first)
+DecodingRefreshType       : 1                                      # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                   : 8                                      # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1    : B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0
+Frame2    : B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3    : B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4    : B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5    : B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6    : B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7    : B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8    : B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1 : P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0
+Frame1_v1 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0 
+Frame2_v1 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0 
+Frame3_v1 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2 : B    0   3        0.442    0           1                1       0                            0                                                      2             -2 -1              1 0                0 1
+Frame1_v2 : B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      2             -2 -1              2 0                0 2
+Frame2_v2 : B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       2             -2 -1              2 0                0 2
+Frame3_v2 : B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         2             -2 -1              2 0                0 2
+Frame4_v2 : B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       2             -2 -1              2 0                0 2
+Frame5_v2 : B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame6_v2 : B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+Frame7_v2 : B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       2             -2 -1              3 0                0 3
+Frame8_v2 : B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       2             -2 -1              3 0                0 3
+
+
+ListCombination           : 1                                      # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4           : 1                                      # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                       : 1                                      # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset            : 0                                      # ChromaQPOffset
+ChromaQpOffset2nd         : 0                                      # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent : 1                                 # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS          : 0                                 # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable              : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2      : 0                                 # Range: -13 ~ 13
+LoopFilterTcOffset_div2        : 0                                 # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                            : 1 0                               # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                       : 0                                 # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                           : 0                                 # Non-square transforms (0: OFF, 1: ON)
+AMP                            : 0                                 # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter                : 16                                # ALF Max Number Filters per picture
+ALFParamInSlice                : 0                                 # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode              : 1                                 # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving                : 0                                 # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                                 # illumination compensation (0: OFF, 1: ON)
+IVSEnable                      : 1                                 # inter-view vector scaling (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams            : 1                                 # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                      # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1D2T1T2                           # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(oo1) I(s0.25 s0.5 s0.75)][cx1 B(cc0) B(cc2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(oo1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+#============ Misc. ================
+QP                        : 25 34        # Quantization parameter(0-51), second QP for Depth
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+SourceWidth               : 1920                                    # input frame width
+SourceHeight              : 1088                                    # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 1 9 5                                 # camera numbers of coded views (in coding order)
+
+
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_balloons.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_balloons.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_balloons.cfg	(revision 341)
@@ -0,0 +1,5 @@
+#Balloons
+#ViewNum    StartFrame   EndFrame  FocalLength   Position  CShift     ZNear       ZFar
+1           0            299       2241.25607    5.0       701.5      448.251214  11206.280350
+3           0            299       2241.25607    15.0      701.5      448.251214  11206.280350
+5           0            299       2241.25607    25.0      701.5      448.251214  11206.280350
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_bookarrival.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_bookarrival.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_bookarrival.cfg	(revision 341)
@@ -0,0 +1,5 @@
+#BookArrival
+#ViewNum    StartFrame   EndFrame  FocalLength        Position       CShift   ZNear      ZFar
+10          0            99        1399.466666666666  -5.205949      512      23.175928  54.077165
+8           0            99        1399.466666666666  -4.046711      512      23.175928  54.077165
+6           0            99        1399.466666666666  -2.892842      512      23.439447  54.692044
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_gtfly.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_gtfly.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_gtfly.cfg	(revision 341)
@@ -0,0 +1,1002 @@
+# GTFly
+#ViewNum StartFrame EndFrame FocalLength Position      CShift   ZNear  ZFar
+1	0	0	2519.92835	2824.796184	960	70625	662000
+1	1	1	2519.92835	2796.781248	960	69812.5	663000
+1	2	2	2519.92835	2768.828518	960	68937.5	664500
+1	3	3	2519.92835	2740.939995	960	68125	665500
+1	4	4	2519.92835	2713.1179	960	67312.5	667000
+1	5	5	2519.92835	2685.364456	960	66500	668500
+1	6	6	2519.92835	2657.68166	960	65750	673500
+1	7	7	2519.92835	2630.071736	960	65000	1259000
+1	8	8	2519.92835	2602.536904	960	64250	1264000
+1	9	9	2519.92835	2575.079387	960	63531.3	1268000
+1	10	10	2519.92835	2547.701406	960	62843.8	1273000
+1	11	11	2519.92835	2520.404739	960	62156.3	1277000
+1	12	12	2519.92835	2493.192051	960	61531.3	1282000
+1	13	13	2519.92835	2466.06512	960	60906.3	1287000
+1	14	14	2519.92835	2439.026167	960	60281.3	1292000
+1	15	15	2519.92835	2412.077637	960	59718.8	1297000
+1	16	16	2519.92835	2385.221528	960	59062.5	1302000
+1	17	17	2519.92835	2358.459841	960	58031.3	1307000
+1	18	18	2519.92835	2331.79502	960	57000	1312000
+1	19	19	2519.92835	2305.229063	960	56031.3	1317000
+1	20	20	2519.92835	2278.764192	960	55593.8	1323000
+1	21	21	2519.92835	2252.402629	960	56375	1328000
+1	22	22	2519.92835	2226.146375	960	55812.5	1333000
+1	23	23	2519.92835	2199.997649	960	55250	1338000
+1	24	24	2519.92835	2173.958896	960	54718.8	1343000
+1	25	25	2519.92835	2148.031672	960	54156.3	1348000
+1	26	26	2519.92835	2122.218865	960	53625	1354000
+1	27	27	2519.92835	2096.522029	960	53093.8	1359000
+1	28	28	2519.92835	2070.943608	960	52531.3	1364000
+1	29	29	2519.92835	2045.486047	960	52000	1369000
+1	30	30	2519.92835	2020.150901	960	51468.8	1374000
+1	31	31	2519.92835	1994.940835	960	50937.5	1379000
+1	32	32	2519.92835	1969.857627	960	50406.3	1384000
+1	33	33	2519.92835	1944.903943	960	49906.3	1389000
+1	34	34	2519.92835	1920.081338	960	49375	1394000
+1	35	35	2519.92835	1895.392478	960	48843.8	1400000
+1	36	36	2519.92835	1870.839363	960	48343.8	1405000
+1	37	37	2519.92835	1846.423992	960	47812.5	1411000
+1	38	38	2519.92835	1822.148809	960	47312.5	1416000
+1	39	39	2519.92835	1798.015813	960	46781.3	1422000
+1	40	40	2519.92835	1774.027227	960	46281.3	1428000
+1	41	41	2519.92835	1750.18516	960	45781.3	1433000
+1	42	42	2519.92835	1726.491835	960	45281.3	1437000
+1	43	43	2519.92835	1702.949362	960	44781.3	1442000
+1	44	44	2519.92835	1679.559962	960	44281.3	1444000
+1	45	45	2519.92835	1656.325858	960	43781.3	1447000
+1	46	46	2519.92835	1633.249049	960	43312.5	1449000
+1	47	47	2519.92835	1610.331868	960	42812.5	1451000
+1	48	48	2519.92835	1587.576313	960	42312.5	1453000
+1	49	49	2519.92835	1564.984719	960	41343.8	1455000
+1	50	50	2519.92835	1542.559084	960	40281.3	1457000
+1	51	51	2519.92835	1520.301742	960	39187.5	1459000
+1	52	52	2519.92835	1498.214802	960	38125	1460000
+1	53	53	2519.92835	1476.300265	960	37062.5	1463000
+1	54	54	2519.92835	1454.560574	960	35968.8	1465000
+1	55	55	2519.92835	1432.997728	960	34906.3	1468000
+1	56	56	2519.92835	1411.61395	960	33843.8	1471000
+1	57	57	2519.92835	1390.41135	960	33156.3	1474000
+1	58	58	2519.92835	1369.39215	960	37656.3	1477000
+1	59	59	2519.92835	1348.558459	960	37187.5	1479000
+1	60	60	2519.92835	1327.912501	960	36750	1482000
+1	61	61	2519.92835	1307.456497	960	36312.5	1484000
+1	62	62	2519.92835	1287.192445	960	35843.8	1486000
+1	63	63	2519.92835	1267.122568	960	35406.3	1489000
+1	64	64	2519.92835	1247.249088	960	34968.8	1492000
+1	65	65	2519.92835	1227.574226	960	34562.5	1495000
+1	66	66	2519.92835	1208.099982	960	34125	1498000
+1	67	67	2519.92835	1188.828688	960	33687.5	1505000
+1	68	68	2519.92835	1169.762344	960	33281.3	1510000
+1	69	69	2519.92835	1150.903282	960	32843.8	1515000
+1	70	70	2519.92835	1132.253503	960	32437.5	1518000
+1	71	71	2519.92835	1113.815339	960	32031.3	1522000
+1	72	72	2519.92835	1095.59079	960	31609.4	1526000
+1	73	73	2519.92835	1077.582188	960	31203.1	1529000
+1	74	74	2519.92835	1059.791532	960	30796.9	1533000
+1	75	75	2519.92835	1042.221156	960	30406.3	1536000
+1	76	76	2519.92835	1024.873059	960	30000	1539000
+1	77	77	2519.92835	1007.749574	960	29609.4	1543000
+1	78	78	2519.92835	990.8528113	960	29218.8	1547000
+1	79	79	2519.92835	974.1847705	960	28843.8	1550000
+1	80	80	2519.92835	957.7478955	960	28453.1	1554000
+1	81	81	2519.92835	941.5441858	960	28078.1	1558000
+1	82	82	2519.92835	925.5758075	960	27703.1	1562000
+1	83	83	2519.92835	909.8449268	960	27328.1	1566000
+1	84	84	2519.92835	894.3538208	960	26953.1	1569000
+1	85	85	2519.92835	879.1044891	960	26593.8	1573000
+1	86	86	2519.92835	864.099209	960	26234.4	1576000
+1	87	87	2519.92835	849.3401465	960	25875	1579000
+1	88	88	2519.92835	834.8294122	960	25515.6	1582000
+1	89	89	2519.92835	820.5692279	960	25156.3	1584000
+1	90	90	2519.92835	806.5617041	960	24812.5	1587000
+1	91	91	2519.92835	792.8090625	960	24468.8	1590000
+1	92	92	2519.92835	779.3134137	960	24125	1592000
+1	93	93	2519.92835	766.0769238	960	23781.3	1595000
+1	94	94	2519.92835	753.1018146	960	23453.1	1599000
+1	95	95	2519.92835	740.3902521	960	23109.4	1603000
+1	96	96	2519.92835	727.9443469	960	22296.9	1606000
+1	97	97	2519.92835	715.7662653	960	21406.3	1610000
+1	98	98	2519.92835	703.8582288	960	20515.6	1614000
+1	99	99	2519.92835	692.222348	960	20093.8	1617000
+1	100	100	2519.92835	680.8608447	960	19281.3	1619000
+1	101	101	2519.92835	669.775885	960	21203.1	1622000
+1	102	102	2519.92835	658.9695239	960	20390.6	1625000
+1	103	103	2519.92835	648.4440387	960	19546.9	1628000
+1	104	104	2519.92835	638.2015955	960	18796.9	1631000
+1	105	105	2519.92835	628.2443048	960	18062.5	1634000
+1	106	106	2519.92835	618.5743329	960	17453.1	1638000
+1	107	107	2519.92835	609.1939014	960	19406.3	1641000
+1	108	108	2519.92835	600.1051764	960	19109.4	1644000
+1	109	109	2519.92835	591.310213	960	18828.1	1646000
+1	110	110	2519.92835	582.811344	960	18546.9	1649000
+1	111	111	2519.92835	574.6105688	960	18281.3	1652000
+1	112	112	2519.92835	566.7101648	960	18000	1654000
+1	113	113	2519.92835	559.1122424	960	17734.4	1656000
+1	114	114	2519.92835	551.8190234	960	17468.8	1659000
+1	115	115	2519.92835	544.8326184	960	17203.1	1661000
+1	116	116	2519.92835	538.155249	960	16937.5	1663000
+1	117	117	2519.92835	531.7890259	960	16687.5	1665000
+1	118	118	2519.92835	525.7361151	960	16437.5	1668000
+1	119	119	2519.92835	519.9987384	960	16187.5	1671000
+1	120	120	2519.92835	514.4477606	960	15937.5	1673000
+1	121	121	2519.92835	508.9524359	960	15640.6	1677000
+1	122	122	2519.92835	503.5123755	960	14929.7	1000000000
+1	123	123	2519.92835	498.1273016	960	14390.6	1000000000
+1	124	124	2519.92835	492.7967145	960	13687.5	1000000000
+1	125	125	2519.92835	487.5203918	960	12945.3	1000000000
+1	126	126	2519.92835	482.2978894	960	12859.4	1000000000
+1	127	127	2519.92835	477.1288739	960	14312.5	1000000000
+1	128	128	2519.92835	472.0130121	960	14093.8	1000000000
+1	129	129	2519.92835	466.9499152	960	13882.8	1000000000
+1	130	130	2519.92835	461.9392499	960	13664.1	1000000000
+1	131	131	2519.92835	456.9805997	960	13460.9	1000000000
+1	132	132	2519.92835	452.0736868	960	13250	1000000000
+1	133	133	2519.92835	447.2180948	960	13046.9	1000000000
+1	134	134	2519.92835	442.4134625	960	12781.3	1000000000
+1	135	135	2519.92835	437.6594846	960	12218.8	1000000000
+1	136	136	2519.92835	432.9557443	960	11726.6	1000000000
+1	137	137	2519.92835	428.3019086	960	12164.1	1000000000
+1	138	138	2519.92835	423.6976163	960	11656.3	1000000000
+1	139	139	2519.92835	419.1425064	960	11179.7	1000000000
+1	140	140	2519.92835	414.6362457	960	10757.8	1000000000
+1	141	141	2519.92835	410.1784177	960	10523.4	1000000000
+1	142	142	2519.92835	405.7687167	960	11367.2	1000000000
+1	143	143	2519.92835	401.4067542	960	11195.3	1000000000
+1	144	144	2519.92835	397.0921967	960	11023.4	1000000000
+1	145	145	2519.92835	392.8246555	960	10859.4	1000000000
+1	146	146	2519.92835	388.6037973	960	10695.3	1000000000
+1	147	147	2519.92835	384.4292334	960	10539.1	1000000000
+1	148	148	2519.92835	380.3006305	960	10171.9	1000000000
+1	149	149	2519.92835	376.2176276	960	9585.9	1000000000
+1	150	150	2519.92835	372.1798636	960	9117.2	1000000000
+1	151	151	2519.92835	368.1869775	960	8687.5	1000000000
+1	152	152	2519.92835	364.2386084	960	8671.9	1000000000
+1	153	153	2519.92835	360.3343951	960	8023.4	1000000000
+1	154	154	2519.92835	356.4739767	960	7410.2	1000000000
+1	155	155	2519.92835	352.65702	960	6812.5	1000000000
+1	156	156	2519.92835	348.883136	960	6218.8	1000000000
+1	157	157	2519.92835	345.1519638	960	5976.6	1770000
+1	158	158	2519.92835	341.4631702	960	5363.3	1000000000
+1	159	159	2519.92835	337.8163663	960	4859.4	1000000000
+1	160	160	2519.92835	334.2112466	960	4293	1000000000
+1	161	161	2519.92835	330.6473669	960	8664.1	1000000000
+1	162	162	2519.92835	327.1244495	960	8554.7	1000000000
+1	163	163	2519.92835	323.6421054	960	8453.1	1000000000
+1	164	164	2519.92835	320.199946	960	8351.6	1000000000
+1	165	165	2519.92835	316.7976657	960	8257.8	1000000000
+1	166	166	2519.92835	313.4348758	960	8164.1	1000000000
+1	167	167	2519.92835	310.1112152	960	8070.3	1000000000
+1	168	168	2519.92835	306.8263229	960	7988.3	1000000000
+1	169	169	2519.92835	303.5798657	960	7902.3	1000000000
+1	170	170	2519.92835	300.3714548	960	7824.2	1000000000
+1	171	171	2519.92835	297.2007568	960	7746.1	1000000000
+1	172	172	2519.92835	294.0673831	960	7671.9	1000000000
+1	173	173	2519.92835	290.9710004	960	7605.5	1000000000
+1	174	174	2519.92835	287.9112198	960	7539.1	1000000000
+1	175	175	2519.92835	284.8877359	960	7476.6	1000000000
+1	176	176	2519.92835	281.9001321	960	7414.1	1000000000
+1	177	177	2519.92835	278.9480753	960	7351.6	1000000000
+1	178	178	2519.92835	276.031232	960	7277.3	1000000000
+1	179	179	2519.92835	273.1491858	960	7203.1	1000000000
+1	180	180	2519.92835	270.3016312	960	7128.9	1000000000
+1	181	181	2519.92835	267.4881793	960	7058.6	1000000000
+1	182	182	2519.92835	264.7084692	960	6992.2	1000000000
+1	183	183	2519.92835	261.9621677	960	6925.8	1000000000
+1	184	184	2519.92835	259.2488858	960	6859.4	1000000000
+1	185	185	2519.92835	256.5682904	960	6793	1000000000
+1	186	186	2519.92835	253.9200204	960	6730.5	1000000000
+1	187	187	2519.92835	251.3036871	960	6671.9	1000000000
+1	188	188	2519.92835	248.7189572	960	6613.3	1000000000
+1	189	189	2519.92835	246.1654697	960	6554.7	1000000000
+1	190	190	2519.92835	243.6428635	960	6496.1	1000000000
+1	191	191	2519.92835	241.1507776	960	6441.4	1000000000
+1	192	192	2519.92835	238.688851	960	6386.7	1000000000
+1	193	193	2519.92835	236.2567227	960	6335.9	1000000000
+1	194	194	2519.92835	233.8540594	960	6285.2	1000000000
+1	195	195	2519.92835	231.4804724	960	6234.4	1000000000
+1	196	196	2519.92835	229.1356145	960	6183.6	1000000000
+1	197	197	2519.92835	226.8191246	960	6136.7	1000000000
+1	198	198	2519.92835	224.5306418	960	6089.8	1000000000
+1	199	199	2519.92835	222.269805	960	6043	1000000000
+1	200	200	2519.92835	220.0362671	960	5996.1	1000000000
+1	201	201	2519.92835	217.8296532	960	5945.3	1000000000
+1	202	202	2519.92835	215.64963	960	5894.5	1000000000
+1	203	203	2519.92835	213.4958087	960	5843.8	1000000000
+1	204	204	2519.92835	211.3678423	960	5793	1000000000
+1	205	205	2519.92835	209.2653696	960	5746.1	1000000000
+1	206	206	2519.92835	207.1880435	960	5695.3	1000000000
+1	207	207	2519.92835	205.1355031	960	5648.4	1000000000
+1	208	208	2519.92835	203.1073734	960	5605.5	1000000000
+1	209	209	2519.92835	201.1033072	960	5558.6	1000000000
+1	210	210	2519.92835	199.1229436	960	5519.5	1000000000
+1	211	211	2519.92835	197.1659215	960	5476.6	1000000000
+1	212	212	2519.92835	195.2318938	960	5441.4	1000000000
+1	213	213	2519.92835	193.3204855	960	5406.3	1000000000
+1	214	214	2519.92835	191.4313358	960	5375	1000000000
+1	215	215	2519.92835	189.5641112	960	5343.8	1000000000
+1	216	216	2519.92835	187.718423	960	5316.4	1000000000
+1	217	217	2519.92835	185.8939241	960	5293	1000000000
+1	218	218	2519.92835	184.0902673	960	5269.5	1000000000
+1	219	219	2519.92835	182.3070778	960	5250	1000000000
+1	220	220	2519.92835	180.5439944	960	5230.5	1000000000
+1	221	221	2519.92835	178.7962685	960	5214.8	1000000000
+1	222	222	2519.92835	177.0593454	960	5199.2	1000000000
+1	223	223	2519.92835	175.3332253	960	5003.9	1000000000
+1	224	224	2519.92835	173.6178941	960	4632.8	1000000000
+1	225	225	2519.92835	171.9133243	960	4324.2	1000000000
+1	226	226	2519.92835	170.2195296	960	4289.1	1000000000
+1	227	227	2519.92835	168.5364822	960	4195.3	1000000000
+1	228	228	2519.92835	166.8641684	960	3898.4	1000000000
+1	229	229	2519.92835	165.2026019	960	5085.9	1000000000
+1	230	230	2519.92835	163.5517412	960	5074.2	1000000000
+1	231	231	2519.92835	161.9115862	960	5062.5	1000000000
+1	232	232	2519.92835	160.282123	960	5054.7	1000000000
+1	233	233	2519.92835	158.6633377	960	5050.8	1000000000
+1	234	234	2519.92835	157.0552304	960	5046.9	1000000000
+1	235	235	2519.92835	155.4577872	960	5046.9	1000000000
+1	236	236	2519.92835	153.8709941	960	4882.8	1000000000
+1	237	237	2519.92835	152.2948373	960	4578.1	1000000000
+1	238	238	2519.92835	150.729303	960	4359.4	1000000000
+1	239	239	2519.92835	149.1743771	960	4257.8	1000000000
+1	240	240	2519.92835	147.6300598	960	4683.6	1000000000
+1	241	241	2519.92835	146.0963371	960	4363.3	1000000000
+1	242	242	2519.92835	144.5731813	960	4043	1000000000
+1	243	243	2519.92835	143.0606062	960	3765.6	1000000000
+1	244	244	2519.92835	141.5585841	960	3552.7	1000000000
+1	245	245	2519.92835	140.067115	960	3285.2	1000000000
+1	246	246	2519.92835	138.5861711	960	3156.3	1000000000
+1	247	247	2519.92835	137.1157524	960	4976.6	1000000000
+1	248	248	2519.92835	135.655845	960	4964.8	1000000000
+1	249	249	2519.92835	134.2064351	960	4953.1	1000000000
+2	0	0	2519.92835	2471.696661	960	70625	662000
+2	1	1	2519.92835	2447.183592	960	69812.5	663000
+2	2	2	2519.92835	2422.724953	960	68937.5	664500
+2	3	3	2519.92835	2398.322496	960	68125	665500
+2	4	4	2519.92835	2373.978163	960	67312.5	667000
+2	5	5	2519.92835	2349.693899	960	66500	668500
+2	6	6	2519.92835	2325.471453	960	65750	674500
+2	7	7	2519.92835	2301.312769	960	65000	1259000
+2	8	8	2519.92835	2277.219791	960	64250	1264000
+2	9	9	2519.92835	2253.194464	960	63531.3	1268000
+2	10	10	2519.92835	2229.23873	960	62843.8	1273000
+2	11	11	2519.92835	2205.354146	960	62156.3	1278000
+2	12	12	2519.92835	2181.543044	960	61531.3	1282000
+2	13	13	2519.92835	2157.80698	960	60906.3	1287000
+2	14	14	2519.92835	2134.147896	960	60281.3	1292000
+2	15	15	2519.92835	2110.567932	960	59718.8	1297000
+2	16	16	2519.92835	2087.068837	960	59062.5	1302000
+2	17	17	2519.92835	2063.652361	960	58031.3	1307000
+2	18	18	2519.92835	2040.320642	960	56968.8	1312000
+2	19	19	2519.92835	2017.07543	960	55968.8	1318000
+2	20	20	2519.92835	1993.918668	960	55468.8	1323000
+2	21	21	2519.92835	1970.852301	960	56375	1328000
+2	22	22	2519.92835	1947.878078	960	55812.5	1333000
+2	23	23	2519.92835	1924.997943	960	55250	1338000
+2	24	24	2519.92835	1902.214034	960	54718.8	1343000
+2	25	25	2519.92835	1879.527713	960	54156.3	1349000
+2	26	26	2519.92835	1856.941507	960	53625	1354000
+2	27	27	2519.92835	1834.456775	960	53093.8	1359000
+2	28	28	2519.92835	1812.075657	960	52531.3	1364000
+2	29	29	2519.92835	1789.800291	960	52000	1369000
+2	30	30	2519.92835	1767.632038	960	51468.8	1374000
+2	31	31	2519.92835	1745.573231	960	50937.5	1379000
+2	32	32	2519.92835	1723.625424	960	50406.3	1384000
+2	33	33	2519.92835	1701.79095	960	49906.3	1389000
+2	34	34	2519.92835	1680.071171	960	49375	1394000
+2	35	35	2519.92835	1658.468418	960	48843.8	1400000
+2	36	36	2519.92835	1636.984442	960	48343.8	1405000
+2	37	37	2519.92835	1615.620993	960	47812.5	1411000
+2	38	38	2519.92835	1594.380208	960	47312.5	1416000
+2	39	39	2519.92835	1573.263836	960	46781.3	1422000
+2	40	40	2519.92835	1552.273823	960	46281.3	1428000
+2	41	41	2519.92835	1531.412015	960	45781.3	1433000
+2	42	42	2519.92835	1510.680355	960	45281.3	1437000
+2	43	43	2519.92835	1490.080691	960	44781.3	1442000
+2	44	44	2519.92835	1469.614967	960	44281.3	1444000
+2	45	45	2519.92835	1449.285126	960	43781.3	1447000
+2	46	46	2519.92835	1429.092918	960	43312.5	1449000
+2	47	47	2519.92835	1409.040384	960	42812.5	1451000
+2	48	48	2519.92835	1389.129274	960	42312.5	1453000
+2	49	49	2519.92835	1369.361629	960	41343.8	1455000
+2	50	50	2519.92835	1349.739199	960	40281.3	1457000
+2	51	51	2519.92835	1330.264024	960	39187.5	1459000
+2	52	52	2519.92835	1310.937952	960	38125	1460000
+2	53	53	2519.92835	1291.762732	960	37062.5	1463000
+2	54	54	2519.92835	1272.740502	960	35968.8	1465000
+2	55	55	2519.92835	1253.873012	960	34906.3	1468000
+2	56	56	2519.92835	1235.162206	960	33843.8	1471000
+2	57	57	2519.92835	1216.609931	960	33156.3	1474000
+2	58	58	2519.92835	1198.218131	960	37656.3	1476000
+2	59	59	2519.92835	1179.988652	960	37187.5	1479000
+2	60	60	2519.92835	1161.923439	960	36750	1482000
+2	61	61	2519.92835	1144.024435	960	36312.5	1484000
+2	62	62	2519.92835	1126.293389	960	35843.8	1486000
+2	63	63	2519.92835	1108.732247	960	35406.3	1489000
+2	64	64	2519.92835	1091.342952	960	34968.8	1492000
+2	65	65	2519.92835	1074.127448	960	34562.5	1495000
+2	66	66	2519.92835	1057.087484	960	34125	1498000
+2	67	67	2519.92835	1040.225102	960	33687.5	1505000
+2	68	68	2519.92835	1023.542051	960	33281.3	1510000
+2	69	69	2519.92835	1007.040372	960	32843.8	1515000
+2	70	70	2519.92835	990.7218155	960	32437.5	1518000
+2	71	71	2519.92835	974.5884219	960	32031.3	1522000
+2	72	72	2519.92835	958.6419411	960	31609.4	1526000
+2	73	73	2519.92835	942.8844141	960	31203.1	1529000
+2	74	74	2519.92835	927.3175905	960	30796.9	1533000
+2	75	75	2519.92835	911.9435115	960	30406.3	1536000
+2	76	76	2519.92835	896.7639267	960	30000	1539000
+2	77	77	2519.92835	881.7808772	960	29609.4	1543000
+2	78	78	2519.92835	866.9962099	960	29218.8	1547000
+2	79	79	2519.92835	852.4116742	960	28843.8	1550000
+2	80	80	2519.92835	838.0294086	960	28453.1	1554000
+2	81	81	2519.92835	823.8511626	960	28078.1	1558000
+2	82	82	2519.92835	809.8788316	960	27703.1	1562000
+2	83	83	2519.92835	796.1143109	960	27328.1	1566000
+2	84	84	2519.92835	782.5595932	960	26953.1	1569000
+2	85	85	2519.92835	769.216428	960	26593.8	1573000
+2	86	86	2519.92835	756.0868079	960	26234.4	1576000
+2	87	87	2519.92835	743.1726282	960	25875	1579000
+2	88	88	2519.92835	730.4757357	960	25515.6	1582000
+2	89	89	2519.92835	717.9980744	960	25156.3	1584000
+2	90	90	2519.92835	705.7414911	960	24812.5	1587000
+2	91	91	2519.92835	693.7079297	960	24468.8	1590000
+2	92	92	2519.92835	681.899237	960	24125	1592000
+2	93	93	2519.92835	670.3173083	960	23781.3	1595000
+2	94	94	2519.92835	658.9640878	960	23453.1	1599000
+2	95	95	2519.92835	647.8414706	960	23125	1603000
+2	96	96	2519.92835	636.9513036	960	22296.9	1606000
+2	97	97	2519.92835	626.2954821	960	21406.3	1610000
+2	98	98	2519.92835	615.8759502	960	20515.6	1614000
+2	99	99	2519.92835	605.6945545	960	20093.8	1617000
+2	100	100	2519.92835	595.7532391	960	19281.3	1619000
+2	101	101	2519.92835	586.0538994	960	21203.1	1622000
+2	102	102	2519.92835	576.5983334	960	20390.6	1625000
+2	103	103	2519.92835	567.3885339	960	19546.9	1628000
+2	104	104	2519.92835	558.426396	960	18796.9	1631000
+2	105	105	2519.92835	549.7137667	960	18062.5	1634000
+2	106	106	2519.92835	541.2525413	960	17453.1	1638000
+2	107	107	2519.92835	533.0446637	960	19406.3	1641000
+2	108	108	2519.92835	525.0920293	960	19109.4	1644000
+2	109	109	2519.92835	517.3964364	960	18828.1	1646000
+2	110	110	2519.92835	509.959926	960	18546.9	1649000
+2	111	111	2519.92835	502.7842477	960	18281.3	1652000
+2	112	112	2519.92835	495.8713942	960	18000	1654000
+2	113	113	2519.92835	489.2232121	960	17734.4	1656000
+2	114	114	2519.92835	482.8416455	960	17468.8	1659000
+2	115	115	2519.92835	476.7285411	960	17203.1	1661000
+2	116	116	2519.92835	470.8858429	960	16937.5	1663000
+2	117	117	2519.92835	465.3153976	960	16687.5	1665000
+2	118	118	2519.92835	460.0191007	960	16437.5	1668000
+2	119	119	2519.92835	454.9988961	960	16187.5	1671000
+2	120	120	2519.92835	450.1417905	960	15937.5	1673000
+2	121	121	2519.92835	445.3333814	960	15640.6	1677000
+2	122	122	2519.92835	440.5733286	960	14921.9	1000000000
+2	123	123	2519.92835	435.8613889	960	14382.8	1000000000
+2	124	124	2519.92835	431.1971252	960	13679.7	1000000000
+2	125	125	2519.92835	426.5803429	960	12937.5	1000000000
+2	126	126	2519.92835	422.0106532	960	12429.7	1000000000
+2	127	127	2519.92835	417.4877647	960	14312.5	1000000000
+2	128	128	2519.92835	413.0113856	960	14093.8	1000000000
+2	129	129	2519.92835	408.5811758	960	13875	1000000000
+2	130	130	2519.92835	404.1968436	960	13664.1	1000000000
+2	131	131	2519.92835	399.8580247	960	13453.1	1000000000
+2	132	132	2519.92835	395.564476	960	13250	1000000000
+2	133	133	2519.92835	391.3158329	960	13046.9	1000000000
+2	134	134	2519.92835	387.1117797	960	12781.3	1000000000
+2	135	135	2519.92835	382.952049	960	12218.8	1000000000
+2	136	136	2519.92835	378.8362763	960	11726.6	1000000000
+2	137	137	2519.92835	374.76417	960	12125	1000000000
+2	138	138	2519.92835	370.7354142	960	11617.2	1000000000
+2	139	139	2519.92835	366.7496931	960	11132.8	1000000000
+2	140	140	2519.92835	362.806715	960	10687.5	1000000000
+2	141	141	2519.92835	358.9061155	960	10421.9	1000000000
+2	142	142	2519.92835	355.0476271	960	11359.4	1000000000
+2	143	143	2519.92835	351.2309099	960	11187.5	1000000000
+2	144	144	2519.92835	347.4556721	960	11023.4	1000000000
+2	145	145	2519.92835	343.7215735	960	10859.4	1000000000
+2	146	146	2519.92835	340.0283226	960	10695.3	1000000000
+2	147	147	2519.92835	336.3755792	960	10539.1	1000000000
+2	148	148	2519.92835	332.7630517	960	10171.9	1000000000
+2	149	149	2519.92835	329.1904241	960	9585.9	1000000000
+2	150	150	2519.92835	325.6573806	960	9117.2	1000000000
+2	151	151	2519.92835	322.1636053	960	8687.5	1000000000
+2	152	152	2519.92835	318.7087823	960	8671.9	1000000000
+2	153	153	2519.92835	315.2925957	960	8023.4	1000000000
+2	154	154	2519.92835	311.9147297	960	7418	1000000000
+2	155	155	2519.92835	308.5748925	960	6820.3	1000000000
+2	156	156	2519.92835	305.272744	960	6226.6	1000000000
+2	157	157	2519.92835	302.0079683	960	5976.6	1763000
+2	158	158	2519.92835	298.7802739	960	5359.4	1000000000
+2	159	159	2519.92835	295.5893205	960	4855.5	1000000000
+2	160	160	2519.92835	292.4348408	960	4293	1000000000
+2	161	161	2519.92835	289.3164461	960	8664.1	1000000000
+2	162	162	2519.92835	286.2338933	960	8554.7	1000000000
+2	163	163	2519.92835	283.1868422	960	8453.1	1000000000
+2	164	164	2519.92835	280.1749527	960	8351.6	1000000000
+2	165	165	2519.92835	277.1979575	960	8250	1000000000
+2	166	166	2519.92835	274.2555163	960	8156.3	1000000000
+2	167	167	2519.92835	271.3473133	960	8070.3	1000000000
+2	168	168	2519.92835	268.4730326	960	7984.4	1000000000
+2	169	169	2519.92835	265.6323825	960	7898.4	1000000000
+2	170	170	2519.92835	262.8250229	960	7820.3	1000000000
+2	171	171	2519.92835	260.0506622	960	7742.2	1000000000
+2	172	172	2519.92835	257.3089602	960	7668	1000000000
+2	173	173	2519.92835	254.5996253	960	7597.7	1000000000
+2	174	174	2519.92835	251.9223173	960	7531.3	1000000000
+2	175	175	2519.92835	249.2767689	960	7468.8	1000000000
+2	176	176	2519.92835	246.6626156	960	7406.3	1000000000
+2	177	177	2519.92835	244.0795658	960	7347.7	1000000000
+2	178	178	2519.92835	241.527328	960	7277.3	1000000000
+2	179	179	2519.92835	239.0055376	960	7203.1	1000000000
+2	180	180	2519.92835	236.5139273	960	7128.9	1000000000
+2	181	181	2519.92835	234.0521569	960	7058.6	1000000000
+2	182	182	2519.92835	231.6199106	960	6992.2	1000000000
+2	183	183	2519.92835	229.2168967	960	6925.8	1000000000
+2	184	184	2519.92835	226.8427751	960	6859.4	1000000000
+2	185	185	2519.92835	224.4972541	960	6793	1000000000
+2	186	186	2519.92835	222.1800179	960	6730.5	1000000000
+2	187	187	2519.92835	219.8907262	960	6671.9	1000000000
+2	188	188	2519.92835	217.6290876	960	6613.3	1000000000
+2	189	189	2519.92835	215.394786	960	6554.7	1000000000
+2	190	190	2519.92835	213.1875055	960	6496.1	1000000000
+2	191	191	2519.92835	211.0069304	960	6441.4	1000000000
+2	192	192	2519.92835	208.8527446	960	6386.7	1000000000
+2	193	193	2519.92835	206.7246324	960	6335.9	1000000000
+2	194	194	2519.92835	204.622302	960	6285.2	1000000000
+2	195	195	2519.92835	202.5454134	960	6234.4	1000000000
+2	196	196	2519.92835	200.4936627	960	6183.6	1000000000
+2	197	197	2519.92835	198.466734	960	6136.7	1000000000
+2	198	198	2519.92835	196.4643116	960	6089.8	1000000000
+2	199	199	2519.92835	194.4860794	960	6043	1000000000
+2	200	200	2519.92835	192.5317337	960	5996.1	1000000000
+2	201	201	2519.92835	190.6009465	960	5945.3	1000000000
+2	202	202	2519.92835	188.6934262	960	5894.5	1000000000
+2	203	203	2519.92835	186.8088326	960	5843.8	1000000000
+2	204	204	2519.92835	184.946862	960	5793	1000000000
+2	205	205	2519.92835	183.1071984	960	5746.1	1000000000
+2	206	206	2519.92835	181.2895381	960	5695.3	1000000000
+2	207	207	2519.92835	179.4935652	960	5648.4	1000000000
+2	208	208	2519.92835	177.7189517	960	5605.5	1000000000
+2	209	209	2519.92835	175.9653938	960	5558.6	1000000000
+2	210	210	2519.92835	174.2325756	960	5519.5	1000000000
+2	211	211	2519.92835	172.5201813	960	5476.6	1000000000
+2	212	212	2519.92835	170.827907	960	5441.4	1000000000
+2	213	213	2519.92835	169.1554248	960	5406.3	1000000000
+2	214	214	2519.92835	167.5024188	960	5375	1000000000
+2	215	215	2519.92835	165.8685973	960	5343.8	1000000000
+2	216	216	2519.92835	164.2536201	960	5316.4	1000000000
+2	217	217	2519.92835	162.6571836	960	5293	1000000000
+2	218	218	2519.92835	161.0789839	960	5269.5	1000000000
+2	219	219	2519.92835	159.5186931	960	5250	1000000000
+2	220	220	2519.92835	157.9759951	960	5230.5	1000000000
+2	221	221	2519.92835	156.4467349	960	5214.8	1000000000
+2	222	222	2519.92835	154.9269272	960	5199.2	1000000000
+2	223	223	2519.92835	153.4165721	960	5007.8	1000000000
+2	224	224	2519.92835	151.9156574	960	4628.9	1000000000
+2	225	225	2519.92835	150.4241587	960	4320.3	1000000000
+2	226	226	2519.92835	148.9420884	960	4289.1	1000000000
+2	227	227	2519.92835	147.469422	960	4195.3	1000000000
+2	228	228	2519.92835	146.0061473	960	4058.6	1000000000
+2	229	229	2519.92835	144.5522767	960	5089.8	1000000000
+2	230	230	2519.92835	143.1077735	960	5078.1	1000000000
+2	231	231	2519.92835	141.6726379	960	5066.4	1000000000
+2	232	232	2519.92835	140.2468576	960	5058.6	1000000000
+2	233	233	2519.92835	138.8304205	960	5050.8	1000000000
+2	234	234	2519.92835	137.4233266	960	5050.8	1000000000
+2	235	235	2519.92835	136.0255638	960	5050.8	1000000000
+2	236	236	2519.92835	134.6371198	960	4882.8	1000000000
+2	237	237	2519.92835	133.2579827	960	4578.1	1000000000
+2	238	238	2519.92835	131.8881401	960	4394.5	1000000000
+2	239	239	2519.92835	130.52758	960	4257.8	1000000000
+2	240	240	2519.92835	129.1763023	960	4683.6	1000000000
+2	241	241	2519.92835	127.834295	960	4363.3	1000000000
+2	242	242	2519.92835	126.5015336	960	4043	1000000000
+2	243	243	2519.92835	125.1780305	960	3765.6	1000000000
+2	244	244	2519.92835	123.8637611	960	3552.7	1000000000
+2	245	245	2519.92835	122.5587256	960	3285.2	1000000000
+2	246	246	2519.92835	121.2628997	960	3156.3	1000000000
+2	247	247	2519.92835	119.9762834	960	4976.6	1000000000
+2	248	248	2519.92835	118.6988644	960	4964.8	1000000000
+2	249	249	2519.92835	117.4306307	960	4953.1	1000000000
+5	0	0	2519.92835	1412.398092	960	70625	662000
+5	1	1	2519.92835	1398.390624	960	69812.5	663000
+5	2	2	2519.92835	1384.414259	960	68937.5	664500
+5	3	3	2519.92835	1370.469998	960	68125	665500
+5	4	4	2519.92835	1356.55895	960	67312.5	667000
+5	5	5	2519.92835	1342.682228	960	66500	669500
+5	6	6	2519.92835	1328.84083	960	65750	676000
+5	7	7	2519.92835	1315.035868	960	65000	1260000
+5	8	8	2519.92835	1301.268452	960	64250	1264000
+5	9	9	2519.92835	1287.539694	960	63531.25	1269000
+5	10	10	2519.92835	1273.850703	960	62843.75	1273000
+5	11	11	2519.92835	1260.202369	960	62156.25	1278000
+5	12	12	2519.92835	1246.596025	960	61531.25	1283000
+5	13	13	2519.92835	1233.03256	960	60906.25	1287000
+5	14	14	2519.92835	1219.513083	960	60281.25	1292000
+5	15	15	2519.92835	1206.038818	960	59718.75	1297000
+5	16	16	2519.92835	1192.610764	960	59062.5	1303000
+5	17	17	2519.92835	1179.229921	960	58000	1308000
+5	18	18	2519.92835	1165.89751	960	57000	1313000
+5	19	19	2519.92835	1152.614531	960	55968.75	1318000
+5	20	20	2519.92835	1139.382096	960	54906.25	1323000
+5	21	21	2519.92835	1126.201315	960	53875	1328000
+5	22	22	2519.92835	1113.073187	960	53375	1333000
+5	23	23	2519.92835	1099.998824	960	55250	1338000
+5	24	24	2519.92835	1086.979448	960	54718.75	1344000
+5	25	25	2519.92835	1074.015836	960	54156.25	1349000
+5	26	26	2519.92835	1061.109432	960	53625	1354000
+5	27	27	2519.92835	1048.261014	960	53093.75	1359000
+5	28	28	2519.92835	1035.471804	960	52531.25	1364000
+5	29	29	2519.92835	1022.743024	960	52000	1369000
+5	30	30	2519.92835	1010.07545	960	51468.75	1374000
+5	31	31	2519.92835	997.4704175	960	50937.5	1379000
+5	32	32	2519.92835	984.9288135	960	50406.25	1384000
+5	33	33	2519.92835	972.4519714	960	49906.25	1389000
+5	34	34	2519.92835	960.0406689	960	49375	1395000
+5	35	35	2519.92835	947.696239	960	48843.75	1400000
+5	36	36	2519.92835	935.4196814	960	48343.75	1406000
+5	37	37	2519.92835	923.2119958	960	47812.5	1411000
+5	38	38	2519.92835	911.0744043	960	47312.5	1417000
+5	39	39	2519.92835	899.0079065	960	46781.25	1422000
+5	40	40	2519.92835	887.0136133	960	46281.25	1428000
+5	41	41	2519.92835	875.09258	960	45781.25	1433000
+5	42	42	2519.92835	863.2459174	960	45281.25	1437000
+5	43	43	2519.92835	851.4746808	960	44781.25	1442000
+5	44	44	2519.92835	839.7799811	960	44281.25	1444000
+5	45	45	2519.92835	828.1629291	960	43781.25	1447000
+5	46	46	2519.92835	816.6245245	960	43312.5	1449000
+5	47	47	2519.92835	805.1659338	960	42812.5	1451000
+5	48	48	2519.92835	793.7881567	960	42312.5	1453000
+5	49	49	2519.92835	782.4923596	960	41343.75	1455000
+5	50	50	2519.92835	771.2795422	960	40281.25	1457000
+5	51	51	2519.92835	760.150871	960	39187.5	1459000
+5	52	52	2519.92835	749.1074011	960	38125	1460000
+5	53	53	2519.92835	738.1501324	960	37062.5	1463000
+5	54	54	2519.92835	727.2802869	960	35968.75	1465000
+5	55	55	2519.92835	716.4988641	960	34906.25	1468000
+5	56	56	2519.92835	705.8069751	960	33843.75	1471000
+5	57	57	2519.92835	695.205675	960	33156.25	1474000
+5	58	58	2519.92835	684.6960748	960	37656.25	1477000
+5	59	59	2519.92835	674.2792297	960	37187.5	1479000
+5	60	60	2519.92835	663.9562506	960	36750	1482000
+5	61	61	2519.92835	653.7282483	960	36312.5	1484000
+5	62	62	2519.92835	643.5962225	960	35843.75	1486000
+5	63	63	2519.92835	633.5612842	960	35406.25	1489000
+5	64	64	2519.92835	623.6245441	960	34968.75	1492000
+5	65	65	2519.92835	613.787113	960	34562.5	1495000
+5	66	66	2519.92835	604.0499908	960	34125	1498000
+5	67	67	2519.92835	594.4143439	960	33687.5	1505000
+5	68	68	2519.92835	584.8811719	960	33281.25	1510000
+5	69	69	2519.92835	575.4516412	960	32843.75	1515000
+5	70	70	2519.92835	566.1267517	960	32437.5	1518000
+5	71	71	2519.92835	556.9076697	960	32031.25	1522000
+5	72	72	2519.92835	547.7953949	960	31609.375	1526000
+5	73	73	2519.92835	538.7910938	960	31203.125	1529000
+5	74	74	2519.92835	529.895766	960	30796.875	1533000
+5	75	75	2519.92835	521.110578	960	30406.25	1536000
+5	76	76	2519.92835	512.4365295	960	30000	1539000
+5	77	77	2519.92835	503.874787	960	29609.375	1543000
+5	78	78	2519.92835	495.4264056	960	29218.75	1547000
+5	79	79	2519.92835	487.0923853	960	28843.75	1550000
+5	80	80	2519.92835	478.8739478	960	28453.125	1554000
+5	81	81	2519.92835	470.7720929	960	28078.125	1558000
+5	82	82	2519.92835	462.7879037	960	27703.125	1562000
+5	83	83	2519.92835	454.9224634	960	27328.125	1566000
+5	84	84	2519.92835	447.1769104	960	26953.125	1569000
+5	85	85	2519.92835	439.5522446	960	26593.75	1573000
+5	86	86	2519.92835	432.0496045	960	26234.375	1576000
+5	87	87	2519.92835	424.6700732	960	25875	1579000
+5	88	88	2519.92835	417.4147061	960	25515.625	1582000
+5	89	89	2519.92835	410.284614	960	25156.25	1584000
+5	90	90	2519.92835	403.2808521	960	24812.5	1587000
+5	91	91	2519.92835	396.4045313	960	24468.75	1590000
+5	92	92	2519.92835	389.6567068	960	24125	1592000
+5	93	93	2519.92835	383.0384619	960	23781.25	1595000
+5	94	94	2519.92835	376.5509073	960	23453.125	1599000
+5	95	95	2519.92835	370.195126	960	23109.375	1603000
+5	96	96	2519.92835	363.9721735	960	22296.875	1606000
+5	97	97	2519.92835	357.8831326	960	21406.25	1610000
+5	98	98	2519.92835	351.9291144	960	20515.625	1614000
+5	99	99	2519.92835	346.111174	960	20093.75	1617000
+5	100	100	2519.92835	340.4304224	960	19281.25	1619000
+5	101	101	2519.92835	334.8879425	960	21203.125	1622000
+5	102	102	2519.92835	329.484762	960	20406.25	1625000
+5	103	103	2519.92835	324.2220193	960	19546.875	1628000
+5	104	104	2519.92835	319.1007977	960	18796.875	1630000
+5	105	105	2519.92835	314.1221524	960	18062.5	1634000
+5	106	106	2519.92835	309.2871664	960	17453.125	1638000
+5	107	107	2519.92835	304.5969507	960	19406.25	1641000
+5	108	108	2519.92835	300.0525882	960	19109.375	1644000
+5	109	109	2519.92835	295.6551065	960	18828.125	1646000
+5	110	110	2519.92835	291.405672	960	18546.875	1649000
+5	111	111	2519.92835	287.3052844	960	18265.625	1652000
+5	112	112	2519.92835	283.3550824	960	18000	1654000
+5	113	113	2519.92835	279.5561212	960	17734.375	1656000
+5	114	114	2519.92835	275.9095117	960	17468.75	1659000
+5	115	115	2519.92835	272.4163092	960	17203.125	1661000
+5	116	116	2519.92835	269.0776245	960	16937.5	1663000
+5	117	117	2519.92835	265.8945129	960	16687.5	1665000
+5	118	118	2519.92835	262.8680576	960	16421.875	1668000
+5	119	119	2519.92835	259.9993692	960	16171.875	1671000
+5	120	120	2519.92835	257.2238803	960	15929.688	1673000
+5	121	121	2519.92835	254.476218	960	15640.625	1677000
+5	122	122	2519.92835	251.7561877	960	14929.688	1000000000
+5	123	123	2519.92835	249.0636508	960	14382.813	1000000000
+5	124	124	2519.92835	246.3983572	960	13679.688	1000000000
+5	125	125	2519.92835	243.7601959	960	12937.5	1000000000
+5	126	126	2519.92835	241.1489447	960	12203.125	1000000000
+5	127	127	2519.92835	238.564437	960	12148.438	1000000000
+5	128	128	2519.92835	236.006506	960	14085.938	1000000000
+5	129	129	2519.92835	233.4749576	960	13867.188	1000000000
+5	130	130	2519.92835	230.9696249	960	13656.25	1000000000
+5	131	131	2519.92835	228.4902998	960	13445.313	1000000000
+5	132	132	2519.92835	226.0368434	960	13242.188	1000000000
+5	133	133	2519.92835	223.6090474	960	13039.063	1000000000
+5	134	134	2519.92835	221.2067313	960	12726.563	1000000000
+5	135	135	2519.92835	218.8297423	960	12085.938	1000000000
+5	136	136	2519.92835	216.4778722	960	11585.938	1000000000
+5	137	137	2519.92835	214.1509543	960	11273.438	1000000000
+5	138	138	2519.92835	211.8488081	960	11507.813	1000000000
+5	139	139	2519.92835	209.5712532	960	11007.813	1000000000
+5	140	140	2519.92835	207.3181229	960	10531.25	1000000000
+5	141	141	2519.92835	205.0892088	960	10148.438	1000000000
+5	142	142	2519.92835	202.8843584	960	10023.438	1000000000
+5	143	143	2519.92835	200.7033771	960	11179.688	1000000000
+5	144	144	2519.92835	198.5460983	960	11015.625	1000000000
+5	145	145	2519.92835	196.4123277	960	10851.563	1000000000
+5	146	146	2519.92835	194.3018987	960	10687.5	1000000000
+5	147	147	2519.92835	192.2146167	960	10531.25	1000000000
+5	148	148	2519.92835	190.1503152	960	10171.875	1000000000
+5	149	149	2519.92835	188.1088138	960	9585.938	1000000000
+5	150	150	2519.92835	186.0899318	960	9117.188	1000000000
+5	151	151	2519.92835	184.0934888	960	8687.5	1000000000
+5	152	152	2519.92835	182.1193042	960	8671.875	1000000000
+5	153	153	2519.92835	180.1671976	960	8046.875	1000000000
+5	154	154	2519.92835	178.2369884	960	7441.406	1000000000
+5	155	155	2519.92835	176.32851	960	6843.75	1000000000
+5	156	156	2519.92835	174.441568	960	6250	1000000000
+5	157	157	2519.92835	172.5759819	960	5976.563	1681000
+5	158	158	2519.92835	170.7315851	960	5347.656	1000000000
+5	159	159	2519.92835	168.9081831	960	4738.281	1000000000
+5	160	160	2519.92835	167.1056233	960	4257.813	1000000000
+5	161	161	2519.92835	165.3236835	960	3685.547	1000000000
+5	162	162	2519.92835	163.5622247	960	8546.875	1000000000
+5	163	163	2519.92835	161.8210527	960	8437.5	1000000000
+5	164	164	2519.92835	160.099973	960	8335.938	1000000000
+5	165	165	2519.92835	158.3988329	960	8242.188	1000000000
+5	166	166	2519.92835	156.7174379	960	8148.438	1000000000
+5	167	167	2519.92835	155.0556076	960	8054.688	1000000000
+5	168	168	2519.92835	153.4131615	960	7972.656	1000000000
+5	169	169	2519.92835	151.7899329	960	7886.719	1000000000
+5	170	170	2519.92835	150.1857274	960	7804.688	1000000000
+5	171	171	2519.92835	148.6003784	960	7726.563	1000000000
+5	172	172	2519.92835	147.0336916	960	7578.125	1000000000
+5	173	173	2519.92835	145.4855002	960	7582.031	1000000000
+5	174	174	2519.92835	143.9556099	960	7511.719	1000000000
+5	175	175	2519.92835	142.443868	960	7445.313	1000000000
+5	176	176	2519.92835	140.9500661	960	7382.813	1000000000
+5	177	177	2519.92835	139.4740376	960	7324.219	1000000000
+5	178	178	2519.92835	138.015616	960	7265.625	1000000000
+5	179	179	2519.92835	136.5745929	960	7203.125	1000000000
+5	180	180	2519.92835	135.1508156	960	7128.906	1000000000
+5	181	181	2519.92835	133.7440897	960	7058.594	1000000000
+5	182	182	2519.92835	132.3542346	960	6992.188	1000000000
+5	183	183	2519.92835	130.9810838	960	6925.781	1000000000
+5	184	184	2519.92835	129.6244429	960	6859.375	1000000000
+5	185	185	2519.92835	128.2841452	960	6792.969	1000000000
+5	186	186	2519.92835	126.9600102	960	6730.469	1000000000
+5	187	187	2519.92835	125.6518436	960	6671.875	1000000000
+5	188	188	2519.92835	124.3594786	960	6613.281	1000000000
+5	189	189	2519.92835	123.0827348	960	6554.688	1000000000
+5	190	190	2519.92835	121.8214317	960	6496.094	1000000000
+5	191	191	2519.92835	120.5753888	960	6441.406	1000000000
+5	192	192	2519.92835	119.3444255	960	6386.719	1000000000
+5	193	193	2519.92835	118.1283614	960	6335.938	1000000000
+5	194	194	2519.92835	116.9270297	960	6285.156	1000000000
+5	195	195	2519.92835	115.7402362	960	6234.375	1000000000
+5	196	196	2519.92835	114.5678072	960	6183.594	1000000000
+5	197	197	2519.92835	113.4095623	960	6136.719	1000000000
+5	198	198	2519.92835	112.2653209	960	6089.844	1000000000
+5	199	199	2519.92835	111.1349025	960	6042.969	1000000000
+5	200	200	2519.92835	110.0181335	960	5996.094	1000000000
+5	201	201	2519.92835	108.9148266	960	5945.313	1000000000
+5	202	202	2519.92835	107.824815	960	5894.531	1000000000
+5	203	203	2519.92835	106.7479044	960	5843.75	1000000000
+5	204	204	2519.92835	105.6839211	960	5792.969	1000000000
+5	205	205	2519.92835	104.6326848	960	5746.094	1000000000
+5	206	206	2519.92835	103.5940218	960	5695.313	1000000000
+5	207	207	2519.92835	102.5677515	960	5648.438	1000000000
+5	208	208	2519.92835	101.5536867	960	5605.469	1000000000
+5	209	209	2519.92835	100.5516536	960	5558.594	1000000000
+5	210	210	2519.92835	99.56147179	960	5519.531	1000000000
+5	211	211	2519.92835	98.58296074	960	5476.563	1000000000
+5	212	212	2519.92835	97.61594688	960	5441.406	1000000000
+5	213	213	2519.92835	96.66024277	960	5406.25	1000000000
+5	214	214	2519.92835	95.71566788	960	5371.094	1000000000
+5	215	215	2519.92835	94.78205559	960	5343.75	1000000000
+5	216	216	2519.92835	93.8592115	960	5316.406	1000000000
+5	217	217	2519.92835	92.94696205	960	5292.969	1000000000
+5	218	218	2519.92835	92.04513367	960	5269.531	1000000000
+5	219	219	2519.92835	91.15353889	960	5250	1000000000
+5	220	220	2519.92835	90.27199722	960	5230.469	1000000000
+5	221	221	2519.92835	89.39813423	960	5214.844	1000000000
+5	222	222	2519.92835	88.5296727	960	5199.219	1000000000
+5	223	223	2519.92835	87.66661263	960	5003.906	1000000000
+5	224	224	2519.92835	86.80894707	960	4644.531	1000000000
+5	225	225	2519.92835	85.95666214	960	4441.406	1000000000
+5	226	226	2519.92835	85.10976479	960	4445.313	1000000000
+5	227	227	2519.92835	84.26824112	960	4195.313	1000000000
+5	228	228	2519.92835	83.4320842	960	5113.281	1000000000
+5	229	229	2519.92835	82.60130096	960	5097.656	1000000000
+5	230	230	2519.92835	81.77587059	960	5082.031	1000000000
+5	231	231	2519.92835	80.95579308	960	5074.219	1000000000
+5	232	232	2519.92835	80.14106148	960	5062.5	1000000000
+5	233	233	2519.92835	79.33166885	960	5058.594	1000000000
+5	234	234	2519.92835	78.5276152	960	5054.688	1000000000
+5	235	235	2519.92835	77.72889359	960	5054.688	1000000000
+5	236	236	2519.92835	76.93549706	960	4882.813	1000000000
+5	237	237	2519.92835	76.14741867	960	4578.125	1000000000
+5	238	238	2519.92835	75.36465149	960	4394.531	1000000000
+5	239	239	2519.92835	74.58718857	960	4855.469	1000000000
+5	240	240	2519.92835	73.81502991	960	4683.594	1000000000
+5	241	241	2519.92835	73.04816856	960	4363.281	1000000000
+5	242	242	2519.92835	72.28659065	960	4042.969	1000000000
+5	243	243	2519.92835	71.53030312	960	3785.156	1000000000
+5	244	244	2519.92835	70.77929207	960	3552.734	1000000000
+5	245	245	2519.92835	70.03355751	960	3302.734	1000000000
+5	246	246	2519.92835	69.29308556	960	3164.063	1000000000
+5	247	247	2519.92835	68.55787621	960	4976.563	1000000000
+5	248	248	2519.92835	67.82792252	960	4964.844	1000000000
+5	249	249	2519.92835	67.10321754	960	4953.125	1000000000
+9	0	0	2519.92835	0	960	70625	662000
+9	1	1	2519.92835	0	960	69750	663000
+9	2	2	2519.92835	0	960	68937.5	664500
+9	3	3	2519.92835	0	960	68125	666000
+9	4	4	2519.92835	0	960	67312.5	667000
+9	5	5	2519.92835	0	960	66500	670500
+9	6	6	2519.92835	0	960	65750	1256000
+9	7	7	2519.92835	0	960	65000	1260000
+9	8	8	2519.92835	0	960	64250	1265000
+9	9	9	2519.92835	0	960	63531.25	1269000
+9	10	10	2519.92835	0	960	62843.75	1274000
+9	11	11	2519.92835	0	960	62156.25	1278000
+9	12	12	2519.92835	0	960	61531.25	1283000
+9	13	13	2519.92835	0	960	60906.25	1288000
+9	14	14	2519.92835	0	960	60281.25	1293000
+9	15	15	2519.92835	0	960	59718.75	1298000
+9	16	16	2519.92835	0	960	59062.5	1303000
+9	17	17	2519.92835	0	960	58031.25	1308000
+9	18	18	2519.92835	0	960	57000	1313000
+9	19	19	2519.92835	0	960	55937.5	1318000
+9	20	20	2519.92835	0	960	54937.5	1324000
+9	21	21	2519.92835	0	960	53875	1329000
+9	22	22	2519.92835	0	960	52843.75	1334000
+9	23	23	2519.92835	0	960	51812.5	1339000
+9	24	24	2519.92835	0	960	51312.5	1344000
+9	25	25	2519.92835	0	960	54156.25	1349000
+9	26	26	2519.92835	0	960	53625	1354000
+9	27	27	2519.92835	0	960	53093.75	1359000
+9	28	28	2519.92835	0	960	52531.25	1364000
+9	29	29	2519.92835	0	960	52000	1369000
+9	30	30	2519.92835	0	960	51468.75	1374000
+9	31	31	2519.92835	0	960	50937.5	1379000
+9	32	32	2519.92835	0	960	50406.25	1384000
+9	33	33	2519.92835	0	960	49906.25	1390000
+9	34	34	2519.92835	0	960	49375	1395000
+9	35	35	2519.92835	0	960	48843.75	1401000
+9	36	36	2519.92835	0	960	48343.75	1406000
+9	37	37	2519.92835	0	960	47812.5	1412000
+9	38	38	2519.92835	0	960	47312.5	1417000
+9	39	39	2519.92835	0	960	46781.25	1423000
+9	40	40	2519.92835	0	960	46281.25	1429000
+9	41	41	2519.92835	0	960	45781.25	1433000
+9	42	42	2519.92835	0	960	45281.25	1438000
+9	43	43	2519.92835	0	960	44781.25	1442000
+9	44	44	2519.92835	0	960	44281.25	1444000
+9	45	45	2519.92835	0	960	43781.25	1447000
+9	46	46	2519.92835	0	960	43312.5	1449000
+9	47	47	2519.92835	0	960	42812.5	1451000
+9	48	48	2519.92835	0	960	42312.5	1453000
+9	49	49	2519.92835	0	960	41343.75	1455000
+9	50	50	2519.92835	0	960	40281.25	1457000
+9	51	51	2519.92835	0	960	39187.5	1459000
+9	52	52	2519.92835	0	960	38125	1460000
+9	53	53	2519.92835	0	960	37062.5	1463000
+9	54	54	2519.92835	0	960	35968.75	1465000
+9	55	55	2519.92835	0	960	34906.25	1468000
+9	56	56	2519.92835	0	960	33843.75	1471000
+9	57	57	2519.92835	0	960	33156.25	1474000
+9	58	58	2519.92835	0	960	37656.25	1476000
+9	59	59	2519.92835	0	960	37187.5	1479000
+9	60	60	2519.92835	0	960	36750	1482000
+9	61	61	2519.92835	0	960	36312.5	1484000
+9	62	62	2519.92835	0	960	35843.75	1486000
+9	63	63	2519.92835	0	960	35406.25	1489000
+9	64	64	2519.92835	0	960	34968.75	1492000
+9	65	65	2519.92835	0	960	34562.5	1495000
+9	66	66	2519.92835	0	960	34125	1498000
+9	67	67	2519.92835	0	960	33687.5	1505000
+9	68	68	2519.92835	0	960	33281.25	1510000
+9	69	69	2519.92835	0	960	32843.75	1515000
+9	70	70	2519.92835	0	960	32437.5	1518000
+9	71	71	2519.92835	0	960	32031.25	1522000
+9	72	72	2519.92835	0	960	31609.375	1526000
+9	73	73	2519.92835	0	960	31203.125	1529000
+9	74	74	2519.92835	0	960	30796.875	1533000
+9	75	75	2519.92835	0	960	30406.25	1536000
+9	76	76	2519.92835	0	960	30000	1539000
+9	77	77	2519.92835	0	960	29609.375	1543000
+9	78	78	2519.92835	0	960	29218.75	1547000
+9	79	79	2519.92835	0	960	28843.75	1550000
+9	80	80	2519.92835	0	960	28453.125	1554000
+9	81	81	2519.92835	0	960	28078.125	1558000
+9	82	82	2519.92835	0	960	27703.125	1562000
+9	83	83	2519.92835	0	960	27328.125	1566000
+9	84	84	2519.92835	0	960	26953.125	1569000
+9	85	85	2519.92835	0	960	26593.75	1573000
+9	86	86	2519.92835	0	960	26234.375	1576000
+9	87	87	2519.92835	0	960	25875	1579000
+9	88	88	2519.92835	0	960	25515.625	1582000
+9	89	89	2519.92835	0	960	25156.25	1584000
+9	90	90	2519.92835	0	960	24812.5	1587000
+9	91	91	2519.92835	0	960	24468.75	1590000
+9	92	92	2519.92835	0	960	24125	1592000
+9	93	93	2519.92835	0	960	23781.25	1595000
+9	94	94	2519.92835	0	960	23453.125	1599000
+9	95	95	2519.92835	0	960	23109.375	1603000
+9	96	96	2519.92835	0	960	22296.875	1606000
+9	97	97	2519.92835	0	960	21406.25	1610000
+9	98	98	2519.92835	0	960	20515.625	1614000
+9	99	99	2519.92835	0	960	20093.75	1617000
+9	100	100	2519.92835	0	960	19281.25	1619000
+9	101	101	2519.92835	0	960	21203.125	1622000
+9	102	102	2519.92835	0	960	20406.25	1625000
+9	103	103	2519.92835	0	960	19546.875	1628000
+9	104	104	2519.92835	0	960	18796.875	1631000
+9	105	105	2519.92835	0	960	18062.5	1634000
+9	106	106	2519.92835	0	960	17453.125	1638000
+9	107	107	2519.92835	0	960	19406.25	1641000
+9	108	108	2519.92835	0	960	19109.375	1644000
+9	109	109	2519.92835	0	960	18828.125	1646000
+9	110	110	2519.92835	0	960	18546.875	1649000
+9	111	111	2519.92835	0	960	18265.625	1652000
+9	112	112	2519.92835	0	960	18000	1654000
+9	113	113	2519.92835	0	960	17718.75	1656000
+9	114	114	2519.92835	0	960	17453.125	1659000
+9	115	115	2519.92835	0	960	17187.5	1661000
+9	116	116	2519.92835	0	960	16937.5	1663000
+9	117	117	2519.92835	0	960	16671.875	1665000
+9	118	118	2519.92835	0	960	16421.875	1668000
+9	119	119	2519.92835	0	960	16171.875	1671000
+9	120	120	2519.92835	0	960	15921.875	1673000
+9	121	121	2519.92835	0	960	15640.625	1677000
+9	122	122	2519.92835	0	960	14976.563	1000000000
+9	123	123	2519.92835	0	960	14382.813	1000000000
+9	124	124	2519.92835	0	960	13679.688	1000000000
+9	125	125	2519.92835	0	960	12937.5	1000000000
+9	126	126	2519.92835	0	960	12203.125	1000000000
+9	127	127	2519.92835	0	960	11507.813	1000000000
+9	128	128	2519.92835	0	960	14078.125	1000000000
+9	129	129	2519.92835	0	960	13859.375	1000000000
+9	130	130	2519.92835	0	960	13648.438	1000000000
+9	131	131	2519.92835	0	960	13437.5	1000000000
+9	132	132	2519.92835	0	960	13234.375	1000000000
+9	133	133	2519.92835	0	960	13031.25	1000000000
+9	134	134	2519.92835	0	960	12710.938	1000000000
+9	135	135	2519.92835	0	960	12078.125	1000000000
+9	136	136	2519.92835	0	960	11585.938	1000000000
+9	137	137	2519.92835	0	960	11031.25	1000000000
+9	138	138	2519.92835	0	960	11359.375	1000000000
+9	139	139	2519.92835	0	960	10859.375	1000000000
+9	140	140	2519.92835	0	960	10367.188	1000000000
+9	141	141	2519.92835	0	960	9906.25	1000000000
+9	142	142	2519.92835	0	960	9585.938	1000000000
+9	143	143	2519.92835	0	960	11171.875	1000000000
+9	144	144	2519.92835	0	960	11000	1000000000
+9	145	145	2519.92835	0	960	10835.938	1000000000
+9	146	146	2519.92835	0	960	10671.875	1000000000
+9	147	147	2519.92835	0	960	10515.625	1000000000
+9	148	148	2519.92835	0	960	10171.875	1000000000
+9	149	149	2519.92835	0	960	9585.938	1000000000
+9	150	150	2519.92835	0	960	9117.188	1000000000
+9	151	151	2519.92835	0	960	8687.5	1000000000
+9	152	152	2519.92835	0	960	8679.688	1000000000
+9	153	153	2519.92835	0	960	8070.313	1000000000
+9	154	154	2519.92835	0	960	7472.656	1000000000
+9	155	155	2519.92835	0	960	6875	1000000000
+9	156	156	2519.92835	0	960	6277.344	1000000000
+9	157	157	2519.92835	0	960	5976.563	1690000
+9	158	158	2519.92835	0	960	5347.656	1000000000
+9	159	159	2519.92835	0	960	4726.563	1000000000
+9	160	160	2519.92835	0	960	4226.563	1000000000
+9	161	161	2519.92835	0	960	3658.203	1000000000
+9	162	162	2519.92835	0	960	8531.25	1000000000
+9	163	163	2519.92835	0	960	8429.688	1000000000
+9	164	164	2519.92835	0	960	8328.125	1000000000
+9	165	165	2519.92835	0	960	8226.563	1000000000
+9	166	166	2519.92835	0	960	8132.813	1000000000
+9	167	167	2519.92835	0	960	8046.875	1000000000
+9	168	168	2519.92835	0	960	7957.031	1000000000
+9	169	169	2519.92835	0	960	7871.094	1000000000
+9	170	170	2519.92835	0	960	7789.063	1000000000
+9	171	171	2519.92835	0	960	7710.938	1000000000
+9	172	172	2519.92835	0	960	7386.719	1000000000
+9	173	173	2519.92835	0	960	7121.094	1000000000
+9	174	174	2519.92835	0	960	7488.281	1000000000
+9	175	175	2519.92835	0	960	7421.875	1000000000
+9	176	176	2519.92835	0	960	7355.469	1000000000
+9	177	177	2519.92835	0	960	7296.875	1000000000
+9	178	178	2519.92835	0	960	7234.375	1000000000
+9	179	179	2519.92835	0	960	7175.781	1000000000
+9	180	180	2519.92835	0	960	7121.094	1000000000
+9	181	181	2519.92835	0	960	7058.594	1000000000
+9	182	182	2519.92835	0	960	6992.188	1000000000
+9	183	183	2519.92835	0	960	6925.781	1000000000
+9	184	184	2519.92835	0	960	6859.375	1000000000
+9	185	185	2519.92835	0	960	6792.969	1000000000
+9	186	186	2519.92835	0	960	6730.469	1000000000
+9	187	187	2519.92835	0	960	6671.875	1000000000
+9	188	188	2519.92835	0	960	6613.281	1000000000
+9	189	189	2519.92835	0	960	6554.688	1000000000
+9	190	190	2519.92835	0	960	6496.094	1000000000
+9	191	191	2519.92835	0	960	6441.406	1000000000
+9	192	192	2519.92835	0	960	6386.719	1000000000
+9	193	193	2519.92835	0	960	6335.938	1000000000
+9	194	194	2519.92835	0	960	6285.156	1000000000
+9	195	195	2519.92835	0	960	6234.375	1000000000
+9	196	196	2519.92835	0	960	6183.594	1000000000
+9	197	197	2519.92835	0	960	6136.719	1000000000
+9	198	198	2519.92835	0	960	6089.844	1000000000
+9	199	199	2519.92835	0	960	6042.969	1000000000
+9	200	200	2519.92835	0	960	5996.094	1000000000
+9	201	201	2519.92835	0	960	5945.313	1000000000
+9	202	202	2519.92835	0	960	5894.531	1000000000
+9	203	203	2519.92835	0	960	5843.75	1000000000
+9	204	204	2519.92835	0	960	5792.969	1000000000
+9	205	205	2519.92835	0	960	5746.094	1000000000
+9	206	206	2519.92835	0	960	5695.313	1000000000
+9	207	207	2519.92835	0	960	5648.438	1000000000
+9	208	208	2519.92835	0	960	5605.469	1000000000
+9	209	209	2519.92835	0	960	5558.594	1000000000
+9	210	210	2519.92835	0	960	5519.531	1000000000
+9	211	211	2519.92835	0	960	5476.563	1000000000
+9	212	212	2519.92835	0	960	5441.406	1000000000
+9	213	213	2519.92835	0	960	5406.25	1000000000
+9	214	214	2519.92835	0	960	5371.094	1000000000
+9	215	215	2519.92835	0	960	5343.75	1000000000
+9	216	216	2519.92835	0	960	5316.406	1000000000
+9	217	217	2519.92835	0	960	5292.969	1000000000
+9	218	218	2519.92835	0	960	5269.531	1000000000
+9	219	219	2519.92835	0	960	5250	1000000000
+9	220	220	2519.92835	0	960	5230.469	1000000000
+9	221	221	2519.92835	0	960	5214.844	1000000000
+9	222	222	2519.92835	0	960	5199.219	1000000000
+9	223	223	2519.92835	0	960	5007.813	1000000000
+9	224	224	2519.92835	0	960	4695.313	1000000000
+9	225	225	2519.92835	0	960	4566.406	1000000000
+9	226	226	2519.92835	0	960	4484.375	1000000000
+9	227	227	2519.92835	0	960	4246.094	1000000000
+9	228	228	2519.92835	0	960	5121.094	1000000000
+9	229	229	2519.92835	0	960	5105.469	1000000000
+9	230	230	2519.92835	0	960	5093.75	1000000000
+9	231	231	2519.92835	0	960	5082.031	1000000000
+9	232	232	2519.92835	0	960	5074.219	1000000000
+9	233	233	2519.92835	0	960	5066.406	1000000000
+9	234	234	2519.92835	0	960	5062.5	1000000000
+9	235	235	2519.92835	0	960	5058.594	1000000000
+9	236	236	2519.92835	0	960	4882.813	1000000000
+9	237	237	2519.92835	0	960	4664.063	1000000000
+9	238	238	2519.92835	0	960	4539.063	1000000000
+9	239	239	2519.92835	0	960	4855.469	1000000000
+9	240	240	2519.92835	0	960	4683.594	1000000000
+9	241	241	2519.92835	0	960	4363.281	1000000000
+9	242	242	2519.92835	0	960	4042.969	1000000000
+9	243	243	2519.92835	0	960	3812.5	1000000000
+9	244	244	2519.92835	0	960	3582.031	1000000000
+9	245	245	2519.92835	0	960	3332.031	1000000000
+9	246	246	2519.92835	0	960	4984.375	1000000000
+9	247	247	2519.92835	0	960	4976.563	1000000000
+9	248	248	2519.92835	0	960	4964.844	1000000000
+9	249	249	2519.92835	0	960	4953.125	1000000000
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_kendo.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_kendo.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_kendo.cfg	(revision 341)
@@ -0,0 +1,6 @@
+#Kendo
+# two z-value files, took the one from depth directory
+#ViewNum    StartFrame   EndFrame  FocalLength         Position   CShift    ZNear         ZFar
+1           0            299       2241.25607          5.0        701.5     448.251214    11206.280350
+3           0            299       2241.25607          15.0       701.5     448.251214    11206.280350
+5           0            299       2241.25607          25.0       701.5     448.251214    11206.280350
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_lovebird1.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_lovebird1.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_lovebird1.cfg	(revision 341)
@@ -0,0 +1,7 @@
+# Lovebird1
+# Znear and far values retrieved from VS-CFG files on ETRI-Server
+# assymetric ?? see mail from fons??
+#ViewNum    StartFrame   EndFrame  FocalLength          Position      CShift              ZNear         ZFar
+4           0            239       2017.8074684219137   77.31768727   555.4121600029979   -2228.745812  -156012.206815
+6           0            239       2017.8074684219137    0.0          555.4121600029979   -2228.745812  -156012.206815
+8           0            239       2017.8074684219137  -70.80434924   555.4121600029979   -2437.690731  -156012.206794
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_newspaper.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_newspaper.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_newspaper.cfg	(revision 341)
@@ -0,0 +1,6 @@
+#Newspaper
+# two z-value files, took the one from depth directory
+#ViewNum    StartFrame   EndFrame  FocalLength         Position                CShift                  ZNear         ZFar
+2           0            299       2929.4940521927465  108.93286665364974      307.63334410569644      -2715.181648  -9050.605493
+4           0            299       2929.4940521927465  16.24854644348285       307.63334410569644      -2715.181648  -9050.605493
+6           0            299       2929.4940521927465  -76.43577376668404      307.63334410569644      -2715.181648  -9050.605493
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_para.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_para.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_para.cfg	(revision 341)
@@ -0,0 +1,5 @@
+#BookArrival
+#ViewNum    StartFrame   EndFrame  FocalLength        Position       CShift   ZNear      ZFar
+10          0            99        1399.466666666666  -5.205949      0        23.175928  54.077165
+8           0            99        1399.466666666666  -4.046711      0        23.175928  54.077165
+6           0            99        1399.466666666666  -2.892842      0        23.439447  54.692044
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_poznanhall2.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_poznanhall2.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_poznanhall2.cfg	(revision 341)
@@ -0,0 +1,5 @@
+# Poznan Hall2
+#ViewNum    StartFrame   EndFrame  FocalLength          Position      CShift              ZNear         ZFar
+5           0            199       1732.875727          7.965116      943.231169      -23.394160        -172.531931
+6           0            199       1732.875727          9.558140      943.231169      -23.394160        -172.531931
+7           0            199       1732.875727         11.151163      943.231169      -23.394160        -172.531931
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_poznanstreet.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_poznanstreet.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_poznanstreet.cfg	(revision 341)
@@ -0,0 +1,5 @@
+# Poznan Street
+#ViewNum    StartFrame   EndFrame  FocalLength          Position      CShift              ZNear         ZFar
+3           0            299       1732.875727          4.779070      943.231169      -34.506386        -2760.510889
+4           0            299       1732.875727          6.372093      943.231169      -34.506386        -2760.510889
+5           0            299       1732.875727          7.965116      943.231169      -34.506386        -2760.510889
Index: branches/HTM-6.2-dev1-Samsung/cfg/cam_undodancer.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/cam_undodancer.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/cam_undodancer.cfg	(revision 341)
@@ -0,0 +1,6 @@
+# UndoDancer
+#ViewNum    StartFrame   EndFrame  FocalLength          Position      CShift   ZNear  ZFar
+1           0            249       2302.852541609168    -80.0         960.0    2289   213500 		
+2           0            249       2302.852541609168    -60.0         960.0    2289   213500 		
+5           0            249       2302.852541609168      0.0         960.0    2289   213500 		 
+9           0            249       2302.852541609168     80.0         960.0    2289   213500 		
Index: branches/HTM-6.2-dev1-Samsung/cfg/encoder_mvd.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/encoder_mvd.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/encoder_mvd.cfg	(revision 341)
@@ -0,0 +1,231 @@
+#========== file i/o ==========
+InputFile_0               : org_0.yuv                              # video input file for view 0
+InputFile_1               : org_1.yuv                              # video input file for view 1
+InputFile_2               : org_2.yuv                              # video input file for view 2
+
+DepthInputFile_0          : org_depth_0.yuv                        # depth input file for view 0
+DepthInputFile_1          : org_depth_1.yuv                        # depth input file for view 1
+DepthInputFile_2          : org_depth_2.yuv                        # depth input file for view 2
+
+ReconFile_0               : rec_0.yuv                              # video output file for view 0
+ReconFile_1               : rec_1.yuv                              # video output file for view 1
+ReconFile_2               : rec_2.yuv                              # video output file for view 2
+
+DepthReconFile_0          : rec_depth_0.yuv                        # depth output file for view 0
+DepthReconFile_1          : rec_depth_1.yuv                        # depth output file for view 1
+DepthReconFile_2          : rec_depth_2.yuv                        # depth output file for view 2
+
+BitstreamFile             : stream.bit                             # bitstream file
+
+#========== general coding parameters ==========
+NumberOfViews             : 3                                      # number of views to be coded
+CodeDepthMaps             : 1                                      # encode depth maps
+FrameSkip                 : 0                                      # number of frames to be skipped at beginning of input sequences
+InputBitDepth             : 8                                      # bit depth of input files
+OutputBitDepth            : 8                                      # bit depth of output files
+InternalBitDepth          : 8                                      # internal bit depth used for coding
+
+CroppingMode              : 0                                      # Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping)
+CropLeft                  : 0                                      # Left cropping/padding for cropping mode 3
+CropRight                 : 0                                      # Right cropping/padding for cropping mode 3
+CropTop                   : 0                                      # Top cropping/padding for cropping mode 3
+CropBottom                : 0                                      # Bottom cropping/padding for cropping mode 3
+HorizontalPadding         : 0                                      # horizontal source padding for cropping mode 2
+VerticalPadding           : 0                                      # vertical source padding for cropping mode 2
+
+
+#========== camera parameters ==========
+CameraParameterFile       : cam_pars.txt                           # camera parameter file
+CodedCamParsPrecision     : 5                                      # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#========== coding unit definitions ==========
+MaxCUWidth                : 64                                     # maximum coding unit witdh  (in luma samples) 
+MaxCUHeight               : 64                                     # maximum coding unit height (in luma samples)
+MaxPartitionDepth         : 4                                      # maximum coding unit depth
+QuadtreeTULog2MaxSize     : 5                                      # log2 of maximum transform size
+QuadtreeTULog2MinSize     : 2                                      # log2 of minimum transform size
+QuadtreeTUMaxDepthIntra   : 3                                      # maximum transform tree depth for intra-coded CU's
+QuadtreeTUMaxDepthInter   : 3                                      # maximum transform tree depth for inter-coded CU's
+
+
+#========== coding structure ==========
+IntraPeriod                   : 24          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+# V0        Type POC QPoffset QPfactor temporal_id #ref_pics_active ref_pic #ref_pics reference pictures predict deltaRIdx-1 deltaRPS #ref_idcs reference idcs  #IV_ref_pics  IV reference pics  IV ref list pos
+Frame1:     B    8   1        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      0 
+Frame2:     B    4   2        0.3536   0           2                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       0
+Frame3:     B    2   3        0.3536   0           2                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         0
+Frame4:     B    1   4        0.68     0           2                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       0
+Frame5:     B    3   4        0.68     0           2                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       0
+Frame6:     B    6   3        0.3536   0           2                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       0
+Frame7:     B    5   4        0.68     0           2                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       0
+Frame8:     B    7   4        0.68     0           2                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       0
+FrameI_v1:  P    0   3        0.442    0           1                1       0                            0                                                      1             -1                 1                  0  
+Frame1_v1:  B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -1                 2                  0  
+Frame2_v1:  B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -1                 2                  0  
+Frame3_v1:  B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -1                 2                  0  
+Frame4_v1:  B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -1                 2                  0  
+Frame5_v1:  B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+Frame6_v1:  B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -1                 3                  0  
+Frame7_v1:  B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -1                 3                  0  
+Frame8_v1:  B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -1                 3                  0  
+FrameI_v2:  P    0   3        0.442    0           1                1       0                            0                                                      1             -2                 1                  0  
+Frame1_v2:  B    8   4        0.442    0           4                1       4         -8 -10 -12 -16     0                                                      1             -2                 2                  0  
+Frame2_v2:  B    4   5        0.3536   0           3                1       3         -4 -6  4           1       0           4        5         1 1 0 0 1       1             -2                 2                  0  
+Frame3_v2:  B    2   6        0.3536   0           3                1       4         -2 -4  2 6         1       0           2        4         1 1 1 1         1             -2                 2                  0  
+Frame4_v2:  B    1   7        0.68     0           3                0       4         -1  1  3 7         1       0           1        5         1 0 1 1 1       1             -2                 2                  0  
+Frame5_v2:  B    3   7        0.68     0           3                0       4         -1 -3  1 5         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+Frame6_v2:  B    6   6        0.3536   0           3                1       4         -2 -4 -6 2         1       0          -3        5         1 1 1 1 0       1             -2                 3                  0  
+Frame7_v2:  B    5   7        0.68     0           3                0       4         -1 -5  1 3         1       0           1        5         1 0 1 1 1       1             -2                 3                  0  
+Frame8_v2:  B    7   7        0.68     0           3                0       4         -1 -3 -7 1         1       0          -2        5         1 1 1 1 0       1             -2                 3                  0  
+
+ListCombination               : 1           # Use combined list for uni-prediction in B-slices
+LCModification            : 0                                      # enables signalling of combined reference list derivation
+DisableInter4x4               : 1           # Disable Inter4x4 (1: Disable Inter4x4, 0: Enable Inter4x4)
+
+
+#========== encoder control /motion search ==========
+FastSearch                : 1                                      # motion search mode (0:Full search, 1:Diamond, 2:PMVFAST)
+SearchRange               : 96                                     # motion search range (in luma samples)
+BipredSearchRange         : 4                                      # motion search range for bi-prediction refinement (in luma samples)
+HadamardME                : 1                                      # use Hadamard SAD for fractional-sample search
+FEN                       : 1                                      # use fast encoder control
+FDM                           : 1           # Fast Decision for Merge RD cost
+TMVP                      : 1                                      # Enable TMVP
+ECU                       : 0                                      # Early CU setting
+CFM                       : 0                                      # Cbf fast mode setting
+SBACRD                    : 1                                      # SBAC based RD estimation
+ASR                       : 0                                      # adaptive motion search range
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+MaxCuDQPDepth             : 0                                      # max depth of a minimum CuDQP for sub-LCU-level delta QP
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+ChromaQpOffset                : 0           # ChromaQPOffset
+ChromaQpOffset2nd             : 0           # ChromaQPOffset2nd
+AdaptiveQpSelection       : 0                                      # AdaptiveQpSelection
+AdaptiveQP                : 0                                      # QP adaptation based on a psycho-visual model
+MaxQPAdaptationRange      : 6                                      # QP adaptation range
+LambdaModifier0           : 1.0                                    # Lambda modifier for temporal layer 0
+LambdaModifier1           : 1.0                                    # Lambda modifier for temporal layer 1
+LambdaModifier2           : 1.0                                    # Lambda modifier for temporal layer 2
+LambdaModifier3           : 1.0                                    # Lambda modifier for temporal layer 3
+
+
+#=========== Quantization Matrix =================
+ScalingList               : 0                                      # ScalingList 0 : off, 1 : default, 2 : file read
+# ScalingListFile         :                                        # Scaling List file name. If file is not exist, use Default Matrix.
+
+
+#============ Lossless ================
+LosslessCuEnabled         : 0                                      # 1: Set "qpprime_y_zero_transquant_bypass_flag=1" and enable the lossless mode as well as the RD-based mode selection process.
+
+
+#========== slices ==========
+SliceGranularity          : 0                                      # Slice granularity relative the LCU size
+SliceMode                 : 0                                      # slice mode (0:off, 1:max # of LCUs, 2:max # of bytes)
+SliceArgument             : 1500                                   # slice argument (SliceMode1:max # of LCUs, SliceMode2: max # of bytes)
+EntropySliceMode          : 0                                      # entropy slices (0:off, 1:max # of LCUs, 2:max # of bins)
+EntropySliceArgument      : 180000                                 # entropy slice argument (EntropySliceMode1:max # of LCUs, EntropySliceMode2:max # of bins)
+LFCrossSliceBoundaryFlag  : 1                                      # loop-filtering across slice boundaries
+
+
+#========== deblocking ==========
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInAPS         : 0           # Dbl params in APS or SliceHeader (0=SliceHeader, 1=APS)
+LoopFilterDisable             : 0 1                               # disable deblocking filter
+LoopFilterBetaOffset_div2     : 0           # Range: -13 ~ 13
+LoopFilterTcOffset_div2       : 0           # Range: -13 ~ 13
+
+
+#========== coding tools ==========
+ALFEncodePassReduction         : 0                                 # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+SAO                           : 1 0         # Sample adaptive offset  (0: OFF, 1: ON)
+ALF                            : 0 0                               # Adaptive loop filter  (0: OFF, 1: ON)
+LMChroma                      : 0           # Chroma from luma intra prediction mode (0: OFF, 1: ON)
+NSQT                          : 0           # Non-square transforms (0: OFF, 1: ON)
+AMP                           : 0           # Asymmetric motion partitions (0: OFF, 1: ON)
+ALFMaxNumFilter               : 16          # ALF Max Number Filters per picture
+ALFParamInSlice               : 0           # ALF params in SliceHeader or APS (0=APS, 1=SliceHeader)
+ALFPicBasedEncode             : 1           # ALF LCU-based or picture-based encoding (0: LCU-based, 1: Picture-based)  
+MaxNumOffsetsPerPic            : 2048                              # default
+SAOInterleaving               : 0           # SAO interleaving flag (0: SAO parameter in APS, 1: SAO parameter in slice data) 
+ConstrainedIntraPred           : 0                                 # Constrained Intra Prediction
+weighted_pred_flag             : 0                                 # weighted prediction flag (P-Slices)
+weighted_bipred_idc            : 0                                 # weighted bipred idc (B-Slices)
+SignHideFlag                   : 1                                 # sign hiding
+SignHideThreshold              : 4                                 # sign hiding threshold
+IlluCompEnable                 : 1                                 # illumination compensation (0: OFF, 1: ON)
+
+#============ 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 ================
+TileInfoPresentFlag            : 1                                 # 0: tiles parameters are NOT present in the PPS, 1: tiles parameters are present in the PPS 
+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)
+TileLocationInSliceHeaderFlag  : 0                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile location information to slice header, 0: Disable writing tile location information to slice header.
+TileMarkerFlag                 : 1                                 # If TileBoundaryIndependenceIdc==0 flag is ignored, 1: Enable writing tile markers, 0: Disable writing tile markers.
+MaxTileMarkerEntryPoints       : 4                                 # Maximum number of uniformly-spaced tile entry points (using tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.
+TileControlPresentFlag         : 1                                 # 0: tiles behavior control parameters are NOT present in the PPS,  1: tiles behavior control parameters are present in the PPS
+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.
+WaveFrontFlush                 : 0                                 # 0: No CABAC resets are performed, 1: A CABAC reset is performed at the end of each LCU line.
+WaveFrontSubstreams                 : 1                # >0: This many substreams per slice (or per tile if TileBoundaryIndependenceIdc=1) will be produced.
+
+
+#========== multiview coding tools ==========
+PredDepthMapGen           : 1                                      # generation of prediction depth maps (0:off, 1:using coded motion data, 2:using coded depth maps)
+MultiviewMvPred           : 7                                      # usage of prediction depth maps (0:off, 1:for interview, 2:for inter, 4:for merge, X:bit-wise combinations)
+MultiviewMvRegMode        : 1                                      # use original depth maps for regularizing inter-view motion vector
+MultiviewMvRegLambdaScale : 1.0                                    # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1                                      # inter-view residual prediction (0:off, 1:on)
+InterViewSkip             : 0                                      # interview SKIP mode
+InterViewSkipLambdaScale  : 8                                      # lambda scale for inter-view skip mode
+DisparitySearchRangeRestriction : 0                                # 0: No disparity restriction 1: Use disparity restriction
+VerticalDisparitySearchRange    : 56                               # vertical disparity search range (in luma samples)
+FCO                        : 0                                     # Flexible coding order flag in 3DV
+FCOCodingOrder             : T0D0D1T1D2T2                              # Coding order for Flexible coding order in 3DV
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+MVI                       : 1                                      # motion parameter inheritance
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+QTLPC                     : 1                                      # use of quadtree limitation + predictive coding of the quadtree for depth coding
+SDC                       : 1                                      # use simplified depth coding tree
+DLT                       : 1                                      # use depth lookup table
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string (3 view) 
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0)        I(s0.25 s0.5 s0.75)]                                                   # VSO configuration string (2 view) 
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][ox2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string 
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) I(s0.25 s0.5 s0.75)]  # VSO configuration string
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+
+
+
+#============ Misc. ================
+SEIpictureDigest          : 0                                      # Control generation of picture_digest SEI messages
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: branches/HTM-6.2-dev1-Samsung/cfg/renderer.cfg
===================================================================
--- branches/HTM-6.2-dev1-Samsung/cfg/renderer.cfg	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/cfg/renderer.cfg	(revision 341)
@@ -0,0 +1,54 @@
+#======== Input and Output Files =======
+VideoInputFileBaseName  : C:\md\vids\original\MPEG_MVD_bookarrival_VN$_CTv_RS768X1024.yuv # input video file basename, '$' is replaced by BaseViewCameraNumber
+DepthInputFileBaseName  : C:\md\vids\original\MPEG_MVD_bookarrival_VN$_CTd_RS768X1024.yuv # input depth file basename, '$' is replaced by BaseViewCameraNumber
+SynthOutputFileBaseName : C:\md\temp\book_synth_$_RS768X1024.yuv                           # output video file basename, '$' is replaced by SynthViewCameraNumber
+ContOutputFileNumbering : 0                         # for SynthOutputFileBaseName only: 0 = Replace '$' with real view numbers, 1 = Replace '$' from Left View to Right View beginning with 0
+
+#======== Input and Output Files (alternatively )=======
+#VideoInputFile_0        : C:\md\vids\original\MPEG_MVD_bookarrival_VN10_CTv_RS768X1024.yuv
+#VideoInputFile_1        : C:\md\vids\original\MPEG_MVD_bookarrival_VN08_CTv_RS768X1024.yuv
+#VideoInputFile_2        : C:\md\vids\original\MPEG_MVD_bookarrival_VN06_CTv_RS768X1024.yuv
+
+#DepthInputFile_0        : C:\md\vids\original\MPEG_MVD_bookarrival_VN10_CTd_RS768X1024.yuv
+#DepthInputFile_1        : C:\md\vids\original\MPEG_MVD_bookarrival_VN08_CTd_RS768X1024.yuv
+#DepthInputFile_2        : C:\md\vids\original\MPEG_MVD_bookarrival_VN06_CTd_RS768X1024.yuv
+
+#SynthOutputFile_0       : C:\md\temp\book_synth_0_RS768X1024.yuv  
+#SynthOutputFile_1       : C:\md\temp\book_synth_1_RS768X1024.yuv  
+#SynthOutputFile_2       : C:\md\temp\book_synth_2_RS768X1024.yuv  
+# ...
+
+
+#======== File Specification =======
+SourceWidth             : 1024                      # width in pel
+SourceHeight            : 768                       # height in pel
+FrameSkip               : 0                         # frames to skip from beginning
+FramesToBeRendered      : 5                         # 0 for all
+
+#======== Camera Specification =======
+BaseViewCameraNumbers   : 10 8 6                    # numbers of base views, (From left to right)
+SynthViewCameraNumbers  : 0 : 0.25 : 2              # numbers or range of synthesized views (original views are copied)
+CameraParameterFile     : c:\md\codecs\MVDC005_64\cfg\cam_para.cfg              # name of camera parameter file
+
+#======== Rendering Parameters =======
+RenderDirection         : 0                         # 0: interpolate, 1: extrapolate from left, 2: exterpolate from right 
+RenderMode              : 0                         # 0: use Renderer, 1: use Model, 10: generate used pels map
+
+#======== Pre/ PostProcesssing ======== 
+TemporalDepthFilter     : 0                         # 0: off, 1: temporal depth filter of non-moving blocks ( tool from VSRS Software)
+SimEnhance              : 1                         # 0: off, 1: on, Similarity enhancement
+
+#======== Interpolation ======== 
+ShiftPrecision          : 2                         # precision of Shifts 0: full pel, 1: half pel, 2: quater pel
+
+#======== Hole Filling ======== 
+HoleFillingMode         : 1                         # 0: none, 1: line wise background extension
+
+#======== Blending ======== 
+BlendMode               : 0                         # blending of left and right image: 0: average, 1: holes from right, 2: only holes from left, 3: adaptively from BaseViewCameraNumbers order
+BlendZThresPerc         : 30                        # Z-difference threshold for blending in percent of total Z-range
+BlendUseDistWeight      : 1                         # 0: blending using average; 1: weight blending depending on view distance 
+BlendHoleMargin         : 6                         # Margin next holes to blend with other view in interpolation or to cut in extrapolation ( should be 2 for extrapolation)
+
+#======== Others ===========
+Sweep                   : 0                         # Output all views to one file
Index: branches/HTM-6.2-dev1-Samsung/compat/msvc/stdint.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/compat/msvc/stdint.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/compat/msvc/stdint.h	(revision 341)
@@ -0,0 +1,13 @@
+#pragma once
+
+/* a minimal set of C99 types for use with MSVC */
+
+typedef signed char int8_t;
+typedef short int int16_t;
+typedef int int32_t;
+typedef __int64 int64_t;
+
+typedef unsigned char uint8_t;
+typedef unsigned short int uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned __int64 uint64_t;
Index: branches/HTM-6.2-dev1-Samsung/doc/Doxyfile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/doc/Doxyfile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/doc/Doxyfile	(revision 341)
@@ -0,0 +1,1796 @@
+# Doxyfile 1.7.5
+
+# 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
+# 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 (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# 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.
+
+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.
+
+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-3.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 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.
+
+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.
+
+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.
+
+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.
+
+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 
+# brief descriptions will be completely suppressed.
+
+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"
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         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 
+# description.
+
+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 
+# operators of the base classes will not be shown.
+
+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.
+
+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.
+
+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.
+
+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.)
+
+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.)
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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 
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to 
+# enable parsing support.
+
+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.
+
+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.
+
+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 
+# all members of a group must be documented explicitly.
+
+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.
+
+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).
+
+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).
+
+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 
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+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
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# 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
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class 
+# will be included in the documentation.
+
+EXTRACT_PRIVATE        = YES
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file 
+# will be included in the documentation.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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 
+# and Mac users are advised to set this option to NO.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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 
+# list will mention the files that were used to generate the documentation.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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)
+
+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.
+
+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.
+
+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.
+
+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
+
+FILE_PATTERNS          = *.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
+
+# 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.
+
+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 
+# from the input.
+
+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/*
+
+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, 
+# 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.
+
+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.
+
+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).
+
+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.
+
+SOURCE_BROWSER         = YES
+
+# Setting the INLINE_SOURCES tag to YES will include the body 
+# of functions and classes directly in the documentation.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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])
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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).
+
+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 
+# for more information.
+
+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.
+
+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.
+
+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 
+# string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+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.
+
+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 
+# 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).
+
+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.
+
+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.
+
+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.
+
+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
+
+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
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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 
+# higher quality PDF documentation.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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
+
+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.
+
+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)
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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 = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will 
+# evaluate all C-preprocessor directives found in the sources and include 
+# 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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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.
+
+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).
+
+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.
+
+INTERACTIVE_SVG        = NO
+
+# The tag DOT_PATH 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 
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+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).
+
+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.
+
+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.
+
+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.
+
+DOT_CLEANUP            = YES
Index: branches/HTM-6.2-dev1-Samsung/doc/mainpage.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/doc/mainpage.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/doc/mainpage.h	(revision 341)
@@ -0,0 +1,65 @@
+#include "TLibCommon/CommonDef.h"
+
+/**
+ * \file mainpage.h
+ * \brief HEVC referece documentation main page (no functional use)
+ * \mainpage
+ *
+ * \section Introduction
+ *
+ *  This is the doxygen generated documentation of the HEVC HM reference software. 
+ *     
+ *  For detailed information see the sub-pages of this site.
+ *
+ *  For information on the <b>subversion repositories</b> and the <b>software manual</b> see
+ *  http://hevc.hhi.fraunhofer.de
+ *
+ *  For <b>bug reporting and known issues</b> see:
+ *  http://hevc.kw.bbc.co.uk/trac/
+ *
+ * \section License
+ *
+ * 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-2012, 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.
+ *
+ *  \note
+ *     This document is automatically generated from the source code and special documentation tags.
+ *     For more details on the used documentation system see http://www.doxygen.org
+ *
+ *  \defgroup TLibCommon   TLibCommon  - Library containing functionality that is shared between encoder and decoder
+ *  \defgroup TLibEncoder  TLibEncoder - Library containing encoder functionality
+ *  \defgroup TLibDecoder  TLibDecoder - Library containing encoder functionality
+ *  \defgroup libMD5       libMD5      - MD5 helper functions
+ *  \defgroup TAppCommon   TAppCommon  - Application support library
+ *  \defgroup TAppEncoder  TAppEncoder - Encoder application
+ *  \defgroup TAppDecoder  TAppDecoder - Decoder application
+ */
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 341)
@@ -0,0 +1,128 @@
+/* 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-2012, 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     TAppDecCfg.cpp
+    \brief    Decoder configuration class
+*/
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include "TAppDecCfg.h"
+#include "TAppCommon/program_options_lite.h"
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param argc number of arguments
+    \param argv array of arguments
+ */
+Bool TAppDecCfg::parseCfg( Int argc, Char* argv[] )
+{
+  bool do_help = false;
+  string cfg_BitstreamFile;
+  string cfg_ReconFile;
+  string cfg_ScaleOffsetFile;
+
+  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")
+  ("ScaleOffsetFile,p", cfg_ScaleOffsetFile, string(""), "file with coded scales and offsets")
+  ("SkipFrames,s", m_iSkipFrame, 0, "number of frames to skip before random access")
+  ("OutputBitDepth,d", m_outputBitDepth, 0u, "bit depth of YUV output file (use 0 for native depth)")
+  ("MaxTemporalLayer,t", m_iMaxTemporalLayer, -1, "Maximum Temporal Layer to be decoded. -1 to decode all layers")
+  ("SEIpictureDigest", m_pictureDigestEnabled, true, "Control handling of picture_digest SEI messages\n"
+                                              "\t1: check\n"
+                                              "\t0: ignore")
+  ;
+
+  po::setDefaults(opts);
+  const list<const char*>& argv_unhandled = po::scanArgv(opts, argc, (const char**) argv);
+
+  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)
+  {
+    po::doHelp(cout, opts);
+    return false;
+  }
+
+  /* convert std::string to c string for compatability */
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
+  m_pchScaleOffsetFile = cfg_ScaleOffsetFile.empty() ? NULL : strdup(cfg_ScaleOffsetFile.c_str());
+
+
+  if (!m_pchBitstreamFile)
+  {
+    fprintf(stderr, "No input file specified, aborting\n");
+    return false;
+  }
+
+  return true;
+}
+
+Void TAppDecCfg::xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName)
+{
+  size_t iInLength     = strlen(pchInputFileName);
+  size_t iAppendLength = strlen(pchStringToAppend); 
+
+  rpchOutputFileName = (Char*) malloc(iInLength+iAppendLength+1);                        
+  Char* pCDot = strrchr(pchInputFileName,'.');         
+  pCDot = pCDot ? pCDot : pchInputFileName + iInLength;        
+  size_t iCharsToDot = pCDot - pchInputFileName ; 
+  size_t iCharsToEnd = iInLength - iCharsToDot;         
+  strncpy(rpchOutputFileName                            ,  pchInputFileName            , iCharsToDot  );
+  strncpy(rpchOutputFileName+ iCharsToDot               ,  pchStringToAppend           , iAppendLength); 
+  strncpy(rpchOutputFileName+ iCharsToDot+iAppendLength ,  pchInputFileName+iCharsToDot, iCharsToEnd  );        
+  rpchOutputFileName[iInLength+iAppendLength] = '\0';          
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecCfg.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecCfg.h	(revision 341)
@@ -0,0 +1,79 @@
+/* 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-2012, 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     TAppDecCfg.h
+    \brief    Decoder configuration class (header)
+*/
+
+#ifndef __TAPPDECCFG__
+#define __TAPPDECCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Decoder configuration class
+class TAppDecCfg
+{
+protected:
+  char*         m_pchBitstreamFile;                   ///< input bitstream file name
+  char*         m_pchReconFile;                       ///< output reconstruction file name
+  char*         m_pchScaleOffsetFile;                 ///< output coded scale and offset parameters
+  Int           m_iSkipFrame;                         ///< counter for frames prior to the random access point to skip
+  UInt          m_outputBitDepth;                     ///< bit depth used for writing output
+
+  Int           m_iMaxTemporalLayer;                  ///< maximum temporal layer to be decoded
+  bool m_pictureDigestEnabled; ///< enable(1)/disable(0) acting on SEI picture_digest message
+  Void xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName); ///< create filenames
+
+public:
+  TAppDecCfg()          {}
+  virtual ~TAppDecCfg() {}
+  
+  Bool  parseCfg        ( Int argc, Char* argv[] );   ///< initialize option class from configuration
+};
+
+//! \}
+
+#endif
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecTop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecTop.cpp	(revision 341)
@@ -0,0 +1,751 @@
+/* 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-2012, 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     TAppDecTop.cpp
+    \brief    Decoder application class
+*/
+
+#include <list>
+#include <vector>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppDecTop.h"
+#include "TLibDecoder/AnnexBread.h"
+#include "TLibDecoder/NALread.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppDecTop::TAppDecTop()
+{
+  ::memset (m_abDecFlag, 0, sizeof (m_abDecFlag));
+  m_useDepth = false;
+  m_pScaleOffsetFile  = 0;
+}
+
+Void TAppDecTop::create()
+{
+}
+
+Void TAppDecTop::destroy()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - create internal class
+ - initialize internal class
+ - until the end of the bitstream, call decoding function in TDecTop class
+ - delete allocated buffers
+ - destroy internal class
+ .
+ */
+Void TAppDecTop::decode()
+{
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  increaseNumberOfViews( 0, 0, 0 );
+#else
+  increaseNumberOfViews( 1 );
+#endif
+  
+#if FLEX_CODING_ORDER_M23723
+  Int iDepthViewIdx = 0;
+  Int iTextureViewIdx=0;
+  Bool firstFrame=1;
+  Bool viewIdZero=true;
+  Int fcoIndex=0;  //when the current frame is not first frame,use FCO_index stand for viewDepth. 
+#endif
+
+  Int                 viewDepthId = 0;
+  Int                 previousViewDepthId  = 0;
+  UInt                uiPOC[MAX_VIEW_NUM*2];
+  TComList<TComPic*>* pcListPic[MAX_VIEW_NUM*2];
+  Bool                newPicture[MAX_VIEW_NUM*2];
+  Bool                previousPictureDecoded = false;
+  for( Int i = 0; i < MAX_VIEW_NUM*2; i++ )
+  {
+    uiPOC[i] = 0;
+    pcListPic[i] = NULL;
+    newPicture[i] = false;
+#if FLEX_CODING_ORDER_M23723
+    m_fcoOrder[i] = ' ';
+#endif
+
+  }
+
+  ifstream bitstreamFile(m_pchBitstreamFile, ifstream::in | ifstream::binary);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for reading\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  if( m_pchScaleOffsetFile ) 
+  { 
+    m_pScaleOffsetFile = ::fopen( m_pchScaleOffsetFile, "wt" ); 
+    AOF( m_pScaleOffsetFile ); 
+  }
+  m_cCamParsCollector.init( m_pScaleOffsetFile );
+
+  InputByteStream bytestream(bitstreamFile);
+
+  while (!!bitstreamFile)
+  {
+    /* location serves to work around a design fault in the decoder, whereby
+     * the process of reading a new slice that is the first slice of a new frame
+     * requires the TDecTop::decode() method to be called again with the same
+     * nal unit. */
+    streampos location = bitstreamFile.tellg();
+    AnnexBStats stats = AnnexBStats();
+    vector<uint8_t> nalUnit;
+    InputNALUnit nalu;
+    byteStreamNALUnit(bytestream, nalUnit, stats);
+
+    // call actual decoding function
+    if (nalUnit.empty())
+    {
+      /* this can happen if the following occur:
+       *  - empty input file
+       *  - two back-to-back start_code_prefixes
+       *  - start_code_prefix immediately followed by EOF
+       */
+      fprintf(stderr, "Warning: Attempt to decode an empty NAL unit\n");
+    }
+    else
+    {
+      read(nalu, nalUnit);
+#if QC_MVHEVC_B0046
+    viewDepthId = nalu.m_layerId;
+    Int depth = 0;
+    Int viewId = viewDepthId;
+#else
+#if VIDYO_VPS_INTEGRATION
+      Int viewId = 0;
+      Int depth = 0;
+      
+      if(nalu.m_nalUnitType != NAL_UNIT_VPS || nalu.m_layerId)
+      {
+        // code assumes that the first nal unit is VPS
+        // currently, this is a hack that requires non-first VPSs have non-zero layer_id
+        viewId = getVPSAccess()->getActiveVPS()->getViewId(nalu.m_layerId);
+        depth = getVPSAccess()->getActiveVPS()->getDepthFlag(nalu.m_layerId);
+      }
+#if FLEX_CODING_ORDER_M23723
+      if (viewId>0)
+      {
+        viewIdZero=false;
+      }
+      if (viewIdZero==false&&viewId==0)
+      {
+        firstFrame=0; //if viewId has been more than zero and now it set to zero again, we can see that it is not the first view
+      }
+      if (firstFrame)
+      { // if the current view is first frame, we set the viewDepthId as texture plus depth and get the FCO order 
+        viewDepthId = iDepthViewIdx+iTextureViewIdx;
+        m_fcoViewDepthId=viewDepthId;
+      }
+      else
+      {//if current view is not first frame, we set the viewDepthId depended on the FCO order
+        viewDepthId=0;
+        if (depth)
+        {
+          for (fcoIndex=0;fcoIndex<2*MAX_VIEW_NUM;fcoIndex++ )
+          {
+            if (m_fcoOrder[fcoIndex]=='D')
+            {
+              if (viewId==viewDepthId)
+                break;
+              else
+                viewDepthId++;
+            }
+          }
+        }
+        else
+        {
+          for (fcoIndex=0;fcoIndex<2*MAX_VIEW_NUM;fcoIndex++ )
+          {
+            if (m_fcoOrder[fcoIndex]=='T')
+            {
+              if (viewId==viewDepthId)
+                break;
+              else
+                viewDepthId++;
+            }
+          }
+        }
+
+        viewDepthId=fcoIndex;
+
+      }
+
+
+#else
+      viewDepthId = nalu.m_layerId;   // coding order T0D0T1D1T2D2
+#endif
+    
+#else
+      Int viewId = nalu.m_viewId;
+      Int depth = nalu.m_isDepth ? 1 : 0;
+#if FLEX_CODING_ORDER_M23723
+      if (viewId>0)
+      {
+        viewIdZero=false;
+      }
+      if (viewIdZero==false&&viewId==0)
+      {
+        firstFrame=0;
+      }
+      if (firstFrame)
+      {
+        viewDepthId = iDepthViewIdx+iTextureViewIdx;
+        m_fcoViewDepthId=viewDepthId;
+      }
+      else
+      {
+        viewDepthId=0;
+        if (depth)
+        {
+          for (fcoIndex=0;fcoIndex<2*MAX_VIEW_NUM;fcoIndex++ )
+          {
+            if (m_fcoOrder[fcoIndex]=='D')
+            {
+              if (viewId==viewDepthId)
+                break;
+              else
+                viewDepthId++;
+            }
+          }
+        }
+        else
+        {
+          for (fcoIndex=0;fcoIndex<2*MAX_VIEW_NUM;fcoIndex++ )
+          {
+            if (m_fcoOrder[fcoIndex]=='T')
+            {
+              if (viewId==viewDepthId)
+                break;
+              else
+                viewDepthId++;
+            }
+          }
+        }
+        viewDepthId=fcoIndex;
+      }
+#else
+      viewDepthId = viewId * 2 + depth;   // coding order T0D0T1D1T2D2
+#endif
+#endif
+#endif     
+      newPicture[viewDepthId] = false;
+      if( viewDepthId >= m_tDecTop.size() )      
+      {
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+        increaseNumberOfViews( viewDepthId, viewId, depth );
+#else
+        increaseNumberOfViews( viewDepthId +1 );
+#endif   
+      }
+      if(m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer)
+      {
+        previousPictureDecoded = false; 
+      }
+      if(m_tDecTop.size() > 1 && (viewDepthId != previousViewDepthId) && previousPictureDecoded )
+      {
+        m_tDecTop[previousViewDepthId]->executeDeblockAndAlf(uiPOC[previousViewDepthId], pcListPic[previousViewDepthId], m_iSkipFrame, m_pocLastDisplay[previousViewDepthId]);
+      } 
+      if( ( viewDepthId == 0 && (viewDepthId != previousViewDepthId) ) || m_tDecTop.size() == 1 )
+      {
+#if H3D_IVRP
+        for( Int i = 0; i < m_tDecTop.size(); i++ )
+        {
+          m_tDecTop[i]->deleteExtraPicBuffers( uiPOC[i] );
+        }
+#endif
+        for( Int i = 0; i < m_tDecTop.size(); i++ )
+        {
+          m_tDecTop[i]->compressMotion( uiPOC[i] );
+        }
+      }   
+      if( !(m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) )
+      {
+#if QC_MVHEVC_B0046
+        if(viewDepthId && m_tDecTop[viewDepthId]->m_bFirstNal== false)
+        {
+          m_tDecTop[viewDepthId]->m_bFirstNal = true;
+          ParameterSetManagerDecoder* pDecV0 = m_tDecTop[0]->xGetParaSetDec();
+          m_tDecTop[viewDepthId]->xCopyVPS(pDecV0->getPrefetchedVPS(0));
+          m_tDecTop[viewDepthId]->xCopySPS(pDecV0->getPrefetchedSPS(0));
+          m_tDecTop[viewDepthId]->xCopyPPS(pDecV0->getPrefetchedPPS(0));
+        }
+#endif
+        newPicture[viewDepthId] = m_tDecTop[viewDepthId]->decode(nalu, m_iSkipFrame, m_pocLastDisplay[viewDepthId]);
+        if (newPicture[viewDepthId])
+        {
+          bitstreamFile.clear();
+          /* location points to the current nalunit payload[1] due to the
+           * need for the annexB parser to read three extra bytes.
+           * [1] except for the first NAL unit in the file
+           *     (but bNewPicture doesn't happen then) */
+          bitstreamFile.seekg(location-streamoff(3));
+          bytestream.reset();
+        }
+        if( nalu.isSlice() )
+        {
+          previousPictureDecoded = true;
+#if FLEX_CODING_ORDER_M23723
+        if (firstFrame)
+        {
+            if (depth)
+            {
+                iDepthViewIdx++;
+                m_fcoOrder[viewDepthId]='D';
+            }
+            else
+           {
+                iTextureViewIdx++;
+                m_fcoOrder[viewDepthId]='T';
+           }
+          }
+
+#endif
+        }
+      }
+    }
+    if( ( (newPicture[viewDepthId] || !bitstreamFile) && m_tDecTop.size() == 1) || (!bitstreamFile && previousPictureDecoded == true) )  
+    {
+      m_tDecTop[viewDepthId]->executeDeblockAndAlf(uiPOC[viewDepthId], pcListPic[viewDepthId], m_iSkipFrame, m_pocLastDisplay[viewDepthId]);
+    }
+    if( pcListPic[viewDepthId] )
+    {
+#if QC_REM_IDV_B0046
+      Int iviewId = m_tDecTop[viewDepthId]->getViewId();
+      if( newPicture[viewDepthId] && (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR || ((nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR && iviewId) && m_tDecTop[viewDepthId]->getNalUnitTypeBaseView() == NAL_UNIT_CODED_SLICE_IDR)) )
+#else
+      if( newPicture[viewDepthId] && (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDV && m_tDecTop[viewDepthId]->getNalUnitTypeBaseView() == NAL_UNIT_CODED_SLICE_IDR)) )
+#endif
+      {
+        xFlushOutput( pcListPic[viewDepthId], viewDepthId );
+      }
+      // write reconstruction to file
+      if(newPicture[viewDepthId])
+      {
+        xWriteOutput( pcListPic[viewDepthId], viewDepthId, nalu.m_temporalId );
+      }
+    }
+    previousViewDepthId = viewDepthId;
+  } 
+  if( m_cCamParsCollector.isInitialized() )
+  {
+    m_cCamParsCollector.setSlice( 0 );
+  }
+  // last frame
+  for( Int viewDepthIdx = 0; viewDepthIdx < m_tDecTop.size(); viewDepthIdx++ )
+  {
+    xFlushOutput( pcListPic[viewDepthIdx], viewDepthIdx );
+  }  
+  xDestroyDecLib();
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TAppDecTop::xDestroyDecLib()
+{
+
+  for(Int viewDepthIdx=0; viewDepthIdx<m_tVideoIOYuvReconFile.size() ; viewDepthIdx++)
+  {
+    if( m_tVideoIOYuvReconFile[viewDepthIdx] )
+    {
+      m_tVideoIOYuvReconFile[viewDepthIdx]->close();
+      delete m_tVideoIOYuvReconFile[viewDepthIdx]; 
+      m_tVideoIOYuvReconFile[viewDepthIdx] = NULL ;
+    }
+  }
+
+  for(Int viewDepthIdx=0; viewDepthIdx<m_tDecTop.size() ; viewDepthIdx++)
+  {
+    if( m_tDecTop[viewDepthIdx] )
+    {
+      if( !m_useDepth && (viewDepthIdx % 2 == 1) )
+      {
+      }
+      else
+      {
+        m_tDecTop[viewDepthIdx]->deletePicBuffer();
+        m_tDecTop[viewDepthIdx]->destroy() ;
+      }
+#if QC_MVHEVC_B0046
+      if(viewDepthIdx)
+      {
+         //Call clear function to remove the record, which has been freed during viewDepthIdx = 0 case.
+        m_tDecTop[viewDepthIdx]->xGetParaSetDec()->clearSPS();
+        m_tDecTop[viewDepthIdx]->xGetParaSetDec()->clearVPS();
+        m_tDecTop[viewDepthIdx]->xGetParaSetDec()->clearPPS();
+      }
+#endif
+      delete m_tDecTop[viewDepthIdx] ; 
+      m_tDecTop[viewDepthIdx] = NULL ;
+    }
+  }
+
+  m_cCamParsCollector.uninit();
+  if( m_pScaleOffsetFile ) 
+  { 
+    ::fclose( m_pScaleOffsetFile ); 
+  }
+}
+
+Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, Int viewDepthId, UInt tId )
+{
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+  Int not_displayed = 0;
+
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_pocLastDisplay[viewDepthId])
+    {
+       not_displayed++;
+    }
+    iterPic++;
+  }
+  iterPic   = pcListPic->begin();
+  
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+    TComSPS *sps = pcPic->getSlice(0)->getSPS();
+    
+    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getSlice(0)->getSPS()->getNumReorderPics(tId) && pcPic->getPOC() > m_pocLastDisplay[viewDepthId]))
+    {
+      // write to file
+       not_displayed--;
+      if ( m_pchReconFile )
+      {
+        m_tVideoIOYuvReconFile[viewDepthId]->write( pcPic->getPicYuvRec(), sps->getPicCropLeftOffset(), sps->getPicCropRightOffset(), sps->getPicCropTopOffset(), sps->getPicCropBottomOffset() );
+      }
+      
+      // update POC of display order
+      m_pocLastDisplay[viewDepthId] = pcPic->getPOC();
+      
+      // 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);
+    }
+    
+    iterPic++;
+  }
+}
+
+/** \param pcListPic list of pictures to be written to file
+    \todo            DYN_REF_FREE should be revised
+ */
+Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic, Int viewDepthId )
+{
+  if(!pcListPic)
+  {
+    return;
+  } 
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+
+  iterPic   = pcListPic->begin();
+  
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+    TComSPS *sps = pcPic->getSlice(0)->getSPS();
+
+    if ( pcPic->getOutputMark() )
+    {
+      // write to file
+      if ( m_pchReconFile )
+      {
+        m_tVideoIOYuvReconFile[viewDepthId]->write( pcPic->getPicYuvRec(), sps->getPicCropLeftOffset(), sps->getPicCropRightOffset(), sps->getPicCropTopOffset(), sps->getPicCropBottomOffset() );
+      }
+      
+      // update POC of display order
+      m_pocLastDisplay[viewDepthId] = pcPic->getPOC();
+      
+      // 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);
+    }
+    
+    iterPic++;
+  }
+  pcListPic->clear();
+  m_pocLastDisplay[viewDepthId] = -MAX_INT;
+}
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+Void  TAppDecTop::increaseNumberOfViews  ( UInt layerId, UInt viewId, UInt isDepth )
+#else
+Void  TAppDecTop::increaseNumberOfViews  ( Int newNumberOfViewDepth )
+#endif
+{
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Int newNumberOfViewDepth = layerId + 1;
+#endif
+  if ( m_outputBitDepth == 0 )
+  {
+    m_outputBitDepth = g_uiBitDepth + g_uiBitIncrement;
+  }
+#if !VIDYO_VPS_INTEGRATION&!QC_MVHEVC_B0046
+  Int viewId = (newNumberOfViewDepth-1)>>1;   // coding order T0D0T1D1T2D2
+  Bool isDepth = ((newNumberOfViewDepth % 2) == 0);  // coding order T0D0T1D1T2D2
+#endif
+  if( isDepth )
+    m_useDepth = true;
+
+  if ( m_pchReconFile )
+  { 
+    while( m_tVideoIOYuvReconFile.size() < newNumberOfViewDepth)
+    {
+      m_tVideoIOYuvReconFile.push_back(new TVideoIOYuv);
+      Char buffer[4];
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+      sprintf(buffer,"_%i", viewId );
+#else
+      sprintf(buffer,"_%i", (Int)(m_tVideoIOYuvReconFile.size()-1) / 2 );
+#endif
+      Char* nextFilename = NULL;
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+      if( isDepth)
+#else
+      if( (m_tVideoIOYuvReconFile.size() % 2) == 0 )
+#endif
+      {
+        Char* pchTempFilename = NULL;
+        xAppendToFileNameEnd( m_pchReconFile, "_depth", pchTempFilename);
+        xAppendToFileNameEnd( pchTempFilename, buffer, nextFilename);
+        free ( pchTempFilename );
+      }
+      else
+      {
+        xAppendToFileNameEnd( m_pchReconFile, buffer, nextFilename);
+      }
+#if !VIDYO_VPS_INTEGRATION&!QC_MVHEVC_B0046
+      if( isDepth || ( !isDepth && (m_tVideoIOYuvReconFile.size() % 2) == 1 ) )
+#endif
+      {
+        m_tVideoIOYuvReconFile.back()->open( nextFilename, true, m_outputBitDepth, g_uiBitDepth + g_uiBitIncrement );
+      }
+      free ( nextFilename );
+    }
+  }
+
+  while( m_pocLastDisplay.size() < newNumberOfViewDepth )
+  {
+    m_pocLastDisplay.push_back(-MAX_INT+m_iSkipFrame);
+  }
+  while( m_tDecTop.size() < newNumberOfViewDepth)
+  {
+    m_tDecTop.push_back(new TDecTop);
+#if !VIDYO_VPS_INTEGRATION&!QC_MVHEVC_B0046
+    if( isDepth || ( !isDepth && (m_tVideoIOYuvReconFile.size() % 2) == 1 ) )
+    {
+#endif
+      m_tDecTop.back()->create();
+      m_tDecTop.back()->init( this, newNumberOfViewDepth == 1);
+      m_tDecTop.back()->setViewId( viewId );
+      m_tDecTop.back()->setIsDepth( isDepth );
+      m_tDecTop.back()->setPictureDigestEnabled(m_pictureDigestEnabled);
+      m_tDecTop.back()->setCamParsCollector( &m_cCamParsCollector );
+#if !VIDYO_VPS_INTEGRATION&!QC_MVHEVC_B0046
+    }
+#endif
+  }
+}
+
+TDecTop* TAppDecTop::getTDecTop( Int viewId, Bool isDepth )
+{ 
+#if FLEX_CODING_ORDER_M23723
+  Int viewnumber=0;
+  Int i=0;
+  Bool fcoFlag=0;
+  if (viewId>m_fcoViewDepthId)
+  {
+    return NULL;
+  }
+  else
+  {
+    if (isDepth)
+   {
+      for ( i=0; i<=m_fcoViewDepthId;i++)
+      {
+         if (m_fcoOrder[i]=='D')
+         {
+           if (viewnumber==viewId)
+           {
+             fcoFlag=1;
+             break;
+           }
+           else
+             viewnumber++;
+         }
+      }
+    }
+    else
+    {
+      for ( i=0; i<=m_fcoViewDepthId;i++)
+      {
+        if (m_fcoOrder[i]=='T')
+        {
+          if (viewnumber==viewId)
+          {
+            fcoFlag=1;
+            break;
+          }
+          else
+            viewnumber++;
+        }
+      }
+    }
+    if (fcoFlag)
+    {
+      return m_tDecTop[i];
+    }
+    else
+      return NULL;
+    
+  }
+
+    // coding order T0D0T1D1T2D2
+#else
+  return m_tDecTop[(isDepth ? 1 : 0) + viewId * 2];  // coding order T0D0T1D1T2D2
+#endif
+ 
+} 
+
+std::vector<TComPic*> TAppDecTop::getInterViewRefPics( Int viewId, Int poc, Bool isDepth, TComSPS* sps )
+{
+  std::vector<TComPic*> apcRefPics( sps->getNumberOfUsableInterViewRefs(), (TComPic*)NULL );
+  for( Int k = 0; k < sps->getNumberOfUsableInterViewRefs(); k++ )
+  {
+    TComPic* pcRefPic = xGetPicFromView( sps->getUsableInterViewRef( k ) + viewId, poc, isDepth );
+    assert( pcRefPic != NULL );
+    apcRefPics[k] = pcRefPic;
+  }
+  return apcRefPics;
+}
+
+TComPic* TAppDecTop::xGetPicFromView( Int viewId, Int poc, Bool isDepth )
+{
+  assert( ( viewId >= 0 ) );
+
+#if FLEX_CODING_ORDER_M23723
+if (getTDecTop(viewId,isDepth))
+{
+  TComList<TComPic*>* apcListPic = getTDecTop( viewId, isDepth )->getListPic();
+  TComPic* pcPic = NULL;
+  for( TComList<TComPic*>::iterator it=apcListPic->begin(); it!=apcListPic->end(); it++ )
+  {
+    if( (*it)->getPOC() == poc )
+    {
+      pcPic = *it;
+      break;
+    }
+  }
+  return pcPic;
+}
+else
+  return NULL;
+#else
+
+  TComList<TComPic*>* apcListPic = getTDecTop( viewId, isDepth )->getListPic();
+  TComPic* pcPic = NULL;
+  for( TComList<TComPic*>::iterator it=apcListPic->begin(); it!=apcListPic->end(); it++ )
+  {
+    if( (*it)->getPOC() == poc )
+    {
+      pcPic = *it;
+      break;
+    }
+  }
+  return pcPic;
+#endif
+}
+
+#if MERL_VSP_C0152
+Void TAppDecTop::setBWVSPLUT(TComSlice* pcSlice,  Int iCodedViewIdx,  Int iCurPoc)
+{
+  //first view does not have VSP 
+  if((iCodedViewIdx == 0)) return;
+
+  AOT( iCodedViewIdx <= 0);
+  //AOT( iCodedViewIdx >= m_iNumberOfViews );
+  Int iNeighborViewId = 0;
+  //  Int* piShiftLUT = bRenderFromLeft ? m_cCamParsCollector.getBaseViewShiftLUTI()[iCodedViewIdx][iNeighborViewId][0] : m_cCamParsCollector.getBaseViewShiftLUTI()[iNeighborViewId][iCodedViewIdx][0];
+  Int* piShiftLUT = m_cCamParsCollector.getBaseViewShiftLUTI()[iNeighborViewId][iCodedViewIdx][0];
+  pcSlice->setBWVSPLUTParam(piShiftLUT, 2-LOG2_DISP_PREC_LUT );
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecTop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/TAppDecTop.h	(revision 341)
@@ -0,0 +1,131 @@
+/* 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-2012, 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     TAppDecTop.h
+    \brief    Decoder application class (header)
+*/
+
+#ifndef __TAPPDECTOP__
+#define __TAPPDECTOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComDepthMapGenerator.h"
+#include "TLibDecoder/TDecTop.h"
+#include "TAppDecCfg.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// decoder application class
+class TAppDecTop : public TAppDecCfg
+{
+private:
+  // class interface
+  std::vector<TDecTop*>           m_tDecTop;                      ///< decoder classes
+
+  std::vector<TVideoIOYuv*>       m_tVideoIOYuvReconFile;         ///< reconstruction YUV class
+
+  // for output control
+  Bool                            m_abDecFlag[ MAX_GOP ];         ///< decoded flag in one GOP
+  std::vector<Int>                m_pocLastDisplay;               ///< last POC in display order
+  Bool                            m_useDepth;
+
+#if FLEX_CODING_ORDER_M23723
+  Int  m_fcoViewDepthId;
+  Char m_fcoOrder[MAX_VIEW_NUM*2];
+#endif
+
+  FILE*                           m_pScaleOffsetFile;
+  CamParsCollector                m_cCamParsCollector;
+#if DEPTH_MAP_GENERATION
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  TComVPSAccess                   m_cVPSAccess;
+#endif
+  TComSPSAccess                   m_cSPSAccess;
+  TComAUPicAccess                 m_cAUPicAccess;
+#endif
+
+public:
+  TAppDecTop();
+  virtual ~TAppDecTop() {}
+  
+  Void  create            (); ///< create internal members
+  Void  destroy           (); ///< destroy internal members
+  Void  decode            (); ///< main decoding function
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void  increaseNumberOfViews  (UInt layerId, UInt viewId, UInt isDepth);
+#else
+  Void  increaseNumberOfViews  (Int newNumberOfViewDepth);
+#endif
+  TDecTop* getTDecTop     ( Int viewId, Bool isDepth );
+
+  std::vector<TComPic*> getInterViewRefPics( Int viewId, Int poc, Bool isDepth, TComSPS* sps );
+  TComPic*              getPicFromView     ( Int viewId, Int poc, bool isDepth ) { return xGetPicFromView( viewId, poc, isDepth ); }
+
+#if DEPTH_MAP_GENERATION
+#if VIDYO_VPS_INTEGRATION
+  TComVPSAccess*    getVPSAccess  () { return &m_cVPSAccess;   }
+#endif
+  TComSPSAccess*    getSPSAccess  () { return &m_cSPSAccess;   }
+  TComAUPicAccess*  getAUPicAccess() { return &m_cAUPicAccess; }
+  TDecTop*          getDecTop0    () { return m_tDecTop[0]; }
+#endif
+
+#if MERL_VSP_C0152
+  Void  setBWVSPLUT( TComSlice* pcSlice, Int iCodedViewIdx, Int iCurPoc   );
+#endif
+
+protected:
+//  Void  xCreateDecLib     (); ///< create internal classes
+  Void  xDestroyDecLib    (); ///< destroy internal classes
+//  Void  xInitDecLib       (); ///< initialize decoder class
+  
+  Void  xWriteOutput      ( TComList<TComPic*>* pcListPic, Int viewDepthId, UInt tId); ///< write YUV to file
+  Void  xFlushOutput      ( TComList<TComPic*>* pcListPic, Int viewDepthId ); ///< flush all remaining decoded pictures to file
+
+  TComPic* xGetPicFromView( Int viewId, Int poc, Bool isDepth );
+};
+
+//! \}
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/decmain.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/decmain.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppDecoder/decmain.cpp	(revision 341)
@@ -0,0 +1,96 @@
+/* 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-2012, 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     decmain.cpp
+    \brief    Decoder application main
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include "TAppDecTop.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+bool g_md5_mismatch = false; ///< top level flag that indicates if there has been a decoding mismatch
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppDecTop  cTAppDecTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "3D-HTM Software: Decoder Version [%s] based on HM Version [%s]", NV_VERSION, HM_VERSION );
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // create application decoder class
+  cTAppDecTop.create();
+
+  // parse configuration
+  if(!cTAppDecTop.parseCfg( argc, argv ))
+  {
+    cTAppDecTop.destroy();
+    return 1;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call decoding function
+  cTAppDecTop.decode();
+
+  if (g_md5_mismatch)
+  {
+    printf("\n\n***ERROR*** A decoding mismatch occured: signalled md5sum does not match\n");
+  }
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  // destroy application decoder class
+  cTAppDecTop.destroy();
+
+  return g_md5_mismatch ? EXIT_FAILURE : EXIT_SUCCESS;
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 341)
@@ -0,0 +1,1817 @@
+/* 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-2012, 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     TAppEncCfg.cpp
+    \brief    Handle encoder configuration parameters
+*/
+
+#include <stdlib.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+#include "TLibCommon/TComRom.h"
+#include "TAppEncCfg.h"
+#include "TAppCommon/program_options_lite.h"
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppEncoder
+//! \{
+
+/* configuration helper funcs */
+void doOldStyleCmdlineOn(po::Options& opts, const std::string& arg);
+void doOldStyleCmdlineOff(po::Options& opts, const std::string& arg);
+
+// ====================================================================================================================
+// Local constants
+// ====================================================================================================================
+
+/// max value of source padding size
+/** \todo replace it by command line option
+ */
+#define MAX_PAD_SIZE                16
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncCfg::TAppEncCfg()
+{
+  m_aidQP = NULL;
+  m_aidQPdepth = NULL;
+}
+
+TAppEncCfg::~TAppEncCfg()
+{
+  if ( m_aidQP )
+  {
+    delete[] m_aidQP; m_aidQP = NULL;
+  }
+
+  if ( m_aidQPdepth )
+  {
+    delete[] m_aidQPdepth; m_aidQPdepth = NULL;
+  }
+
+  for(Int i = 0; i< m_pchInputFileList.size(); i++ )
+  {
+    if ( m_pchInputFileList[i] != NULL )
+      free (m_pchInputFileList[i]);
+  }
+  for(Int i = 0; i< m_pchDepthInputFileList.size(); i++ )
+  {
+    if ( m_pchDepthInputFileList[i] != NULL )
+      free (m_pchDepthInputFileList[i]);
+  }
+  for(Int i = 0; i< m_pchReconFileList.size(); i++ )
+  {
+    if ( m_pchReconFileList[i] != NULL )
+      free (m_pchReconFileList[i]);
+  }
+  for(Int i = 0; i< m_pchDepthReconFileList.size(); i++ )
+  {
+    if ( m_pchDepthReconFileList[i] != NULL )
+      free (m_pchDepthReconFileList[i]);
+  }
+  if (m_pchBitstreamFile != NULL)
+    free (m_pchBitstreamFile) ;
+#if FLEX_CODING_ORDER_M23723
+  if (m_pchMVCJointCodingOrder != NULL)
+  {
+    free(m_pchMVCJointCodingOrder) ;
+  }
+#endif
+#if HHI_VSO
+  if (  m_pchVSOConfig != NULL)
+    free (  m_pchVSOConfig );
+#endif
+
+ if ( m_pchCameraParameterFile != NULL )
+   free ( m_pchCameraParameterFile ); 
+
+ if ( m_pchBaseViewCameraNumbers != NULL )
+   free ( m_pchBaseViewCameraNumbers ); 
+
+ if ( m_pchdQPFile      != NULL ) 
+   free ( m_pchdQPFile      );
+
+ if ( m_pchColumnWidth  != NULL ) 
+   free ( m_pchColumnWidth  );
+
+ if ( m_pchRowHeight    != NULL ) 
+   free ( m_pchRowHeight    );
+
+ if ( m_scalingListFile != NULL ) 
+   free ( m_scalingListFile );
+
+
+}
+
+Void TAppEncCfg::create()
+{
+}
+
+Void TAppEncCfg::destroy()
+{
+}
+
+std::istringstream &operator>>( std::istringstream &in, GOPEntryMvc &entry )     //input
+{
+  in>>entry.m_sliceType;
+  in>>entry.m_POC;
+  in>>entry.m_QPOffset;
+  in>>entry.m_QPFactor;
+  in>>entry.m_temporalId;
+  in>>entry.m_numRefPicsActive;
+  in>>entry.m_refPic;
+  in>>entry.m_numRefPics;
+  for ( Int i = 0; i < entry.m_numRefPics; i++ )
+  {
+    in>>entry.m_referencePics[i];
+  }
+  in>>entry.m_interRPSPrediction;
+  if (entry.m_interRPSPrediction)
+  {
+    in>>entry.m_deltaRIdxMinus1;
+    in>>entry.m_deltaRPS;
+    in>>entry.m_numRefIdc;
+    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
+    {
+      in>>entry.m_refIdc[i];
+    }
+  }
+  in>>entry.m_numInterViewRefPics;
+  for( Int i = 0; i < entry.m_numInterViewRefPics; i++ )
+  {
+    in>>entry.m_interViewRefs[i];
+  }
+  for( Int i = 0; i < entry.m_numInterViewRefPics; i++ )
+  {
+    in>>entry.m_interViewRefPosL0[i];
+  }
+  for( Int i = 0; i < entry.m_numInterViewRefPics; i++ )
+  {
+    in>>entry.m_interViewRefPosL1[i];
+  }
+  return in;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  argc        number of arguments
+    \param  argv        array of arguments
+    \retval             true when success
+ */
+Bool TAppEncCfg::parseCfg( Int argc, Char* argv[] )
+{
+  bool do_help = false;
+  
+  string cfg_BitstreamFile;
+  string cfg_dQPFile;
+  string cfg_ColumnWidth;
+  string cfg_RowHeight;
+  string cfg_ScalingListFile;
+
+ #if FLEX_CODING_ORDER_M23723
+  string cfg_JointCodingOrdering;
+#endif
+
+  po::Options opts;
+  opts.addOptions()
+  ("help", do_help, false, "this help text")
+  ("c", po::parseConfigFile, "configuration file name")
+  
+  /* File, I/O and source parameters */
+  ("InputFile_%d,i_%d",       m_pchInputFileList,       (char *) 0 , MAX_VIEW_NUM ,   "original Yuv input file name %d")
+  ("DepthInputFile_%d,di_%d", m_pchDepthInputFileList,  (char *) 0 , MAX_VIEW_NUM ,   "original Yuv depth input file name %d")
+  ("ReconFile_%d,o_%d",       m_pchReconFileList,       (char *) 0 , MAX_VIEW_NUM ,   "reconstructed Yuv output file name %d")
+  ("DepthReconFile_%d,do_%d", m_pchDepthReconFileList,  (char *) 0 , MAX_VIEW_NUM ,   "reconstructed Yuv depth output file name %d")
+  ("BitstreamFile,b",         cfg_BitstreamFile,        string(""),                   "bitstream output file name")
+  ("CodeDepthMaps",           m_bUsingDepthMaps,        false,                        "Encode depth maps" )
+  ("CodedCamParsPrecision",   m_iCodedCamParPrecision,  STD_CAM_PARAMETERS_PRECISION, "precision for coding of camera parameters (in units of 2^(-x) luma samples)" )
+  ("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")
+  ("SourceWidth,-wdt",        m_iSourceWidth,           0,                            "Source picture width")
+  ("SourceHeight,-hgt",       m_iSourceHeight,          0,                            "Source picture height")
+  ("CroppingMode",            m_croppingMode,           0,                            "Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping")
+  ("CropLeft",                m_cropLeft,               0,                            "Left cropping/padding for cropping mode 3")
+  ("CropRight",               m_cropRight,              0,                            "Right cropping/padding for cropping mode 3")
+  ("CropTop",                 m_cropTop,                0,                            "Top cropping/padding for cropping mode 3")
+  ("CropBottom",              m_cropBottom,             0,                            "Bottom cropping/padding for cropping mode 3")
+  ("HorizontalPadding,-pdx",  m_aiPad[0],               0,                            "horizontal source padding for cropping mode 2")
+  ("VerticalPadding,-pdy",    m_aiPad[1],               0,                            "vertical source padding for cropping mode 2")
+  ("InputBitDepth",         m_uiInputBitDepth, 8u, "bit-depth of input file")
+  ("BitDepth",              m_uiInputBitDepth, 8u, "deprecated alias of InputBitDepth")
+  ("OutputBitDepth",        m_uiOutputBitDepth, 0u, "bit-depth of output file")
+  ("InternalBitDepth",      m_uiInternalBitDepth, 0u, "Internal bit-depth (BitDepth+BitIncrement)")
+  ("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_iFrameToBeEncoded, 0, "number of frames to be encoded (default=all)")
+  ("FrameToBeEncoded",      m_iFrameToBeEncoded, 0, "deprecated alias of FramesToBeEncoded")
+  
+  ("NumberOfViews",         m_iNumberOfViews,    0, "Number of views")
+#if FLEX_CODING_ORDER_M23723
+  ("FCO",               m_b3DVFlexOrder,   false, "flexible coding order flag" )
+  ("FCOCodingOrder",   cfg_JointCodingOrdering,  string(""), "The coding order for joint texture-depth coding")
+#endif
+  /* Unit definition parameters */
+  ("MaxCUWidth",          m_uiMaxCUWidth,  64u)
+  ("MaxCUHeight",         m_uiMaxCUHeight, 64u)
+  /* todo: remove defaults from MaxCUSize */
+  ("MaxCUSize,s",         m_uiMaxCUWidth,  64u, "max CU size")
+  ("MaxCUSize,s",         m_uiMaxCUHeight, 64u, "max CU size")
+  ("MaxPartitionDepth,h", m_uiMaxCUDepth,   4u, "CU depth")
+  
+  ("QuadtreeTULog2MaxSize", m_uiQuadtreeTULog2MaxSize, 6u)
+  ("QuadtreeTULog2MinSize", m_uiQuadtreeTULog2MinSize, 2u)
+  
+  ("QuadtreeTUMaxDepthIntra", m_uiQuadtreeTUMaxDepthIntra, 1u)
+  ("QuadtreeTUMaxDepthInter", m_uiQuadtreeTUMaxDepthInter, 2u)
+  
+  /* Coding structure paramters */
+  ("IntraPeriod,-ip",m_iIntraPeriod, -1, "intra period in frames, (-1: only first frame)")
+  ("DecodingRefreshType,-dr",m_iDecodingRefreshType, 0, "intra refresh, (0:none 1:CRA 2:IDR)")
+  ("GOPSize,g",      m_iGOPSize,      1, "GOP size of temporal structure")
+  ("ListCombination,-lc", m_bUseLComb, true, "combined reference list flag for uni-prediction in B-slices")
+  ("LCModification", m_bLCMod, false, "enables signalling of combined reference list derivation")
+  ("DisableInter4x4", m_bDisInter4x4, true, "Disable Inter 4x4")
+  ("NSQT", m_enableNSQT, true, "Enable non-square transforms")
+  ("AMP", m_enableAMP, true, "Enable asymmetric motion partitions")
+  /* motion options */
+  ("FastSearch", m_iFastSearch, 1, "0:Full search  1:Diamond  2:PMVFAST")
+  ("SearchRange,-sr",m_iSearchRange, 96, "motion search range")
+#if DV_V_RESTRICTION_B0037
+  ("DisparitySearchRangeRestriction",m_bUseDisparitySearchRangeRestriction, false, "restrict disparity search range")
+  ("VerticalDisparitySearchRange",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")
+  
+  /* Quantization parameters */
+  ("QP,q",          m_adQP,     std::vector<double>(1,32), "Qp value, if value is float, QP is switched once during encoding, if two values are given the second is used for depth")
+  ("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")
+
+    ("ChromaQpOffset,   -cqo",   m_iChromaQpOffset,           0, "ChromaQpOffset")
+    ("ChromaQpOffset2nd,-cqo2",  m_iChromaQpOffset2nd,        0, "ChromaQpOffset2nd")
+
+#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_abUseRDOQ, std::vector<Bool>(1,true), "Enable RDOQ")
+  ("TemporalLayerQPOffset_L0,-tq0", m_aiTLayerQPOffset[0], MAX_QP + 1, "QP offset of temporal layer 0")
+  ("TemporalLayerQPOffset_L1,-tq1", m_aiTLayerQPOffset[1], MAX_QP + 1, "QP offset of temporal layer 1")
+  ("TemporalLayerQPOffset_L2,-tq2", m_aiTLayerQPOffset[2], MAX_QP + 1, "QP offset of temporal layer 2")
+  ("TemporalLayerQPOffset_L3,-tq3", m_aiTLayerQPOffset[3], MAX_QP + 1, "QP offset of temporal layer 3")
+  
+
+  /* Entropy coding parameters */
+  ("SBACRD", m_bUseSBACRD, true, "SBAC based RD estimation")
+  
+  /* Deblocking filter parameters */
+  ("LoopFilterDisable", m_abLoopFilterDisable, std::vector<Bool>(1,false), "Disables LoopFilter")
+
+  ("LoopFilterOffsetInAPS", m_loopFilterOffsetInAPS, false)
+  ("LoopFilterBetaOffset_div2", m_loopFilterBetaOffsetDiv2, 0 )
+  ("LoopFilterTcOffset_div2", m_loopFilterTcOffsetDiv2, 0 )
+#if LGE_ILLUCOMP_B0045
+#if LGE_ILLUCOMP_DEPTH_C0046
+  ("IlluCompEnable", m_abUseIC, std::vector<Bool>(2, true), "Enable illumination compensation for inter-view prediction")
+#else
+  ("IlluCompEnable",                  m_bUseIC                  , true         , "Use illumination compensation for inter-view prediction" )
+#endif
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  ("IVSEnable",                       m_bUseIVS                 , true         , "Use inter-view vector scaling" )
+#endif
+  ("DeblockingFilterControlPresent", m_DeblockingFilterControlPresent, true)
+
+  /* Camera Paremetes */
+  ("CameraParameterFile,cpf", m_pchCameraParameterFile,    (Char *) 0, "Camera Parameter File Name")
+#if QC_MVHEVC_B0046
+  ("BaseViewCameraNumbers" ,  m_aiVId,     std::vector<Int>(1, MAX_VIEW_NUM), "Numbers of base views")
+#endif
+  ("BaseViewCameraNumbers" ,  m_pchBaseViewCameraNumbers,  (Char *) 0, "Numbers of base views")
+
+  /* View Synthesis Optimization */
+
+#if HHI_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")
+
+#if HHI_VSO_LS_TABLE_M23714
+  ("VSOLSTable",                      m_bVSOLSTable             , true          , "Depth QP dependent video/depth rate allocation by Lagrange multiplier" )    
+#endif
+
+#if SAIT_VSO_EST_A0033
+  ("UseEstimatedVSD",                 m_bUseEstimatedVSD        , true          , "Model based VSD estimation instead of rendering based for some encoder decisions" )      
+#endif
+#if LGE_VSO_EARLY_SKIP_A0093
+  ("VSOEarlySkip",                    m_bVSOEarlySkip           , true          , "Early skip of VSO computation if synthesis error assumed to be zero" )      
+#endif
+  ("ForceLambdaScaleVSO",             m_bForceLambdaScaleVSO    , false         , "Force using Lambda Scale VSO also in non-VSO-Mode")
+#if HHI_VSO_DIST_INT
+  ("AllowNegDist",                    m_bAllowNegDist           , true          , "Allow negative Distortion in VSO")
+#endif
+#if LGE_WVSO_A0119
+  ("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
+
+#if H3D_QTL
+  ("QTLPC",                           m_bUseQTLPC               , true         , "Use depth Quadtree Limitation + Predictive Coding" )
+#endif
+
+#endif
+
+#if DEPTH_MAP_GENERATION
+  ("PredDepthMapGen",  m_uiPredDepthMapGeneration, (UInt)0, "generation of prediction depth maps for motion data prediction" )
+#endif
+#if H3D_IVMP
+  ("MultiviewMvPred",  m_uiMultiviewMvPredMode,    (UInt)0, "usage of predicted depth maps" )
+  ("MultiviewMvRegMode",        m_uiMultiviewMvRegMode,         (UInt)0, "regularization mode for multiview motion vectors" )
+  ("MultiviewMvRegLambdaScale", m_dMultiviewMvRegLambdaScale, (Double)0, "lambda scale for multiview motion vector regularization" )
+#endif
+#if H3D_IVRP
+  ("MultiviewResPred", m_uiMultiviewResPredMode,   (UInt)0, "usage of inter-view residual prediction" )
+#endif
+
+  /* Coding tools */
+  ("LMChroma", m_bUseLMChroma, true, "intra chroma prediction based on recontructed luma")
+
+  ("ALF", m_abUseALF, std::vector<Bool>(1,true), "Enables ALF")
+  ("SAO", m_abUseSAO, std::vector<Bool>(1, true), "SAO")
+  ("MaxNumOffsetsPerPic", m_maxNumOffsetsPerPic, 2048, "2048: default")   
+  ("SAOInterleaving", m_saoInterleavingFlag, false, "0: SAO Picture Mode, 1: SAO Interleaving ")   
+
+  ("ALFEncodePassReduction", m_iALFEncodePassReduction, 0, "0:Original 16-pass, 1: 1-pass, 2: 2-pass encoding")
+
+  ("ALFMaxNumFilter,-ALFMNF", m_iALFMaxNumberFilters, 16, "16: No Constrained, 1-15: Constrained max number of filter")
+  ("ALFParamInSlice", m_bALFParamInSlice, false, "ALF parameters in 0: APS, 1: slice header")
+  ("ALFPicBasedEncode", m_bALFPicBasedEncode, true, "ALF picture-based encoding 0: false, 1: true")
+
+    ("SliceMode",            m_iSliceMode,           0, "0: Disable all Recon slice limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes")
+    ("SliceArgument",        m_iSliceArgument,       0, "if SliceMode==1 SliceArgument represents max # of LCUs. if SliceMode==2 SliceArgument represents max # of bytes.")
+    ("EntropySliceMode",     m_iEntropySliceMode,    0, "0: Disable all entropy slice limits, 1: Enforce max # of LCUs, 2: Enforce constraint based entropy slices")
+    ("EntropySliceArgument", m_iEntropySliceArgument,0, "if EntropySliceMode==1 SliceArgument represents max # of LCUs. if EntropySliceMode==2 EntropySliceArgument represents max # of bins.")
+    ("SliceGranularity",     m_iSliceGranularity,    0, "0: Slices always end at LCU borders. 1-3: slices may end at a depth of 1-3 below LCU level.")
+    ("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)
+#if LOSSLESS_CODING
+    ("LosslessCuEnabled", m_useLossless, false)
+#endif
+    ("weighted_pred_flag,-wpP",     m_bUseWeightPred, false, "weighted prediction flag (P-Slices)")
+    ("weighted_bipred_idc,-wpBidc", m_uiBiPredIdc,    0u,    "weighted bipred idc (B-Slices)")
+    ("TileInfoPresentFlag",         m_iColumnRowInfoPresent,         1,          "0: tiles parameters are NOT present in the PPS. 1: tiles parameters are present in the PPS")
+    ("UniformSpacingIdc",           m_iUniformSpacingIdr,            0,          "Indicates if the column and row boundaries are distributed uniformly")
+    ("NumTileColumnsMinus1",        m_iNumColumnsMinus1,             0,          "Number of columns in a picture minus 1")
+    ("ColumnWidthArray",            cfg_ColumnWidth,                 string(""), "Array containing ColumnWidth values in units of LCU")
+    ("NumTileRowsMinus1",           m_iNumRowsMinus1,                0,          "Number of rows in a picture minus 1")
+    ("RowHeightArray",              cfg_RowHeight,                   string(""), "Array containing RowHeight values in units of LCU")
+    ("TileLocationInSliceHeaderFlag", m_iTileLocationInSliceHeaderFlag, 0,       "0: Disable transmission of tile location in slice header. 1: Transmit tile locations in slice header.")
+    ("TileMarkerFlag",                m_iTileMarkerFlag,                0,       "0: Disable transmission of lightweight tile marker. 1: Transmit light weight tile marker.")
+    ("MaxTileMarkerEntryPoints",    m_iMaxTileMarkerEntryPoints,    4,       "Maximum number of uniformly-spaced tile entry points (using light weigh tile markers). Default=4. If number of tiles < MaxTileMarkerEntryPoints then all tiles have entry points.")
+    ("TileControlPresentFlag",       m_iTileBehaviorControlPresentFlag,         1,          "0: tiles behavior control parameters are NOT present in the PPS. 1: tiles behavior control parameters are present in the PPS")
+    ("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")
+    ("WaveFrontFlush",              m_iWaveFrontFlush,               0,          "Flush and terminate CABAC coding for each LCU line")
+    ("WaveFrontSubstreams",         m_iWaveFrontSubstreams,          1,          "# coded substreams wanted; per tile if TileBoundaryIndependenceIdc is 1, otherwise per frame")
+    ("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)
+    ("SignHideThreshold,-TSIG",          m_signHidingThreshold,         4)
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  ("DMM",                         m_bUseDMM,                       false,      "depth model modes flag")
+#endif
+
+  /* Misc. */
+  ("SEIpictureDigest", m_pictureDigestEnabled, true, "Control generation of picture_digest SEI messages\n"
+                                              "\t1: use MD5\n"
+                                              "\t0: disable")
+
+#if TMVP_DEPTH_SWITCH
+  ("TMVP", m_enableTMVP, std::vector<Bool>(1,true), "Enable TMVP" )
+#else
+  ("TMVP", m_enableTMVP, true, "Enable TMVP" )
+#endif
+
+  ("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")
+#if HHI_INTERVIEW_SKIP
+  ("InterViewSkip",  m_bInterViewSkip,    false, "usage of interview skip" )
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  ("InterViewSkipLambdaScale",  m_dInterViewSkipLambdaScale,    (Double)8, "lambda scale for interview skip" )
+#endif
+#endif
+  /* Compatability with old style -1 FOO or -0 FOO options. */
+  ("1", doOldStyleCmdlineOn, "turn option <name> on")
+  ("0", doOldStyleCmdlineOff, "turn option <name> off")
+#if HHI_MPI
+  ("MVI", m_bUseMVI, false, "use motion vector inheritance for depth map coding")
+#endif
+#if RWTH_SDC_DLT_B0036
+  ("DLT", m_bUseDLT, true, "use depth lookup table for depth map coding")
+  ("SDC", m_bUseSDC, true, "use simplified depth coding tree")
+#endif
+  ;
+  
+  // parse coding structure
+  for( Int k = 0; k < MAX_VIEW_NUM; k++ )
+  {
+    if( k == 0 )
+    {
+      for( Int i = 1; i < MAX_GOP + 1; i++ ) 
+      {
+        std::ostringstream cOSS;
+        cOSS<<"Frame"<<i;
+        opts.addOptions()( cOSS.str(), m_GOPListsMvc[k][i-1], GOPEntryMvc() );
+      }
+    }
+    else
+    {
+      std::ostringstream cOSS1;
+      cOSS1<<"FrameI"<<"_v"<<k;
+      opts.addOptions()(cOSS1.str(), m_GOPListsMvc[k][MAX_GOP], GOPEntryMvc());
+
+      for( Int i = 1; i < MAX_GOP + 1; i++ ) 
+      {
+        std::ostringstream cOSS2;
+        cOSS2<<"Frame"<<i<<"_v"<<k;
+        opts.addOptions()(cOSS2.str(), m_GOPListsMvc[k][i-1], GOPEntryMvc());
+      }
+    }
+  }
+
+  po::setDefaults(opts);
+  const list<const char*>& argv_unhandled = po::scanArgv(opts, argc, (const char**) argv);
+
+  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);
+    xPrintUsage();
+    return false;
+  }
+  
+  /*
+   * Set any derived parameters
+   */
+  /* convert std::string to c string for compatability */
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
+#if FLEX_CODING_ORDER_M23723
+  m_pchMVCJointCodingOrder= cfg_JointCodingOrdering.empty()?NULL:strdup(cfg_JointCodingOrdering.c_str());
+  // If flexible order is enabled and if depth comes before the texture for a view, disable VSO
+#if HHI_VSO && DISABLE_FCO_FOR_VSO
+  Bool depthComesFirst = false;
+  int iter = 0;
+  if ( m_b3DVFlexOrder )
+  {
+    for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+    {
+      iter = 0; 
+      for ( Int ii=1; ii<12; ii+=2 )
+      {
+        Int iViewIdxCfg = (Int)(m_pchMVCJointCodingOrder[ii]-'0');
+        if ( iViewIdxCfg == iViewIdx )
+        {
+          iter ++; 
+          if ( m_pchMVCJointCodingOrder[ii-1]=='D' ) // depth comes first for this view
+          {
+            if(iter == 1)
+           { 
+            depthComesFirst = true;
+            break;
+           }
+          }
+          else
+          {
+            assert(m_pchMVCJointCodingOrder[ii-1]=='T');
+          }
+        }
+      }
+    }
+  }
+  if (depthComesFirst)
+  {
+    m_bUseVSO = false;
+  }
+#endif
+#endif
+  m_pchColumnWidth = cfg_ColumnWidth.empty() ? NULL: strdup(cfg_ColumnWidth.c_str());
+  m_pchRowHeight = cfg_RowHeight.empty() ? NULL : strdup(cfg_RowHeight.c_str());
+  m_scalingListFile = cfg_ScalingListFile.empty() ? NULL : strdup(cfg_ScalingListFile.c_str());
+  
+  if ( m_bUsingDepthMaps )
+  {
+    for(Int i = 0; i < m_pchDepthReconFileList.size() ; i++)
+    {
+      if ((m_pchDepthInputFileList[i] != NULL) && (m_pchReconFileList[i] != NULL) && (i < m_iNumberOfViews) )
+      {
+        if (m_pchDepthReconFileList[i] == NULL )
+        {
+          xAppendToFileNameEnd( m_pchReconFileList[i], "_depth", m_pchDepthReconFileList[i] );
+        }
+      }
+      else
+      {
+        m_pchDepthReconFileList[i] = NULL;
+      }
+    };
+  }
+  if ( m_adQP.size() < 2 )
+  {
+    m_adQP.push_back( m_adQP[0] );
+  };
+  for (UInt uiK = 0; uiK < m_adQP.size(); uiK++)
+  {
+    m_aiQP.push_back( (Int)( m_adQP[uiK] ) );
+  }
+
+  switch (m_croppingMode)
+  {
+  case 0:
+    {
+      // no cropping or padding
+      m_cropLeft = m_cropRight = m_cropTop = m_cropBottom = 0;
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  case 1:
+    {
+      // automatic padding to minimum CU size
+      Int minCuSize = m_uiMaxCUHeight >> (m_uiMaxCUDepth - 1);
+      if (m_iSourceWidth % minCuSize)
+      {
+        m_aiPad[0] = m_cropRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
+        m_iSourceWidth  += m_cropRight;
+      }
+      if (m_iSourceHeight % minCuSize)
+      {
+        m_aiPad[1] = m_cropBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
+        m_iSourceHeight += m_cropBottom;
+      }
+      break;
+    }
+  case 2:
+    {
+      //padding
+      m_iSourceWidth  += m_aiPad[0];
+      m_iSourceHeight += m_aiPad[1];
+      m_cropRight  = m_aiPad[0];
+      m_cropBottom = m_aiPad[1];
+      break;
+    }
+  case 3:
+    {
+      // cropping
+      if ((m_cropLeft == 0) && (m_cropRight == 0) && (m_cropTop == 0) && (m_cropBottom == 0))
+      {
+        fprintf(stderr, "Warning: Cropping enabled, but all cropping parameters set to zero\n");
+      }
+      if ((m_aiPad[1] != 0) || (m_aiPad[0]!=0))
+      {
+        fprintf(stderr, "Warning: Cropping enabled, padding parameters will be ignored\n");
+      }
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  }
+  
+  // allocate slice-based dQP values
+  m_aidQP = new Int[ m_iFrameToBeEncoded + m_iGOPSize + 1 ];
+  m_aidQPdepth =  new Int[ m_iFrameToBeEncoded + m_iGOPSize + 1 ];
+  ::memset( m_aidQP, 0, sizeof(Int)*( m_iFrameToBeEncoded + m_iGOPSize + 1 ) );
+  ::memset( m_aidQPdepth, 0, sizeof(Int)*( m_iFrameToBeEncoded + 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
+  m_aiQP[0] = (Int)( m_adQP[0] );
+  if ( m_aiQP[0] < m_adQP[0] )
+  {
+    Int iSwitchPOC = (Int)( m_iFrameToBeEncoded - (m_adQP[0] - m_aiQP[0])*m_iFrameToBeEncoded + 0.5 );
+    
+    iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
+    for ( Int i=iSwitchPOC; i<m_iFrameToBeEncoded + m_iGOPSize + 1; i++ )
+    {
+      m_aidQP[i] = 1;
+    }
+  }
+
+  m_aiQP[1] = (Int)( m_adQP[1] );
+  if ( m_aiQP[1] < m_adQP[1] )
+  {
+    Int iSwitchPOC = (Int)( m_iFrameToBeEncoded - (m_adQP[1] - m_aiQP[1])*m_iFrameToBeEncoded + 0.5 );
+
+    iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
+    for ( Int i=iSwitchPOC; i<m_iFrameToBeEncoded + m_iGOPSize + 1; i++ )
+    {
+      m_aidQPdepth[i] = 1;
+    }
+  }
+
+  // reading external dQP description from file
+  if ( m_pchdQPFile )
+  {
+    FILE* fpt=fopen( m_pchdQPFile, "r" );
+    if ( fpt )
+    {
+      Int iValue;
+      Int iPOC = 0;
+      while ( iPOC < m_iFrameToBeEncoded )
+      {
+        if ( fscanf(fpt, "%d", &iValue ) == EOF ) break;
+        m_aidQP[ iPOC ] = iValue;
+        iPOC++;
+      }
+      fclose(fpt);
+    }
+  }
+
+#if HHI_VSO
+  m_bUseVSO = m_bUseVSO && m_bUsingDepthMaps && (m_uiVSOMode != 0);
+#endif
+
+#if LGE_WVSO_A0119
+  m_bUseWVSO = m_bUseVSO && m_bUseWVSO && m_bUsingDepthMaps;
+#endif
+  xCleanUpVectors();
+
+
+#if TMVP_DEPTH_SWITCH
+  if ( m_enableTMVP.size() < 2)
+  {
+    m_enableTMVP.push_back( m_enableTMVP[0]  );
+  }
+#endif
+ 
+
+#if HHI_VSO
+  if ( m_abUseALF .size() < 2)
+    m_abUseALF .push_back( m_bUseVSO ? false : m_abUseALF[0]  );
+
+  if ( m_abUseRDOQ.size() < 2)
+    m_abUseRDOQ.push_back( m_bUseVSO ? true : m_abUseRDOQ[0] );
+
+  if ( m_abLoopFilterDisable.size() < 2)
+    m_abLoopFilterDisable.push_back( m_bUseVSO ? true : m_abLoopFilterDisable[0]  );
+
+  if (m_abUseSAO.size() < 2)
+    m_abUseSAO.push_back            ( m_bUseVSO ? false : m_abUseSAO[0] );
+#else
+  if ( m_abUseALF .size() < 2)
+    m_abUseALF .push_back( m_abUseALF[0]  );
+
+  if ( m_abUseRDOQ.size() < 2)
+    m_abUseRDOQ.push_back( m_abUseRDOQ[0] );
+
+  if ( m_abLoopFilterDisable.size() < 2)
+    m_abLoopFilterDisable.push_back( m_abLoopFilterDisable[0]  );
+
+  if (m_abUseSAO.size() < 2)
+    m_abUseSAO.push_back            ( m_abUseSAO[0] );
+#endif
+
+#if HHI_VSO
+
+#if HHI_VSO_LS_TABLE_M23714
+  // 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  
+  }; 
+  if ( m_bVSOLSTable )
+  {
+    AOT( (m_aiQP[1] < 0) || (m_aiQP[1] > 51));
+    m_dLambdaScaleVSO *= adLambdaScaleTable[m_aiQP[1]]; 
+  }
+#endif
+#endif
+
+ // set global variables
+  xSetGlobal();
+
+  // read and check camera parameters
+#if HHI_VSO
+if ( m_bUseVSO && m_uiVSOMode == 4)
+{
+  m_cRenModStrParser.setString( m_iNumberOfViews, m_pchVSOConfig );
+  m_cCameraData     .init     ( (UInt)m_iNumberOfViews,
+                                      m_uiInputBitDepth,
+                                (UInt)m_iCodedCamParPrecision,
+                                      m_FrameSkip,
+                                (UInt)m_iFrameToBeEncoded,
+                                      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_uiInputBitDepth,
+                                (UInt)m_iCodedCamParPrecision,
+                                      m_FrameSkip,
+                                (UInt)m_iFrameToBeEncoded,
+                                      m_pchCameraParameterFile,
+                                      m_pchBaseViewCameraNumbers,
+                                      m_pchVSOConfig,
+                                      NULL,
+                                      LOG2_DISP_PREC_LUT );
+}
+else
+{
+  m_cCameraData     .init     ( (UInt)m_iNumberOfViews,
+    m_uiInputBitDepth,
+    (UInt)m_iCodedCamParPrecision,
+    m_FrameSkip,
+    (UInt)m_iFrameToBeEncoded,
+    m_pchCameraParameterFile,
+    m_pchBaseViewCameraNumbers,
+    NULL,
+    NULL,
+    LOG2_DISP_PREC_LUT );
+}
+#else
+#if !QC_MVHEVC_B0046
+  m_cCameraData     .init     ( (UInt)m_iNumberOfViews,
+    m_uiInputBitDepth,
+    (UInt)m_iCodedCamParPrecision,
+    m_FrameSkip,
+    (UInt)m_iFrameToBeEncoded,
+    m_pchCameraParameterFile,
+    m_pchBaseViewCameraNumbers,
+    NULL,
+    NULL,
+    LOG2_DISP_PREC_LUT );
+#endif
+#endif
+
+
+  // check validity of input parameters
+  xCheckParameter();
+#if !QC_MVHEVC_B0046
+  m_cCameraData.check( false, true );
+#endif
+  // print-out parameters
+  xPrintParameter();
+  
+  return true;
+}
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+Bool confirmPara(Bool bflag, const char* message);
+
+Void TAppEncCfg::xCheckParameter()
+{
+  bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+  // check range of parameters
+  xConfirmPara( m_uiInputBitDepth < 8,                                                      "InputBitDepth must be at least 8" );
+  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
+  xConfirmPara( m_iFrameToBeEncoded <= 0,                                                   "Total Number Of Frames encoded must be more than 0" );
+  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" );
+  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < m_iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
+  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 2,                   "Decoding Refresh Type must be equal to 0, 1 or 2" );
+  xConfirmPara( m_aiQP[0] < -6 * ((Int)m_uiInternalBitDepth - 8) || m_aiQP[0] > 51,         "QP exceeds supported range (-QpBDOffsety to 51)" );
+  if ( m_aiQP.size() >= 2 )
+  {
+    xConfirmPara( m_aiQP[1] < -6 * ((Int)m_uiInternalBitDepth - 8) || m_aiQP[1] > 51,       "QP depth exceeds supported range (-QpBDOffsety to 51)" );
+  }
+  xConfirmPara( m_iALFEncodePassReduction < 0 || m_iALFEncodePassReduction > 2,             "ALFEncodePassReduction must be equal to 0, 1 or 2");
+  xConfirmPara( m_iALFMaxNumberFilters < 1,                                                 "ALFMaxNumFilter should be larger than 1");  
+  xConfirmPara( m_loopFilterBetaOffsetDiv2 < -13 || m_loopFilterBetaOffsetDiv2 > 13,          "Loop Filter Beta Offset div. 2 exceeds supported range (-13 to 13)");
+  xConfirmPara( m_loopFilterTcOffsetDiv2 < -13 || m_loopFilterTcOffsetDiv2 > 13,              "Loop Filter Tc Offset div. 2 exceeds supported range (-13 to 13)");
+  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" );
+#if DV_V_RESTRICTION_B0037
+  xConfirmPara( m_iVerticalDisparitySearchRange <= 0 ,                                      "Vertical Disparity Search Range must be more than 0" );
+#endif
+  xConfirmPara( m_bipredSearchRange < 0 ,                                                   "Search Range must be more than 0" );
+  xConfirmPara( m_iMaxDeltaQP > 7,                                                          "Absolute Delta QP exceeds supported range (0 to 7)" );
+  xConfirmPara( m_iMaxCuDQPDepth > m_uiMaxCUDepth - 1,                                          "Absolute depth for a minimum CuDQP exceeds maximum coding unit depth" );
+
+  xConfirmPara( m_iChromaQpOffset    < -12,   "Min. Chroma Qp Offset is -12"     );
+  xConfirmPara( m_iChromaQpOffset    >  12,   "Max. Chroma Qp Offset is  12"     );
+  xConfirmPara( m_iChromaQpOffset2nd < -12,   "Min. Chroma Qp Offset 2nd is -12" );
+  xConfirmPara( m_iChromaQpOffset2nd >  12,   "Max. Chroma Qp Offset 2nd is  12" );
+
+  xConfirmPara( m_iQPAdaptationRange <= 0,                                                  "QP Adaptation Range must be more than 0" );
+  if (m_iDecodingRefreshType == 2)
+  {
+    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+  }
+  xConfirmPara( (m_uiMaxCUWidth  >> m_uiMaxCUDepth) < 4,                                    "Minimum partition width size should be larger than or equal to 8");
+  xConfirmPara( (m_uiMaxCUHeight >> m_uiMaxCUDepth) < 4,                                    "Minimum partition height size should be larger than or equal to 8");
+  xConfirmPara( m_uiMaxCUWidth < 16,                                                        "Maximum partition width size should be larger than or equal to 16");
+  xConfirmPara( m_uiMaxCUHeight < 16,                                                       "Maximum partition height size should be larger than or equal to 16");
+  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_uiQuadtreeTULog2MinSize > 5,                                        "QuadtreeTULog2MinSize must be 5 or smaller.");
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize < 2,                                        "QuadtreeTULog2MaxSize must be 2 or greater.");
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize > 5,                                        "QuadtreeTULog2MaxSize must be 5 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( m_uiQuadtreeTUMaxDepthInter < 1,                                                         "QuadtreeTUMaxDepthInter must be greater than or equal to 1" );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthInter > m_uiQuadtreeTULog2MaxSize - m_uiQuadtreeTULog2MinSize + 1, "QuadtreeTUMaxDepthInter must be less than or equal to the difference between QuadtreeTULog2MaxSize and QuadtreeTULog2MinSize plus 1" );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthIntra < 1,                                                         "QuadtreeTUMaxDepthIntra must be greater than or equal to 1" );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthIntra > m_uiQuadtreeTULog2MaxSize - m_uiQuadtreeTULog2MinSize + 1, "QuadtreeTUMaxDepthIntra must be less than or equal to the difference between QuadtreeTULog2MaxSize and QuadtreeTULog2MinSize plus 1" );
+
+  xConfirmPara( m_iNumberOfViews > MAX_VIEW_NUM ,                                     "NumberOfViews must be less than or equal to MAX_VIEW_NUM");
+  xConfirmPara    ( Int( m_pchInputFileList.size() ) < m_iNumberOfViews,              "Number of InputFiles must be greater than or equal to NumberOfViews" );
+  xConfirmPara    ( Int( m_pchReconFileList.size() ) < m_iNumberOfViews,              "Number of ReconFiles must be greater than or equal to NumberOfViews" );
+  xConfirmPara    ( m_iCodedCamParPrecision < 0 || m_iCodedCamParPrecision > 5,       "CodedCamParsPrecision must be in range of 0..5" );
+#if HHI_INTERVIEW_SKIP
+  xConfirmPara    ( m_bInterViewSkip && !m_bUsingDepthMaps,                       "RenderingSkipMode requires CodeDepthMaps = 1" );
+#endif
+#if DEPTH_MAP_GENERATION
+  xConfirmPara    ( m_uiPredDepthMapGeneration > 2,                                   "PredDepthMapGen must be less than or equal to 2" );
+  xConfirmPara    ( m_uiPredDepthMapGeneration >= 2 && !m_bUsingDepthMaps,            "PredDepthMapGen >= 2 requires CodeDepthMaps = 1" );
+#endif
+#if H3D_IVMP
+  xConfirmPara    ( m_uiMultiviewMvPredMode > 7,                                      "MultiviewMvPred must be less than or equal to 7" );
+  xConfirmPara    ( m_uiMultiviewMvPredMode > 0 && m_uiPredDepthMapGeneration == 0 ,  "MultiviewMvPred > 0 requires PredDepthMapGen > 0" );
+  xConfirmPara    ( m_uiMultiviewMvRegMode       > 1,                                 "MultiviewMvRegMode must be less than or equal to 1" );
+  xConfirmPara    ( m_dMultiviewMvRegLambdaScale < 0.0,                               "MultiviewMvRegLambdaScale must not be negative" );
+  if( m_uiMultiviewMvRegMode )
+  {
+    xConfirmPara  ( Int( m_pchDepthInputFileList.size() ) < m_iNumberOfViews,         "MultiviewMvRegMode > 0 requires the presence of input depth maps" );
+  }
+#endif
+#if H3D_IVRP
+  xConfirmPara    ( m_uiMultiviewResPredMode > 1,                                     "MultiviewResPred must be less than or equal to 1" );
+  xConfirmPara    ( m_uiMultiviewResPredMode > 0 && m_uiPredDepthMapGeneration == 0 , "MultiviewResPred > 0 requires PredDepthMapGen > 0" );
+#endif
+  if( m_bUsingDepthMaps )
+  {
+    xConfirmPara  ( Int( m_pchDepthInputFileList.size() ) < m_iNumberOfViews,         "Number of DepthInputFiles must be greater than or equal to NumberOfViews" );
+    xConfirmPara  ( Int( m_pchDepthReconFileList.size() ) < m_iNumberOfViews,         "Number of DepthReconFiles must be greater than or equal to NumberOfViews" );
+
+#if HHI_VSO
+    if( m_bUseVSO )
+    {
+      xConfirmPara( m_pchCameraParameterFile    == 0                             ,   "CameraParameterFile must be given");
+      xConfirmPara(   m_pchVSOConfig            == 0                             ,   "VSO Setup string 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_uiVSOMode > 4 ,                                                "VSO Mode must be less than 5");
+    }
+#endif
+  }
+#if ADAPTIVE_QP_SELECTION
+  xConfirmPara( m_bUseAdaptQpSelect == true && m_aiQP[0] < 0,                                              "AdaptiveQpSelection must be disabled when QP < 0.");
+  xConfirmPara( m_bUseAdaptQpSelect == true && m_aiQP[1] < 0,                                              "AdaptiveQpSelection must be disabled when QP < 0.");
+  xConfirmPara( m_bUseAdaptQpSelect == true && (m_iChromaQpOffset !=0 || m_iChromaQpOffset2nd != 0 ),  "AdaptiveQpSelection must be disabled when ChromaQpOffset is not equal to 0.");
+#endif
+
+  if( m_usePCM)
+  {
+    xConfirmPara(  m_uiPCMLog2MinSize < 3,                                      "PCMLog2MinSize must be 3 or greater.");
+    xConfirmPara(  m_uiPCMLog2MinSize > 5,                                      "PCMLog2MinSize must be 5 or smaller.");
+    xConfirmPara(  m_pcmLog2MaxSize > 5,                                        "PCMLog2MaxSize must be 5 or smaller.");
+    xConfirmPara(  m_pcmLog2MaxSize < m_uiPCMLog2MinSize,                       "PCMLog2MaxSize must be equal to or greater than m_uiPCMLog2MinSize.");
+  }
+
+  xConfirmPara( m_iSliceMode < 0 || m_iSliceMode > 3, "SliceMode exceeds supported range (0 to 3)" );
+  if (m_iSliceMode!=0)
+  {
+    xConfirmPara( m_iSliceArgument < 1 ,         "SliceArgument should be larger than or equal to 1" );
+  }
+  if (m_iSliceMode==3)
+  {
+    xConfirmPara( m_iSliceGranularity > 0 ,      "When SliceMode == 3 is chosen, the SliceGranularity must be 0" );
+  }
+  xConfirmPara( m_iEntropySliceMode < 0 || m_iEntropySliceMode > 2, "EntropySliceMode exceeds supported range (0 to 2)" );
+  if (m_iEntropySliceMode!=0)
+  {
+    xConfirmPara( m_iEntropySliceArgument < 1 ,         "EntropySliceArgument should be larger than or equal to 1" );
+  }
+  xConfirmPara( m_iSliceGranularity >= m_uiMaxCUDepth, "SliceGranularity must be smaller than maximum cu depth");
+  xConfirmPara( m_iSliceGranularity <0 || m_iSliceGranularity > 3, "SliceGranularity exceeds supported range (0 to 3)" );
+  xConfirmPara( m_iSliceGranularity > m_iMaxCuDQPDepth, "SliceGranularity must be smaller smaller than or equal to maximum dqp depth" );
+
+  bool tileFlag = (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0 );
+  xConfirmPara( tileFlag && m_iEntropySliceMode,            "Tile and Entropy Slice can not be applied together");
+  xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together");
+  xConfirmPara( m_iWaveFrontSynchro && m_iEntropySliceMode, "Wavefront and Entropy Slice can not be applied together");  
+
+  // max CU width and height should be power of 2
+  UInt ui = m_uiMaxCUWidth;
+  while(ui)
+  {
+    ui >>= 1;
+    if( (ui & 1) == 1)
+      xConfirmPara( ui != 1 , "Width should be 2^n");
+  }
+  ui = m_uiMaxCUHeight;
+  while(ui)
+  {
+    ui >>= 1;
+    if( (ui & 1) == 1)
+      xConfirmPara( ui != 1 , "Height should be 2^n");
+  }
+  
+  xConfirmPara( m_iWaveFrontSynchro < 0, "WaveFrontSynchro cannot be negative" );
+  xConfirmPara( m_iWaveFrontFlush < 0, "WaveFrontFlush 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" );
+
+#undef xConfirmPara
+  if (check_failed)
+  {
+    exit(EXIT_FAILURE);
+  }
+
+  xCheckCodingStructureMvc();
+}
+
+Void TAppEncCfg::xCheckCodingStructureMvc()
+{
+  bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+
+  // validate that POC of same frame is identical across multiple views
+  Bool bErrorMvePoc = false;
+  if( m_iNumberOfViews > 1 )
+  {
+    for( Int k = 1; k < m_iNumberOfViews; k++ )
+    {
+      for( Int i = 0; i < MAX_GOP; i++ )
+      {
+        if( m_GOPListsMvc[k][i].m_POC != m_GOPListsMvc[0][i].m_POC )
+        {
+          printf( "\nError: Frame%d_v%d POC %d is not identical to Frame%d POC\n", i, k, m_GOPListsMvc[k][i].m_POC, i );
+          bErrorMvePoc = true;
+        }
+      }
+    }
+  }
+  xConfirmPara( bErrorMvePoc,  "Invalid inter-view POC structure given" );
+
+  // validate that baseview has no inter-view refs 
+  Bool bErrorIvpBase = false;
+  for( Int i = 0; i < MAX_GOP; i++ )
+  {
+    if( m_GOPListsMvc[0][i].m_numInterViewRefPics != 0 )
+    {
+      printf( "\nError: Frame%d inter_view refs not available in view 0\n", i );
+      bErrorIvpBase = true;
+    }
+  }
+  xConfirmPara( bErrorIvpBase, "Inter-view refs not possible in base view" );
+
+  // validate inter-view refs
+  Bool bErrorIvpEnhV = false;
+  if( m_iNumberOfViews > 1 )
+  {
+    for( Int k = 1; k < m_iNumberOfViews; k++ )
+    {
+      for( Int i = 0; i < MAX_GOP+1; i++ )
+      {
+        for( Int j = 0; j < m_GOPListsMvc[k][i].m_numInterViewRefPics; j++ )
+        {
+          Int iAbsViewId = m_GOPListsMvc[k][i].m_interViewRefs[j] + k;
+          if( iAbsViewId < 0 || iAbsViewId >= k )
+          {
+            printf( "\nError: inter-view ref pic %d is not available for Frame%d_v%d\n", m_GOPListsMvc[k][i].m_interViewRefs[j], i, k );
+            bErrorIvpEnhV = true;
+          }
+          if( m_GOPListsMvc[k][i].m_interViewRefPosL0[j] < 0 || m_GOPListsMvc[k][i].m_interViewRefPosL0[j] > m_GOPListsMvc[k][i].m_numRefPicsActive )
+          {
+            printf( "\nError: inter-view ref pos %d on L0 is not available for Frame%d_v%d\n", m_GOPListsMvc[k][i].m_interViewRefPosL0[j], i, k );
+            bErrorIvpEnhV = true;
+          }
+          if( m_GOPListsMvc[k][i].m_interViewRefPosL1[j] < 0 || m_GOPListsMvc[k][i].m_interViewRefPosL1[j] > m_GOPListsMvc[k][i].m_numRefPicsActive )
+          {
+            printf( "\nError: inter-view ref pos %d on L1 is not available for Frame%d_v%d\n", m_GOPListsMvc[k][i].m_interViewRefPosL1[j], i, k );
+            bErrorIvpEnhV = true;
+          }
+        }
+        if( i == MAX_GOP ) // inter-view refs at I pic position in base view
+        {
+          if( m_GOPListsMvc[k][MAX_GOP].m_sliceType != 'B' && m_GOPListsMvc[k][MAX_GOP].m_sliceType != 'P' && m_GOPListsMvc[k][MAX_GOP].m_sliceType != 'I' )
+          {
+            printf( "\nError: slice type of FrameI_v%d must be equal to B or P or I\n", k );
+            bErrorIvpEnhV = true;
+          }
+
+          if( m_GOPListsMvc[k][MAX_GOP].m_POC != 0 )
+          {
+            printf( "\nError: POC %d not possible for FrameI_v%d, must be 0\n", m_GOPListsMvc[k][MAX_GOP].m_POC, k );
+            bErrorIvpEnhV = true;
+          }
+
+          if( m_GOPListsMvc[k][MAX_GOP].m_temporalId != 0 )
+          {
+            printf( "\nWarning: Temporal id of FrameI_v%d must be 0 (cp. I-frame in base view)\n", k );
+            m_GOPListsMvc[k][MAX_GOP].m_temporalId = 0;
+          }
+
+          if( !(m_GOPListsMvc[k][MAX_GOP].m_refPic) )
+          {
+            printf( "\nWarning: FrameI_v%d must be ref pic (cp. I-frame in base view)\n", k );
+            m_GOPListsMvc[k][MAX_GOP].m_refPic = true;
+          }
+
+          if( m_GOPListsMvc[k][MAX_GOP].m_numRefPics != 0 )
+          {
+            printf( "\nWarning: temporal references not possible for FrameI_v%d\n", k );
+            for( Int j = 0; j < m_GOPListsMvc[k][MAX_GOP].m_numRefPics; j++ )
+            {
+              m_GOPListsMvc[k][MAX_GOP].m_referencePics[j] = 0;
+            }
+            m_GOPListsMvc[k][MAX_GOP].m_numRefPics = 0;
+          }
+
+          if( m_GOPListsMvc[k][MAX_GOP].m_interRPSPrediction )
+          {
+            printf( "\nError: inter RPS prediction not possible for FrameI_v%d, must be 0\n", k );
+            bErrorIvpEnhV = true;
+          }
+
+          if( m_GOPListsMvc[k][MAX_GOP].m_sliceType == 'I' && m_GOPListsMvc[k][MAX_GOP].m_numInterViewRefPics != 0 )
+          {
+            printf( "\nError: inter-view prediction not possible for FrameI_v%d with slice type I, #IV_ref_pics must be 0\n", k );
+            bErrorIvpEnhV = true;
+          }
+
+          if( m_GOPListsMvc[k][MAX_GOP].m_numRefPicsActive > m_GOPListsMvc[k][MAX_GOP].m_numInterViewRefPics )
+          {
+            m_GOPListsMvc[k][MAX_GOP].m_numRefPicsActive = m_GOPListsMvc[k][MAX_GOP].m_numInterViewRefPics;
+          }
+
+          if( m_GOPListsMvc[k][MAX_GOP].m_sliceType == 'P' )
+          {
+            if( m_GOPListsMvc[k][MAX_GOP].m_numInterViewRefPics < 1 )
+            {
+              printf( "\nError: #IV_ref_pics must be at least one for FrameI_v%d with slice type P\n", k );
+              bErrorIvpEnhV = true;
+            }
+            else
+            {
+              for( Int j = 0; j < m_GOPListsMvc[k][MAX_GOP].m_numInterViewRefPics; j++ )
+              {
+                if( m_GOPListsMvc[k][MAX_GOP].m_interViewRefPosL1[j] != 0 )
+                {
+                  printf( "\nError: inter-view ref pos %d on L1 not possible for FrameI_v%d with slice type P\n", m_GOPListsMvc[k][MAX_GOP].m_interViewRefPosL1[j], k );
+                  bErrorIvpEnhV = true;
+                }
+              }
+            }
+          }
+
+          if( m_GOPListsMvc[k][MAX_GOP].m_sliceType == 'B' && m_GOPListsMvc[k][MAX_GOP].m_numInterViewRefPics < 1 )
+          {
+            printf( "\nError: #IV_ref_pics must be at least one for FrameI_v%d with slice type B\n", k );
+            bErrorIvpEnhV = true;
+          }
+        }
+      }
+    }
+  }
+  xConfirmPara( bErrorIvpEnhV, "Invalid inter-view coding structure for enhancement views given" );
+
+  // validate temporal coding structure
+  if( !bErrorMvePoc && !bErrorIvpBase && !bErrorIvpEnhV )
+  {
+    for( Int viewId = 0; viewId < m_iNumberOfViews; viewId++ )
+    {
+      Bool verifiedGOP = false;
+      Bool errorGOP    = false;
+      Int  checkGOP    = 1;
+      Int  numRefs     = 1;
+      Int refList[MAX_NUM_REF_PICS+1];
+      refList[0] = 0;
+      Bool isOK[MAX_GOP];
+      for( Int i = 0; i < MAX_GOP; i++ ) { isOK[i] = false; }
+      Int numOK = 0;
+      m_extraRPSs[viewId] = 0;
+      //start looping through frames in coding order until we can verify that the GOP structure is correct.
+      while( !verifiedGOP && !errorGOP )
+      {
+        Int curGOP = (checkGOP-1)%m_iGOPSize;
+        Int curPOC = ((checkGOP-1)/m_iGOPSize)*m_iGOPSize + m_GOPListsMvc[viewId][curGOP].m_POC;    
+        if( m_GOPListsMvc[viewId][curGOP].m_POC < 0 )
+        {
+          printf( "\nError: found fewer Reference Picture Sets than GOPSize for view %d\n", viewId );
+          errorGOP = true;
+        }
+        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_GOPListsMvc[viewId][curGOP].m_numRefPics; i++ ) 
+          {
+            Int absPOC = curPOC + m_GOPListsMvc[viewId][curGOP].m_referencePics[i];
+            if( absPOC < 0 )
+            {
+              beforeI = true;
+            }
+            else 
+            {
+              Bool found = false;
+              for( Int j = 0; j < numRefs; j++ )
+              {
+                if( refList[j] == absPOC ) 
+                {
+                  found = true;
+                  for( Int k = 0; k < m_iGOPSize; k++ )
+                  {
+                    if( absPOC%m_iGOPSize == m_GOPListsMvc[viewId][k].m_POC%m_iGOPSize )
+                    {
+                      m_GOPListsMvc[viewId][curGOP].m_usedByCurrPic[i] = (m_GOPListsMvc[viewId][k].m_temporalId <= m_GOPListsMvc[viewId][curGOP].m_temporalId);
+                    }
+                  }
+                }
+              }
+              if( !found )
+              {
+                printf("\nError: ref pic %d is not available for GOP frame %d of view %d\n", m_GOPListsMvc[viewId][curGOP].m_referencePics[i], curGOP+1, viewId );
+                errorGOP = true;
+              }
+            }
+          }
+          if( !beforeI && !errorGOP )
+          {
+            //all ref frames were present
+            if( !isOK[curGOP] ) 
+            {
+              numOK++;
+              isOK[curGOP] = true;
+              if( numOK == m_iGOPSize )
+              {
+                verifiedGOP = true;
+              }
+            }
+          }
+          else 
+          {
+            //create a new GOPEntry for this frame containing all the reference pictures that were available (POC > 0)
+            m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]] = m_GOPListsMvc[viewId][curGOP];
+            Int newRefs = 0;
+            for( Int i = 0; i < m_GOPListsMvc[viewId][curGOP].m_numRefPics; i++ )
+            {
+              Int absPOC = curPOC + m_GOPListsMvc[viewId][curGOP].m_referencePics[i];
+              if( absPOC >= 0 )
+              {
+                m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_referencePics[newRefs] = m_GOPListsMvc[viewId][curGOP].m_referencePics[i];
+                m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_usedByCurrPic[newRefs] = m_GOPListsMvc[viewId][curGOP].m_usedByCurrPic[i];
+                newRefs++;
+              }
+            }
+            Int numPrefRefs = m_GOPListsMvc[viewId][curGOP].m_numRefPicsActive;
+
+            for( Int offset = -1; offset > -checkGOP; offset-- )
+            {
+              //step backwards in coding order and include any extra available pictures we might find useful to replace the ones with POC < 0.
+              Int offGOP =  (checkGOP - 1 + offset)%m_iGOPSize;
+              Int offPOC = ((checkGOP - 1 + offset)/m_iGOPSize) * m_iGOPSize + m_GOPListsMvc[viewId][offGOP].m_POC;
+              if( offPOC >= 0 && m_GOPListsMvc[viewId][offGOP].m_refPic && m_GOPListsMvc[viewId][offGOP].m_temporalId <= m_GOPListsMvc[viewId][curGOP].m_temporalId )
+              {
+                Bool newRef = false;
+                for( Int i = 0; i < numRefs; i++ )
+                {
+                  if( refList[i] == offPOC )
+                  {
+                    newRef = true;
+                  }
+                }
+                for( Int i = 0; i < newRefs; i++ ) 
+                {
+                  if( m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_referencePics[i] == (offPOC - curPOC) )
+                  {
+                    newRef = false;
+                  }
+                }
+                if( newRef ) 
+                {
+                  Int insertPoint = newRefs;
+                  //this picture can be added, find appropriate place in list and insert it.
+                  for( Int j = 0; j < newRefs; j++ )
+                  {
+                    if( m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_referencePics[j] < (offPOC - curPOC) || 
+                        m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_referencePics[j] > 0 )
+                    {
+                      insertPoint = j;
+                      break;
+                    }
+                  }
+                  Int prev = offPOC - curPOC;
+                  Int prevUsed = (m_GOPListsMvc[viewId][offGOP].m_temporalId <= m_GOPListsMvc[viewId][curGOP].m_temporalId);
+                  for( Int j = insertPoint; j < newRefs+1; j++ )
+                  {
+                    Int newPrev = m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_referencePics[j];
+                    Int newUsed = m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_usedByCurrPic[j];
+                    m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_referencePics[j] = prev;
+                    m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_usedByCurrPic[j] = prevUsed;
+                    prevUsed = newUsed;
+                    prev = newPrev;
+                  }
+                  newRefs++;
+                }
+              }
+              if( newRefs >= numPrefRefs )
+              {
+                break;
+              }
+            }
+            m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_numRefPics = newRefs;
+            m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_POC = curPOC;
+            if( m_extraRPSs[viewId] == 0 )
+            {
+              m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_interRPSPrediction = 0;
+              m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_numRefIdc = 0;
+            }
+            else
+            {
+              Int rIdx =  m_iGOPSize + m_extraRPSs[viewId] - 1;
+              Int refPOC = m_GOPListsMvc[viewId][rIdx].m_POC;
+              Int refPics = m_GOPListsMvc[viewId][rIdx].m_numRefPics;
+              Int newIdc = 0;
+              for( Int i = 0; i <= refPics; i++ )
+              {
+                Int deltaPOC = ((i != refPics)? m_GOPListsMvc[viewId][rIdx].m_referencePics[i] : 0);  // check if the reference abs POC is >= 0
+                Int absPOCref = refPOC + deltaPOC;
+                Int refIdc = 0;
+                for( Int j = 0; j < m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_numRefPics; j++ )
+                {
+                  if( (absPOCref - curPOC) == m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_referencePics[j] )
+                  {
+                    if( m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_usedByCurrPic[j] )
+                    {
+                      refIdc = 1;
+                    }
+                    else
+                    {
+                      refIdc = 2;
+                    }
+                  }
+                }
+                m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_refIdc[newIdc] = refIdc;
+                newIdc++;
+              }
+              m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_interRPSPrediction = 1;  
+              m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_numRefIdc = newIdc;
+              m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_deltaRPS = refPOC - m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_POC; 
+              m_GOPListsMvc[viewId][m_iGOPSize+m_extraRPSs[viewId]].m_deltaRIdxMinus1 = 0; 
+            }
+            curGOP = m_iGOPSize + m_extraRPSs[viewId];
+            m_extraRPSs[viewId]++;
+          }
+          numRefs = 0;
+          for( Int i = 0; i < m_GOPListsMvc[viewId][curGOP].m_numRefPics; i++ )
+          {
+            Int absPOC = curPOC + m_GOPListsMvc[viewId][curGOP].m_referencePics[i];
+            if( absPOC >= 0 )
+            {
+              refList[numRefs] = absPOC;
+              numRefs++;
+            }
+          }
+          refList[numRefs] = curPOC;
+          numRefs++;
+        }
+        checkGOP++;
+      }
+      xConfirmPara( errorGOP, "Invalid GOP structure given" );
+      m_maxTempLayer[viewId] = 1;
+      for( Int i = 0; i < m_iGOPSize; i++ ) 
+      {
+        if( m_GOPListsMvc[viewId][i].m_temporalId >= m_maxTempLayer[viewId] )
+        {
+          m_maxTempLayer[viewId] = m_GOPListsMvc[viewId][i].m_temporalId + 1;
+        }
+        xConfirmPara( m_GOPListsMvc[viewId][i].m_sliceType != 'B' && m_GOPListsMvc[viewId][i].m_sliceType != 'P', "Slice type must be equal to B or P" );
+      }
+
+      for( Int i = 0; i < MAX_TLAYER; i++ )
+      {
+        m_numReorderPics[viewId][i] = 0;
+        m_maxDecPicBuffering[viewId][i] = 0;
+      }
+      for( Int i = 0; i < m_iGOPSize; i++ ) 
+      {
+        if( m_GOPListsMvc[viewId][i].m_numRefPics > m_maxDecPicBuffering[viewId][m_GOPListsMvc[viewId][i].m_temporalId] )
+        {
+          m_maxDecPicBuffering[viewId][m_GOPListsMvc[viewId][i].m_temporalId] = m_GOPListsMvc[viewId][i].m_numRefPics;
+        }
+        Int highestDecodingNumberWithLowerPOC = 0; 
+        for( Int j = 0; j < m_iGOPSize; j++ )
+        {
+          if( m_GOPListsMvc[viewId][j].m_POC <= m_GOPListsMvc[viewId][i].m_POC )
+          {
+            highestDecodingNumberWithLowerPOC = j;
+          }
+        }
+        Int numReorder = 0;
+        for( Int j = 0; j < highestDecodingNumberWithLowerPOC; j++ )
+        {
+          if( m_GOPListsMvc[viewId][j].m_temporalId <= m_GOPListsMvc[viewId][i].m_temporalId && 
+              m_GOPListsMvc[viewId][j].m_POC        >  m_GOPListsMvc[viewId][i].m_POC )
+          {
+            numReorder++;
+          }
+        }    
+        if( numReorder > m_numReorderPics[viewId][m_GOPListsMvc[viewId][i].m_temporalId] )
+        {
+          m_numReorderPics[viewId][m_GOPListsMvc[viewId][i].m_temporalId] = numReorder;
+        }
+      }
+      for( Int i = 0; i < MAX_TLAYER-1; i++ ) 
+      {
+        // a lower layer can not have higher value of m_numReorderPics than a higher layer
+        if( m_numReorderPics[viewId][i+1] < m_numReorderPics[viewId][i] )
+        {
+          m_numReorderPics[viewId][i+1] = m_numReorderPics[viewId][i];
+        }
+        // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ], inclusive
+        if( m_numReorderPics[viewId][i] > m_maxDecPicBuffering[viewId][i] )
+        {
+          m_maxDecPicBuffering[viewId][i] = m_numReorderPics[viewId][i];
+        }
+        // a lower layer can not have higher value of m_uiMaxDecPicBuffering than a higher layer
+        if( m_maxDecPicBuffering[viewId][i+1] < m_maxDecPicBuffering[viewId][i] )
+        {
+          m_maxDecPicBuffering[viewId][i+1] = m_maxDecPicBuffering[viewId][i];
+        }
+      }
+      // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ], inclusive
+      if( m_numReorderPics[viewId][MAX_TLAYER-1] > m_maxDecPicBuffering[viewId][MAX_TLAYER-1] )
+      {
+        m_maxDecPicBuffering[viewId][MAX_TLAYER-1] = m_numReorderPics[viewId][MAX_TLAYER-1];
+      }
+
+      xConfirmPara( m_bUseLComb == false && m_numReorderPics[viewId][MAX_TLAYER-1] != 0, "ListCombination can only be 0 in low delay coding (more precisely when L0 and L1 are identical)" );  // Note however this is not the full necessary condition as ref_pic_list_combination_flag can only be 0 if L0 == L1.
+    }
+  }
+#undef xConfirmPara
+  if( check_failed )
+  {
+    exit(EXIT_FAILURE);
+  }
+}
+
+template <class T>
+Void
+TAppEncCfg::xCleanUpVector( std::vector<T>& rcVec, const T& rcInvalid )
+{
+  Int iFirstInv = (Int)rcVec.size();
+  for( Int iIdx = 0; iIdx < (Int)rcVec.size(); iIdx++ )
+  {
+    if( rcVec[ iIdx ] == rcInvalid )
+    {
+      iFirstInv = iIdx;
+      break;
+    }
+  }
+  while( (Int)rcVec.size() > iFirstInv )
+  {
+    rcVec.pop_back();
+  }
+}
+
+Void
+TAppEncCfg::xCleanUpVectors()
+{
+  xCleanUpVector( m_pchInputFileList,       (char*)0 );
+  xCleanUpVector( m_pchDepthInputFileList,  (char*)0 );
+  xCleanUpVector( m_pchReconFileList,       (char*)0 );
+  xCleanUpVector( m_pchDepthReconFileList,  (char*)0 );
+}
+
+/** \todo use of global variables should be removed later
+ */
+Void TAppEncCfg::xSetGlobal()
+{
+  // 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
+#if FULL_NBIT
+  g_uiBitDepth = m_uiInternalBitDepth;
+  g_uiBitIncrement = 0;
+#else
+  g_uiBitDepth = 8;
+  g_uiBitIncrement = m_uiInternalBitDepth - g_uiBitDepth;
+#endif
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  g_iDeltaDCsQuantOffset = g_uiBitIncrement - 2;
+#endif
+
+  g_uiBASE_MAX     = ((1<<(g_uiBitDepth))-1);
+  
+#if IBDI_NOCLIP_RANGE
+  g_uiIBDI_MAX     = g_uiBASE_MAX << g_uiBitIncrement;
+#else
+  g_uiIBDI_MAX     = ((1<<(g_uiBitDepth+g_uiBitIncrement))-1);
+#endif
+  
+  if (m_uiOutputBitDepth == 0)
+  {
+    m_uiOutputBitDepth = m_uiInternalBitDepth;
+  }
+
+  g_uiPCMBitDepthLuma = m_uiPCMBitDepthLuma = ((m_bPCMInputBitDepthFlag)? m_uiInputBitDepth : m_uiInternalBitDepth);
+  g_uiPCMBitDepthChroma = ((m_bPCMInputBitDepthFlag)? m_uiInputBitDepth : m_uiInternalBitDepth);
+}
+
+Void TAppEncCfg::xPrintParameter()
+{
+  printf("\n");
+  for( Int iCounter = 0; iCounter< m_iNumberOfViews; iCounter++)
+  {
+    printf("Texture Input File %i            : %s\n", iCounter, m_pchInputFileList[iCounter]);
+  }
+  if( m_bUsingDepthMaps )
+  {
+    for( Int iCounter = 0; iCounter < m_iNumberOfViews; iCounter++)
+    {
+      printf("Depth Input File %i              : %s\n", iCounter, m_pchDepthInputFileList[iCounter]);
+    }
+  }
+  printf("Bitstream File                  : %s\n", m_pchBitstreamFile      );
+  for( Int iCounter = 0; iCounter< m_iNumberOfViews; iCounter++)
+  {
+    printf("Texture Reconstruction File %i   : %s\n", iCounter, m_pchReconFileList[iCounter]);
+  }
+  if( m_bUsingDepthMaps )
+  {
+    for( Int iCounter = 0; iCounter< m_iNumberOfViews; iCounter++)
+    {
+      printf("Depth Reconstruction File %i     : %s\n", iCounter, m_pchDepthReconFileList[iCounter]);
+    }
+  }
+  printf("Real     Format              : %dx%d %dHz\n", m_iSourceWidth - m_cropLeft - m_cropRight, m_iSourceHeight - m_cropTop - m_cropBottom, m_iFrameRate );
+  printf("Internal Format              : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+  printf("Frame index                  : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_iFrameToBeEncoded-1, m_iFrameToBeEncoded );
+  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 DV_V_RESTRICTION_B0037
+  printf("Disp search range restriction: %d\n", m_bUseDisparitySearchRangeRestriction );
+  printf("Vertical disp search range   : %d\n", m_iVerticalDisparitySearchRange );
+#endif
+  printf("Intra period                 : %d\n", m_iIntraPeriod );
+  printf("Decoding refresh type        : %d\n", m_iDecodingRefreshType );
+  printf("QP Texture                   : %5.2f\n", m_adQP[0] );
+  if( m_bUsingDepthMaps )
+  {
+    printf("QP Depth                     : %5.2f\n", m_adQP[ m_adQP.size()  < 2 ? 0 : 1] );
+  }
+  printf("Max dQP signaling depth      : %d\n", m_iMaxCuDQPDepth);
+
+  printf("Chroma Qp Offset             : %d\n", m_iChromaQpOffset   );
+  printf("Chroma Qp Offset 2nd         : %d\n", m_iChromaQpOffset2nd);
+
+  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           : %d\n", m_uiInternalBitDepth );
+  printf("PCM sample bit depth         : %d\n", m_uiPCMBitDepthLuma );
+  if((m_uiMaxCUWidth >> m_uiMaxCUDepth) == 4)
+  {
+    printf("DisableInter4x4              : %d\n", m_bDisInter4x4);  
+  }
+
+printf("Loop Filter Disabled         : %d %d\n", m_abLoopFilterDisable[0] ? 1 : 0,  m_abLoopFilterDisable[1] ? 1 : 0 );
+  printf("Coded Camera Param. Precision: %d\n", m_iCodedCamParPrecision);
+
+#if HHI_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    );
+#if HHI_VSO_DIST_INT
+    printf("VSO Negative Distortion      : %d\n",    m_bAllowNegDist ? 1 : 0);
+#endif
+#if HHI_VSO_LS_TABLE_M23714
+    printf("VSO LS Table                 : %d\n",    m_bVSOLSTable ? 1 : 0);    
+#endif
+#if SAIT_VSO_EST_A0033
+    printf("VSO Estimated VSD            : %d\n",    m_bUseEstimatedVSD ? 1 : 0);        
+#endif
+#if LGE_VSO_EARLY_SKIP_A0093
+    printf("VSO Early Skip               : %d\n",    m_bVSOEarlySkip ? 1 : 0);    
+#endif
+   
+  }
+#endif
+#if HHI_INTERVIEW_SKIP
+    printf("InterView Skip:              : %d\n",    m_bInterViewSkip ? 1:0 );
+    printf("InterView Skip Lambda Scale  : %f\n",    m_dInterViewSkipLambdaScale );
+#endif
+
+  printf("\n");
+  
+  printf("TOOL CFG General: ");  
+  printf("ALFMNF:%d ", m_iALFMaxNumberFilters);
+  printf("ALFInSlice:%d ", m_bALFParamInSlice);
+  printf("ALFPicEnc:%d ", m_bALFPicBasedEncode);
+  printf("IBD:%d ", !!g_uiBitIncrement);
+  printf("HAD:%d ", m_bUseHADME           );
+  printf("SRD:%d ", m_bUseSBACRD          );
+  printf("SQP:%d ", m_uiDeltaQpRD         );
+  printf("ASR:%d ", m_bUseASR             );
+  printf("LComb:%d ", m_bUseLComb         );
+  printf("LCMod:%d ", m_bLCMod         );
+  printf("FEN:%d ", m_bUseFastEnc         );
+  printf("ECU:%d ", m_bUseEarlyCU         );
+  printf("FDM:%d ", m_useFastDecisionForMerge );
+  printf("CFM:%d ", m_bUseCbfFastMode         );
+  printf("RQT:%d ", 1     );
+  printf("LMC:%d ", m_bUseLMChroma        ); 
+  printf("Slice: G=%d M=%d ", m_iSliceGranularity, m_iSliceMode);
+  if (m_iSliceMode!=0)
+  {
+    printf("A=%d ", m_iSliceArgument);
+  }
+  printf("EntropySlice: M=%d ",m_iEntropySliceMode);
+  if (m_iEntropySliceMode!=0)
+  {
+    printf("A=%d ", m_iEntropySliceArgument);
+  }
+  printf("CIP:%d ", m_bUseConstrainedIntraPred);
+  printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
+  printf("SAOInterleaving:%d ", (m_saoInterleavingFlag)?(1):(0));
+#if LOSSLESS_CODING
+  printf("LosslessCuEnabled:%d ", (m_useLossless)? 1:0 );
+#endif  
+  printf("WPP:%d ", (Int)m_bUseWeightPred);
+  printf("WPB:%d ", m_uiBiPredIdc);
+  printf("TileLocationInSliceHdr:%d ", m_iTileLocationInSliceHeaderFlag);
+  printf("TileMarker:%d", m_iTileMarkerFlag);
+  if (m_iTileMarkerFlag)
+  {
+    printf("[%d] ", m_iMaxTileMarkerEntryPoints);
+  }
+  else
+  {
+    printf(" ");
+  }
+  printf(" WaveFrontSynchro:%d WaveFrontFlush:%d WaveFrontSubstreams:%d",
+          m_iWaveFrontSynchro, m_iWaveFrontFlush, m_iWaveFrontSubstreams);
+  printf(" ScalingList:%d ", m_useScalingListId );
+
+#if !TMVP_DEPTH_SWITCH
+  printf("TMVP:%d ", m_enableTMVP     );
+#endif
+
+#if ADAPTIVE_QP_SELECTION
+  printf("AQpS:%d", m_bUseAdaptQpSelect   );
+#endif
+
+  printf(" SignBitHidingFlag:%d SignBitHidingThreshold:%d", m_signHideFlag, m_signHidingThreshold);
+  printf("\n");
+  printf("TOOL CFG VIDEO  : ");
+  printf("ALF:%d ", (m_abUseALF [0] ? 1 : 0) );
+  printf("SAO:%d ", (m_abUseSAO [0] ? 1 : 0));
+  printf("RDQ:%d ", (m_abUseRDOQ[0] ? 1 : 0) );
+#if TMVP_DEPTH_SWITCH
+  printf("TMVP:%d ", (m_enableTMVP[0] ? 1 : 0) );
+#endif
+#if LGE_ILLUCOMP_B0045
+#if LGE_ILLUCOMP_DEPTH_C0046
+  printf("IlluCompEnable: %d %d", m_abUseIC[0] ? 1 : 0, m_abUseIC[1] ? 1 : 0);
+#else
+  printf("IlluCompEnable: %d ", m_bUseIC);
+#endif
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  printf("IVSEnable: %d ", m_bUseIVS);
+#endif
+  printf("\n");
+
+  printf("TOOL CFG DEPTH  : ");
+  printf("ALF:%d ", (m_abUseALF [1] ? 1 : 0));
+  printf("SAO:%d ", (m_abUseSAO [1] ? 1 : 0));
+  printf("RDQ:%d ", (m_abUseRDOQ[1] ? 1 : 0));
+#if TMVP_DEPTH_SWITCH
+  printf("TMVP:%d ", (m_enableTMVP[1] ? 1 : 0) );
+#endif
+#if FLEX_CODING_ORDER_M23723
+  printf("FCO:%d ",   (m_b3DVFlexOrder ? 1: 0));
+
+  if(m_b3DVFlexOrder)
+  {
+    printf("CodingOrder: %s ", m_pchMVCJointCodingOrder);
+  }
+#endif
+#if HHI_VSO
+  printf("VSO:%d ", m_bUseVSO             );
+#endif
+#if LGE_WVSO_A0119
+  printf("WVSO:%d ", m_bUseWVSO );
+#endif
+#if H3D_QTL
+  printf("QTLPC:%d ", m_bUseQTLPC);
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  printf("DMM:%d ", m_bUseDMM );
+#endif
+#if HHI_MPI
+  printf("MVI:%d ", m_bUseMVI ? 1 : 0 );
+#endif
+#if RWTH_SDC_DLT_B0036
+  printf("SDC:%d ", m_bUseSDC ? 1 : 0 );
+  printf("DLT:%d ", m_bUseDLT ? 1 : 0 );
+#endif
+#if LGE_WVSO_A0119
+  if ( m_bUseWVSO )
+    printf("\nVSO : VSD : SAD weight = %d : %d : %d ", m_iVSOWeight, m_iVSDWeight, m_iDWeight );
+#endif
+  printf("\n\n");
+  
+  fflush(stdout);
+}
+
+Void TAppEncCfg::xPrintUsage()
+{
+  printf( "          <name> = ALF - adaptive loop filter\n");
+  printf( "                   IBD - bit-depth increasement\n");
+  printf( "                   GPB - generalized B instead of P in low-delay mode\n");
+  printf( "                   HAD - hadamard ME for fractional-pel\n");
+  printf( "                   SRD - SBAC based RD estimation\n");
+  printf( "                   RDQ - RDOQ\n");
+  printf( "                   LDC - low-delay mode\n");
+  printf( "                   NRF - non-reference frame marking in last layer\n");
+  printf( "                   BQP - hier-P style QP assignment in low-delay mode\n");
+  printf( "                   PAD - automatic source padding of multiple of 16\n");
+  printf( "                   ASR - adaptive motion search range\n");
+  printf( "                   FEN - fast encoder setting\n");  
+  printf( "                   ECU - Early CU setting\n");
+  printf( "                   CFM - Cbf fast mode setting\n");
+  printf( "                   LMC - intra chroma prediction based on luma\n");
+  printf( "\n" );
+  printf( "  Example 1) TAppEncoder.exe -c test.cfg -q 32 -g 8 -f 9 -s 64 -h 4\n");
+  printf("              -> QP 32, hierarchical-B GOP 8, 9 frames, 64x64-8x8 CU (~4x4 PU)\n\n");
+  printf( "  Example 2) TAppEncoder.exe -c test.cfg -q 32 -g 4 -f 9 -s 64 -h 4 -1 LDC\n");
+  printf("              -> QP 32, hierarchical-P GOP 4, 9 frames, 64x64-8x8 CU (~4x4 PU)\n\n");
+}
+
+Bool confirmPara(Bool bflag, const char* message)
+{
+  if (!bflag)
+    return false;
+  
+  printf("Error: %s\n",message);
+  return true;
+}
+
+/* helper function */
+/* for handling "-1/-0 FOO" */
+void translateOldStyleCmdline(const char* value, po::Options& opts, const std::string& arg)
+{
+  const char* argv[] = {arg.c_str(), value};
+  /* replace some short names with their long name varients */
+  if (arg == "LDC")
+  {
+    argv[0] = "LowDelayCoding";
+  }
+  else if (arg == "RDQ")
+  {
+    argv[0] = "RDOQ";
+  }
+  else if (arg == "HAD")
+  {
+    argv[0] = "HadamardME";
+  }
+  else if (arg == "SRD")
+  {
+    argv[0] = "SBACRD";
+  }
+  else if (arg == "IBD")
+  {
+    argv[0] = "BitIncrement";
+  }
+  /* issue a warning for change in FEN behaviour */
+  if (arg == "FEN")
+  {
+    /* xxx todo */
+  }
+  po::storePair(opts, argv[0], argv[1]);
+}
+
+void doOldStyleCmdlineOn(po::Options& opts, const std::string& arg)
+{
+  if (arg == "IBD")
+  {
+    translateOldStyleCmdline("4", opts, arg);
+    return;
+  }
+  translateOldStyleCmdline("1", opts, arg);
+}
+
+void doOldStyleCmdlineOff(po::Options& opts, const std::string& arg)
+{
+  translateOldStyleCmdline("0", opts, arg);
+}
+
+Void TAppEncCfg::xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName)
+{
+  size_t iInLength     = strlen(pchInputFileName);
+  size_t iAppendLength = strlen(pchStringToAppend);
+
+  rpchOutputFileName = (Char*) malloc(iInLength+iAppendLength+1);
+  Char* pCDot = strrchr(pchInputFileName,'.');
+  pCDot = pCDot ? pCDot : pchInputFileName + iInLength;
+  size_t iCharsToDot = pCDot - pchInputFileName ;
+  size_t iCharsToEnd = iInLength - iCharsToDot;
+  strncpy(rpchOutputFileName                            ,  pchInputFileName            , iCharsToDot  );
+  strncpy(rpchOutputFileName+ iCharsToDot               ,  pchStringToAppend           , iAppendLength);
+  strncpy(rpchOutputFileName+ iCharsToDot+iAppendLength ,  pchInputFileName+iCharsToDot, iCharsToEnd  );
+  rpchOutputFileName[iInLength+iAppendLength] = '\0';
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncCfg.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncCfg.h	(revision 341)
@@ -0,0 +1,356 @@
+/* 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-2012, 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     TAppEncCfg.h
+    \brief    Handle encoder configuration parameters (header)
+*/
+
+#ifndef __TAPPENCCFG__
+#define __TAPPENCCFG__
+
+#include "TLibCommon/CommonDef.h"
+
+#include "TLibEncoder/TEncCfg.h"
+#include "TAppCommon/TAppComCamPara.h"
+#include "TLibRenderer/TRenTop.h"
+#include "TLibRenderer/TRenModel.h"
+#include "TLibRenderer/TRenModSetupStrParser.h"
+
+#include <sstream>
+#include <vector>
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TAppEncCfg
+{
+protected:
+  // file I/O
+  std::vector<char*>     m_pchInputFileList;                  ///< source file names
+  std::vector<char*>     m_pchDepthInputFileList;             ///< source depth file names
+  std::vector<char*>     m_pchReconFileList;                  ///< output reconstruction file names
+  std::vector<char*>     m_pchDepthReconFileList;             ///< output depth reconstruction file names
+  char*     m_pchBitstreamFile;                               ///< output bitstream file
+  Double    m_adLambdaModifier[ MAX_TLAYER ];                 ///< Lambda modifier array for each temporal layer
+  // source specification
+  Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
+  unsigned int m_FrameSkip;                                   ///< number of skipped frames from the beginning
+  Int       m_iSourceWidth;                                   ///< source width in pixel
+  Int       m_iSourceHeight;                                  ///< source height in pixel
+  Int       m_croppingMode;
+  Int       m_cropLeft;
+  Int       m_cropRight;
+  Int       m_cropTop;
+  Int       m_cropBottom;
+  Int       m_iFrameToBeEncoded;                              ///< number of encoded frames
+  Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+  
+  Int       m_iNumberOfViews;                                 ///< number Views to Encode
+  Bool      m_bUsingDepthMaps;
+  
+#if FLEX_CODING_ORDER_M23723
+  Char*  m_pchMVCJointCodingOrder;      ///<  texture-depth coding order
+  Bool    m_b3DVFlexOrder;    ///<  flexible coding order flag
+#endif
+
+  // coding structure
+  Int       m_iIntraPeriod;                                   ///< period of I-slice (random access period)
+  Int       m_iDecodingRefreshType;                           ///< random access type
+  Int       m_iGOPSize;                                       ///< GOP size of hierarchical structure
+  Int       m_extraRPSs[MAX_VIEW_NUM];
+  GOPEntryMvc m_GOPListsMvc[MAX_VIEW_NUM][MAX_GOP+1];
+  Int       m_numReorderPics[MAX_VIEW_NUM][MAX_TLAYER];       ///< total number of reorder pictures
+  Int       m_maxDecPicBuffering[MAX_VIEW_NUM][MAX_TLAYER];   ///< total number of reference pictures needed for decoding
+  Bool      m_bUseLComb;                                      ///< flag for using combined reference list for uni-prediction in B-slices (JCTVC-D421)
+  Bool      m_bLCMod;                                         ///< flag for specifying whether the combined reference list for uni-prediction in B-slices is uploaded explicitly
+  Bool      m_bDisInter4x4;
+  Bool      m_enableNSQT;                                     ///< flag for enabling NSQT
+  Bool      m_enableAMP;
+  // coding quality
+  std::vector<Double>  m_adQP;                                ///< QP value of key-picture (floating point) [0] video, [1] depth
+  std::vector<Int>     m_aiQP;                                ///< QP value of key-picture (integer) [0] video, [1] depth
+#if QC_MVHEVC_B0046
+  std::vector<Int>     m_aiVId;                                ///< view id
+#endif
+  Int       m_aiTLayerQPOffset[MAX_TLAYER];                   ///< QP offset corresponding to temporal layer depth
+  char*     m_pchdQPFile;                                     ///< QP offset for each slice (initialized from external file)
+  Int*      m_aidQP;                                          ///< array of slice QP values
+  Int*      m_aidQPdepth;                                     ///< array of depth slice QP values
+  Int       m_iMaxDeltaQP;                                    ///< max. |delta QP|
+  UInt      m_uiDeltaQpRD;                                    ///< dQP range for multi-pass slice QP optimization
+  Int       m_iMaxCuDQPDepth;                                 ///< Max. depth for a minimum CuDQPSize (0:default)
+
+  Int       m_iChromaQpOffset;                                 ///< ChromaQpOffset    (0:default) 
+  Int       m_iChromaQpOffset2nd;                              ///< ChromaQpOffset2nd (0:default)
+
+#if ADAPTIVE_QP_SELECTION
+  Bool      m_bUseAdaptQpSelect;
+#endif
+
+  Bool      m_bUseAdaptiveQP;                                 ///< Flag for enabling QP adaptation based on a psycho-visual model
+  Int       m_iQPAdaptationRange;                             ///< dQP range by QP adaptation
+  
+  Int       m_maxTempLayer[MAX_VIEW_NUM];                     ///< Max temporal layer
+
+  // coding unit (CU) definition
+  UInt      m_uiMaxCUWidth;                                   ///< max. CU width in pixel
+  UInt      m_uiMaxCUHeight;                                  ///< max. CU height in pixel
+  UInt      m_uiMaxCUDepth;                                   ///< max. CU depth
+  
+  // transfom unit (TU) definition
+  UInt      m_uiQuadtreeTULog2MaxSize;
+  UInt      m_uiQuadtreeTULog2MinSize;
+  
+  UInt      m_uiQuadtreeTUMaxDepthInter;
+  UInt      m_uiQuadtreeTUMaxDepthIntra;
+  
+  // coding tools (bit-depth)
+  UInt      m_uiInputBitDepth;                                ///< bit-depth of input file
+  UInt      m_uiOutputBitDepth;                               ///< bit-depth of output file
+  UInt      m_uiInternalBitDepth;                             ///< Internal bit-depth (BitDepth+BitIncrement)
+
+  // coding tools (PCM bit-depth)
+  Bool      m_bPCMInputBitDepthFlag;                          ///< 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+  UInt      m_uiPCMBitDepthLuma;                              ///< PCM bit-depth for luma
+
+  // coding tool (lossless)
+#if LOSSLESS_CODING
+  Bool      m_useLossless;                                    ///< flag for using lossless coding
+#endif
+  vector<Bool> m_abUseSAO;
+#if LGE_ILLUCOMP_B0045
+#if LGE_ILLUCOMP_DEPTH_C0046
+  vector<Bool> m_abUseIC;                                    ///< flag for using illumination compensation for inter-view prediction
+#else
+  Bool      m_bUseIC;                                     ///< flag for using illumination compensation for inter-view prediction
+#endif
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Bool      m_bUseIVS;                                        ///< flag for using inter-view vector scaling
+#endif
+  Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
+  Bool      m_saoInterleavingFlag;                            ///< SAO interleaving flag
+  // coding tools (loop filter)
+  vector<Bool> m_abUseALF;                                    ///< flag for using adaptive loop filter [0] - video, [1] - depth
+  Int       m_iALFEncodePassReduction;                        //!< ALF encoding pass, 0 = original 16-pass, 1 = 1-pass, 2 = 2-pass
+  
+  Int       m_iALFMaxNumberFilters;                           ///< ALF Max Number Filters in one picture
+  Bool      m_bALFParamInSlice;
+  Bool      m_bALFPicBasedEncode;
+
+  vector<Bool> m_abLoopFilterDisable;                         ///< flag for using deblocking filter filter [0] - video, [1] - depth
+  Bool      m_loopFilterOffsetInAPS;                         ///< offset for deblocking filter in 0 = slice header, 1 = APS
+  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_bUseLMChroma;                                  ///< JL: Chroma intra prediction based on luma signal
+
+  // coding tools (PCM)
+  Bool      m_usePCM;                                         ///< flag for using IPCM
+  UInt      m_pcmLog2MaxSize;                                 ///< log2 of maximum PCM block size
+  UInt      m_uiPCMLog2MinSize;                               ///< log2 of minimum PCM block size
+  Bool      m_bPCMFilterDisableFlag;                          ///< PCM filter disable flag
+
+  // coding tools (encoder-only parameters)
+  Bool      m_bUseSBACRD;                                     ///< flag for using RD optimization based on SBAC
+  Bool      m_bUseASR;                                        ///< flag for using adaptive motion search range
+  Bool      m_bUseHADME;                                      ///< flag for using HAD in sub-pel ME
+vector<Bool> m_abUseRDOQ;                                   ///< flag for using RD optimized quantization [0]-video, [1]-depth
+  Int       m_iFastSearch;                                    ///< ME mode, 0 = full, 1 = diamond, 2 = PMVFAST
+  Int       m_iSearchRange;                                   ///< ME search range
+#if DV_V_RESTRICTION_B0037
+  Bool      m_bUseDisparitySearchRangeRestriction;            ///< restrict vertical search range for inter-view prediction
+  Int       m_iVerticalDisparitySearchRange;                  ///< ME vertical search range for inter-view prediction 
+#endif
+  Int       m_bipredSearchRange;                              ///< ME search range for bipred refinement
+  Bool      m_bUseFastEnc;                                    ///< flag for using fast encoder setting
+#if HHI_INTERVIEW_SKIP
+  Bool      m_bInterViewSkip;                            ///< usage of interview skip mode ( do not transmit residual)
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  Double    m_dInterViewSkipLambdaScale;                 ///< lambda scale for interview skip
+#endif
+#endif
+  Bool      m_bUseEarlyCU;                                    ///< flag for using Early CU setting
+
+#if DEPTH_MAP_GENERATION
+  UInt      m_uiPredDepthMapGeneration;                       ///< using of (virtual) depth maps for texture coding
+#endif
+#if H3D_IVMP
+  UInt      m_uiMultiviewMvPredMode;                          ///< usage of predictors for multi-view mv prediction
+  UInt      m_uiMultiviewMvRegMode;                           ///< regularization for multiview motion vectors
+  Double    m_dMultiviewMvRegLambdaScale;                     ///< lambda scale for multiview motion vectors regularization
+#endif
+#if H3D_IVRP
+  UInt      m_uiMultiviewResPredMode;          ///< using multiview residual prediction
+#endif
+
+  Bool      m_useFastDecisionForMerge;         ///< flag for using Fast Decision Merge RD-Cost 
+  Bool      m_bUseCbfFastMode;                 ///< flag for using Cbf Fast PU Mode Decision
+  Int       m_iSliceMode;                      ///< 0: Disable all Recon slice limits, 1 : Maximum number of largest coding units per slice, 2: Maximum number of bytes in a slice
+  Int       m_iSliceArgument;                  ///< If m_iSliceMode==1, m_iSliceArgument=max. # of largest coding units. If m_iSliceMode==2, m_iSliceArgument=max. # of bytes.
+  Int       m_iEntropySliceMode;               ///< 0: Disable all entropy slice limits, 1 : Maximum number of largest coding units per slice, 2: Constraint based entropy slice
+  Int       m_iEntropySliceArgument;           ///< If m_iEntropySliceMode==1, m_iEntropySliceArgument=max. # of largest coding units. If m_iEntropySliceMode==2, m_iEntropySliceArgument=max. # of bins.
+
+  Int       m_iSliceGranularity;               ///< 0: Slices always end at LCU borders. 1-3: slices may end at a depth of 1-3 below LCU level.
+  Bool      m_bLFCrossSliceBoundaryFlag;       ///< 0: Cross-slice-boundary in-loop filtering 1: non-cross-slice-boundary in-loop filtering
+  Int       m_iTileBehaviorControlPresentFlag; //!< 1: tile behavior control parameters are in PPS 0: tile behavior control parameters are not in PPS
+  Bool      m_bLFCrossTileBoundaryFlag;        //!< 1: Cross-tile-boundary in-loop filtering 0: non-cross-tile-boundary in-loop filtering
+  Int       m_iColumnRowInfoPresent;
+  Int       m_iUniformSpacingIdr;
+  Int       m_iNumColumnsMinus1;
+  char*     m_pchColumnWidth;
+  Int       m_iNumRowsMinus1;
+  char*     m_pchRowHeight;
+  Int       m_iTileLocationInSliceHeaderFlag; //< enable(1)/disable(0) transmitssion of tile location in slice header
+  Int       m_iTileMarkerFlag;              //< enable(1)/disable(0) transmitssion of light weight tile marker
+  Int       m_iMaxTileMarkerEntryPoints;    //< maximum number of tile markers allowed in a slice (controls degree of parallelism)
+  Double    m_dMaxTileMarkerOffset;         //< Calculated offset. Light weight tile markers will be transmitted for TileIdx= Offset, 2*Offset, 3*Offset ... 
+
+  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_iWaveFrontFlush; //< enable(1)/disable(0) the CABAC flush at the end of each line of LCUs.
+  Int       m_iWaveFrontSubstreams; //< If iWaveFrontSynchro, this is the number of substreams per frame (dependent tiles) or per tile (independent tiles).
+
+  Bool      m_bUseConstrainedIntraPred;                       ///< flag for using constrained intra prediction
+  
+  bool m_pictureDigestEnabled; ///< enable(1)/disable(0) md5 computation and SEI signalling
+
+  // weighted prediction
+  Bool      m_bUseWeightPred;                                 ///< Use of explicit Weighting Prediction for P_SLICE
+  UInt      m_uiBiPredIdc;                                    ///< Use of Bi-Directional Weighting Prediction (B_SLICE): explicit(1) or implicit(2)
+
+#if TMVP_DEPTH_SWITCH
+  vector<Bool> m_enableTMVP;                                  ///< Enable TMVP [0] video, [1] depth
+#else
+  Bool      m_enableTMVP;
+#endif
+
+  Int       m_signHideFlag;
+  Int       m_signHidingThreshold;
+#if HHI_MPI
+  Bool      m_bUseMVI;  ///< flag for using Motion Vector Inheritance for depth map coding
+#endif
+#if RWTH_SDC_DLT_B0036
+  Bool      m_bUseDLT;
+  Bool      m_bUseSDC;
+#endif
+
+  Int       m_useScalingListId;                               ///< using quantization matrix
+  char*     m_scalingListFile;                                ///< quantization matrix file name
+
+  // camera parameter
+  Char*     m_pchCameraParameterFile;                         ///< camera parameter file
+  Char*     m_pchBaseViewCameraNumbers;
+#if !QC_MVHEVC_B0046
+  TAppComCamPara m_cCameraData;
+#endif
+  Int       m_iCodedCamParPrecision;                          ///< precision for coding of camera parameters
+
+#if HHI_VSO
+  Char*     m_pchVSOConfig;
+  Bool      m_bUseVSO;                                    ///< flag for using View Synthesis Optimization
+#if HHI_VSO_LS_TABLE_M23714
+  Bool      m_bVSOLSTable;                                ///< Depth QP dependent Lagrange parameter optimization (m23714)
+#endif
+#if LGE_VSO_EARLY_SKIP_A0093
+  Bool      m_bVSOEarlySkip;                              ///< Early skip of VSO computation (JCT3V-A0093 modification 4)
+#endif
+  //// 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
+#if HHI_VSO_DIST_INT
+  Bool      m_bAllowNegDist;                              ///< Allow negative distortion in VSO
+#endif
+  UInt      m_uiVSOMode;                                  ///< Number of VSO Mode, 1 = , 2 = simple, org vs. ren, 3 = simple, ren vs. ren, 4 = full  
+#endif
+#if 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)  
+#endif
+#if LGE_WVSO_A0119
+  Bool      m_bUseWVSO;                                    ///< flag for using View Synthesis Optimization  
+  Int       m_iVSOWeight;
+  Int       m_iVSDWeight;
+  Int       m_iDWeight;
+#endif
+  // coding tools (depth intra modes)
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool      m_bUseDMM;                                        ///< flag for using DMM
+#endif
+
+#if H3D_QTL
+  Bool      m_bUseQTLPC;                                      ///< flag for using depth QuadTree Limitation + Predictive Coding
+#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
+  
+  Void  xCleanUpVectors ();                                   ///< clean up vector sizes
+  Void  xInitCameraPars ();                                   ///< init camera parameters
+
+
+  // set MVD Parameters and LUTs
+  Void xSetShiftParameters();
+  Void xGetShiftParameter( UInt uiSourceView, UInt uiTargetView, bool bExternal, double& rdScale, double& rdOffset ); ///< Get one Shift Parameters
+
+  Void  xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char* & rpchOutputFileName);
+
+  Void  xCheckCodingStructureMvc();                           ///< validate and configure inter-view coding structure
+
+  template <class T> Void xCleanUpVector( std::vector<T>& rcVec, const T& rcInvalid );
+#if HHI_VSO
+  // Ren Model String
+  TRenModSetupStrParser       m_cRenModStrParser;
+#endif
+public:
+  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
+
+//! \}
+
+#endif // __TAPPENCCFG__
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncTop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncTop.cpp	(revision 341)
@@ -0,0 +1,1664 @@
+/* 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-2012, 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     TAppEncTop.cpp
+    \brief    Encoder application class
+*/
+
+#include <list>
+#include <fstream>
+#include <stdlib.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppEncTop.h"
+#include "TLibEncoder/AnnexBwrite.h"
+
+using namespace std;
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncTop::TAppEncTop()
+{
+  m_totalBytes = 0;
+  m_essentialBytes = 0;
+}
+
+TAppEncTop::~TAppEncTop()
+{
+}
+
+Void TAppEncTop::xInitLibCfg()
+{
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+#if !QC_MVHEVC_B0046
+  UInt layerId = 0;
+#endif
+  // TODO: fix the assumption here that the temporal structures are all equal across all layers???
+  m_cVPS.setMaxTLayers( m_maxTempLayer[0] );
+#if QC_MVHEVC_B0046
+  m_cVPS.setMaxLayers( m_iNumberOfViews );
+#else
+  m_cVPS.setMaxLayers( m_iNumberOfViews * (m_bUsingDepthMaps ? 2:1) );
+#endif
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_cVPS.setNumReorderPics( m_numReorderPics[0][i], i );
+    m_cVPS.setMaxDecPicBuffering( m_maxDecPicBuffering[0][i], i );
+  }
+#endif
+  
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+  {
+    m_frameRcvd.push_back(0);
+    m_acTEncTopList.push_back(new TEncTop); 
+    m_acTVideoIOYuvInputFileList.push_back(new TVideoIOYuv);
+    m_acTVideoIOYuvReconFileList.push_back(new TVideoIOYuv);
+    m_picYuvRec.push_back(new TComList<TComPicYuv*>) ;
+
+    m_acTEncTopList[iViewIdx]->setFrameRate                    ( m_iFrameRate );
+    m_acTEncTopList[iViewIdx]->setFrameSkip                    ( m_FrameSkip );
+    m_acTEncTopList[iViewIdx]->setSourceWidth                  ( m_iSourceWidth );
+    m_acTEncTopList[iViewIdx]->setSourceHeight                 ( m_iSourceHeight );
+    m_acTEncTopList[iViewIdx]->setCroppingMode                 ( m_croppingMode );
+    m_acTEncTopList[iViewIdx]->setCropLeft                     ( m_cropLeft );
+    m_acTEncTopList[iViewIdx]->setCropRight                    ( m_cropRight );
+    m_acTEncTopList[iViewIdx]->setCropTop                      ( m_cropTop );
+    m_acTEncTopList[iViewIdx]->setCropBottom                   ( m_cropBottom );
+    m_acTEncTopList[iViewIdx]->setFrameToBeEncoded             ( m_iFrameToBeEncoded );
+    m_acTEncTopList[iViewIdx]->setViewId                       ( iViewIdx );
+    m_acTEncTopList[iViewIdx]->setIsDepth                      ( false );
+#if QC_MVHEVC_B0046
+    m_acTEncTopList[iViewIdx]->setLayerId                      ( iViewIdx );
+    m_cVPS.setViewId                                           ( m_aiVId[ iViewIdx ], iViewIdx );
+#else
+    m_acTEncTopList[iViewIdx]->setViewOrderIdx                 ( m_cCameraData.getViewOrderIndex()[ iViewIdx ] );
+#if VIDYO_VPS_INTEGRATION
+    layerId = iViewIdx * (m_bUsingDepthMaps ? 2:1);
+    m_acTEncTopList[iViewIdx]->setLayerId                      ( layerId );
+    m_cVPS.setDepthFlag                                        ( false, layerId );
+    m_cVPS.setViewId                                           ( iViewIdx, layerId );
+    m_cVPS.setViewOrderIdx                                     ( m_cCameraData.getViewOrderIndex()[ iViewIdx ], layerId );
+    // TODO: set correct dependentFlag and dependentLayer
+    m_cVPS.setDependentFlag                                    ( iViewIdx ? true:false, layerId );
+    m_cVPS.setDependentLayer                                   ( layerId - (m_bUsingDepthMaps ? 2:1), layerId );
+#if INTER_VIEW_VECTOR_SCALING_C0115
+    m_cVPS.setIVScalingFlag                                    ( m_bUseIVS );
+#endif
+#endif
+    
+    m_acTEncTopList[iViewIdx]->setCamParPrecision              ( m_cCameraData.getCamParsCodedPrecision  () );
+    m_acTEncTopList[iViewIdx]->setCamParInSliceHeader          ( m_cCameraData.getVaryingCameraParameters() );
+    m_acTEncTopList[iViewIdx]->setCodedScale                   ( m_cCameraData.getCodedScale             () );
+    m_acTEncTopList[iViewIdx]->setCodedOffset                  ( m_cCameraData.getCodedOffset            () );
+#endif   
+
+  //====== Coding Structure ========
+    m_acTEncTopList[iViewIdx]->setIntraPeriod                  ( m_iIntraPeriod );
+    m_acTEncTopList[iViewIdx]->setDecodingRefreshType          ( m_iDecodingRefreshType );
+    m_acTEncTopList[iViewIdx]->setGOPSize                      ( m_iGOPSize );
+    m_acTEncTopList[iViewIdx]->setGopList                      ( m_GOPListsMvc[iViewIdx] );
+    m_acTEncTopList[iViewIdx]->setExtraRPSs                    ( m_extraRPSs[iViewIdx] );
+    for(Int i = 0; i < MAX_TLAYER; i++)
+    {
+      m_acTEncTopList[iViewIdx]->setNumReorderPics             ( m_numReorderPics[iViewIdx][i], i );
+      m_acTEncTopList[iViewIdx]->setMaxDecPicBuffering         ( m_maxDecPicBuffering[iViewIdx][i], i );
+    }
+    for( UInt uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
+    {
+      m_acTEncTopList[iViewIdx]->setLambdaModifier( uiLoop, m_adLambdaModifier[ uiLoop ] );
+    }
+    m_acTEncTopList[iViewIdx]->setQP                           ( m_aiQP[0] );
+  
+    m_acTEncTopList[iViewIdx]->setTemporalLayerQPOffset        ( m_aiTLayerQPOffset );
+    m_acTEncTopList[iViewIdx]->setPad                          ( m_aiPad );
+    
+    m_acTEncTopList[iViewIdx]->setMaxTempLayer                 ( m_maxTempLayer[iViewIdx] );
+
+    m_acTEncTopList[iViewIdx]->setDisInter4x4                  ( m_bDisInter4x4);
+  
+    m_acTEncTopList[iViewIdx]->setUseNSQT( m_enableNSQT );
+    m_acTEncTopList[iViewIdx]->setUseAMP( m_enableAMP );
+  
+  //===== Slice ========
+  
+  //====== Loop/Deblock Filter ========
+    m_acTEncTopList[iViewIdx]->setLoopFilterDisable            ( m_abLoopFilterDisable[0]       );
+    m_acTEncTopList[iViewIdx]->setLoopFilterOffsetInAPS        ( m_loopFilterOffsetInAPS );
+    m_acTEncTopList[iViewIdx]->setLoopFilterBetaOffset         ( m_loopFilterBetaOffsetDiv2  );
+    m_acTEncTopList[iViewIdx]->setLoopFilterTcOffset           ( m_loopFilterTcOffsetDiv2    );
+    m_acTEncTopList[iViewIdx]->setDeblockingFilterControlPresent( m_DeblockingFilterControlPresent);
+
+  //====== Motion search ========
+    m_acTEncTopList[iViewIdx]->setFastSearch                   ( m_iFastSearch  );
+    m_acTEncTopList[iViewIdx]->setSearchRange                  ( m_iSearchRange );
+    m_acTEncTopList[iViewIdx]->setBipredSearchRange            ( m_bipredSearchRange );
+#if DV_V_RESTRICTION_B0037
+    m_acTEncTopList[iViewIdx]->setUseDisparitySearchRangeRestriction ( m_bUseDisparitySearchRangeRestriction );
+    m_acTEncTopList[iViewIdx]->setVerticalDisparitySearchRange( m_iVerticalDisparitySearchRange );
+#endif
+  //====== Quality control ========
+    m_acTEncTopList[iViewIdx]->setMaxDeltaQP                   ( m_iMaxDeltaQP  );
+    m_acTEncTopList[iViewIdx]->setMaxCuDQPDepth                ( m_iMaxCuDQPDepth  );
+
+    m_acTEncTopList[iViewIdx]->setChromaQpOffset               ( m_iChromaQpOffset     );
+    m_acTEncTopList[iViewIdx]->setChromaQpOffset2nd            ( m_iChromaQpOffset2nd  );
+
+#if ADAPTIVE_QP_SELECTION
+    m_acTEncTopList[iViewIdx]->setUseAdaptQpSelect             ( m_bUseAdaptQpSelect   );
+#endif
+
+#if LOSSLESS_CODING
+    Int lowestQP;
+    lowestQP =  - ( (Int)(6*(g_uiBitDepth + g_uiBitIncrement - 8)) );
+    if ((m_iMaxDeltaQP == 0 ) && (m_aiQP[0] == lowestQP) && (m_useLossless == true))
+    {
+      m_bUseAdaptiveQP = false;
+    }
+#endif
+
+    m_acTEncTopList[iViewIdx]->setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
+    m_acTEncTopList[iViewIdx]->setQPAdaptationRange            ( m_iQPAdaptationRange );
+  
+#if HHI_VSO
+    //====== VSO =========
+    m_acTEncTopList[iViewIdx]->setForceLambdaScaleVSO          ( false );
+    m_acTEncTopList[iViewIdx]->setLambdaScaleVSO               ( 1     );
+    m_acTEncTopList[iViewIdx]->setVSOMode                      ( 0     );
+    m_acTEncTopList[iViewIdx]->setUseVSO                       ( false ); 
+#if SAIT_VSO_EST_A0033
+    m_acTEncTopList[iViewIdx]->setUseEstimatedVSD              ( false );
+#endif
+#if LGE_WVSO_A0119
+    m_acTEncTopList[iViewIdx]->setUseWVSO                      ( false ); 
+#endif
+#endif
+
+#if DEPTH_MAP_GENERATION
+    m_acTEncTopList[iViewIdx]->setPredDepthMapGeneration       ( m_uiPredDepthMapGeneration );
+    m_acTEncTopList[iViewIdx]->setPdmPrecision                 ( (UInt)m_cCameraData.getPdmPrecision     () );
+    m_acTEncTopList[iViewIdx]->setPdmScaleNomDelta             (       m_cCameraData.getPdmScaleNomDelta () );
+    m_acTEncTopList[iViewIdx]->setPdmOffset                    (       m_cCameraData.getPdmOffset        () );
+#endif
+#if H3D_IVMP
+    m_acTEncTopList[iViewIdx]->setMultiviewMvPredMode          ( m_uiMultiviewMvPredMode );
+    m_acTEncTopList[iViewIdx]->setMultiviewMvRegMode           ( iViewIdx ? m_uiMultiviewMvRegMode       : 0   );
+    m_acTEncTopList[iViewIdx]->setMultiviewMvRegLambdaScale    ( iViewIdx ? m_dMultiviewMvRegLambdaScale : 0.0 );
+#endif
+#if H3D_IVRP
+    m_acTEncTopList[iViewIdx]->setMultiviewResPredMode         ( m_uiMultiviewResPredMode );
+#endif
+
+  //====== Tool list ========
+    m_acTEncTopList[iViewIdx]->setUseSBACRD                    ( m_bUseSBACRD   );
+    m_acTEncTopList[iViewIdx]->setDeltaQpRD                    ( m_uiDeltaQpRD  );
+    m_acTEncTopList[iViewIdx]->setUseASR                       ( m_bUseASR      );
+    m_acTEncTopList[iViewIdx]->setUseHADME                     ( m_bUseHADME    );
+    m_acTEncTopList[iViewIdx]->setUseALF                       ( m_abUseALF[0]  );
+    m_acTEncTopList[iViewIdx]->setALFEncodePassReduction       ( m_iALFEncodePassReduction );
+#if LOSSLESS_CODING
+    m_acTEncTopList[iViewIdx]->setUseLossless                  ( m_useLossless );
+#endif
+    m_acTEncTopList[iViewIdx]->setALFMaxNumberFilters          ( m_iALFMaxNumberFilters ) ;
+
+    m_acTEncTopList[iViewIdx]->setUseLComb                     ( m_bUseLComb    );
+    m_acTEncTopList[iViewIdx]->setLCMod                        ( m_bLCMod         );
+    m_acTEncTopList[iViewIdx]->setdQPs                         ( m_aidQP        );
+    m_acTEncTopList[iViewIdx]->setUseRDOQ                      ( m_abUseRDOQ[0] );
+    m_acTEncTopList[iViewIdx]->setQuadtreeTULog2MaxSize        ( m_uiQuadtreeTULog2MaxSize );
+    m_acTEncTopList[iViewIdx]->setQuadtreeTULog2MinSize        ( m_uiQuadtreeTULog2MinSize );
+    m_acTEncTopList[iViewIdx]->setQuadtreeTUMaxDepthInter      ( m_uiQuadtreeTUMaxDepthInter );
+    m_acTEncTopList[iViewIdx]->setQuadtreeTUMaxDepthIntra      ( m_uiQuadtreeTUMaxDepthIntra );
+    m_acTEncTopList[iViewIdx]->setUseFastEnc                   ( m_bUseFastEnc  );
+    m_acTEncTopList[iViewIdx]->setUseEarlyCU                   ( m_bUseEarlyCU  ); 
+    m_acTEncTopList[iViewIdx]->setUseFastDecisionForMerge      ( m_useFastDecisionForMerge  );
+    m_acTEncTopList[iViewIdx]->setUseCbfFastMode               ( m_bUseCbfFastMode  );
+#if HHI_INTERVIEW_SKIP
+    m_acTEncTopList[iViewIdx]->setInterViewSkip            ( iViewIdx>0 ? m_bInterViewSkip : false );
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+    m_acTEncTopList[iViewIdx]->setInterViewSkipLambdaScale ( iViewIdx>0 ? (UInt)m_dInterViewSkipLambdaScale : 1 );
+#endif
+#endif
+    m_acTEncTopList[iViewIdx]->setUseLMChroma                  ( m_bUseLMChroma );
+    m_acTEncTopList[iViewIdx]->setUseConstrainedIntraPred      ( m_bUseConstrainedIntraPred );
+    m_acTEncTopList[iViewIdx]->setPCMLog2MinSize               ( m_uiPCMLog2MinSize);
+    m_acTEncTopList[iViewIdx]->setUsePCM                       ( m_usePCM );
+    m_acTEncTopList[iViewIdx]->setPCMLog2MaxSize               ( m_pcmLog2MaxSize);
+
+  //====== Weighted Prediction ========
+    m_acTEncTopList[iViewIdx]->setUseWP                        ( m_bUseWeightPred      );
+    m_acTEncTopList[iViewIdx]->setWPBiPredIdc                  ( m_uiBiPredIdc         );
+  //====== Slice ========
+    m_acTEncTopList[iViewIdx]->setSliceMode                    ( m_iSliceMode                );
+    m_acTEncTopList[iViewIdx]->setSliceArgument                ( m_iSliceArgument            );
+
+  //====== Entropy Slice ========
+    m_acTEncTopList[iViewIdx]->setEntropySliceMode             ( m_iEntropySliceMode         );
+    m_acTEncTopList[iViewIdx]->setEntropySliceArgument         ( m_iEntropySliceArgument     );
+    int iNumPartInCU = 1<<(m_uiMaxCUDepth<<1);
+    if(m_iEntropySliceMode==SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE)
+    {
+      m_acTEncTopList[iViewIdx]->setEntropySliceArgument ( m_iEntropySliceArgument * ( iNumPartInCU >> ( m_iSliceGranularity << 1 ) ) );
+    }
+    if(m_iSliceMode==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE)
+    {
+      m_acTEncTopList[iViewIdx]->setSliceArgument ( m_iSliceArgument * ( iNumPartInCU >> ( m_iSliceGranularity << 1 ) ) );
+    }
+    if(m_iSliceMode==AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE)
+    {
+      m_acTEncTopList[iViewIdx]->setSliceArgument ( m_iSliceArgument );
+    }
+    m_acTEncTopList[iViewIdx]->setSliceGranularity        ( m_iSliceGranularity         );
+    if(m_iSliceMode == 0 )
+    {
+      m_bLFCrossSliceBoundaryFlag = true;
+    }
+    m_acTEncTopList[iViewIdx]->setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+    m_acTEncTopList[iViewIdx]->setUseSAO               ( m_abUseSAO[0]     );
+#if LGE_ILLUCOMP_B0045
+#if LGE_ILLUCOMP_DEPTH_C0046
+    m_acTEncTopList[iViewIdx]->setUseIC                ( m_abUseIC[0]      );
+#else
+    m_acTEncTopList[iViewIdx]->setUseIC                ( m_bUseIC          );
+#endif
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+    m_acTEncTopList[iViewIdx]->setUseIVS               ( m_bUseIVS          );
+#endif
+    m_acTEncTopList[iViewIdx]->setMaxNumOffsetsPerPic (m_maxNumOffsetsPerPic);
+    m_acTEncTopList[iViewIdx]->setSaoInterleavingFlag (m_saoInterleavingFlag);
+    m_acTEncTopList[iViewIdx]->setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag); 
+    m_acTEncTopList[iViewIdx]->setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag); 
+
+    m_acTEncTopList[iViewIdx]->setPictureDigestEnabled(m_pictureDigestEnabled);
+
+    m_acTEncTopList[iViewIdx]->setColumnRowInfoPresent       ( m_iColumnRowInfoPresent );
+    m_acTEncTopList[iViewIdx]->setUniformSpacingIdr          ( m_iUniformSpacingIdr );
+    m_acTEncTopList[iViewIdx]->setNumColumnsMinus1           ( m_iNumColumnsMinus1 );
+    m_acTEncTopList[iViewIdx]->setNumRowsMinus1              ( m_iNumRowsMinus1 );
+    if(m_iUniformSpacingIdr==0)
+    {
+      m_acTEncTopList[iViewIdx]->setColumnWidth              ( m_pchColumnWidth );
+      m_acTEncTopList[iViewIdx]->setRowHeight                ( m_pchRowHeight );
+    }
+    m_acTEncTopList[iViewIdx]->xCheckGSParameters();
+    m_acTEncTopList[iViewIdx]->setTileLocationInSliceHeaderFlag ( m_iTileLocationInSliceHeaderFlag );
+    m_acTEncTopList[iViewIdx]->setTileMarkerFlag              ( m_iTileMarkerFlag );
+    m_acTEncTopList[iViewIdx]->setMaxTileMarkerEntryPoints    ( m_iMaxTileMarkerEntryPoints );
+  
+    Int uiTilesCount          = (m_iNumRowsMinus1+1) * (m_iNumColumnsMinus1+1);
+    m_dMaxTileMarkerOffset    = ((Double)uiTilesCount) / m_iMaxTileMarkerEntryPoints;
+    m_acTEncTopList[iViewIdx]->setMaxTileMarkerOffset         ( m_dMaxTileMarkerOffset );
+    m_acTEncTopList[iViewIdx]->setTileBehaviorControlPresentFlag( m_iTileBehaviorControlPresentFlag );
+    if(uiTilesCount == 1)
+    {
+      m_bLFCrossTileBoundaryFlag = true; 
+    }
+    m_acTEncTopList[iViewIdx]->setLFCrossTileBoundaryFlag( m_bLFCrossTileBoundaryFlag );
+    m_acTEncTopList[iViewIdx]->setWaveFrontSynchro           ( m_iWaveFrontSynchro );
+    m_acTEncTopList[iViewIdx]->setWaveFrontFlush             ( m_iWaveFrontFlush );
+    m_acTEncTopList[iViewIdx]->setWaveFrontSubstreams        ( m_iWaveFrontSubstreams );
+#if TMVP_DEPTH_SWITCH
+    m_acTEncTopList[iViewIdx]->setEnableTMVP                 ( m_enableTMVP[0] );
+#else
+    m_acTEncTopList[iViewIdx]->setEnableTMVP ( m_enableTMVP );
+#endif
+    m_acTEncTopList[iViewIdx]->setUseScalingListId           ( m_useScalingListId  );
+    m_acTEncTopList[iViewIdx]->setScalingListFile            ( m_scalingListFile   );
+    m_acTEncTopList[iViewIdx]->setSignHideFlag(m_signHideFlag);
+    m_acTEncTopList[iViewIdx]->setTSIG(m_signHidingThreshold);
+
+    if(uiTilesCount > 1)
+    {
+      m_bALFParamInSlice = false;
+      m_bALFPicBasedEncode = true;
+    }
+    m_acTEncTopList[iViewIdx]->setALFParamInSlice              ( m_bALFParamInSlice);
+    m_acTEncTopList[iViewIdx]->setALFPicBasedEncode            ( m_bALFPicBasedEncode);
+
+    //====== Depth tools ========
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    m_acTEncTopList[iViewIdx]->setUseDMM                     ( false );
+#endif
+#if H3D_QTL
+    m_acTEncTopList[iViewIdx]->setUseQTLPC                   ( false );
+#endif
+#if HHI_MPI
+    m_acTEncTopList[iViewIdx]->setUseMVI( false );
+#endif
+#if RWTH_SDC_DLT_B0036
+    m_acTEncTopList[iViewIdx]->setUseDLT                      ( false );
+    m_acTEncTopList[iViewIdx]->setUseSDC                      ( false );
+#endif
+  }
+  if( m_bUsingDepthMaps )
+  {
+    for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+    {
+
+#if FLEX_CODING_ORDER_M23723
+      // Detect whether depth comes before than texture for this view
+      Bool isDepthFirst = false;
+      if ( m_b3DVFlexOrder )
+      {
+        for ( Int ii=1; ii<12; ii+=2 )
+        {
+          Int iViewIdxCfg = (Int)(m_pchMVCJointCodingOrder[ii]-'0');
+          if ( iViewIdxCfg == iViewIdx )
+          {
+            if ( m_pchMVCJointCodingOrder[ii-1]=='D' ) // depth comes first for this view
+            {
+              isDepthFirst = true;
+            }
+            else
+            {
+              assert(m_pchMVCJointCodingOrder[ii-1]=='T');
+            }
+            break;
+          }
+        }
+      }
+#endif
+
+      m_depthFrameRcvd.push_back(0);
+      m_acTEncDepthTopList.push_back(new TEncTop); 
+      m_acTVideoIOYuvDepthInputFileList.push_back(new TVideoIOYuv);
+      m_acTVideoIOYuvDepthReconFileList.push_back(new TVideoIOYuv);
+      m_picYuvDepthRec.push_back(new TComList<TComPicYuv*>) ;
+
+      m_acTEncDepthTopList[iViewIdx]->setFrameRate                    ( m_iFrameRate );
+      m_acTEncDepthTopList[iViewIdx]->setFrameSkip                    ( m_FrameSkip );
+      m_acTEncDepthTopList[iViewIdx]->setSourceWidth                  ( m_iSourceWidth );
+      m_acTEncDepthTopList[iViewIdx]->setSourceHeight                 ( m_iSourceHeight );
+      m_acTEncDepthTopList[iViewIdx]->setCroppingMode                 ( m_croppingMode );
+      m_acTEncDepthTopList[iViewIdx]->setCropLeft                     ( m_cropLeft );
+      m_acTEncDepthTopList[iViewIdx]->setCropRight                    ( m_cropRight );
+      m_acTEncDepthTopList[iViewIdx]->setCropTop                      ( m_cropTop );
+      m_acTEncDepthTopList[iViewIdx]->setCropBottom                   ( m_cropBottom );
+      m_acTEncDepthTopList[iViewIdx]->setFrameToBeEncoded             ( m_iFrameToBeEncoded );
+      m_acTEncDepthTopList[iViewIdx]->setViewId                       ( iViewIdx );
+      m_acTEncDepthTopList[iViewIdx]->setIsDepth                      ( true );
+#if QC_MVHEVC_B0046
+      m_acTEncDepthTopList[iViewIdx]->setLayerId                      ( iViewIdx );
+#else
+      m_acTEncDepthTopList[iViewIdx]->setViewOrderIdx                 ( m_cCameraData.getViewOrderIndex()[ iViewIdx ] );
+#endif
+#if VIDYO_VPS_INTEGRATION
+      layerId = iViewIdx * 2 + 1;
+      m_acTEncDepthTopList[iViewIdx]->setLayerId                      ( layerId );
+      m_cVPS.setDepthFlag                                             ( true, layerId );
+      m_cVPS.setViewId                                                ( iViewIdx, layerId );
+      m_cVPS.setViewOrderIdx                                          ( m_cCameraData.getViewOrderIndex()[ iViewIdx ], layerId );
+      m_cVPS.setDependentFlag                                         ( true, layerId );
+      m_cVPS.setDependentLayer                                        ( layerId-1, layerId);
+#endif
+#if FCO_FIX_SPS_CHANGE
+      m_acTEncDepthTopList[iViewIdx]->setCamParPrecision              ( m_cCameraData.getCamParsCodedPrecision  () );
+      m_acTEncDepthTopList[iViewIdx]->setCamParInSliceHeader          ( m_cCameraData.getVaryingCameraParameters() );
+      m_acTEncDepthTopList[iViewIdx]->setCodedScale                   ( m_cCameraData.getCodedScale             () );
+      m_acTEncDepthTopList[iViewIdx]->setCodedOffset                  ( m_cCameraData.getCodedOffset            () );
+#else
+      m_acTEncDepthTopList[iViewIdx]->setCamParPrecision              ( 0 );
+      m_acTEncDepthTopList[iViewIdx]->setCamParInSliceHeader          ( false );
+      m_acTEncDepthTopList[iViewIdx]->setCodedScale                   ( 0 );
+      m_acTEncDepthTopList[iViewIdx]->setCodedOffset                  ( 0 );
+#endif
+
+      //====== Coding Structure ========
+      m_acTEncDepthTopList[iViewIdx]->setIntraPeriod                  ( m_iIntraPeriod );
+      m_acTEncDepthTopList[iViewIdx]->setDecodingRefreshType          ( m_iDecodingRefreshType );
+      m_acTEncDepthTopList[iViewIdx]->setGOPSize                      ( m_iGOPSize );
+      m_acTEncDepthTopList[iViewIdx]->setGopList                      ( m_GOPListsMvc[iViewIdx] );
+      m_acTEncDepthTopList[iViewIdx]->setExtraRPSs                    ( m_extraRPSs[iViewIdx] );
+      for(Int i = 0; i < MAX_TLAYER; i++)
+      {
+        m_acTEncDepthTopList[iViewIdx]->setNumReorderPics             ( m_numReorderPics[iViewIdx][i], i );
+        m_acTEncDepthTopList[iViewIdx]->setMaxDecPicBuffering         ( m_maxDecPicBuffering[iViewIdx][i], i );
+      }
+      for( UInt uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
+      {
+        m_acTEncDepthTopList[iViewIdx]->setLambdaModifier( uiLoop, m_adLambdaModifier[ uiLoop ] );
+      }
+      m_acTEncDepthTopList[iViewIdx]->setQP                           ( m_aiQP[1] );
+
+      m_acTEncDepthTopList[iViewIdx]->setTemporalLayerQPOffset        ( m_aiTLayerQPOffset );
+      m_acTEncDepthTopList[iViewIdx]->setPad                          ( m_aiPad );
+
+      m_acTEncDepthTopList[iViewIdx]->setMaxTempLayer                 ( m_maxTempLayer[iViewIdx] );
+
+      m_acTEncDepthTopList[iViewIdx]->setDisInter4x4                  ( m_bDisInter4x4);
+
+      m_acTEncDepthTopList[iViewIdx]->setUseNSQT( m_enableNSQT );
+      m_acTEncDepthTopList[iViewIdx]->setUseAMP( m_enableAMP );
+
+      //===== Slice ========
+
+      //====== Loop/Deblock Filter ========
+      m_acTEncDepthTopList[iViewIdx]->setLoopFilterDisable            ( m_abLoopFilterDisable[1]   );
+      m_acTEncDepthTopList[iViewIdx]->setLoopFilterOffsetInAPS        ( m_loopFilterOffsetInAPS );
+      m_acTEncDepthTopList[iViewIdx]->setLoopFilterBetaOffset         ( m_loopFilterBetaOffsetDiv2  );
+      m_acTEncDepthTopList[iViewIdx]->setLoopFilterTcOffset           ( m_loopFilterTcOffsetDiv2    );
+      m_acTEncDepthTopList[iViewIdx]->setDeblockingFilterControlPresent( m_DeblockingFilterControlPresent);
+
+      //====== Motion search ========
+      m_acTEncDepthTopList[iViewIdx]->setFastSearch                   ( m_iFastSearch  );
+      m_acTEncDepthTopList[iViewIdx]->setSearchRange                  ( m_iSearchRange );
+      m_acTEncDepthTopList[iViewIdx]->setBipredSearchRange            ( m_bipredSearchRange );
+#if DV_V_RESTRICTION_B0037
+      m_acTEncDepthTopList[iViewIdx]->setUseDisparitySearchRangeRestriction ( m_bUseDisparitySearchRangeRestriction );
+      m_acTEncDepthTopList[iViewIdx]->setVerticalDisparitySearchRange( m_iVerticalDisparitySearchRange );
+#endif
+      //====== Quality control ========
+      m_acTEncDepthTopList[iViewIdx]->setMaxDeltaQP                   ( m_iMaxDeltaQP  );
+      m_acTEncDepthTopList[iViewIdx]->setMaxCuDQPDepth                ( m_iMaxCuDQPDepth  );
+
+      m_acTEncDepthTopList[iViewIdx]->setChromaQpOffset               ( m_iChromaQpOffset     );
+      m_acTEncDepthTopList[iViewIdx]->setChromaQpOffset2nd            ( m_iChromaQpOffset2nd  );
+
+#if ADAPTIVE_QP_SELECTION
+      m_acTEncDepthTopList[iViewIdx]->setUseAdaptQpSelect             ( m_bUseAdaptQpSelect   );
+#endif
+
+      m_acTEncDepthTopList[iViewIdx]->setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
+      m_acTEncDepthTopList[iViewIdx]->setQPAdaptationRange            ( m_iQPAdaptationRange );
+
+      //====== Tool list ========
+      m_acTEncDepthTopList[iViewIdx]->setUseSBACRD                    ( m_bUseSBACRD   );
+      m_acTEncDepthTopList[iViewIdx]->setDeltaQpRD                    ( m_uiDeltaQpRD  );
+      m_acTEncDepthTopList[iViewIdx]->setUseASR                       ( m_bUseASR      );
+      m_acTEncDepthTopList[iViewIdx]->setUseHADME                     ( m_bUseHADME    );
+      m_acTEncDepthTopList[iViewIdx]->setUseALF                       ( m_abUseALF[1]  );
+      m_acTEncDepthTopList[iViewIdx]->setALFEncodePassReduction       ( m_iALFEncodePassReduction );
+#if LOSSLESS_CODING
+      m_acTEncDepthTopList[iViewIdx]->setUseLossless                  ( m_useLossless );
+#endif
+      m_acTEncDepthTopList[iViewIdx]->setALFMaxNumberFilters          ( m_iALFMaxNumberFilters ) ;
+
+      m_acTEncDepthTopList[iViewIdx]->setUseLComb                     ( m_bUseLComb    );
+      m_acTEncDepthTopList[iViewIdx]->setLCMod                        ( m_bLCMod       );
+      m_acTEncDepthTopList[iViewIdx]->setdQPs                         ( m_aidQPdepth   );
+      m_acTEncDepthTopList[iViewIdx]->setUseRDOQ                      ( m_abUseRDOQ[1] );
+      m_acTEncDepthTopList[iViewIdx]->setQuadtreeTULog2MaxSize        ( m_uiQuadtreeTULog2MaxSize );
+      m_acTEncDepthTopList[iViewIdx]->setQuadtreeTULog2MinSize        ( m_uiQuadtreeTULog2MinSize );
+      m_acTEncDepthTopList[iViewIdx]->setQuadtreeTUMaxDepthInter      ( m_uiQuadtreeTUMaxDepthInter );
+      m_acTEncDepthTopList[iViewIdx]->setQuadtreeTUMaxDepthIntra      ( m_uiQuadtreeTUMaxDepthIntra );
+      m_acTEncDepthTopList[iViewIdx]->setUseFastEnc                   ( m_bUseFastEnc  );
+      m_acTEncDepthTopList[iViewIdx]->setUseEarlyCU                   ( m_bUseEarlyCU  ); 
+      m_acTEncDepthTopList[iViewIdx]->setUseFastDecisionForMerge      ( m_useFastDecisionForMerge  );
+      m_acTEncDepthTopList[iViewIdx]->setUseCbfFastMode               ( m_bUseCbfFastMode  );
+#if HHI_INTERVIEW_SKIP
+      m_acTEncDepthTopList[iViewIdx]->setInterViewSkip            ( 0 );
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+      m_acTEncDepthTopList[iViewIdx]->setInterViewSkipLambdaScale ( 1 );
+#endif
+#endif
+      m_acTEncDepthTopList[iViewIdx]->setUseLMChroma                  ( m_bUseLMChroma );
+      m_acTEncDepthTopList[iViewIdx]->setUseConstrainedIntraPred      ( m_bUseConstrainedIntraPred );
+      m_acTEncDepthTopList[iViewIdx]->setPCMLog2MinSize               ( m_uiPCMLog2MinSize);
+      m_acTEncDepthTopList[iViewIdx]->setUsePCM                       ( m_usePCM );
+      m_acTEncDepthTopList[iViewIdx]->setPCMLog2MaxSize               ( m_pcmLog2MaxSize);
+      //====== VSO ========
+#if HHI_VSO
+      m_acTEncDepthTopList[iViewIdx]->setUseVSO                       ( m_bUseVSO      ); //GT: might be enabled/disabled later for VSO Mode 4
+      m_acTEncDepthTopList[iViewIdx]->setForceLambdaScaleVSO          ( m_bForceLambdaScaleVSO );
+      m_acTEncDepthTopList[iViewIdx]->setLambdaScaleVSO               ( m_dLambdaScaleVSO );
+#if HHI_VSO_DIST_INT
+      m_acTEncDepthTopList[iViewIdx]->setAllowNegDist                 ( m_bAllowNegDist );
+#endif
+      m_acTEncDepthTopList[iViewIdx]->setVSOMode                      ( m_uiVSOMode );
+
+#if SAIT_VSO_EST_A0033
+      m_acTEncDepthTopList[iViewIdx]->setUseEstimatedVSD              ( m_bUseEstimatedVSD );
+#endif
+#if LGE_WVSO_A0119
+      m_acTEncDepthTopList[iViewIdx]->setUseWVSO                      ( m_bUseWVSO         );
+#endif
+#endif
+
+#if DEPTH_MAP_GENERATION
+      m_acTEncDepthTopList[iViewIdx]->setPredDepthMapGeneration       ( 0 );
+#endif
+#if H3D_IVMP
+      m_acTEncDepthTopList[iViewIdx]->setMultiviewMvPredMode          ( 0 );
+      m_acTEncDepthTopList[iViewIdx]->setMultiviewMvRegMode           ( 0 );
+      m_acTEncDepthTopList[iViewIdx]->setMultiviewMvRegLambdaScale    ( 0.0 );
+#endif
+#if H3D_IVRP
+      m_acTEncDepthTopList[iViewIdx]->setMultiviewResPredMode         ( 0 );
+#endif
+
+      //====== Weighted Prediction ========
+      m_acTEncDepthTopList[iViewIdx]->setUseWP                        ( m_bUseWeightPred      );
+      m_acTEncDepthTopList[iViewIdx]->setWPBiPredIdc                  ( m_uiBiPredIdc         );
+      //====== Slice ========
+      m_acTEncDepthTopList[iViewIdx]->setSliceMode                    ( m_iSliceMode                );
+      m_acTEncDepthTopList[iViewIdx]->setSliceArgument                ( m_iSliceArgument            );
+
+      //====== Entropy Slice ========
+      m_acTEncDepthTopList[iViewIdx]->setEntropySliceMode             ( m_iEntropySliceMode         );
+      m_acTEncDepthTopList[iViewIdx]->setEntropySliceArgument         ( m_iEntropySliceArgument     );
+      int iNumPartInCU = 1<<(m_uiMaxCUDepth<<1);
+      if(m_iEntropySliceMode==SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE)
+      {
+        m_acTEncDepthTopList[iViewIdx]->setEntropySliceArgument ( m_iEntropySliceArgument * ( iNumPartInCU >> ( m_iSliceGranularity << 1 ) ) );
+      }
+      if(m_iSliceMode==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE)
+      {
+        m_acTEncDepthTopList[iViewIdx]->setSliceArgument ( m_iSliceArgument * ( iNumPartInCU >> ( m_iSliceGranularity << 1 ) ) );
+      }
+      if(m_iSliceMode==AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE)
+      {
+        m_acTEncDepthTopList[iViewIdx]->setSliceArgument ( m_iSliceArgument );
+      }
+      m_acTEncDepthTopList[iViewIdx]->setSliceGranularity        ( m_iSliceGranularity         );
+      if(m_iSliceMode == 0 )
+      {
+        m_bLFCrossSliceBoundaryFlag = true;
+      }
+      m_acTEncDepthTopList[iViewIdx]->setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+      m_acTEncDepthTopList[iViewIdx]->setUseSAO               ( m_abUseSAO[1]     );
+#if LGE_ILLUCOMP_B0045
+#if LGE_ILLUCOMP_DEPTH_C0046
+      m_acTEncDepthTopList[iViewIdx]->setUseIC                ( m_abUseIC[1] );
+#else
+      m_acTEncDepthTopList[iViewIdx]->setUseIC                ( false     );
+#endif
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+     m_acTEncDepthTopList[iViewIdx]->setUseIVS                ( m_bUseIVS );
+#endif
+      m_acTEncDepthTopList[iViewIdx]->setMaxNumOffsetsPerPic (m_maxNumOffsetsPerPic);
+      m_acTEncDepthTopList[iViewIdx]->setSaoInterleavingFlag (m_saoInterleavingFlag);
+      m_acTEncDepthTopList[iViewIdx]->setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag); 
+      m_acTEncDepthTopList[iViewIdx]->setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag); 
+
+      m_acTEncDepthTopList[iViewIdx]->setPictureDigestEnabled(m_pictureDigestEnabled);
+
+      m_acTEncDepthTopList[iViewIdx]->setColumnRowInfoPresent       ( m_iColumnRowInfoPresent );
+      m_acTEncDepthTopList[iViewIdx]->setUniformSpacingIdr          ( m_iUniformSpacingIdr );
+      m_acTEncDepthTopList[iViewIdx]->setNumColumnsMinus1           ( m_iNumColumnsMinus1 );
+      m_acTEncDepthTopList[iViewIdx]->setNumRowsMinus1              ( m_iNumRowsMinus1 );
+      if(m_iUniformSpacingIdr==0)
+      {
+        m_acTEncDepthTopList[iViewIdx]->setColumnWidth              ( m_pchColumnWidth );
+        m_acTEncDepthTopList[iViewIdx]->setRowHeight                ( m_pchRowHeight );
+      }
+      m_acTEncDepthTopList[iViewIdx]->xCheckGSParameters();
+      m_acTEncDepthTopList[iViewIdx]->setTileLocationInSliceHeaderFlag ( m_iTileLocationInSliceHeaderFlag );
+      m_acTEncDepthTopList[iViewIdx]->setTileMarkerFlag              ( m_iTileMarkerFlag );
+      m_acTEncDepthTopList[iViewIdx]->setMaxTileMarkerEntryPoints    ( m_iMaxTileMarkerEntryPoints );
+
+      Int uiTilesCount          = (m_iNumRowsMinus1+1) * (m_iNumColumnsMinus1+1);
+      m_dMaxTileMarkerOffset    = ((Double)uiTilesCount) / m_iMaxTileMarkerEntryPoints;
+      m_acTEncDepthTopList[iViewIdx]->setMaxTileMarkerOffset         ( m_dMaxTileMarkerOffset );
+      m_acTEncDepthTopList[iViewIdx]->setTileBehaviorControlPresentFlag( m_iTileBehaviorControlPresentFlag );
+      if(uiTilesCount == 1)
+      {
+        m_bLFCrossTileBoundaryFlag = true; 
+      }
+      m_acTEncDepthTopList[iViewIdx]->setLFCrossTileBoundaryFlag( m_bLFCrossTileBoundaryFlag );
+      m_acTEncDepthTopList[iViewIdx]->setWaveFrontSynchro           ( m_iWaveFrontSynchro );
+      m_acTEncDepthTopList[iViewIdx]->setWaveFrontFlush             ( m_iWaveFrontFlush );
+      m_acTEncDepthTopList[iViewIdx]->setWaveFrontSubstreams        ( m_iWaveFrontSubstreams );
+#if TMVP_DEPTH_SWITCH
+      m_acTEncDepthTopList[iViewIdx]->setEnableTMVP                 ( m_enableTMVP[1] );
+#else
+      m_acTEncDepthTopList[iViewIdx]->setEnableTMVP ( m_enableTMVP );
+#endif
+      m_acTEncDepthTopList[iViewIdx]->setUseScalingListId           ( m_useScalingListId  );
+      m_acTEncDepthTopList[iViewIdx]->setScalingListFile            ( m_scalingListFile   );
+      m_acTEncDepthTopList[iViewIdx]->setSignHideFlag(m_signHideFlag);
+      m_acTEncDepthTopList[iViewIdx]->setTSIG(m_signHidingThreshold);
+
+      if(uiTilesCount > 1)
+      {
+        m_bALFParamInSlice = false;
+        m_bALFPicBasedEncode = true;
+      }
+      m_acTEncDepthTopList[iViewIdx]->setALFParamInSlice              ( m_bALFParamInSlice);
+      m_acTEncDepthTopList[iViewIdx]->setALFPicBasedEncode            ( m_bALFPicBasedEncode);
+
+  //====== Depth tools ========
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    m_acTEncDepthTopList[iViewIdx]->setUseDMM                     ( m_bUseDMM );
+#endif
+#if FLEX_CODING_ORDER_M23723 && HHI_DMM_PRED_TEX
+    m_acTEncDepthTopList[iViewIdx]->setUseDMM34( (m_b3DVFlexOrder && isDepthFirst) ? false : m_bUseDMM );
+#endif
+
+#if H3D_QTL
+    m_acTEncDepthTopList[iViewIdx]->setUseQTLPC                   (m_bUseQTLPC);
+#endif
+#if HHI_MPI
+#if FLEX_CODING_ORDER_M23723
+    m_acTEncDepthTopList[iViewIdx]->setUseMVI( (m_b3DVFlexOrder && isDepthFirst) ? false : m_bUseMVI );
+#else
+     m_acTEncDepthTopList[iViewIdx]->setUseMVI( m_bUseMVI );
+#endif
+#endif
+#if RWTH_SDC_DLT_B0036
+      m_acTEncDepthTopList[iViewIdx]->setUseDLT                   ( m_bUseDLT );
+      m_acTEncDepthTopList[iViewIdx]->setUseSDC                   ( m_bUseSDC );
+#endif
+    }
+  }
+
+#if H3D_IVMP
+  else if( m_uiMultiviewMvRegMode )
+  {
+    for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+    {
+      m_acTVideoIOYuvDepthInputFileList.push_back( new TVideoIOYuv );
+    }
+  }
+#endif
+
+#if HHI_VSO
+  if ( m_bUseVSO )
+  {
+    if ( m_uiVSOMode == 4 )
+    {
+#if LGE_VSO_EARLY_SKIP_A0093
+      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 );
+#endif
+
+      for ( Int iViewNum = 0; iViewNum < m_iNumberOfViews; iViewNum++ )
+      {
+        for (Int iContent = 0; iContent < 2; iContent++ )
+        {
+          Int iNumOfModels   = m_cRenModStrParser.getNumOfModelsForView(iViewNum, iContent);
+          Bool bUseVSO = (iNumOfModels != 0);
+
+          TEncTop* pcEncTop = ( iContent == 0 ) ? m_acTEncTopList[iViewNum] : m_acTEncDepthTopList[iViewNum];
+          pcEncTop->setUseVSO( bUseVSO );
+          pcEncTop->getRdCost()->setRenModel( bUseVSO ? &m_cRendererModel : NULL );
+
+          for (Int iCurModel = 0; iCurModel < iNumOfModels; iCurModel++ )
+          {
+            Int iModelNum; Int iLeftViewNum; Int iRightViewNum; Int iDump; Int iOrgRefNum; Int iBlendMode;
+
+            m_cRenModStrParser.getSingleModelData  ( iViewNum, iContent, iCurModel, iModelNum, iBlendMode, iLeftViewNum, iRightViewNum, iOrgRefNum, iDump ) ;
+            m_cRendererModel  .createSingleModel   ( iViewNum, iContent, iModelNum, iLeftViewNum, iRightViewNum, (iOrgRefNum != -1), iBlendMode );
+          }
+        }
+      }
+    }
+    else
+    {
+      AOT(true);
+    }
+#if LGE_WVSO_A0119 
+    for ( Int iViewNum = 0; iViewNum < m_iNumberOfViews; iViewNum++ )
+    {
+      for (Int iContent = 0; iContent < 2; iContent++ )
+      {
+        TEncTop* pcEncTop = ( iContent == 0 ) ? m_acTEncTopList[iViewNum] : m_acTEncDepthTopList[iViewNum]; 
+        pcEncTop->setUseWVSO  ( m_bUseWVSO );
+        pcEncTop->setVSOWeight( m_iVSOWeight );
+        pcEncTop->setVSDWeight( m_iVSDWeight );
+        pcEncTop->setDWeight  ( m_iDWeight );
+      }
+    }
+#endif
+  }
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  m_cUsedPelsRenderer.init(m_iSourceWidth, m_iSourceHeight, true, 0, LOG2_DISP_PREC_LUT, true, 0, 0, 0, 0, 0, 6, 4, 1, 0, 6 );
+#endif
+
+}
+
+Void TAppEncTop::xCreateLib()
+{
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+  {
+    m_acTVideoIOYuvInputFileList[iViewIdx]->open( m_pchInputFileList[iViewIdx],     false, m_uiInputBitDepth, m_uiInternalBitDepth );  // read  mode
+    m_acTVideoIOYuvInputFileList[iViewIdx]->skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1]);
+
+    if (m_pchReconFileList[iViewIdx])
+      m_acTVideoIOYuvReconFileList[iViewIdx]->open(m_pchReconFileList[iViewIdx], true, m_uiOutputBitDepth, m_uiInternalBitDepth);  // write mode
+    m_acTEncTopList[iViewIdx]->create();
+    if( m_bUsingDepthMaps )
+    {
+      m_acTVideoIOYuvDepthInputFileList[iViewIdx]->open( m_pchDepthInputFileList[iViewIdx],     false, m_uiInputBitDepth, m_uiInternalBitDepth );  // read  mode
+      m_acTVideoIOYuvDepthInputFileList[iViewIdx]->skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1]);
+
+      if (m_pchDepthReconFileList[iViewIdx])
+        m_acTVideoIOYuvDepthReconFileList[iViewIdx]->open(m_pchDepthReconFileList[iViewIdx], true, m_uiOutputBitDepth, m_uiInternalBitDepth);  // write mode
+      m_acTEncDepthTopList[iViewIdx]->create();
+    }
+#if H3D_IVMP
+    else if( m_uiMultiviewMvRegMode )
+    {
+      m_acTVideoIOYuvDepthInputFileList[iViewIdx]->open( m_pchDepthInputFileList[iViewIdx],     false, m_uiInputBitDepth, m_uiInternalBitDepth );  // read  mode
+      m_acTVideoIOYuvDepthInputFileList[iViewIdx]->skipFrames(m_FrameSkip, m_iSourceWidth, m_iSourceHeight);
+    }
+#endif
+  }
+}
+
+Void TAppEncTop::xDestroyLib()
+{
+  // Video I/O
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+  {
+    m_acTVideoIOYuvInputFileList[iViewIdx]->close();
+    m_acTVideoIOYuvReconFileList[iViewIdx]->close();
+    delete m_acTVideoIOYuvInputFileList[iViewIdx] ; 
+    m_acTVideoIOYuvInputFileList[iViewIdx] = NULL;
+    delete m_acTVideoIOYuvReconFileList[iViewIdx] ; 
+    m_acTVideoIOYuvReconFileList[iViewIdx] = NULL;
+    m_acTEncTopList[iViewIdx]->deletePicBuffer();
+    m_acTEncTopList[iViewIdx]->destroy();
+    delete m_acTEncTopList[iViewIdx] ; 
+    m_acTEncTopList[iViewIdx] = NULL;
+    delete m_picYuvRec[iViewIdx] ; 
+    m_picYuvRec[iViewIdx] = NULL;
+
+    if( iViewIdx < Int( m_acTVideoIOYuvDepthInputFileList.size() ) && m_acTVideoIOYuvDepthInputFileList[iViewIdx] )
+    {
+      m_acTVideoIOYuvDepthInputFileList[iViewIdx]->close( );
+      delete m_acTVideoIOYuvDepthInputFileList[iViewIdx];
+      m_acTVideoIOYuvDepthInputFileList[iViewIdx] = NULL;
+    }
+    if( iViewIdx < Int( m_acTVideoIOYuvDepthReconFileList.size() ) && m_acTVideoIOYuvDepthReconFileList[iViewIdx] )
+    {
+      m_acTVideoIOYuvDepthReconFileList[iViewIdx]->close () ;
+      delete m_acTVideoIOYuvDepthReconFileList[iViewIdx];
+      m_acTVideoIOYuvDepthReconFileList[iViewIdx] = NULL;
+    }
+    if( iViewIdx < Int( m_acTEncDepthTopList.size() ) && m_acTEncDepthTopList[iViewIdx] )
+    {
+      m_acTEncDepthTopList[iViewIdx]->deletePicBuffer();
+      m_acTEncDepthTopList[iViewIdx]->destroy();
+      delete m_acTEncDepthTopList[iViewIdx];
+      m_acTEncDepthTopList[iViewIdx] = NULL;
+    }
+    if( iViewIdx < Int( m_picYuvDepthRec.size() ) && m_picYuvDepthRec[iViewIdx] )
+    {
+      delete m_picYuvDepthRec[iViewIdx] ; 
+      m_picYuvDepthRec[iViewIdx] = NULL;
+    }
+  }
+}
+
+Void TAppEncTop::xInitLib()
+{
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+  {
+    m_acTEncTopList[iViewIdx]->init( this );
+#if QC_MVHEVC_B0046
+  //set setNumDirectRefLayer
+  Int iNumDirectRef = m_acTEncTopList[iViewIdx]->getSPS()->getNumberOfUsableInterViewRefs();
+  m_acTEncTopList[iViewIdx]->getEncTop()->getVPS()->setNumDirectRefLayer(iNumDirectRef, iViewIdx);
+  for(Int iNumIvRef = 0; iNumIvRef < iNumDirectRef; iNumIvRef ++)
+  {
+    Int iLayerId = m_acTEncTopList[iViewIdx]->getSPS()->getUsableInterViewRef(iNumIvRef);
+    m_acTEncTopList[iViewIdx]->getEncTop()->getVPS()->setDirectRefLayerId( iLayerId + iViewIdx, iViewIdx, iNumIvRef);
+  }
+#endif
+  }
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+  {
+    m_acTEncTopList[iViewIdx]->setTEncTopList( &m_acTEncTopList  );
+  }
+  if ( m_bUsingDepthMaps )
+  {
+    for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+    {
+      m_acTEncDepthTopList[iViewIdx]->init( this );
+    }
+    for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+    {
+      m_acTEncDepthTopList[iViewIdx]->setTEncTopList( &m_acTEncDepthTopList  );
+    }
+  }
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - create internal class
+ - initialize internal variable
+ - until the end of input YUV file, call encoding function in TEncTop class
+ - delete allocated buffers
+ - destroy internal class
+ .
+ */
+Void TAppEncTop::encode()
+{
+  fstream bitstreamFile(m_pchBitstreamFile, fstream::binary | fstream::out);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  TComPicYuv*       pcPicYuvOrg = new TComPicYuv;
+  TComPicYuv*       pcDepthPicYuvOrg = new TComPicYuv;
+#if !QC_MVHEVC_B0046
+  TComPicYuv*       pcPdmDepthOrg    = new TComPicYuv;
+#endif
+  TComPicYuv*       pcPicYuvRec = NULL;
+  TComPicYuv*       pcDepthPicYuvRec = NULL;
+
+  // initialize internal class & member variables
+  xInitLibCfg();
+  xCreateLib();
+  xInitLib();
+  
+  // main encoder loop
+  Bool  allEos = false;
+  std::vector<Bool>  eos ;
+  std::vector<Bool>  depthEos ;
+  Int maxGopSize = 0;
+  Int gopSize = 1;
+  
+  list<AccessUnit> outputAccessUnits; ///< list of access units to write out.  is populated by the encoding process
+  maxGopSize = (std::max)(maxGopSize, m_acTEncTopList[0]->getGOPSize());   
+
+  for(Int iViewIdx=0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+  {
+    eos.push_back( false );
+    depthEos.push_back( false );
+    
+#if RWTH_SDC_DLT_B0036
+    if( m_bUsingDepthMaps && m_bUseDLT )
+      xAnalyzeInputBaseDepth(iViewIdx, m_iIntraPeriod);
+#endif
+  }
+
+  // allocate original YUV buffer
+  pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  pcDepthPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+
+#if H3D_IVMP
+  if( m_uiMultiviewMvRegMode )
+  {
+    pcPdmDepthOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  }
+#endif
+
+  while ( !allEos )
+  {
+    for(Int iViewIdx=0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+    {
+      Int frmCnt = 0;
+      while ( !eos[iViewIdx] && !(frmCnt == gopSize))
+      {
+        // get buffers
+        xGetBuffer(pcPicYuvRec, iViewIdx, false);
+
+        // read input YUV file
+        m_acTVideoIOYuvInputFileList[iViewIdx]->read( pcPicYuvOrg, m_aiPad );
+      
+#if H3D_IVMP
+        if( m_uiMultiviewMvRegMode && iViewIdx )
+        {
+          m_acTVideoIOYuvDepthInputFileList[iViewIdx]->read( pcPdmDepthOrg, m_aiPad, m_bUsingDepthMaps );
+        }
+#endif
+
+#if H3D_IVMP
+        m_acTEncTopList[iViewIdx]->initNewPic( pcPicYuvOrg, ( m_uiMultiviewMvRegMode && iViewIdx ? pcPdmDepthOrg : 0 ) );
+#else
+        m_acTEncTopList[iViewIdx]->initNewPic( pcPicYuvOrg );
+#endif
+
+        // increase number of received frames
+        m_frameRcvd[iViewIdx]++;
+        frmCnt++;
+        // check end of file
+        eos[iViewIdx] = ( m_acTVideoIOYuvInputFileList[iViewIdx]->isEof() == 1 ?   true : false  );
+        eos[iViewIdx] = ( m_frameRcvd[iViewIdx] == m_iFrameToBeEncoded ?    true : eos[iViewIdx]   );
+        allEos = allEos|eos[iViewIdx] ; 
+      }
+      if( m_bUsingDepthMaps )
+      {
+        Int frmCntDepth = 0;
+        while ( !depthEos[iViewIdx] && !(frmCntDepth == gopSize))
+        {
+          // get buffers
+          xGetBuffer(pcDepthPicYuvRec, iViewIdx, true);
+
+          // read input YUV file
+          m_acTVideoIOYuvDepthInputFileList[iViewIdx]->read( pcDepthPicYuvOrg, m_aiPad );
+
+          m_acTEncDepthTopList[iViewIdx]->initNewPic( pcDepthPicYuvOrg );
+
+          // increase number of received frames
+          m_depthFrameRcvd[iViewIdx]++;
+          frmCntDepth++;
+          // check end of file
+          depthEos[iViewIdx] = ( m_acTVideoIOYuvDepthInputFileList[iViewIdx]->isEof() == 1 ?   true : false  );
+          depthEos[iViewIdx] = ( m_depthFrameRcvd[iViewIdx] == m_iFrameToBeEncoded ?    true : depthEos[iViewIdx]   );
+          allEos = allEos|depthEos[iViewIdx] ; 
+        }
+      }
+    }
+    for ( Int gopId=0; gopId < gopSize; gopId++ )
+    {
+      Int  iNumEncoded = 0;
+
+#if !QC_MVHEVC_B0046
+      UInt iNextPoc = m_acTEncTopList[0] -> getFrameId( gopId );
+      if ( iNextPoc < m_iFrameToBeEncoded )
+      {
+        m_cCameraData.update( iNextPoc );
+      }
+#endif
+
+
+#if FLEX_CODING_ORDER_M23723
+      if (m_b3DVFlexOrder)
+      {
+        Int  iNumDepthEncoded = 0;
+        iNumEncoded = 0;
+        Int i=0;
+        Int iViewIdx=0;
+        Int iNumberofDepthViews = m_bUsingDepthMaps?m_iNumberOfViews:0;
+        for (Int j=0; j < (m_iNumberOfViews+ iNumberofDepthViews); j++ )
+        {
+          if (m_pchMVCJointCodingOrder[i]=='T')
+          {
+
+            i++;
+            assert(isdigit(m_pchMVCJointCodingOrder[i]));
+            iViewIdx = (Int)(m_pchMVCJointCodingOrder[i]-'0');
+#if (FCO_FIX && MERL_VSP_C0152)
+            Int iCurPoc = m_acTEncTopList[iViewIdx]->getFrameId(gopId);
+            if( iCurPoc < m_acTEncTopList[iViewIdx]->getFrameToBeEncoded() && iViewIdx!=0 )
+            {
+              TComPic* pcBaseTxtPic   = getPicFromView(  0, m_acTEncTopList[iViewIdx]->getFrameId(gopId), false ); //get base view reconstructed texture
+              TComPic* pcBaseDepthPic = getPicFromView(  0, m_acTEncTopList[iViewIdx]->getFrameId(gopId), true );  //get base view reconstructed depth
+              TEncSlice* pEncSlice = m_acTEncTopList[iViewIdx]->getSliceEncoder();
+              pEncSlice->setRefPicBaseTxt(pcBaseTxtPic);
+              pEncSlice->setRefPicBaseDepth(pcBaseDepthPic);
+            }
+            setBWVSPLUT( iViewIdx, gopId, false);            
+#endif
+
+            m_acTEncTopList[iViewIdx]->encode( eos[iViewIdx], pcPicYuvOrg, *m_picYuvRec[iViewIdx], outputAccessUnits, iNumEncoded, gopId );
+            xWriteOutput(bitstreamFile, iNumEncoded, outputAccessUnits, iViewIdx, false);
+            outputAccessUnits.clear();
+            i++;
+          }
+          else if ( m_pchMVCJointCodingOrder[i] == 'D')
+          {
+
+            i++;
+            if( m_bUsingDepthMaps )
+            {
+              assert(isdigit(m_pchMVCJointCodingOrder[i]));
+              iViewIdx = (Int)(m_pchMVCJointCodingOrder[i]-'0');
+
+#if SAIT_VSO_EST_A0033
+              if( m_bUseVSO && iNextPoc < m_iFrameToBeEncoded )
+              {
+                m_cCameraData.xSetDispCoeff( iNextPoc, iViewIdx );
+                m_acTEncDepthTopList[iViewIdx]->setDispCoeff( m_cCameraData.getDispCoeff() );
+              }
+#endif
+#if (FCO_FIX && MERL_VSP_C0152)
+              Int iCurPocDepth = m_acTEncDepthTopList[iViewIdx]->getFrameId(gopId);
+              if( iCurPocDepth < m_acTEncDepthTopList[iViewIdx]->getFrameToBeEncoded() && iViewIdx!=0 )
+              {
+                TComPic* pcBaseDepthPic = getPicFromView(  0, m_acTEncDepthTopList[iViewIdx]->getFrameId(gopId), true );
+                TEncSlice* pcSlice = (TEncSlice*) m_acTEncDepthTopList[iViewIdx]->getSliceEncoder();
+                pcSlice->setRefPicBaseDepth(pcBaseDepthPic);
+              }
+              setBWVSPLUT( iViewIdx, gopId, true);
+#endif
+              m_acTEncDepthTopList[iViewIdx]->encode( depthEos[iViewIdx], pcDepthPicYuvOrg, *m_picYuvDepthRec[iViewIdx], outputAccessUnits, iNumDepthEncoded, gopId );
+              xWriteOutput(bitstreamFile, iNumDepthEncoded, outputAccessUnits, iViewIdx, true);
+              outputAccessUnits.clear();
+              i++;
+            }
+          }
+        }
+      }
+      else
+      {
+
+#endif
+      for(Int iViewIdx=0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+      {
+#if SAIT_VSO_EST_A0033
+        if( m_bUseVSO && iNextPoc < m_iFrameToBeEncoded )
+        {
+          m_cCameraData.xSetDispCoeff( iNextPoc, iViewIdx );
+          m_acTEncDepthTopList[iViewIdx]->setDispCoeff( m_cCameraData.getDispCoeff() );
+        }
+#endif
+        iNumEncoded = 0;
+
+#if MERL_VSP_C0152
+#if MERL_VSP_C0152_BugFix_ForNoDepthCase
+        if(m_bUsingDepthMaps) //VSP can be used only when depth is available as input
+        {
+#endif
+        Int iCurPoc = m_acTEncDepthTopList[iViewIdx]->getFrameId(gopId);
+        if( iCurPoc < m_acTEncDepthTopList[iViewIdx]->getFrameToBeEncoded() && iViewIdx!=0 )
+        {
+          TComPic* pcBaseTxtPic   = getPicFromView(  0, m_acTEncDepthTopList[iViewIdx]->getFrameId(gopId), false ); //get base view reconstructed texture
+          TComPic* pcBaseDepthPic = getPicFromView(  0, m_acTEncDepthTopList[iViewIdx]->getFrameId(gopId), true );  //get base view reconstructed depth
+          TEncSlice* pEncSlice = m_acTEncTopList[iViewIdx]->getSliceEncoder();
+          pEncSlice->setRefPicBaseTxt(pcBaseTxtPic);
+          pEncSlice->setRefPicBaseDepth(pcBaseDepthPic);
+        }
+        setBWVSPLUT( iViewIdx, gopId, false);
+#if MERL_VSP_C0152_BugFix_ForNoDepthCase
+        }
+        else
+        {
+          Int iCurPoc = m_acTEncTopList[iViewIdx]->getFrameId(gopId);
+          if( iCurPoc < m_acTEncTopList[iViewIdx]->getFrameToBeEncoded() && iViewIdx!=0 )
+          {
+            TEncSlice* pEncSlice = m_acTEncTopList[iViewIdx]->getSliceEncoder();
+            pEncSlice->setRefPicBaseTxt(NULL);//Initialize the base view reconstructed texture buffer
+            pEncSlice->setRefPicBaseDepth(NULL);//Initialize the base view reconstructed depth buffer
+          }
+        }
+#endif
+
+#endif
+        // call encoding function for one frame
+        m_acTEncTopList[iViewIdx]->encode( eos[iViewIdx], pcPicYuvOrg, *m_picYuvRec[iViewIdx], outputAccessUnits, iNumEncoded, gopId );
+        xWriteOutput(bitstreamFile, iNumEncoded, outputAccessUnits, iViewIdx, false);
+        outputAccessUnits.clear();
+        if( m_bUsingDepthMaps )
+        {
+          Int  iNumDepthEncoded = 0;
+#if MERL_VSP_C0152
+        Int iCurPocDepth = m_acTEncDepthTopList[iViewIdx]->getFrameId(gopId);
+        if( iCurPocDepth < m_acTEncDepthTopList[iViewIdx]->getFrameToBeEncoded() && iViewIdx!=0 )
+        {
+          TComPic* pcBaseDepthPic = getPicFromView(  0, m_acTEncDepthTopList[iViewIdx]->getFrameId(gopId), true );
+          TEncSlice* pcSlice = (TEncSlice*) m_acTEncDepthTopList[iViewIdx]->getSliceEncoder();
+          pcSlice->setRefPicBaseDepth(pcBaseDepthPic);
+        }
+        setBWVSPLUT( iViewIdx, gopId, true);
+#endif
+
+          // call encoding function for one depth frame
+          m_acTEncDepthTopList[iViewIdx]->encode( depthEos[iViewIdx], pcDepthPicYuvOrg, *m_picYuvDepthRec[iViewIdx], outputAccessUnits, iNumDepthEncoded, gopId );
+          xWriteOutput(bitstreamFile, iNumDepthEncoded, outputAccessUnits, iViewIdx, true);
+          outputAccessUnits.clear();
+        }
+      }
+ 
+#if FLEX_CODING_ORDER_M23723
+      }
+#endif
+
+#if HHI_INTERVIEW_SKIP || H3D_IVMP || H3D_IVRP
+      for( Int iViewIdx = 0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+      {
+        if( iViewIdx < (Int)m_acTEncTopList.size() && m_acTEncTopList[iViewIdx] )
+        {
+          m_acTEncTopList[iViewIdx]->deleteExtraPicBuffers( m_acTEncTopList[iViewIdx]->getGOPEncoder()->getPocLastCoded() );
+        }
+        if( iViewIdx < (Int)m_acTEncDepthTopList.size() && m_acTEncDepthTopList[iViewIdx] )
+        {
+          m_acTEncDepthTopList[iViewIdx]->deleteExtraPicBuffers( m_acTEncTopList[iViewIdx]->getGOPEncoder()->getPocLastCoded() );
+        }
+      }
+#endif
+      for(Int iViewIdx=0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+      {
+        m_acTEncTopList[iViewIdx]->compressMotion( m_acTEncTopList[iViewIdx]->getGOPEncoder()->getPocLastCoded() );
+        if( m_bUsingDepthMaps )
+        {
+          m_acTEncDepthTopList[iViewIdx]->compressMotion( m_acTEncDepthTopList[iViewIdx]->getGOPEncoder()->getPocLastCoded() );
+        }
+      }
+    }
+    gopSize = maxGopSize;
+  }
+  // delete original YUV buffer
+  pcPicYuvOrg->destroy();
+  delete pcPicYuvOrg;
+  pcPicYuvOrg = NULL;
+  pcDepthPicYuvOrg->destroy();
+  delete pcDepthPicYuvOrg;
+  pcDepthPicYuvOrg = NULL;
+  
+#if !QC_MVHEVC_B0046
+  if ( pcPdmDepthOrg != NULL && m_uiMultiviewMvRegMode )
+  {
+    pcPdmDepthOrg->destroy();
+    delete pcPdmDepthOrg;     
+    pcPdmDepthOrg = NULL; 
+  };
+#endif
+  
+  for(Int iViewIdx=0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+  {
+    m_acTEncTopList[iViewIdx]->printOutSummary(m_acTEncTopList[iViewIdx]->getNumAllPicCoded());
+    if ( m_bUsingDepthMaps )
+    {
+      m_acTEncDepthTopList[iViewIdx]->printOutSummary(m_acTEncDepthTopList[iViewIdx]->getNumAllPicCoded());
+    }
+  }
+
+  // delete buffers & classes
+  xDeleteBuffer();
+  xDestroyLib();
+
+  return;
+}
+
+TEncTop*  TAppEncTop::getTEncTop( Int viewId, Bool isDepth )    
+{ 
+  if ( isDepth )  
+  {
+    return m_acTEncDepthTopList[viewId]; 
+  } 
+  else
+  { 
+    return m_acTEncTopList[viewId]; 
+  } 
+}
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - application has picture buffer list with size of GOP
+ - picture buffer list acts as ring buffer
+ - end of the list has the latest picture
+ .
+ */
+Void TAppEncTop::xGetBuffer( TComPicYuv*& rpcPicYuvRec, Int iViewIdx, Bool isDepth)
+{
+  assert( m_iGOPSize > 0 );
+  
+  if( !isDepth )
+  {
+    if ( m_picYuvRec[iViewIdx]->size() == (UInt)m_iGOPSize )
+    {
+      rpcPicYuvRec = m_picYuvRec[iViewIdx]->popFront();
+    }
+    else
+    {
+      rpcPicYuvRec = new TComPicYuv; 
+      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+    }
+    m_picYuvRec[iViewIdx]->pushBack( rpcPicYuvRec );
+  }
+  else
+  {
+    if ( m_picYuvDepthRec[iViewIdx]->size() == (UInt)m_iGOPSize )
+    {
+      rpcPicYuvRec = m_picYuvDepthRec[iViewIdx]->popFront();
+    }
+    else
+    {
+      rpcPicYuvRec = new TComPicYuv; 
+      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+    }
+    m_picYuvDepthRec[iViewIdx]->pushBack( rpcPicYuvRec );
+  }
+}
+
+Void TAppEncTop::xDeleteBuffer( )
+{
+  for(Int iViewIdx=0; iViewIdx<m_picYuvRec.size(); iViewIdx++)
+  {
+    if(m_picYuvRec[iViewIdx])
+    {
+      TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_picYuvRec[iViewIdx]->begin();
+      Int iSize = Int( m_picYuvRec[iViewIdx]->size() );
+      for ( Int i = 0; i < iSize; i++ )
+      {
+        TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+        if(pcPicYuvRec)
+        {
+          pcPicYuvRec->destroy();
+          delete pcPicYuvRec; 
+          pcPicYuvRec = NULL;
+        }
+      }
+    } 
+  }
+  for(Int iViewIdx=0; iViewIdx<m_picYuvDepthRec.size(); iViewIdx++)
+  {
+    if(m_picYuvDepthRec[iViewIdx])
+    {
+      TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_picYuvDepthRec[iViewIdx]->begin();
+      Int iSize = Int( m_picYuvDepthRec[iViewIdx]->size() );
+      for ( Int i = 0; i < iSize; i++ )
+      {
+        TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+        if(pcPicYuvRec)
+        {
+          pcPicYuvRec->destroy();
+          delete pcPicYuvRec; 
+          pcPicYuvRec = NULL;
+        }
+      } 
+    }
+  }
+}
+
+/** \param iNumEncoded  number of encoded frames
+ */
+Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, std::list<AccessUnit>& accessUnits, Int iViewIdx, Bool isDepth )
+{
+  Int i;
+  
+  if( iNumEncoded > 0 )
+  {
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = !isDepth ? m_picYuvRec[iViewIdx]->end() : m_picYuvDepthRec[iViewIdx]->end();
+  
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+  
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+      if( !isDepth )
+      {
+        if (m_pchReconFileList[iViewIdx])
+        {
+          m_acTVideoIOYuvReconFileList[iViewIdx]->write( pcPicYuvRec, m_cropLeft, m_cropRight, m_cropTop, m_cropBottom );
+        }
+      }
+      else
+      {
+        if (m_pchDepthReconFileList[iViewIdx])
+        {
+          m_acTVideoIOYuvDepthReconFileList[iViewIdx]->write( pcPicYuvRec, m_cropLeft, m_cropRight, m_cropTop, m_cropBottom );
+        }
+      }
+    }
+  }
+  if( ! accessUnits.empty() )
+  {
+    list<AccessUnit>::iterator aUIter;
+    for( aUIter = accessUnits.begin(); aUIter != accessUnits.end(); aUIter++ )
+    {
+      const vector<unsigned>& stats = writeAnnexB(bitstreamFile, *aUIter);
+      rateStatsAccum(*aUIter, stats);
+    }
+  }
+}
+
+
+TComPicYuv* TAppEncTop::xGetPicYuvFromView( Int iViewIdx, Int iPoc, Bool bDepth, Bool bRecon )
+{
+  TComPic*    pcPic = xGetPicFromView( iViewIdx, iPoc, bDepth);
+  TComPicYuv* pcPicYuv = NULL;
+
+  if (pcPic != NULL)
+  {
+    if( bRecon )
+    {
+      if ( pcPic->getReconMark() )
+      {
+        pcPicYuv = pcPic->getPicYuvRec();
+      }
+    }
+    else
+    {
+      pcPicYuv = pcPic->getPicYuvOrg();
+    }
+  };
+
+  return pcPicYuv;
+};
+
+/**
+ *
+ */
+void TAppEncTop::rateStatsAccum(const AccessUnit& au, const std::vector<unsigned>& annexBsizes)
+{
+  AccessUnit::const_iterator it_au = au.begin();
+  vector<unsigned>::const_iterator it_stats = annexBsizes.begin();
+
+  for (; it_au != au.end(); it_au++, it_stats++)
+  {
+    switch ((*it_au)->m_nalUnitType)
+    {
+    case NAL_UNIT_CODED_SLICE:
+#if !QC_REM_IDV_B0046
+    case NAL_UNIT_CODED_SLICE_IDV:
+#endif
+    case NAL_UNIT_CODED_SLICE_TLA:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_IDR:
+    case NAL_UNIT_SPS:
+    case NAL_UNIT_PPS:
+#if VIDYO_VPS_INTEGRATION
+    case NAL_UNIT_VPS:
+#endif
+      m_essentialBytes += *it_stats;
+      break;
+    default:
+      break;
+    }
+
+    m_totalBytes += *it_stats;
+  }
+}
+
+#if HHI_INTERVIEW_SKIP
+Void TAppEncTop::getUsedPelsMap( Int iViewIdx, Int iPoc, TComPicYuv* pcPicYuvUsedSplsMap )
+{
+  AOT( iViewIdx <= 0);
+  AOT( iViewIdx >= m_iNumberOfViews );
+  AOF( m_cCameraData.getCurFrameId() == iPoc );
+  Int iViewSIdx      = m_cCameraData.getBaseId2SortedId()[iViewIdx];
+  Int iFirstViewSIdx = m_cCameraData.getBaseId2SortedId()[0];
+
+  AOT( iViewSIdx == iFirstViewSIdx );
+
+  Bool bFirstIsLeft = (iFirstViewSIdx < iViewSIdx);
+
+  m_cUsedPelsRenderer.setShiftLUTs(
+      m_cCameraData.getBaseViewShiftLUTD()[0][iViewIdx],
+      m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+      m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+      m_cCameraData.getBaseViewShiftLUTD()[0][iViewIdx],
+      m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+      m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+      -1
+      );
+
+  TComPicYuv* pcPicYuvDepth = xGetPicYuvFromView(0, iPoc, true, true );
+  AOF( pcPicYuvDepth);
+
+  m_cUsedPelsRenderer.getUsedSamplesMap( pcPicYuvDepth, pcPicYuvUsedSplsMap, bFirstIsLeft );
+}
+#endif
+#if HHI_VSO
+Void TAppEncTop::setupRenModel( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset )
+{
+  m_cRendererModel.setupPart( iHorOffset, Min( g_uiMaxCUHeight, m_iSourceHeight - iHorOffset ) ); 
+  Int iEncViewSIdx = m_cCameraData.getBaseId2SortedId()[ iEncViewIdx ];
+
+  // setup base views
+  Int iNumOfBV = m_cRenModStrParser.getNumOfBaseViewsForView( iEncViewSIdx, iEncContent );
+
+  for (Int iCurView = 0; iCurView < iNumOfBV; iCurView++ )
+  {
+    Int iBaseViewSIdx;
+    Int iVideoDistMode;
+    Int iDepthDistMode;
+
+    m_cRenModStrParser.getBaseViewData( iEncViewSIdx, iEncContent, iCurView, iBaseViewSIdx, iVideoDistMode, iDepthDistMode );
+
+    AOT( iVideoDistMode < 0 || iVideoDistMode > 2 );
+
+    Int iBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iBaseViewSIdx ];
+
+    TComPicYuv* pcPicYuvVideoRec  = xGetPicYuvFromView( iBaseViewIdx, iPoc, false, true  );
+    TComPicYuv* pcPicYuvDepthRec  = xGetPicYuvFromView( iBaseViewIdx, iPoc, true , true  );
+    TComPicYuv* pcPicYuvVideoOrg  = xGetPicYuvFromView( iBaseViewIdx, iPoc, false, false );
+    TComPicYuv* pcPicYuvDepthOrg  = xGetPicYuvFromView( iBaseViewIdx, iPoc, true , false );
+
+    TComPicYuv* pcPicYuvVideoRef  = ( iVideoDistMode == 2 ) ? pcPicYuvVideoOrg  : NULL;
+    TComPicYuv* pcPicYuvDepthRef  = ( iDepthDistMode == 2 ) ? pcPicYuvDepthOrg  : NULL;
+
+    TComPicYuv* pcPicYuvVideoTest = ( iVideoDistMode == 0 ) ? pcPicYuvVideoOrg  : pcPicYuvVideoRec;
+    TComPicYuv* pcPicYuvDepthTest = ( iDepthDistMode == 0 ) ? pcPicYuvDepthOrg  : pcPicYuvDepthRec;
+
+    AOT( (iVideoDistMode == 2) != (pcPicYuvVideoRef != NULL) );
+    AOT( (iDepthDistMode == 2) != (pcPicYuvDepthRef != NULL) );
+    AOT( pcPicYuvDepthTest == NULL );
+    AOT( pcPicYuvVideoTest == NULL );
+
+    m_cRendererModel.setBaseView( iBaseViewSIdx, pcPicYuvVideoTest, pcPicYuvDepthTest, pcPicYuvVideoRef, pcPicYuvDepthRef );
+  }
+
+  m_cRendererModel.setErrorMode( iEncViewSIdx, iEncContent, 0 );
+  // setup virtual views
+  Int iNumOfSV  = m_cRenModStrParser.getNumOfModelsForView( iEncViewSIdx, iEncContent );
+  for (Int iCurView = 0; iCurView < iNumOfSV; iCurView++ )
+  {
+    Int iOrgRefBaseViewSIdx;
+    Int iLeftBaseViewSIdx;
+    Int iRightBaseViewSIdx;
+    Int iSynthViewRelNum;
+    Int iModelNum;
+    Int iBlendMode;
+    m_cRenModStrParser.getSingleModelData(iEncViewSIdx, iEncContent, iCurView, iModelNum, iBlendMode,iLeftBaseViewSIdx, iRightBaseViewSIdx, iOrgRefBaseViewSIdx, iSynthViewRelNum );
+
+    Int iLeftBaseViewIdx    = -1;
+    Int iRightBaseViewIdx   = -1;
+
+    TComPicYuv* pcPicYuvOrgRef  = NULL;
+    Int**      ppiShiftLUTLeft  = NULL;
+    Int**      ppiShiftLUTRight = NULL;
+    Int**      ppiBaseShiftLUTLeft  = NULL;
+    Int**      ppiBaseShiftLUTRight = NULL;
+
+
+    Int        iDistToLeft      = -1;
+
+    Int iSynthViewIdx = m_cCameraData.synthRelNum2Idx( iSynthViewRelNum );
+
+    if ( iLeftBaseViewSIdx != -1 )
+    {
+      iLeftBaseViewIdx   = m_cCameraData.getBaseSortedId2Id()   [ iLeftBaseViewSIdx ];
+      ppiShiftLUTLeft    = m_cCameraData.getSynthViewShiftLUTI()[ iLeftBaseViewIdx  ][ iSynthViewIdx  ];
+    }
+
+    if ( iRightBaseViewSIdx != -1 )
+    {
+      iRightBaseViewIdx  = m_cCameraData.getBaseSortedId2Id()   [iRightBaseViewSIdx ];
+      ppiShiftLUTRight   = m_cCameraData.getSynthViewShiftLUTI()[ iRightBaseViewIdx ][ iSynthViewIdx ];
+    }
+
+    if ( iRightBaseViewSIdx != -1 && iLeftBaseViewSIdx != -1 )
+    {
+      iDistToLeft    = m_cCameraData.getRelDistLeft(  iSynthViewIdx , iLeftBaseViewIdx, iRightBaseViewIdx);
+      ppiBaseShiftLUTLeft  = m_cCameraData.getBaseViewShiftLUTI() [ iLeftBaseViewIdx  ][ iRightBaseViewIdx ];
+      ppiBaseShiftLUTRight = m_cCameraData.getBaseViewShiftLUTI() [ iRightBaseViewIdx ][ iLeftBaseViewIdx  ];
+
+    }
+
+    if ( iOrgRefBaseViewSIdx != -1 )
+    {
+      pcPicYuvOrgRef = xGetPicYuvFromView( m_cCameraData.getBaseSortedId2Id()[ iOrgRefBaseViewSIdx ] , iPoc, false, false );
+      AOF ( pcPicYuvOrgRef );
+    }
+
+    m_cRendererModel.setSingleModel( iModelNum, ppiShiftLUTLeft, ppiBaseShiftLUTLeft, ppiShiftLUTRight, ppiBaseShiftLUTRight, iDistToLeft, pcPicYuvOrgRef );
+  }
+}
+#endif
+
+
+
+/*
+void TAppEncTop::printRateSummary()
+{
+  double time = (double) m_iFrameRcvd / m_iFrameRate;
+  printf("Bytes written to file: %u (%.3f kbps)\n", m_totalBytes, 0.008 * m_totalBytes / time);
+#if VERBOSE_RATE
+  printf("Bytes for SPS/PPS/Slice (Incl. Annex B): %u (%.3f kbps)\n", m_essentialBytes, 0.008 * m_essentialBytes / time);
+#endif
+}
+*/
+
+std::vector<TComPic*> TAppEncTop::getInterViewRefPics( Int viewId, Int poc, Bool isDepth, TComSPS* sps )
+{
+  std::vector<TComPic*> apcRefPics( sps->getNumberOfUsableInterViewRefs(), (TComPic*)NULL );
+  for( Int k = 0; k < sps->getNumberOfUsableInterViewRefs(); k++ )
+  {
+    TComPic* pcRefPic = xGetPicFromView( sps->getUsableInterViewRef( k ) + viewId, poc, isDepth );
+    assert( pcRefPic != NULL );
+    apcRefPics[k] = pcRefPic;
+  }
+  return apcRefPics;
+}
+
+TComPic* TAppEncTop::xGetPicFromView( Int viewIdx, Int poc, Bool isDepth )
+{
+  assert( ( viewIdx >= 0 ) && ( viewIdx < m_iNumberOfViews ) );
+
+  TComList<TComPic*>* apcListPic = (isDepth ?  m_acTEncDepthTopList[viewIdx] : m_acTEncTopList[viewIdx])->getListPic() ;
+
+  TComPic* pcPic = NULL;
+  for(TComList<TComPic*>::iterator it=apcListPic->begin(); it!=apcListPic->end(); it++)
+  {
+    if( (*it)->getPOC() == poc )
+    {
+      pcPic = *it ;
+      break ;
+    }
+  }
+
+  return pcPic;
+};
+  
+#if RWTH_SDC_DLT_B0036
+Void TAppEncTop::xAnalyzeInputBaseDepth(Int iViewIdx, UInt uiNumFrames)
+{
+  TComPicYuv*       pcDepthPicYuvOrg = new TComPicYuv;
+  // allocate original YUV buffer
+  pcDepthPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  
+  TVideoIOYuv* depthVideoFile = new TVideoIOYuv;
+  
+  UInt uiMaxDepthValue = g_uiIBDI_MAX;
+  
+  Bool abValidDepths[256];
+  
+  depthVideoFile->open( m_pchDepthInputFileList[iViewIdx], false, m_uiInputBitDepth, m_uiInternalBitDepth );  // read  mode
+  
+  // initialize boolean array
+  for(Int p=0; p<=uiMaxDepthValue; p++)
+    abValidDepths[p] = false;
+  
+  Int iHeight   = pcDepthPicYuvOrg->getHeight();
+  Int iWidth    = pcDepthPicYuvOrg->getWidth();
+  Int iStride   = pcDepthPicYuvOrg->getStride();
+  
+  Pel* pInDM    = pcDepthPicYuvOrg->getLumaAddr();
+  
+  for(Int uiFrame=0; uiFrame < uiNumFrames; uiFrame++ )
+  {
+    depthVideoFile->read( pcDepthPicYuvOrg, m_aiPad, false );
+    
+    // check all pixel values
+    for (Int i=0; i<iHeight; i++)
+    {
+      Int rowOffset = i*iStride;
+      
+      for (Int j=0; j<iWidth; j++)
+      {
+        Pel depthValue = pInDM[rowOffset+j];
+        abValidDepths[depthValue] = true;
+      }
+    }
+  }
+  
+  depthVideoFile->close();
+  
+  pcDepthPicYuvOrg->destroy();
+  delete pcDepthPicYuvOrg;
+  
+  // convert boolean array to idx2Depth LUT
+  UInt* auiIdx2DepthValue = (UInt*) calloc(uiMaxDepthValue, sizeof(UInt));
+  UInt uiNumDepthValues = 0;
+  for(UInt p=0; p<=uiMaxDepthValue; p++)
+  {
+    if( abValidDepths[p] == true)
+    {
+      auiIdx2DepthValue[uiNumDepthValues++] = p;
+    }
+  }
+  
+  if( uiNumFrames == 0 || ceil(Log2(uiNumDepthValues)) == ceil(Log2(g_uiIBDI_MAX)) )
+  {
+    // don't use DLT
+    m_acTEncDepthTopList[iViewIdx]->setUseDLT(false);
+    m_acTEncDepthTopList[iViewIdx]->getSPS()->setUseDLT(false);
+  }
+  
+  // assign LUT
+  if( m_acTEncDepthTopList[iViewIdx]->getUseDLT() )
+    m_acTEncDepthTopList[iViewIdx]->getSPS()->setDepthLUTs(auiIdx2DepthValue, uiNumDepthValues);
+  else
+    m_acTEncDepthTopList[iViewIdx]->getSPS()->setDepthLUTs();
+  
+  // free temporary memory
+  free(auiIdx2DepthValue);
+}
+#endif
+
+#if MERL_VSP_C0152
+Void TAppEncTop::setBWVSPLUT(Int iCodedViewIdx, Int gopId, Bool isDepth)
+{
+  //first view does not have VSP 
+  if((iCodedViewIdx == 0)) return;
+
+  AOT( iCodedViewIdx <= 0);
+  AOT( iCodedViewIdx >= m_iNumberOfViews );
+
+  Int iNeighborViewId = 0;
+  //setting look-up table
+  Int* piShiftLUT = m_cCameraData.getBaseViewShiftLUTI()[iNeighborViewId][iCodedViewIdx][0];
+
+  if(isDepth)
+  {
+    TEncSlice* pcEncSlice = (TEncSlice*) m_acTEncDepthTopList[iCodedViewIdx]->getSliceEncoder();
+    pcEncSlice->setBWVSPLUTParam(  piShiftLUT, LOG2_DISP_PREC_LUT );
+  }
+  else
+  {
+    TEncSlice* pcEncSlice = (TEncSlice*) m_acTEncTopList[iCodedViewIdx]->getSliceEncoder();
+    pcEncSlice->setBWVSPLUTParam(  piShiftLUT, LOG2_DISP_PREC_LUT );
+  }
+
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncTop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/TAppEncTop.h	(revision 341)
@@ -0,0 +1,176 @@
+/* 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-2012, 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     TAppEncTop.h
+    \brief    Encoder application class (header)
+*/
+
+#ifndef __TAPPENCTOP__
+#define __TAPPENCTOP__
+
+#include <list>
+#include <ostream>
+
+#include "TLibEncoder/TEncTop.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TLibCommon/AccessUnit.h"
+#include "TAppEncCfg.h"
+#include "TLibCommon/TComDepthMapGenerator.h"
+#if HHI_VSO || HHI_INTERVIEW_SKIP
+#include "../../Lib/TLibRenderer/TRenTop.h"
+#endif
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder application class
+class TAppEncTop : public TAppEncCfg
+{
+private:
+  // class interface
+  std::vector<TEncTop*>      m_acTEncTopList ;
+  std::vector<TEncTop*>      m_acTEncDepthTopList ;
+  std::vector<TVideoIOYuv*>  m_acTVideoIOYuvInputFileList;  ///< input YUV file
+  std::vector<TVideoIOYuv*>  m_acTVideoIOYuvDepthInputFileList;
+  std::vector<TVideoIOYuv*>  m_acTVideoIOYuvReconFileList;  ///< output reconstruction file
+  std::vector<TVideoIOYuv*>  m_acTVideoIOYuvDepthReconFileList;
+
+  std::vector< TComList<TComPicYuv*>* >  m_picYuvRec;       ///< list of reconstruction YUV files
+  std::vector< TComList<TComPicYuv*>* >  m_picYuvDepthRec;         
+
+  std::vector<Int>           m_frameRcvd;                  ///< number of received frames
+  std::vector<Int>           m_depthFrameRcvd;   
+
+  unsigned                   m_essentialBytes;
+  unsigned                   m_totalBytes;
+
+#if DEPTH_MAP_GENERATION
+#if VIDYO_VPS_INTEGRATION
+  TComVPSAccess               m_cVPSAccess;
+#endif
+  TComSPSAccess               m_cSPSAccess;
+  TComAUPicAccess             m_cAUPicAccess;
+#endif
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  TComVPS                     m_cVPS;
+#endif
+  
+#if HHI_VSO
+  TRenTop                     m_cRendererTop; 
+  TRenModel                   m_cRendererModel;   
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  TRenTop  m_cUsedPelsRenderer;                               ///< renderer for used pels map
+#endif
+
+protected:
+  // initialization
+  Void  xCreateLib        ();                               ///< create files & encoder class
+  Void  xInitLibCfg       ();                               ///< initialize internal variables
+  Void  xInitLib          ();                               ///< initialize encoder class
+  Void  xDestroyLib       ();                               ///< destroy encoder class
+  
+  /// obtain required buffers
+  Void xGetBuffer(TComPicYuv*& rpcPicYuvRec, Int iViewIdx, Bool isDepth);
+  
+  /// delete allocated buffers
+  Void  xDeleteBuffer     ();
+  
+  // file I/O
+  Void xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, std::list<AccessUnit>& accessUnits, Int iViewIdx, Bool isDepth); ///< write bitstream to file
+  void rateStatsAccum(const AccessUnit& au, const std::vector<unsigned>& stats);
+  // void printRateSummary();
+  
+  TComPic* xGetPicFromView( Int viewId, Int iPoc, Bool isDepth );
+  TComPicYuv* xGetPicYuvFromView( Int iViewIdx, Int iPoc, Bool bDepth, Bool bRecon );
+  
+public:
+  TAppEncTop();
+  virtual ~TAppEncTop();
+
+
+  Void        encode      ();                               ///< main encoding function
+  TEncTop*    getTEncTop( Int viewId, Bool isDepth );   
+
+  std::vector<TComPic*> getInterViewRefPics( Int viewId, Int poc, Bool isDepth, TComSPS* sps );
+  TComPic*              getPicFromView     ( Int viewId, Int poc, Bool isDepth ) { return xGetPicFromView( viewId, poc, isDepth ); }
+  TComPicYuv*           getPicYuvFromView  ( Int iViewIdx, Int iPoc, bool bDepth, Bool bRecon ) { return xGetPicYuvFromView( iViewIdx, iPoc, bDepth, bRecon ); }
+
+#if HHI_INTERVIEW_SKIP
+  Void                  getUsedPelsMap   ( Int iViewIdx, Int iPoc, TComPicYuv* pcPicYuvUsedPelsMap );
+#endif
+#if HHI_VSO
+  Void                  setupRenModel    ( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset );
+#endif
+  
+#if QC_MVHEVC_B0046
+  TComVPS*          getVPS()  { return &m_cVPS; }
+#endif
+#if VIDYO_VPS_INTEGRATION
+  TComVPS*          getVPS()  { return &m_cVPS; }
+  TComVPSAccess*    getVPSAccess  () { return &m_cVPSAccess;   }
+#endif
+  
+#if DEPTH_MAP_GENERATION
+  TComSPSAccess*    getSPSAccess  () { return &m_cSPSAccess;   }
+  TComAUPicAccess*  getAUPicAccess() { return &m_cAUPicAccess; }
+#endif
+
+#if HHI_VSO
+  TRenModel* getRenModel    () { return  &m_cRendererModel ; }; 
+#endif
+
+#if HHI_VSO
+private:
+  Void  xStoreVSORefPicsInBuffer();                                                   ///< read in External Ref pic from file and store in buffer
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  Void  xAnalyzeInputBaseDepth(Int iViewIdx, UInt uiNumFrames);
+#endif
+
+#if MERL_VSP_C0152
+  Void setBWVSPLUT( Int iCodedViewIdx, Int gopId, Bool isDepth);
+#endif
+};// END CLASS DEFINITION TAppEncTop
+
+//! \}
+
+#endif // __TAPPENCTOP__
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/encmain.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/encmain.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppEncoder/encmain.cpp	(revision 341)
@@ -0,0 +1,87 @@
+/* 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-2012, 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     encmain.cpp
+    \brief    Encoder application main
+*/
+
+#include <time.h>
+#include "TAppEncTop.h"
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppEncTop  cTAppEncTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "3D-HTM Software: Encoder Version [%s] based on HM Version [%s]", NV_VERSION, HM_VERSION );  
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // create application encoder class
+  cTAppEncTop.create();
+
+  // parse configuration
+  if(!cTAppEncTop.parseCfg( argc, argv ))
+  {
+    cTAppEncTop.destroy();
+    return 1;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call encoding function
+  cTAppEncTop.encode();
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  // destroy application encoder class
+  cTAppEncTop.destroy();
+
+  return 0;
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrCfg.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrCfg.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrCfg.cpp	(revision 341)
@@ -0,0 +1,130 @@
+/* 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-2011, 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 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     TAppExtrCfg.cpp
+    \brief    Extractor configuration class
+*/
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include "TAppExtrCfg.h"
+#include "../../Lib/TAppCommon/program_options_lite.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param argc number of arguments
+    \param argv array of arguments
+ */
+Bool TAppExtrCfg::parseCfg( Int argc, Char* argv[] )
+{
+  bool do_help = false;
+  string cfg_InputBitstreamFile;
+  string cfg_OutputBitstreamFile;
+  string cfg_SpsInfoFile;
+  string cfg_ExtractLayerIds;
+
+  po::Options opts;
+  opts.addOptions()
+  ("help",                   do_help,                   false,      "this help text")
+  ("InputBitstreamFile,i",   cfg_InputBitstreamFile,    string(""), "bitstream input file name")
+  ("OutputBitstreamFile,o",  cfg_OutputBitstreamFile,   string(""), "bitstream output file name")
+  ("SpsInfoFile,s",          cfg_SpsInfoFile,           string(""), "SPS info file name")
+  ("ExtractLayerIds,e",      cfg_ExtractLayerIds,       string(""), "comma-separated list of layer IDs for extraction")
+  ;
+
+  po::setDefaults(opts);
+  const list<const char*>& argv_unhandled = po::scanArgv(opts, argc, (const char**) argv);
+
+  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)
+  {
+    po::doHelp(cout, opts);
+    return false;
+  }
+
+  /* convert std::string to c string for compatability */
+  m_pchInputBitstreamFile = cfg_InputBitstreamFile.empty() ? NULL : strdup(cfg_InputBitstreamFile.c_str());
+  m_pchOutputBitstreamFile = cfg_OutputBitstreamFile.empty() ? NULL : strdup(cfg_OutputBitstreamFile.c_str());
+  m_pchSpsInfoFile = cfg_SpsInfoFile.empty() ? NULL : strdup(cfg_SpsInfoFile.c_str());
+
+  xSplitUIntString( cfg_ExtractLayerIds, m_suiExtractLayerIds );
+
+  if (!m_pchInputBitstreamFile)
+  {
+    fprintf(stderr, "No input file specifed, aborting\n");
+    return false;
+  }
+
+  if (!m_pchOutputBitstreamFile && !m_pchSpsInfoFile)
+  {
+    fprintf(stderr, "No output file specifed, aborting\n");
+    return false;
+  }
+
+  return true;
+}
+
+Void TAppExtrCfg::xSplitUIntString( const std::string& rString, std::set<UInt>& rSet )
+{
+  char* cString = NULL;
+  char* cElement = NULL;
+
+  cString = new char[rString.size()+1];
+  strcpy(cString, rString.c_str());
+
+  cElement = strtok( cString, "," );
+  while ( cElement != NULL )
+  {
+     rSet.insert( atoi( cElement ) );
+     cElement = strtok( NULL, "," );
+  }
+
+  delete cString;
+}
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrCfg.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrCfg.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrCfg.h	(revision 341)
@@ -0,0 +1,75 @@
+/* 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-2011, 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 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     TAppExtrCfg.h
+    \brief    Extractor configuration class (header)
+*/
+
+#ifndef __TAPPEXTRCFG__
+#define __TAPPEXTRCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "../../Lib/TLibCommon/CommonDef.h"
+#include <string>
+#include <set>
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Extractor configuration class
+class TAppExtrCfg
+{
+protected:
+  char*          m_pchInputBitstreamFile;              ///< input bitstream file name
+  char*          m_pchOutputBitstreamFile;             ///< output bitstream file name
+  char*          m_pchSpsInfoFile;                     ///< SPS information file name
+
+  std::set<UInt> m_suiExtractLayerIds;                 ///< list of layer IDs to be extracted
+
+public:
+  TAppExtrCfg()          {}
+  virtual ~TAppExtrCfg() {}
+  
+  Bool  parseCfg        ( Int argc, Char* argv[] );    ///< initialize option class from configuration
+
+protected:
+  Void  xSplitUIntString( const std::string& rString, std::set<UInt>& rList );
+};
+
+#endif
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrTop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrTop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrTop.cpp	(revision 341)
@@ -0,0 +1,146 @@
+/* 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-2011, 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 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     TAppExtrTop.cpp
+    \brief    Extractor application class
+*/
+
+#include "TAppExtrTop.h"
+#include "../../Lib/TLibDecoder/AnnexBread.h"
+#include <fstream>
+#include <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppExtrTop::TAppExtrTop()
+{
+}
+
+TAppExtrTop::~TAppExtrTop()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - until the end of the bitstream, call extraction function in TExtrTop class
+ */
+Void TAppExtrTop::extract()
+{
+
+  ifstream inputBitstreamFile( m_pchInputBitstreamFile, ifstream::in | ifstream::binary );
+  if( inputBitstreamFile.fail() )
+  {
+    fprintf( stderr, "\nfailed to open bitstream file `%s' for reading\n", m_pchInputBitstreamFile );
+    exit( EXIT_FAILURE );
+  }
+
+  fstream outputBitstreamFile;
+  if( m_pchOutputBitstreamFile )
+  {
+    outputBitstreamFile.open( m_pchOutputBitstreamFile, fstream::binary | fstream::out );
+    if( outputBitstreamFile.fail() )
+    {
+      fprintf( stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pchOutputBitstreamFile );
+      exit( EXIT_FAILURE );
+    }
+  }
+
+  InputByteStream inputBytestream( inputBitstreamFile );
+
+  Bool bEndOfFile = false;
+  while( !bEndOfFile )
+  {
+    streampos location = inputBitstreamFile.tellg();
+    AnnexBStats stats = AnnexBStats();
+    vector<uint8_t> nalUnit;
+    InputNALUnit nalu;
+    bEndOfFile = byteStreamNALUnit( inputBytestream, nalUnit, stats );
+
+    // handle NAL unit
+    if( nalUnit.empty() )
+    {
+      /* this can happen if the following occur:
+       *  - empty input file
+       *  - two back-to-back start_code_prefixes
+       *  - start_code_prefix immediately followed by EOF
+       */
+      fprintf( stderr, "Warning: Attempt to decode an empty NAL unit\n" );
+    }
+    else
+    {
+      read( nalu, nalUnit );
+
+      // decide whether to extract packet or not
+      if ( m_cTExtrTop.extract( nalu, m_suiExtractLayerIds ) && outputBitstreamFile.is_open() )
+      {
+        inputBitstreamFile.clear();
+
+        streampos location2 = inputBitstreamFile.tellg();
+        inputBitstreamFile.seekg( location );
+
+        do
+        {
+          outputBitstreamFile.put( inputBitstreamFile.get() );
+        } while( inputBitstreamFile.tellg() != location2 );
+      }
+    }
+  }
+
+  inputBitstreamFile.close();
+  outputBitstreamFile.close();
+
+  // write SPS info file
+  if ( m_pchSpsInfoFile )
+  {
+    fstream cSpsInfoFileHandle( m_pchSpsInfoFile, fstream::binary | fstream::out );
+
+    if( cSpsInfoFileHandle.fail() )
+    {
+      fprintf( stderr, "\nfailed writing SPS info file\n" );
+      exit( EXIT_FAILURE );
+    }
+
+    m_cTExtrTop.dumpSpsInfo( cSpsInfoFileHandle );
+
+    cSpsInfoFileHandle.close();
+  }
+  m_cTExtrTop.dumpSpsInfo( std::cout );
+}
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrTop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrTop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/TAppExtrTop.h	(revision 341)
@@ -0,0 +1,67 @@
+/* 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-2011, 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 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     TAppExtrTop.h
+    \brief    Extractor application class (header)
+*/
+
+#ifndef __TAPPEXTRTOP__
+#define __TAPPEXTRTOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "../../Lib/TLibExtractor/TExtrTop.h"
+#include "TAppExtrCfg.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// extractor application class
+class TAppExtrTop : public TAppExtrCfg
+{
+private:
+  // class interface
+  TExtrTop                       m_cTExtrTop;         ///< extractor class
+
+public:
+  TAppExtrTop();
+  virtual ~TAppExtrTop();
+  
+  Void  extract                  ();                  ///< main extraction function
+};
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/extrmain.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/extrmain.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppExtractor/extrmain.cpp	(revision 341)
@@ -0,0 +1,79 @@
+/* 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-2011, 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 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     extrmain.cpp
+    \brief    Extractor application main
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include "TAppExtrTop.h"
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppExtrTop  cTAppExtrTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "3D-HTM Software: Extractor Version [%s] based on HM Version [%s]", HM_VERSION, NV_VERSION );
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // parse configuration
+  if(!cTAppExtrTop.parseCfg( argc, argv ))
+  {
+    return EXIT_FAILURE;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call extraction function
+  cTAppExtrTop.extract();
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  return EXIT_SUCCESS;
+}
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/RendererMain.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/RendererMain.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/RendererMain.cpp	(revision 341)
@@ -0,0 +1,84 @@
+/* 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-2011, 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 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 <time.h>
+#include "TAppRendererTop.h"
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+  {
+#if !QC_MVHEVC_B0046
+  TAppRendererTop  cTAppRendererTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "3D-HTM software: Renderer Version [%s]", NV_VERSION);  
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // create application renderer class
+  cTAppRendererTop.create();
+
+  // parse configuration
+  if(!cTAppRendererTop.parseCfg( argc, argv ))
+  {
+    cTAppRendererTop.destroy();
+    return 1;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call rendering function
+  cTAppRendererTop.go();
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  // destroy application renderer class
+  cTAppRendererTop.destroy();
+
+  return 0;
+#endif
+}
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererCfg.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 341)
@@ -0,0 +1,518 @@
+/* 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-2011, 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 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 <stdlib.h>
+#include <math.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+
+
+
+#include "TAppRendererCfg.h"
+#include "../../Lib/TAppCommon/program_options_lite.h"
+
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+// ====================================================================================================================
+// Local constants
+// ====================================================================================================================
+
+#define MAX_INPUT_VIEW_NUM          10
+#define MAX_OUTPUT_VIEW_NUM         64
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+#if !QC_MVHEVC_B0046
+TAppRendererCfg::TAppRendererCfg()
+{
+
+}
+
+TAppRendererCfg::~TAppRendererCfg()
+{
+  for(Int i = 0; i< m_pchVideoInputFileList.size(); i++ )
+  {
+    if ( m_pchVideoInputFileList[i] != NULL )
+      free (m_pchVideoInputFileList[i]);
+  }
+
+  for(Int i = 0; i< m_pchDepthInputFileList.size(); i++ )
+  {
+    if ( m_pchDepthInputFileList[i] != NULL )
+      free (m_pchDepthInputFileList[i]);
+  }
+
+  for(Int i = 0; i< m_pchSynthOutputFileList.size(); i++ )
+  {
+    if ( m_pchSynthOutputFileList[i] != NULL )
+      free (m_pchSynthOutputFileList[i]);
+  }
+
+  if ( m_pchVideoInputFileBaseName  ) free( m_pchVideoInputFileBaseName );
+  if ( m_pchDepthInputFileBaseName  ) free( m_pchDepthInputFileBaseName );
+  if ( m_pchSynthOutputFileBaseName ) free( m_pchSynthOutputFileBaseName);
+  if ( m_pchCameraParameterFile     ) free( m_pchCameraParameterFile    );
+  if ( m_pchBaseViewCameraNumbers   ) free( m_pchBaseViewCameraNumbers  );
+  if ( m_pchSynthViewCameraNumbers  ) free( m_pchSynthViewCameraNumbers );
+  if ( m_pchViewConfig              ) free( m_pchViewConfig         );
+}
+
+Void TAppRendererCfg::create()
+{
+}
+
+Void TAppRendererCfg::destroy()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  argc        number of arguments
+\param  argv        array of arguments
+\retval             true when success
+*/
+Bool TAppRendererCfg::parseCfg( Int argc, Char* argv[] )
+{
+  bool do_help = false;
+
+  po::Options opts;
+  opts.addOptions()
+    ("help", do_help, false, "this help text")
+    ("c", po::parseConfigFile, "configuration file name")
+
+    /* File I/O */
+    ("VideoInputFileBaseName,v",  m_pchVideoInputFileBaseName,  (Char*) 0, "Basename to generate video input file names")
+    ("DepthInputFileBaseName,d",  m_pchDepthInputFileBaseName,  (Char*) 0, "Basename to generate depth input file names")
+    ("SynthOutputFileBaseName,s", m_pchSynthOutputFileBaseName, (Char*) 0, "Basename to generate synthesized output file names")
+    ("ContOutputFileNumbering", m_bContOutputFileNumbering  ,  false   , "Continuous Output File Numbering")
+    ("Sweep"                  , m_bSweep                    ,  false   , "Store all views in first Output File")
+
+    ("VideoInputFile_%d,v_%d",  m_pchVideoInputFileList ,    (Char *) 0, MAX_INPUT_VIEW_NUM , "Original Yuv video input file name %d")
+    ("DepthInputFile_%d,d_%d",  m_pchDepthInputFileList ,    (Char *) 0, MAX_INPUT_VIEW_NUM , "Original Yuv depth input file name %d")
+    ("SynthOutputFile_%d,s_%d", m_pchSynthOutputFileList,    (Char *) 0, MAX_OUTPUT_VIEW_NUM, "Synthesized Yuv output file name %d")
+
+    /* Source Specification */
+    ("SourceWidth,-wdt",        m_iSourceWidth,                       0, "Source picture width")
+    ("SourceHeight,-hgt",       m_iSourceHeight,                      0, "Source picture height")
+    ("FrameSkip,-fs",           m_iFrameSkip,                         0, "Number of frames to skip at start of input YUV")
+    ("FramesToBeRendered,f",    m_iFramesToBeRendered,                0, "Number of frames to be rendered (default=all)")
+
+    /* Camera Specification */
+    ("CameraParameterFile,-cpf", m_pchCameraParameterFile,          (Char *) 0, "Camera Parameter File Name")
+    ("BaseViewCameraNumbers"  , m_pchBaseViewCameraNumbers,        (Char *) 0, "Numbers of base views")
+    ("SynthViewCameraNumbers" , m_pchSynthViewCameraNumbers,       (Char *) 0, "Numbers of views to synthesis")
+    ("ViewConfig"             , m_pchViewConfig,                   (Char *) 0, "View Configuration"               )
+
+    /* Renderer Modes */
+    ("Log2SamplingFactor",      m_iLog2SamplingFactor,                0, "Factor for horizontal up sampling before processing"     )
+    ("UVup"              ,      m_bUVUp               ,            true, "Up sampling of chroma planes before processing"          )
+    ("PreProcMode"       ,      m_iPreProcMode        ,               0, "Depth preprocessing: 0 = None, 1 = Binomial filtering"   )
+    ("PreFilterSize"     ,      m_iPreFilterSize      ,               0, "For PreProcMode 1: Half Size of filter kernel"           )
+    ("SimEnhance"        ,      m_bSimEnhance         ,           true, "Similarity enhancement of video" )
+    ("BlendMode"         ,      m_iBlendMode          ,               0, "Blending of left and right image: 0: average, 1: only holes from right, 2: only holes from left, 3: first view in BaseViewOrder as main view" )
+    ("BlendZThresPerc"   ,      m_iBlendZThresPerc    ,              30, "Z-difference threshold for blending in percent of total Z-range"   )
+    ("BlendUseDistWeight",      m_bBlendUseDistWeight ,            true, "0: blend using average; 1: blend factor depends on view distance"  )
+    ("BlendHoleMargin"   ,      m_iBlendHoleMargin    ,               6, "Margin around holes to fill with other view"                       )
+    ("InterpolationMode" ,      m_iInterpolationMode  ,               4, "0: NN, 1:linear (int), 2:linear (double) , 3:cubic Hermite spline (double), 4: 8-tap (int)" )
+    ("HoleFillingMode"   ,      m_iHoleFillingMode    ,               1, "0: None, 1: line wise background extension"              )
+    ("PostProcMode"      ,      m_iPostProcMode       ,               0, "0: None, 1: horizontal 3-tap median"                     )
+    ("RenderMode"        ,      m_iRenderMode         ,               0, "0: Use renderer, 1: use model renderer, 10: create used pels map")
+    ("ShiftPrecision"    ,      m_iShiftPrecision     ,               2, "Shift Precision for Interpolation Mode 4"                )
+    ("TemporalDepthFilter",     m_bTempDepthFilter    ,           false, "Temporal depth filtering"                                )
+    ("RenderDirection"   ,      m_iRenderDirection    ,               0, "0: Interpolate, 1: Extrapolate from left, 2: Extrapolate from right")
+    ("UsedPelMapMarExt"  ,      m_iUsedPelMapMarExt   ,               0, "Margin Extension in Pels for used pels map generation"   );
+
+  po::setDefaults(opts);
+  po::scanArgv(opts, argc, (const char**) argv);
+
+  if (argc == 1 || do_help)
+  {
+    /* argc == 1: no options have been specified */
+    po::doHelp(cout, opts);
+    xPrintUsage();
+    return false;
+  }
+
+  /*
+  * Set any derived parameters before checking
+  */
+
+  xSetGlobal();
+
+  UInt  uiInputBitDepth   = 8;
+  UInt  uiCamParPrecision = 5;
+
+  m_bUseSetupString = ( m_pchViewConfig != NULL ) && ( m_iRenderMode != 0);
+
+  if ( m_iRenderMode == 10 )
+  {
+    m_cCameraData.init( MAX_INPUT_VIEW_NUM, uiInputBitDepth, uiCamParPrecision, (UInt)m_iFrameSkip, (UInt)m_iFramesToBeRendered,
+      m_pchCameraParameterFile, m_pchBaseViewCameraNumbers, NULL, NULL, m_iLog2SamplingFactor+m_iShiftPrecision );
+    m_iNumberOfInputViews  = (Int) m_cCameraData.getBaseViewNumbers() .size();
+    m_iNumberOfOutputViews = m_iNumberOfInputViews - 1;
+    m_iRenderDirection     = 1;
+  }
+  else
+  {
+  if ( m_bUseSetupString )
+  {
+    std::vector<Int>  iaTempViews;
+    std::vector<Int>* piaTempViews;
+    m_cCameraData     .convertNumberString( m_pchBaseViewCameraNumbers, iaTempViews, VIEW_NUM_PREC );
+    m_cRenModStrParser.setString( (Int) iaTempViews.size(), m_pchViewConfig );
+    piaTempViews               = m_cRenModStrParser.getSynthViews();
+    m_iNumberOfOutputViews     = (Int) m_cRenModStrParser.getNumOfModels();
+    m_iNumberOfInputViews      = (Int) m_cRenModStrParser.getNumOfBaseViews();
+    m_bContOutputFileNumbering = true;
+
+  m_cCameraData.init( MAX_INPUT_VIEW_NUM, uiInputBitDepth, uiCamParPrecision, (UInt)m_iFrameSkip, (UInt)m_iFramesToBeRendered,
+      m_pchCameraParameterFile, m_pchBaseViewCameraNumbers, NULL, piaTempViews, m_iLog2SamplingFactor+m_iShiftPrecision );
+  }
+  else
+  {
+  m_cCameraData.init( MAX_INPUT_VIEW_NUM, uiInputBitDepth, uiCamParPrecision, (UInt)m_iFrameSkip, (UInt)m_iFramesToBeRendered,
+      m_pchCameraParameterFile, m_pchBaseViewCameraNumbers, m_pchSynthViewCameraNumbers, NULL, m_iLog2SamplingFactor+m_iShiftPrecision );
+  m_iNumberOfOutputViews = (Int) m_cCameraData.getSynthViewNumbers().size();
+  m_iNumberOfInputViews  = (Int) m_cCameraData.getBaseViewNumbers() .size();
+  }
+  }
+
+  if (m_pchSynthOutputFileBaseName != NULL)
+    xConfirmParameter( strrchr(m_pchSynthOutputFileBaseName,'$')  == 0, "'$' must be a character in SynthOutputFileBaseName");
+
+  if (m_pchDepthInputFileBaseName != NULL)
+    xConfirmParameter( strrchr(m_pchDepthInputFileBaseName, '$')  == 0, "'$' must be a character in DepthInputFileBaseName" );
+
+  if (m_pchVideoInputFileBaseName != NULL)
+    xConfirmParameter( strrchr(m_pchVideoInputFileBaseName, '$')  == 0, "'$' must be a character in VideoInputFileBaseName" );
+
+  xCreateFileNames();
+
+  /*
+  * check validity of input parameters
+  */
+  xCheckParameter();
+  m_cCameraData.check( m_iRenderDirection == 0, m_iFramesToBeRendered != 0 );
+
+  // print-out parameters
+  xPrintParameter();
+
+  return true;
+}
+
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+Void TAppRendererCfg::xCheckParameter()
+{
+  bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= xConfirmParameter(a,b)
+  // check range of parameters
+
+  /// File I/O
+
+  // source specification
+  xConfirmPara( m_iSourceWidth        <= 0,                   "Source width  must be greater than 0" );
+  xConfirmPara( m_iSourceHeight       <= 0,                   "Source height must be greater than 0" );
+  xConfirmPara( m_iFrameSkip          <  0,                   "Frame Skipping must be more than or equal to 0" );
+  xConfirmPara( m_iFramesToBeRendered <  0,                   "Total Number Of Frames rendered must be more than 1" );
+
+
+  // camera specification
+  xConfirmPara( m_iNumberOfInputViews  > MAX_INPUT_VIEW_NUM , "NumberOfInputViews must be less than of equal to MAX_INPUT_VIEW_NUM");
+  xConfirmPara( m_iNumberOfOutputViews > MAX_OUTPUT_VIEW_NUM, "NumberOfOutputViews must be less than of equal to MAX_OUTPUT_VIEW_NUM");
+
+
+  xConfirmPara( m_iRenderDirection < 0 || m_iRenderDirection > 2  , "RenderDirection must be greater than or equal to 0 and less than 3");
+  xConfirmPara(m_iNumberOfOutputViews < 1,                    "Number of OutputViews must be greater or equal to 1");
+  if ( m_iRenderDirection == 0 )
+  {
+    xConfirmPara( m_iNumberOfInputViews < 2,                  "Number of InputViews must be more than or equal to 2");
+  }
+  else
+  {
+    xConfirmPara( m_iNumberOfInputViews < 1,                  "Number of InputViews must be more than or equal to 1");
+  }
+
+  xConfirmPara( m_iLog2SamplingFactor < 0 || m_iLog2SamplingFactor >  4, "Log2SamplingFactor must be more than or equal to 0 and less than 5"  );
+  xConfirmPara( m_iPreProcMode        < 0 || m_iPreProcMode        >  1, "PreProcMode        must be more than or equal to 0 and less than 2"  );
+
+
+  xConfirmPara( m_iPreFilterSize      < 0 || m_iPreFilterSize      >  3, "PreFilterSize      must be more than or equal to 0 and less than 4" );
+  xConfirmPara( m_iBlendMode          < 0 || m_iBlendMode          >  3, "BlendMode          must be more than or equal to 0 and less than 4"  );
+  xConfirmPara( m_iBlendZThresPerc    < 0 || m_iBlendZThresPerc    > 100,"BlendZThresPerc    must be more than or equal to 0 and less than 101"  );
+  xConfirmPara( m_iBlendHoleMargin    < 0 || m_iBlendHoleMargin    >  20,"BlendHoleMargin    must be more than or equal to 0 and less than 19"  );
+  xConfirmPara( m_iInterpolationMode  < 0 || m_iInterpolationMode  >  4, "InterpolationMode  must be more than or equal to 0 and less than 5"  );
+  xConfirmPara( m_iHoleFillingMode    < 0 || m_iHoleFillingMode    >  1, "HoleFillingMode    must be more than or equal to 0 and less than 2"  );
+  xConfirmPara( m_iPostProcMode       < 0 || m_iPostProcMode       >  2, "PostProcMode       must be more than or equal to 0 and less than 3"  );
+
+  Int iNumNonNULL;
+  for (iNumNonNULL = 0; (iNumNonNULL < m_iNumberOfInputViews)  && m_pchDepthInputFileList[iNumNonNULL]; iNumNonNULL++);  xConfirmPara( iNumNonNULL < m_iNumberOfInputViews,  "Number of DepthInputFiles  must be greater than or equal to number of BaseViewNumbers" );
+  for (iNumNonNULL = 0; (iNumNonNULL < m_iNumberOfInputViews)  && m_pchVideoInputFileList[iNumNonNULL]; iNumNonNULL++);  xConfirmPara( iNumNonNULL < m_iNumberOfInputViews,  "Number of DepthInputFiles  must be greater than or equal to number of BaseViewNumbers" );
+
+
+  if ( !m_bSweep )
+  {
+  for (iNumNonNULL = 0; (iNumNonNULL < m_iNumberOfOutputViews) && m_pchSynthOutputFileList[iNumNonNULL]; iNumNonNULL++); xConfirmPara( iNumNonNULL < m_iNumberOfOutputViews, "Number of SynthOutputFiles must be greater than or equal to number of SynthViewNumbers" );
+  }
+  else
+  {
+      xConfirmPara( iNumNonNULL < 1, "Number of SynthOutputFiles must be equal to or more than 1" );
+  }
+
+#undef xConfirmPara
+  if ( check_failed )
+  {
+    exit(EXIT_FAILURE);
+  }
+
+}
+
+
+
+Void TAppRendererCfg::xPrintParameter()
+{
+  printf("\n");
+  for( Int iCounter = 0; iCounter < m_iNumberOfInputViews; iCounter++)
+  {
+    printf("InputVideoFile_%i        : %s\n", iCounter, m_pchVideoInputFileList[iCounter]);
+  }
+  for( Int iCounter = 0; iCounter < m_iNumberOfInputViews; iCounter++)
+  {
+    printf("InputDepthFile_%i        : %s\n", iCounter, m_pchDepthInputFileList[iCounter]);
+  }
+
+  for( Int iCounter = 0; iCounter < m_iNumberOfOutputViews; iCounter++)
+  {
+    printf("SynthOutputFile_%i       : %s\n", iCounter, m_pchSynthOutputFileList[iCounter]);
+  }
+
+  printf("Format                  : %dx%d \n", m_iSourceWidth, m_iSourceHeight );
+  printf("Frame index             : %d - %d (%d frames)\n", m_iFrameSkip, m_iFrameSkip+m_iFramesToBeRendered-1, m_iFramesToBeRendered);
+  printf("CameraParameterFile     : %s\n", m_pchCameraParameterFile );
+  printf("BaseViewNumbers         : %s  (%d views) \n", m_pchBaseViewCameraNumbers , m_iNumberOfInputViews  );
+  printf("Sweep                   : %d\n", m_bSweep               );
+
+  if ( m_bUseSetupString )
+  {
+    printf("ViewConfig              : %s\n", m_pchViewConfig );
+  }
+  else
+  {
+  printf("SynthViewNumbers        : %s  (%d views) \n", m_pchSynthViewCameraNumbers, m_iNumberOfOutputViews );
+  }
+
+  printf("Log2SamplingFactor      : %d\n", m_iLog2SamplingFactor );
+  printf("UVUp                    : %d\n", m_bUVUp               );
+  printf("PreProcMode             : %d\n", m_iPreProcMode        );
+  printf("PreFilterSize           : %d\n", m_iPreFilterSize      );
+  printf("SimEnhance              : %d\n", m_bSimEnhance         );
+  printf("BlendMode               : %d\n", m_iBlendMode          );
+  printf("BlendZThresPerc         : %d\n", m_iBlendZThresPerc    );
+  printf("BlendUseDistWeight      : %d\n", m_bBlendUseDistWeight );
+  printf("BlendHoleMargin         : %d\n", m_iBlendHoleMargin    );
+  printf("InterpolationMode       : %d\n", m_iInterpolationMode  );
+  printf("HoleFillingMode         : %d\n", m_iHoleFillingMode    );
+  printf("PostProcMode            : %d\n", m_iPostProcMode       );
+  printf("ShiftPrecision          : %d\n", m_iShiftPrecision     );
+  printf("TemporalDepthFilter     : %d\n", m_bTempDepthFilter    );
+  printf("RenderMode              : %d\n", m_iRenderMode         );
+  printf("RendererDirection       : %d\n", m_iRenderDirection       );
+
+  if (m_iRenderMode == 10 )
+  {
+    printf("UsedPelMapMarExt        : %d\n", m_iUsedPelMapMarExt );
+  }
+
+  printf("\n");
+
+  //  printf("TOOL CFG: ");
+  //  printf("ALF:%d ", m_bUseALF             );
+  //  printf("\n");
+
+  fflush(stdout);
+}
+
+Void TAppRendererCfg::xPrintUsage()
+{
+  printf( "\n" );
+  printf( "  Example: TAppRenderer.exe -c test.cfg\n\n");
+}
+
+Bool TAppRendererCfg::xConfirmParameter(Bool bflag, const char* message)
+{
+  if (!bflag)
+    return false;
+
+  printf("Error: %s\n",message);
+  return true;
+}
+
+
+Void TAppRendererCfg::xCreateFileNames()
+{
+  if ( m_iRenderMode == 10 )
+    return;
+
+  Int iPrecBefore;
+  Int iPrecAfter;
+
+  xGetMaxPrecision( m_cCameraData.getSynthViewNumbers(), iPrecBefore, iPrecAfter );
+
+
+  if (iPrecBefore > LOG10_VIEW_NUM_PREC )
+  {
+    std::cerr << "Error: View Numbers with more than " << LOG10_VIEW_NUM_PREC << " digits are not supported" << std::endl;
+    exit(EXIT_FAILURE);
+  }
+
+  AOT( !m_bContOutputFileNumbering && (m_cCameraData.getSynthViewNumbers().size() != m_iNumberOfOutputViews ));
+  for(Int iIdx = 0; iIdx < m_iNumberOfOutputViews; iIdx++)
+  {
+    //GT; Create ReconFileNames
+    if (m_pchSynthOutputFileList[iIdx] == NULL )
+    {
+      if ( m_bContOutputFileNumbering )
+      {
+        xAddNumberToFileName( m_pchSynthOutputFileBaseName, m_pchSynthOutputFileList[iIdx], (Int) ((iIdx+1) * VIEW_NUM_PREC) , 2, 0  );
+      }
+      else
+      {
+        xAddNumberToFileName( m_pchSynthOutputFileBaseName, m_pchSynthOutputFileList[iIdx], m_cCameraData.getSynthViewNumbers()[iIdx], iPrecBefore, iPrecAfter  );
+      }
+    }
+  }
+
+  xGetMaxPrecision( m_cCameraData.getBaseViewNumbers(), iPrecBefore, iPrecAfter );
+  for(Int iIdx = 0; iIdx < m_cCameraData.getBaseViewNumbers().size() ; iIdx++)
+  {
+    //GT; Create ReconFileNames
+    if (m_pchVideoInputFileList[iIdx] == NULL )
+    {
+      xAddNumberToFileName( m_pchVideoInputFileBaseName, m_pchVideoInputFileList[iIdx], m_cCameraData.getBaseViewNumbers()[iIdx], iPrecBefore, iPrecAfter  );
+    }
+
+    if (m_pchDepthInputFileList[iIdx] == NULL )
+    {
+      xAddNumberToFileName( m_pchDepthInputFileBaseName, m_pchDepthInputFileList[iIdx], m_cCameraData.getBaseViewNumbers()[iIdx], iPrecBefore, iPrecAfter  );
+    }
+  }
+}
+
+Void TAppRendererCfg::xAddNumberToFileName( Char* pchSourceFileName, Char*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter )
+{
+
+  if ( pchSourceFileName == NULL )
+  {
+    std::cerr << "No BaseName for file name generation given." << std::endl;
+    AOT(true);
+    exit(EXIT_FAILURE);
+  }
+
+  Char pchNumberBuffer[2* LOG10_VIEW_NUM_PREC + 2];
+  Char pchPrintBuffer[10];
+
+  Double dNumberToAdd = ( (Double) iNumberToAdd ) / VIEW_NUM_PREC;
+
+  UInt uiWidth = uiPrecBefore;
+
+  if (uiPrecAfter != 0)
+  {
+    uiWidth += uiPrecAfter + 1;
+  }
+
+  sprintf( pchPrintBuffer, "%%0%d.%df", uiWidth, uiPrecAfter );
+  sprintf( pchNumberBuffer, pchPrintBuffer, dNumberToAdd );
+
+  if ( uiPrecAfter > 0 ) pchNumberBuffer[ uiPrecBefore ] = '_';
+
+  size_t iInLength  = strlen(pchSourceFileName);
+  size_t iAddLength = strlen(pchNumberBuffer);
+
+  rpchTargetFileName = (Char*) malloc(iInLength+iAddLength+1);
+
+  Char* pchPlaceHolder = strrchr(pchSourceFileName,'$');
+  assert( pchPlaceHolder );
+
+  size_t iCharsToPlaceHolder = pchPlaceHolder - pchSourceFileName;
+  size_t iCharsToEnd         = iInLength      - iCharsToPlaceHolder;
+
+  strncpy(rpchTargetFileName                               , pchSourceFileName                      , iCharsToPlaceHolder);
+  strncpy(rpchTargetFileName+iCharsToPlaceHolder           , pchNumberBuffer                        , iAddLength         );
+  strncpy(rpchTargetFileName+iCharsToPlaceHolder+iAddLength, pchSourceFileName+iCharsToPlaceHolder+1, iCharsToEnd-1      );
+  rpchTargetFileName[iInLength+iAddLength-1] = '\0';
+}
+
+Void TAppRendererCfg::xGetMaxPrecision( std::vector< Int > aiIn, Int& iPrecBefore, Int& iPrecAfter )
+{
+  iPrecBefore = 0;
+  iPrecAfter  = 0;
+
+  for (UInt uiK = 0; uiK < aiIn.size(); uiK ++ )
+  {
+    if ( aiIn[uiK] == 0 ) continue;
+
+    Int iCurPrec;
+    iCurPrec = 0;
+    for ( Int iCur = aiIn[uiK]; iCur != 0; iCur /= 10, iCurPrec++ );
+    iPrecBefore = max(iPrecBefore, iCurPrec - LOG10_VIEW_NUM_PREC );
+
+    iCurPrec = 0;
+    for ( Int iCur = 1;  aiIn[uiK] % iCur == 0; iCur *= 10, iCurPrec++);
+    iCurPrec = LOG10_VIEW_NUM_PREC - Min(LOG10_VIEW_NUM_PREC, iCurPrec-1 );
+    iPrecAfter = max(iPrecAfter, iCurPrec );
+  }
+}
+
+Void TAppRendererCfg::xSetGlobal()
+{
+  // set max CU width & height
+  Int iInternalBitDepth = 8;
+  g_uiMaxCUWidth   = 0;
+  g_uiMaxCUHeight  = 0;
+  g_uiBitDepth     = 8;
+  g_uiBitIncrement = iInternalBitDepth - g_uiBitDepth;
+  g_uiBASE_MAX     = ((1<<(g_uiBitDepth))-1);
+  g_uiIBDI_MAX     = ((1<<(g_uiBitDepth+g_uiBitIncrement))-1);
+}
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererCfg.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererCfg.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererCfg.h	(revision 341)
@@ -0,0 +1,138 @@
+/* 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-2011, 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 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 <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+
+
+#ifndef __TAppRENDERERCFG__
+#define __TAppRENDERERCFG__
+
+#include "../../Lib/TAppCommon/TAppComCamPara.h"
+#include "../../Lib/TLibCommon/CommonDef.h"
+#include "../../Lib/TLibRenderer/TRenModel.h"
+#include "../../Lib/TLibRenderer/TRenModSetupStrParser.h"
+#include <string>
+#include <vector>
+#if !QC_MVHEVC_B0046
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TAppRendererCfg
+{
+protected:
+
+  //// file I/O ////
+  Char*              m_pchVideoInputFileBaseName;      ///< input video  file base name, placeholder for numbering $$
+  Char*              m_pchDepthInputFileBaseName;      ///< input depth  file base name, placeholder for numbering $$
+  Char*              m_pchSynthOutputFileBaseName;     ///< output synth file base name, placeholder for numbering $$
+  Bool               m_bContOutputFileNumbering;       ///< use continous numbering instead of view numbering
+  Bool               m_bSweep;                         ///< 1: Store view range in file
+
+  // derived
+  std::vector<Char*> m_pchVideoInputFileList;          ///< source file names
+  std::vector<Char*> m_pchDepthInputFileList;          ///< source depth file names
+  std::vector<Char*> m_pchSynthOutputFileList;         ///< output reconstruction file names
+
+  //// source specification ////
+  Int                m_iSourceWidth;                   ///< source width in pixel
+  Int                m_iSourceHeight;                  ///< source height in pixel
+  Int                m_iFrameSkip;                     ///< number of skipped frames from the beginning
+  Int                m_iFramesToBeRendered;            ///< number of rendered frames
+
+  ////camera specification ////
+  Char*               m_pchCameraParameterFile;         ///< camera parameter file
+  Char*               m_pchSynthViewCameraNumbers;      ///< numbers of views to synthesize
+  Char*               m_pchViewConfig;                  ///< String to setup renderer
+  Char*               m_pchBaseViewCameraNumbers;       ///< numbers of base views
+
+  // derived
+  TAppComCamPara      m_cCameraData;                    ///< class to store camera parameters
+  TRenModSetupStrParser m_cRenModStrParser;             ///< class to manage View to be rendered
+  Bool                m_bUseSetupString;                ///< true if setup string is used
+
+  Int                 m_iNumberOfInputViews;            ///< number of input Views
+  Int                 m_iNumberOfOutputViews;           ///< number views to synthesize
+
+  //// renderer Modes ////
+  Int                 m_iRenderDirection;               ///< 0: interpolate, 1: extrapolate from left, 2: extrapolate from right
+
+  Int                 m_iLog2SamplingFactor;            ///< factor for horizontal upsampling before processing
+  Bool                m_bUVUp;                          ///< upsampling of chroma planes before processing
+  Int                 m_iPreProcMode;                   ///< depth pre-processing: 0 = none, 1 = binominal filtering
+  Int                 m_iPreFilterSize;                 ///< for PreProcMode = 1: size of filter kernel
+  Bool                m_bSimEnhance;                    ///< Similarity enhancement before blending
+  Int                 m_iBlendMode;                     ///< merging of left and right image: 0 = average, 1 = only holes from right, 2 = only holes from left
+  Int                 m_iBlendZThresPerc;               ///< z-difference threshold for blending in percent of total z-range
+  Bool                m_bBlendUseDistWeight;            ///< 0: blend using average; 1: blend factor depends on view distance
+  Int                 m_iBlendHoleMargin;               ///< Margin around boundaries
+  Bool                m_bTempDepthFilter;               ///< Zheijang temporal enhancement filter
+  Int                 m_iInterpolationMode;             ///< 0: NN, 1: linear, 2: cspline
+  Int                 m_iHoleFillingMode;               ///< 0: none, 1: line wise background extension
+  Int                 m_iPostProcMode;                  ///< 0: none, 1: horizontal 3-tap median
+  Int                 m_iRenderMode;                      ///< 0: use renderer
+  Int                 m_iShiftPrecision;                ///< Precision used for Interpolation Mode 4
+  Int                 m_iUsedPelMapMarExt;              ///< Used Pel map extra margin
+
+  Void xCheckParameter ();                              ///< check validity of configuration values
+  Void xPrintParameter ();                              ///< print configuration values
+  Void xPrintUsage     ();                              ///< print usage
+  Void xSetGlobal();
+
+  Void xCreateFileNames();
+  Void xGetMaxPrecision( std::vector< Int > adIn, Int& iPrecBefore, Int& iPrecAfter );
+  Void xAddNumberToFileName( Char* pchSourceFileName, Char*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter );
+public:
+  TAppRendererCfg();
+  virtual ~TAppRendererCfg();
+
+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
+  Bool  xConfirmParameter(Bool bflag, const Char* message);
+
+
+};// END CLASS DEFINITION TAppRendererCfg
+
+
+#endif
+#endif // __TAppRENDERERCFG__
+
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererTop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 341)
@@ -0,0 +1,1020 @@
+/* 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-2011, 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 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 <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+#include <math.h>
+
+#include "TAppRendererTop.h"
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+#if !QC_MVHEVC_B0046
+TAppRendererTop::TAppRendererTop()
+{
+
+}
+
+TAppRendererTop::~TAppRendererTop()
+{
+
+}
+
+
+Void TAppRendererTop::xCreateLib()
+{
+  Int iInteralBitDepth = g_uiBitDepth + g_uiBitIncrement;
+  Int iFileBitDepth    = 8;
+  m_pcRenTop = new TRenTop();
+
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfInputViews; iViewIdx++)
+  {
+    TVideoIOYuv* pcVideoInput = new TVideoIOYuv;
+    TVideoIOYuv* pcDepthInput = new TVideoIOYuv;
+
+    pcVideoInput->open( m_pchVideoInputFileList[iViewIdx], false, iFileBitDepth, iInteralBitDepth );  // read mode
+    pcDepthInput->open( m_pchDepthInputFileList[iViewIdx], false, iFileBitDepth, iInteralBitDepth );  // read mode
+    pcVideoInput->skipFrames(m_iFrameSkip, m_iSourceWidth, m_iSourceHeight  );
+    pcDepthInput->skipFrames(m_iFrameSkip, m_iSourceWidth, m_iSourceHeight  );
+
+    m_apcTVideoIOYuvVideoInput.push_back( pcVideoInput );
+    m_apcTVideoIOYuvDepthInput.push_back( pcDepthInput );
+  }
+
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfOutputViews; iViewIdx++)
+  {
+    TVideoIOYuv* pcSynthOutput = new TVideoIOYuv;
+    pcSynthOutput->open( m_pchSynthOutputFileList[iViewIdx], true, iFileBitDepth, iInteralBitDepth );  // write mode
+    m_apcTVideoIOYuvSynthOutput.push_back( pcSynthOutput );
+  }
+}
+
+
+Void TAppRendererTop::xDestroyLib()
+{
+  delete m_pcRenTop;
+
+  for ( Int iViewIdx = 0; iViewIdx < m_iNumberOfInputViews; iViewIdx++ )
+  {
+    m_apcTVideoIOYuvVideoInput[iViewIdx]->close();
+    m_apcTVideoIOYuvDepthInput[iViewIdx]->close();
+
+    delete m_apcTVideoIOYuvDepthInput[iViewIdx];
+    delete m_apcTVideoIOYuvVideoInput[iViewIdx];
+  };
+
+  for ( Int iViewIdx = 0; iViewIdx < m_iNumberOfOutputViews; iViewIdx++ )
+  {
+    m_apcTVideoIOYuvSynthOutput[iViewIdx]->close();
+    delete m_apcTVideoIOYuvSynthOutput[iViewIdx];
+  };
+}
+
+Void TAppRendererTop::xInitLib()
+{
+    m_pcRenTop->init(
+    m_iSourceWidth,
+    m_iSourceHeight,
+    (m_iRenderDirection != 0),
+    m_iLog2SamplingFactor,
+    m_iLog2SamplingFactor+m_iShiftPrecision,
+    m_bUVUp,
+    m_iPreProcMode,
+    m_iPreFilterSize,
+    m_iBlendMode,
+    m_iBlendZThresPerc,
+    m_bBlendUseDistWeight,
+    m_iBlendHoleMargin,
+    m_iInterpolationMode,
+    m_iHoleFillingMode,
+    m_iPostProcMode,
+    m_iUsedPelMapMarExt
+    );
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+
+
+Void TAppRendererTop::render()
+{
+  xCreateLib();
+  xInitLib();
+
+  // Create Buffers Input Views;
+  std::vector<TComPicYuv*> apcPicYuvBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvBaseDepth;
+
+  // TemporalImprovement Filter
+  std::vector<TComPicYuv*> apcPicYuvLastBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvLastBaseDepth;
+
+  Int aiPad[2] = { 0, 0 };
+
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    TComPicYuv* pcNewVideoPic = new TComPicYuv;
+    TComPicYuv* pcNewDepthPic = new TComPicYuv;
+
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseVideo.push_back(pcNewVideoPic);
+
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+
+    //Temporal improvement Filter
+    if ( m_bTempDepthFilter )
+    {
+      pcNewVideoPic = new TComPicYuv;
+      pcNewDepthPic = new TComPicYuv;
+
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvLastBaseVideo.push_back(pcNewVideoPic);
+
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvLastBaseDepth.push_back(pcNewDepthPic);
+    }
+  }
+
+  // Create Buffer for synthesized View
+  TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+
+  Bool bAnyEOS = false;
+
+  Int iNumOfRenderedFrames = 0;
+  Int iFrame = 0;
+
+  while ( ( ( iNumOfRenderedFrames < m_iFramesToBeRendered ) || ( m_iFramesToBeRendered == 0 ) ) && !bAnyEOS )
+  {
+    if ( iFrame >= m_iFrameSkip ) 
+    {
+      // read in depth and video
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+
+        apcPicYuvBaseVideo[iBaseViewIdx]->extendPicBorder();
+
+        bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
+
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        apcPicYuvBaseDepth[iBaseViewIdx]->extendPicBorder();
+        bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
+
+        if ( m_bTempDepthFilter && (iFrame >= m_iFrameSkip) )
+        {
+          m_pcRenTop->temporalFilterVSRS( apcPicYuvBaseVideo[iBaseViewIdx], apcPicYuvBaseDepth[iBaseViewIdx], apcPicYuvLastBaseVideo[iBaseViewIdx], apcPicYuvLastBaseDepth[iBaseViewIdx], ( iFrame == m_iFrameSkip) );
+        }
+      }
+    }
+    else    
+    {
+      std::cout << "Skipping Frame " << iFrame << std::endl;
+
+      iFrame++;
+      continue;
+    }
+
+    m_cCameraData.update( (UInt)iFrame - m_iFrameSkip );
+
+    for(Int iSynthViewIdx=0; iSynthViewIdx < m_iNumberOfOutputViews; iSynthViewIdx++ )
+    {
+      Int  iLeftBaseViewIdx  = -1;
+      Int  iRightBaseViewIdx = -1;
+
+      Bool bIsBaseView = false;
+
+      Int iRelDistToLeft;
+      Bool bHasLRView = m_cCameraData.getLeftRightBaseView( iSynthViewIdx, iLeftBaseViewIdx, iRightBaseViewIdx, iRelDistToLeft, bIsBaseView );
+      Bool bHasLView = ( iLeftBaseViewIdx != -1 );
+      Bool bHasRView = ( iRightBaseViewIdx != -1 );
+      Bool bRender   = true;
+
+      Int  iBlendMode = m_iBlendMode;
+      Int  iSimEnhBaseView = 0;
+
+      switch( m_iRenderDirection )
+      {
+      /// INTERPOLATION
+      case 0:
+        AOF( bHasLRView || bIsBaseView );
+
+        if ( !bHasLRView && bIsBaseView && m_iBlendMode == 0 )
+        {
+          bRender = false;
+        }
+        else
+        {
+          if ( bIsBaseView )
+          {
+            AOF( iLeftBaseViewIdx == iRightBaseViewIdx );
+            Int iSortedBaseViewIdx = m_cCameraData.getBaseId2SortedId() [iLeftBaseViewIdx];
+
+            if ( m_iBlendMode == 1 )
+            {
+              if ( iSortedBaseViewIdx - 1 >= 0 )
+              {
+                iLeftBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iSortedBaseViewIdx - 1];
+                bRender = true;
+              }
+              else
+              {
+                bRender = false;
+              }
+            }
+            else if ( m_iBlendMode == 2 )
+            {
+              if ( iSortedBaseViewIdx + 1 < m_iNumberOfInputViews )
+              {
+                iRightBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iSortedBaseViewIdx + 1];
+                bRender = true;
+              }
+              else
+              {
+                bRender = false;
+              }
+            }
+          }
+
+          if ( m_iBlendMode == 3 )
+          {
+            if ( bIsBaseView && (iLeftBaseViewIdx == 0) )
+            {
+              bRender = false;
+            }
+            else
+            {
+              Int iDistLeft  = abs( m_cCameraData.getBaseId2SortedId()[0] - m_cCameraData.getBaseId2SortedId() [iLeftBaseViewIdx ]  );
+              Int iDistRight = abs( m_cCameraData.getBaseId2SortedId()[0] - m_cCameraData.getBaseId2SortedId() [iRightBaseViewIdx]  );
+
+              Int iFillViewIdx = iDistLeft > iDistRight ? iLeftBaseViewIdx : iRightBaseViewIdx;
+
+              if( m_cCameraData.getBaseId2SortedId()[0] < m_cCameraData.getBaseId2SortedId() [iFillViewIdx] )
+              {
+                iBlendMode        = 1;
+                iLeftBaseViewIdx  = 0;
+                iRightBaseViewIdx = iFillViewIdx;
+              }
+              else
+              {
+                iBlendMode        = 2;
+                iLeftBaseViewIdx  = iFillViewIdx;
+                iRightBaseViewIdx = 0;
+              }
+
+            }
+          }
+          else
+          {
+            iBlendMode = m_iBlendMode;
+          }
+        }
+
+        if ( m_bSimEnhance )
+        {
+          if ( m_iNumberOfInputViews == 3 && m_cCameraData.getRelSynthViewNumbers()[ iSynthViewIdx ] < VIEW_NUM_PREC  )
+          {
+            iSimEnhBaseView = 2; // Take middle view
+          }
+          else
+          {
+            iSimEnhBaseView = 1; // Take left view
+          }
+        }
+
+          if ( bRender )
+          {
+          std::cout << "Rendering Frame "    << iFrame
+                    << " of View "           << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx    ] / VIEW_NUM_PREC
+                    << "   Left BaseView: "  << (Double) m_cCameraData.getBaseViewNumbers() [iLeftBaseViewIdx ] / VIEW_NUM_PREC
+                    << "   Right BaseView: " << (Double) m_cCameraData.getBaseViewNumbers() [iRightBaseViewIdx] / VIEW_NUM_PREC
+                    << "   BlendMode: "      << iBlendMode
+                    << std::endl;
+
+          m_pcRenTop->setShiftLUTs(
+            m_cCameraData.getSynthViewShiftLUTD()[iLeftBaseViewIdx ][iSynthViewIdx],
+            m_cCameraData.getSynthViewShiftLUTI()[iLeftBaseViewIdx ][iSynthViewIdx],
+            m_cCameraData.getBaseViewShiftLUTI ()[iLeftBaseViewIdx ][iRightBaseViewIdx],
+            m_cCameraData.getSynthViewShiftLUTD()[iRightBaseViewIdx][iSynthViewIdx],
+            m_cCameraData.getSynthViewShiftLUTI()[iRightBaseViewIdx][iSynthViewIdx],
+            m_cCameraData.getBaseViewShiftLUTI ()[iRightBaseViewIdx][iLeftBaseViewIdx ],
+
+            iRelDistToLeft
+          );
+
+          m_pcRenTop->interpolateView(
+            apcPicYuvBaseVideo[iLeftBaseViewIdx ],
+            apcPicYuvBaseDepth[iLeftBaseViewIdx ],
+            apcPicYuvBaseVideo[iRightBaseViewIdx],
+            apcPicYuvBaseDepth[iRightBaseViewIdx],
+            pcPicYuvSynthOut,
+            iBlendMode,
+            iSimEnhBaseView
+            );
+        }
+        else
+        {
+          AOT(iLeftBaseViewIdx != iRightBaseViewIdx );
+          apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut );
+          std::cout << "Copied    Frame " << iFrame
+                    << " of View "        << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC
+                    << "   (BaseView)  "    << std::endl;
+        }
+
+        break;
+      /// EXTRAPOLATION FROM LEFT
+      case 1:
+        if ( !bHasLView ) // View to render is BaseView
+        {
+          bRender = false;
+        }
+
+          if (  bIsBaseView )
+          {
+          AOF( iLeftBaseViewIdx == iRightBaseViewIdx );
+          Int iSortedBaseViewIdx = m_cCameraData.getBaseId2SortedId() [iLeftBaseViewIdx];
+          if ( iSortedBaseViewIdx - 1 >= 0 )
+          {
+            iLeftBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iSortedBaseViewIdx - 1];
+          }
+          else
+          {
+            std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+            apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+            bRender = false;
+          }
+        }
+
+
+        if (bRender)
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          m_pcRenTop->setShiftLUTs( m_cCameraData.getSynthViewShiftLUTD()[iLeftBaseViewIdx ][iSynthViewIdx],
+            m_cCameraData.getSynthViewShiftLUTI()[iLeftBaseViewIdx ][iSynthViewIdx], NULL, NULL, NULL, NULL, -1 );
+          m_pcRenTop->extrapolateView( apcPicYuvBaseVideo[iLeftBaseViewIdx ], apcPicYuvBaseDepth[iLeftBaseViewIdx ], pcPicYuvSynthOut, true );
+        }
+        break;
+      /// EXTRAPOLATION FROM RIGHT
+      case 2:            // extrapolation from right
+        if ( !bHasRView ) // View to render is BaseView
+        {
+          bRender = false;
+        }
+
+          if (  bIsBaseView )
+          {
+
+          AOF( iLeftBaseViewIdx == iRightBaseViewIdx );
+          Int iSortedBaseViewIdx = m_cCameraData.getBaseId2SortedId() [iLeftBaseViewIdx];
+          if ( iSortedBaseViewIdx + 1 < m_iNumberOfInputViews )
+          {
+            iRightBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iSortedBaseViewIdx + 1];
+          }
+          else
+          {
+            std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+            apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+            bRender = false;
+          }
+        }
+
+        if ( bRender )
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          m_pcRenTop->setShiftLUTs( NULL, NULL,NULL, m_cCameraData.getSynthViewShiftLUTD()[iRightBaseViewIdx ][iSynthViewIdx],
+            m_cCameraData.getSynthViewShiftLUTI()[iRightBaseViewIdx ][iSynthViewIdx],NULL, iRelDistToLeft);
+          m_pcRenTop->extrapolateView( apcPicYuvBaseVideo[iRightBaseViewIdx ], apcPicYuvBaseDepth[iRightBaseViewIdx ], pcPicYuvSynthOut, false);
+        }
+        break;
+      }
+
+      // Write Output
+
+      m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iSynthViewIdx]->write( pcPicYuvSynthOut, 0, 0, 0, 0 );
+    }
+    iFrame++;
+    iNumOfRenderedFrames++;
+  }
+
+  // Delete Buffers
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    apcPicYuvBaseVideo[uiBaseView]->destroy();
+    delete apcPicYuvBaseVideo[uiBaseView];
+
+    apcPicYuvBaseDepth[uiBaseView]->destroy();
+    delete apcPicYuvBaseDepth[uiBaseView];
+
+    // Temporal Filter
+    if ( m_bTempDepthFilter )
+    {
+      apcPicYuvLastBaseVideo[uiBaseView]->destroy();
+      delete apcPicYuvLastBaseVideo[uiBaseView];
+
+      apcPicYuvLastBaseDepth[uiBaseView]->destroy();
+      delete apcPicYuvLastBaseDepth[uiBaseView];
+    }
+  }
+
+  pcPicYuvSynthOut->destroy();
+  delete pcPicYuvSynthOut;
+
+  xDestroyLib();
+
+}
+
+Void TAppRendererTop::go()
+{
+  switch ( m_iRenderMode )
+  {
+  case 0:
+    render();
+    break;
+  case 1:
+    renderModel();
+    break;
+  case 10:
+    renderUsedPelsMap( );
+      break;
+
+  default:
+    AOT(true);
+  }
+}
+
+Void TAppRendererTop::renderModel()
+{
+  if ( m_bUseSetupString )
+  {
+    xRenderModelFromString();
+  }
+  else
+  {
+    xRenderModelFromNums();
+  }
+}
+
+Void TAppRendererTop::xRenderModelFromString()
+{
+
+    xCreateLib();
+    xInitLib();
+
+    // Create Buffers Input Views;
+    std::vector<TComPicYuv*> apcPicYuvBaseVideo;
+    std::vector<TComPicYuv*> apcPicYuvBaseDepth;
+
+
+    for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+    {
+      TComPicYuv* pcNewVideoPic = new TComPicYuv;
+      TComPicYuv* pcNewDepthPic = new TComPicYuv;
+
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvBaseVideo.push_back(pcNewVideoPic);
+
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+    }
+
+    Int aiPad[2] = { 0, 0 };
+
+    // Init Model
+    TRenModel cCurModel;
+
+    AOT( m_iLog2SamplingFactor != 0 );
+#if LGE_VSO_EARLY_SKIP_A0093
+    cCurModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin, false );
+#else
+    cCurModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin );
+#endif
+
+    cCurModel.setupPart( 0, m_iSourceHeight  ); 
+
+    for ( Int iViewIdx = 0; iViewIdx < m_iNumberOfInputViews; iViewIdx++ )
+    {
+      Int iNumOfModels   = m_cRenModStrParser.getNumOfModelsForView(iViewIdx, 1);
+
+      for (Int iCurModel = 0; iCurModel < iNumOfModels; iCurModel++ )
+      {
+        Int iModelNum; Int iLeftViewNum; Int iRightViewNum; Int iDump; Int iOrgRefNum; Int iBlendMode;
+        m_cRenModStrParser.getSingleModelData  ( iViewIdx, 1, iCurModel, iModelNum, iBlendMode, iLeftViewNum, iRightViewNum, iOrgRefNum, iDump ) ;
+        cCurModel         .createSingleModel   ( iViewIdx, 1, iModelNum, iLeftViewNum, iRightViewNum, false, iBlendMode );
+
+      }
+    }
+
+    // Create Buffer for synthesized View
+    TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
+    pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+
+    Bool bAnyEOS = false;
+
+    Int iNumOfRenderedFrames = 0;
+    Int iFrame = 0;
+
+    while ( ( ( iNumOfRenderedFrames < m_iFramesToBeRendered ) || ( m_iFramesToBeRendered == 0 ) ) && !bAnyEOS )
+    {
+
+      if ( iFrame >= m_iFrameSkip )
+      {      
+        // read in depth and video
+        for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+        {
+          m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+          bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
+
+          m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+          bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
+        }
+      }
+      else
+      {
+        iFrame++;
+        continue;
+      }
+
+
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        TComPicYuv* pcPicYuvVideo = apcPicYuvBaseVideo[iBaseViewIdx];
+        TComPicYuv* pcPicYuvDepth = apcPicYuvBaseDepth[iBaseViewIdx];
+        Int iBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iBaseViewIdx ];
+        cCurModel.setBaseView( iBaseViewSIdx, pcPicYuvVideo, pcPicYuvDepth, NULL, NULL );
+      }
+
+      m_cCameraData.update( (UInt) ( iFrame - m_iFrameSkip ));
+
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        // setup virtual views
+        Int iBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iBaseViewIdx];
+
+        cCurModel.setErrorMode( iBaseViewSIdx, 1, 0 );
+        Int iNumOfSV  = m_cRenModStrParser.getNumOfModelsForView( iBaseViewSIdx, 1);
+        for (Int iCurView = 0; iCurView < iNumOfSV; iCurView++ )
+        {
+          Int iOrgRefBaseViewSIdx;
+          Int iLeftBaseViewSIdx;
+          Int iRightBaseViewSIdx;
+          Int iSynthViewRelNum;
+          Int iModelNum;
+          Int iBlendMode;
+
+          m_cRenModStrParser.getSingleModelData(iBaseViewSIdx, 1, iCurView, iModelNum, iBlendMode, iLeftBaseViewSIdx, iRightBaseViewSIdx, iOrgRefBaseViewSIdx, iSynthViewRelNum );
+
+          Int iLeftBaseViewIdx    = -1;
+          Int iRightBaseViewIdx   = -1;
+
+          TComPicYuv* pcPicYuvOrgRef  = NULL;
+          Int**      ppiShiftLUTLeft  = NULL;
+          Int**      ppiShiftLUTRight = NULL;
+          Int**      ppiBaseShiftLUTLeft  = NULL;
+          Int**      ppiBaseShiftLUTRight = NULL;
+
+
+          Int        iDistToLeft      = -1;
+
+          Int iSynthViewIdx = m_cCameraData.synthRelNum2Idx( iSynthViewRelNum );
+
+          if ( iLeftBaseViewSIdx != -1 )
+          {
+            iLeftBaseViewIdx   = m_cCameraData.getBaseSortedId2Id()   [ iLeftBaseViewSIdx ];
+            ppiShiftLUTLeft    = m_cCameraData.getSynthViewShiftLUTI()[ iLeftBaseViewIdx  ][ iSynthViewIdx  ];
+          }
+
+          if ( iRightBaseViewSIdx != -1 )
+          {
+            iRightBaseViewIdx  = m_cCameraData.getBaseSortedId2Id()   [iRightBaseViewSIdx ];
+            ppiShiftLUTRight   = m_cCameraData.getSynthViewShiftLUTI()[ iRightBaseViewIdx ][ iSynthViewIdx ];
+          }
+
+          if ( iRightBaseViewSIdx != -1 && iLeftBaseViewSIdx != -1 )
+          {
+
+            ppiBaseShiftLUTLeft  = m_cCameraData.getBaseViewShiftLUTI() [ iLeftBaseViewIdx  ][ iRightBaseViewIdx ];
+            ppiBaseShiftLUTRight = m_cCameraData.getBaseViewShiftLUTI() [ iRightBaseViewIdx ][ iLeftBaseViewIdx  ];
+            iDistToLeft    = m_cCameraData.getRelDistLeft(  iSynthViewIdx , iLeftBaseViewIdx, iRightBaseViewIdx);
+          }
+
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+
+          cCurModel.setSingleModel( iModelNum, ppiShiftLUTLeft, ppiBaseShiftLUTLeft, ppiShiftLUTRight, ppiBaseShiftLUTRight, iDistToLeft, pcPicYuvOrgRef );
+
+          Int iViewPos;
+          if (iLeftBaseViewSIdx != -1 && iRightBaseViewSIdx != -1)
+          {
+            iViewPos = VIEWPOS_MERGED;
+          }
+          else if ( iLeftBaseViewSIdx != -1 )
+          {
+            iViewPos = VIEWPOS_LEFT;
+          }
+          else if ( iRightBaseViewSIdx != -1 )
+          {
+            iViewPos = VIEWPOS_RIGHT;
+          }
+          else
+          {
+            AOT(true);
+          }
+
+          cCurModel.getSynthVideo ( iModelNum, iViewPos, pcPicYuvSynthOut );
+
+          // Write Output
+          m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iModelNum]->write( pcPicYuvSynthOut, 0 ,0 ,0, 0 );
+        }
+      }
+      iFrame++;
+      iNumOfRenderedFrames++;
+  }
+
+    // Delete Buffers
+    for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+    {
+      apcPicYuvBaseVideo[uiBaseView]->destroy();
+      delete apcPicYuvBaseVideo[uiBaseView];
+
+      apcPicYuvBaseDepth[uiBaseView]->destroy();
+      delete apcPicYuvBaseDepth[uiBaseView];
+}
+    pcPicYuvSynthOut->destroy();
+    delete pcPicYuvSynthOut;
+
+    xDestroyLib();
+}
+
+Void TAppRendererTop::xRenderModelFromNums()
+{
+  xCreateLib();
+  xInitLib();
+
+  // Create Buffers Input Views;
+  std::vector<TComPicYuv*> apcPicYuvBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvBaseDepth;
+
+
+  Int aiPad[2] = { 0, 0 };
+
+  // Init Model
+  TRenModel cCurModel;
+
+  AOT( m_iLog2SamplingFactor != 0 );
+  cCurModel.setupPart( 0, m_iSourceHeight  ); 
+#if LGE_VSO_EARLY_SKIP_A0093
+  cCurModel.create( m_iNumberOfInputViews, m_iNumberOfOutputViews, m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin, false );
+#else
+  cCurModel.create( m_iNumberOfInputViews, m_iNumberOfOutputViews, m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin );
+#endif
+
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    TComPicYuv* pcNewVideoPic = new TComPicYuv;
+    TComPicYuv* pcNewDepthPic = new TComPicYuv;
+
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseVideo.push_back(pcNewVideoPic);
+
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+  }
+
+  for(Int iSynthViewIdx=0; iSynthViewIdx < m_iNumberOfOutputViews; iSynthViewIdx++ )
+  {
+    Int  iLeftBaseViewIdx  = -1;
+    Int  iRightBaseViewIdx = -1;
+    Bool bIsBaseView = false;
+
+    Int iRelDistToLeft;
+    m_cCameraData.getLeftRightBaseView( iSynthViewIdx, iLeftBaseViewIdx, iRightBaseViewIdx, iRelDistToLeft,  bIsBaseView );
+
+    if (m_iRenderDirection == 1 )
+    {
+      iRightBaseViewIdx = -1;
+      AOT( iLeftBaseViewIdx == -1);
+    }
+
+    if (m_iRenderDirection == 2 )
+    {
+      iLeftBaseViewIdx = -1;
+      AOT( iRightBaseViewIdx == -1);
+    }
+
+    Int iLeftBaseViewSIdx  = -1;
+    Int iRightBaseViewSIdx = -1;
+
+    if (iLeftBaseViewIdx != -1 )
+    {
+      iLeftBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iLeftBaseViewIdx];
+    }
+
+    if (iRightBaseViewIdx != -1 )
+    {
+      iRightBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iRightBaseViewIdx];
+    }
+    cCurModel.createSingleModel(-1, -1, iSynthViewIdx, iLeftBaseViewSIdx, iRightBaseViewSIdx, false, m_iBlendMode );
+  }
+
+  // Create Buffer for synthesized View
+  TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+
+  Bool bAnyEOS = false;
+
+  Int iNumOfRenderedFrames = 0;
+  Int iFrame = 0;
+
+  while ( ( ( iNumOfRenderedFrames < m_iFramesToBeRendered ) || ( m_iFramesToBeRendered == 0 ) ) && !bAnyEOS )
+  {
+
+    if ( iFrame >= m_iFrameSkip )
+    {      
+      // read in depth and video
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+        bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
+
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
+
+        if ( iFrame >= m_iFrameSkip )
+        {
+          Int iBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iBaseViewIdx];
+          cCurModel.setBaseView( iBaseViewSIdx, apcPicYuvBaseVideo[iBaseViewIdx], apcPicYuvBaseDepth[iBaseViewIdx], NULL, NULL );
+        }
+      }
+    }
+    else
+    {
+      iFrame++;
+      continue;
+    }
+    m_cCameraData.update( (UInt) (iFrame - m_iFrameSkip ));
+    for(Int iSynthViewIdx=0; iSynthViewIdx < m_iNumberOfOutputViews; iSynthViewIdx++ )
+    {
+
+      Int  iLeftBaseViewIdx  = -1;
+      Int  iRightBaseViewIdx = -1;
+
+      Bool bIsBaseView = false;
+
+      Int iRelDistToLeft;
+      Bool bHasLRView = m_cCameraData.getLeftRightBaseView( iSynthViewIdx, iLeftBaseViewIdx, iRightBaseViewIdx, iRelDistToLeft, bIsBaseView );
+      Bool bHasLView = ( iLeftBaseViewIdx != -1 );
+      Bool bHasRView = ( iRightBaseViewIdx != -1 );
+
+      switch( m_iRenderDirection )
+      {
+        /// INTERPOLATION
+      case 0:
+        assert( bHasLRView || bIsBaseView );
+
+        if ( !bHasLRView && bIsBaseView ) // View to render is BaseView
+        {
+          std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+        }
+        else  // Render
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          cCurModel.setSingleModel( iSynthViewIdx,
+                                    m_cCameraData.getSynthViewShiftLUTI()[iLeftBaseViewIdx ][iSynthViewIdx]    ,
+                                    m_cCameraData.getBaseViewShiftLUTI ()[iLeftBaseViewIdx ][iRightBaseViewIdx],
+                                    m_cCameraData.getSynthViewShiftLUTI()[iRightBaseViewIdx][iSynthViewIdx]    ,
+                                    m_cCameraData.getBaseViewShiftLUTI ()[iRightBaseViewIdx][iLeftBaseViewIdx] ,
+                                    iRelDistToLeft,
+                                    NULL );
+          cCurModel.getSynthVideo ( iSynthViewIdx, VIEWPOS_MERGED, pcPicYuvSynthOut );
+        }
+        break;
+        /// EXTRAPOLATION FROM LEFT
+      case 1:
+
+        if ( !bHasLView ) // View to render is BaseView
+        {
+          std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+        }
+        else  // Render
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          cCurModel.setSingleModel( iSynthViewIdx, m_cCameraData.getSynthViewShiftLUTI()[iLeftBaseViewIdx ][iSynthViewIdx], NULL, NULL, NULL, -1,  NULL);
+          cCurModel.getSynthVideo ( iSynthViewIdx, VIEWPOS_LEFT, pcPicYuvSynthOut );
+        }
+        break;
+        /// EXTRAPOLATION FROM RIGHT
+      case 2:            // extrapolation from right
+        if ( !bHasRView ) // View to render is BaseView
+        {
+          std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          apcPicYuvBaseVideo[iRightBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+        }
+        else  // Render
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          cCurModel.setSingleModel( iSynthViewIdx, NULL , NULL, m_cCameraData.getSynthViewShiftLUTI()[iRightBaseViewIdx ][iSynthViewIdx], NULL, -1, NULL);
+          cCurModel.getSynthVideo ( iSynthViewIdx, VIEWPOS_RIGHT, pcPicYuvSynthOut );
+        }
+        break;
+      }
+
+      // Write Output
+      m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iSynthViewIdx]->write( pcPicYuvSynthOut, 0, 0, 0, 0 );
+    }
+    iFrame++;
+    iNumOfRenderedFrames++;
+  }
+
+  // Delete Buffers
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    apcPicYuvBaseVideo[uiBaseView]->destroy();
+    delete apcPicYuvBaseVideo[uiBaseView];
+
+    apcPicYuvBaseDepth[uiBaseView]->destroy();
+    delete apcPicYuvBaseDepth[uiBaseView];
+  }
+  pcPicYuvSynthOut->destroy();
+  delete pcPicYuvSynthOut;
+
+  xDestroyLib();
+
+}
+
+Void TAppRendererTop::renderUsedPelsMap( )
+{
+  xCreateLib();
+  xInitLib();
+
+  // Create Buffers Input Views;
+  std::vector<TComPicYuv*> apcPicYuvBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvBaseDepth;
+
+  // TemporalImprovement Filter
+  std::vector<TComPicYuv*> apcPicYuvLastBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvLastBaseDepth;
+
+  Int aiPad[2] = { 0, 0 };
+
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    TComPicYuv* pcNewVideoPic = new TComPicYuv;
+    TComPicYuv* pcNewDepthPic = new TComPicYuv;
+
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseVideo.push_back(pcNewVideoPic);
+
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+
+    //Temporal improvement Filter
+    if ( m_bTempDepthFilter )
+    {
+      pcNewVideoPic = new TComPicYuv;
+      pcNewDepthPic = new TComPicYuv;
+
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvLastBaseVideo.push_back(pcNewVideoPic);
+
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvLastBaseDepth.push_back(pcNewDepthPic);
+    }
+  }
+
+  // Create Buffer for synthesized View
+  TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+
+  Bool bAnyEOS = false;
+
+  Int iNumOfRenderedFrames = 0;
+  Int iFrame = 0;
+
+  while ( ( ( iNumOfRenderedFrames < m_iFramesToBeRendered ) || ( m_iFramesToBeRendered == 0 ) ) && !bAnyEOS )
+  {
+
+
+    if ( iFrame >= m_iFrameSkip )
+    {      
+      // read in depth and video
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+        apcPicYuvBaseVideo[iBaseViewIdx]->extendPicBorder();
+        bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
+
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        apcPicYuvBaseDepth[iBaseViewIdx]->extendPicBorder();
+        bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
+
+        if ( m_bTempDepthFilter && (iFrame >= m_iFrameSkip) )
+        {
+          m_pcRenTop->temporalFilterVSRS( apcPicYuvBaseVideo[iBaseViewIdx], apcPicYuvBaseDepth[iBaseViewIdx], apcPicYuvLastBaseVideo[iBaseViewIdx], apcPicYuvLastBaseDepth[iBaseViewIdx], ( iFrame == m_iFrameSkip) );
+        }
+      }
+    }
+    else
+    {
+      std::cout << "Skipping Frame " << iFrame << std::endl;
+
+      iFrame++;
+      continue;
+    }
+    m_cCameraData.update( (UInt) ( iFrame - m_iFrameSkip ) );
+
+    for(Int iViewIdx=1; iViewIdx < m_iNumberOfInputViews; iViewIdx++ )
+    {
+      std::cout << "Rendering UsedPelsMap for Frame " << iFrame << " of View " << (Double) m_cCameraData.getBaseViewNumbers()[iViewIdx] << std::endl;
+
+      Int iViewSIdx      = m_cCameraData.getBaseId2SortedId()[iViewIdx];
+      Int iFirstViewSIdx = m_cCameraData.getBaseId2SortedId()[0];
+
+      AOT( iViewSIdx == iFirstViewSIdx );
+
+      Bool bFirstIsLeft = (iFirstViewSIdx < iViewSIdx);
+
+      m_pcRenTop->setShiftLUTs(
+        m_cCameraData.getBaseViewShiftLUTD()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTD()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+        -1
+        );
+
+      m_pcRenTop->getUsedSamplesMap( apcPicYuvBaseDepth[0], pcPicYuvSynthOut, bFirstIsLeft );
+
+      // Write Output
+      m_apcTVideoIOYuvSynthOutput[iViewIdx-1]->write( pcPicYuvSynthOut, 0, 0, 0 );
+
+    }
+    iFrame++;
+    iNumOfRenderedFrames++;
+  }
+
+  // Delete Buffers
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    apcPicYuvBaseVideo[uiBaseView]->destroy();
+    delete apcPicYuvBaseVideo[uiBaseView];
+
+    apcPicYuvBaseDepth[uiBaseView]->destroy();
+    delete apcPicYuvBaseDepth[uiBaseView];
+
+    // Temporal Filter
+    if ( m_bTempDepthFilter )
+    {
+      apcPicYuvLastBaseVideo[uiBaseView]->destroy();
+      delete apcPicYuvLastBaseVideo[uiBaseView];
+
+      apcPicYuvLastBaseDepth[uiBaseView]->destroy();
+      delete apcPicYuvLastBaseDepth[uiBaseView];
+    }
+  }
+  pcPicYuvSynthOut->destroy();
+  delete pcPicYuvSynthOut;
+
+  xDestroyLib();
+
+}
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererTop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererTop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/TAppRenderer/TAppRendererTop.h	(revision 341)
@@ -0,0 +1,91 @@
+/* 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-2011, 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 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 <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+
+#ifndef __TAppRendererTOP__
+#define __TAppRendererTOP__
+
+
+#include "../../Lib/TLibRenderer/TRenTop.h"
+#include "../../Lib/TLibVideoIO/TVideoIOYuv.h"
+#include "TAppRendererCfg.h"
+#include "TAppRendererTop.h"
+#include "../../Lib/TLibRenderer/TRenModel.h"
+
+#if !QC_MVHEVC_B0046
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder application class
+class TAppRendererTop : public TAppRendererCfg
+{
+private:
+  // class interface
+  std::vector<TVideoIOYuv*>     m_apcTVideoIOYuvVideoInput;
+  std::vector<TVideoIOYuv*>    m_apcTVideoIOYuvDepthInput;
+  std::vector<TVideoIOYuv*>     m_apcTVideoIOYuvSynthOutput;
+
+  // RendererInterface
+  TRenTop*                     m_pcRenTop;
+
+protected:
+  // initialization
+  Void  xCreateLib        ();                               ///< create renderer class and video io
+  Void  xInitLib          ();                               ///< initialize renderer class
+  Void  xDestroyLib       ();                               ///< destroy renderer class and video io
+  Void  xRenderModelFromString();                           ///< render using model using setup string
+  Void  xRenderModelFromNums();                             ///< render using model using synth view numbers
+
+
+public:
+  TAppRendererTop();
+  virtual ~TAppRendererTop();
+
+  Void  render      ();                               ///< main encoding function
+  Void  renderModel ();
+  Void  go          ();
+  Void  renderUsedPelsMap();
+
+};// END CLASS DEFINITION TAppRendererTop
+
+#endif
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitrates.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 341)
@@ -0,0 +1,164 @@
+/* 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-2012, 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 "ExtractBitrates.h"
+#include <string>
+#include <sstream>
+#include <cassert>
+#include <limits>
+#include <map>
+
+namespace
+{
+  /// Maintains a sum and a sample-count for calculating averages
+  class Tally
+  {
+    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
+  /// \param iLine The active input stream
+  /// \param character The character to ignore up to
+  /// \throw POCParseException if the stream goes bad before character is encountered or just after character is encountered
+  void ignoreUpTo( const std::string& line, std::istream& iLine, char character )
+  {
+    while( iLine.good( ) && character != iLine.get( ) )
+      ;
+    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
+  /// \return A map that countains the average bitrates for each temporal layer.  Each pair contains the QP value in first and the average bitrate in second.
+  /// \throw POCParseException if an error occured while parsing a POC line
+  std::map< unsigned char, double > extractBitratesForQPs( std::istream& i )
+  {
+    std::map< unsigned char, Tally > tallyMap;
+    
+    while( i.good( ) )
+    {
+      // Initialize variables for this line
+      std::string line;
+      std::getline( i, line );
+      std::istringstream iLine( line );
+      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 );
+      
+      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 );
+      
+      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 );
+      unsigned char qpIndex( ( unsigned char )qpIndexLong );
+      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 );
+      
+      // 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 ) );
+      if( tallyMap.end( ) == iter )
+      {
+        tallyMap[ qpIndex ] = Tally( );
+        iter = tallyMap.find( qpIndex );
+      }
+      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;
+    for( std::map< unsigned char, Tally >::const_iterator iter( tallyMap.begin( ) ); iter != tallyMap.end( ); ++iter )
+    {
+      result[ iter->first ] = iter->second.average( );
+    }
+    return result;
+  }
+}
+
+std::vector< double > extractBitratesForTemporalLayers( std::istream& i )
+{
+  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( );
+      ++expectedNextQPIndex;
+      result.push_back( i->second );
+    }
+  }
+  
+  return result;
+}
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitrates.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 341)
@@ -0,0 +1,71 @@
+/* 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-2012, 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 EXTRACT_BITRATES_H
+#define EXTRACT_BITRATES_H
+
+#include "RuntimeError.h"
+#include <vector>
+
+/// An error occured while parsing a POC line from within a log file
+class POCParseException: public RuntimeError
+{
+  public:
+    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;
+};
+
+/// The QP set from the log file was not contiguous.  The QP set must be contiguous to be able to convert the results into a vector.
+class NonContiguousQPSetException: public RuntimeError
+{
+  public:
+    virtual ~NonContiguousQPSetException( ) throw( ) { }
+  
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Non-contiguous QP set exception"; }
+};
+
+/// Extracts the average bitrates for each of the temporal layers from the given log
+/// \param i The input stream that represents the log
+/// \return A vector of doubles that contains the average bitrates for each temporal layer
+/// \throw POCParseException if an error occured while parsing a POC line
+/// \throw NonContiguousQPSetException if the QP set from the log file was not contiguous
+std::vector< double > extractBitratesForTemporalLayers( std::istream& i );
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 341)
@@ -0,0 +1,99 @@
+/* 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-2012, 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 <iostream>
+#include <cassert>
+#include "ExtractBitrates.h"
+
+/// In out, finds the first occurence of toFind and replaces it with "e"
+/// \pre toFind must have a size of 2
+/// \pre The first character in toFind muts be 'e'
+/// \pre out must contain toFind
+void replaceWithE( std::string &out, const std::string& toFind )
+{
+  assert( 2 == toFind.size( ) );
+  assert( 'e' == toFind[ 0 ] );
+  
+  std::string::size_type pos( out.find( toFind ) );
+  assert( pos != std::string::npos );
+  out.erase( pos + 1, 1 );
+}
+
+/// Formatted output for a double with appropriate formatting applied (correct number of digits, etc.)
+void outputDouble( std::ostream& left, double right )
+{
+  std::ostringstream oss;
+  oss.precision( 6 );
+  oss << std::scientific << right;
+  std::string s( oss.str( ) );
+  
+  replaceWithE( s, "e+" );
+  replaceWithE( s, "e0" );
+  
+  left << s;
+}
+
+int main( int, char** )
+{
+  try
+  {
+    std::vector< double > result( extractBitratesForTemporalLayers( std::cin ) );  // Extract the bitrate vector
+    
+    // Output the bitrate vector
+    if( 0 < result.size( ) )
+    {
+      std::vector< double >::const_iterator iter( result.begin( ) );
+      outputDouble( std::cout, *iter );
+      for( ; ; )
+      {
+        ++iter;
+        if( result.end( ) == iter )
+        {
+          break;
+        }
+        else
+        {
+          std::cout << " ";
+          outputDouble( std::cout, *iter );
+        }
+      }
+    }
+    
+    return 0;
+  }
+  catch( std::exception& e )
+  {
+    std::cerr << e.what( ) << std::endl;
+    return 1;
+  }
+}
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 341)
@@ -0,0 +1,397 @@
+/* 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-2012, 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 "GuessLambdaModifiers.h"
+#include <limits>
+#include <cassert>
+#include <cmath>
+
+namespace
+{
+  /// Formatted input for a bitrate vector
+  /// \param left The input stream that contains the bitrate vector
+  /// \param right The vector to be written to
+  /// \pre right must be empty
+  void parseBitrateVector( std::istream& left, std::vector< double >& right )
+  {
+    assert( right.empty( ) );
+    
+    for( ; ; )
+    {
+      assert( left.good( ) );
+      
+      double bitrate;
+      left >> bitrate;
+      if( left.fail( ) ) break;
+      if( bitrate <= ( double )0.0 )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      else
+      {
+        right.push_back( bitrate );
+      }
+      if( !left.good( ) ) break;
+      
+      if( left.peek( ) == ' ' )
+      {
+        left.ignore( );
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  
+  /// 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
+  /// \param target The target bitrate value that this Lambda-modifier is trying to reach
+  /// \param previousPoint The previous guess
+  /// \return The Lambda-modifier guess
+  /// \pre The given point must contain only positive non-zero values
+  double incrementLambdaModifier(
+      double initialAdjustmentParameter,
+      double targetBitrate,
+      const Point& previousPoint )
+  {
+    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 );
+  }
+}
+
+double polateLambdaModifier( double targetBitrate, const Point& point1, const Point& point2 )
+{
+  assert( 0.0 < point1.lambdaModifier );
+  assert( 0.0 < point2.lambdaModifier );
+  assert( 0.0 < point1.bitrate );
+  assert( 0.0 < point2.bitrate );
+  assert( point1.lambdaModifier != point2.lambdaModifier );
+  assert( point1.bitrate != point2.bitrate );
+  
+  // Calculate and return the result
+  double denominator( point1.bitrate - point2.bitrate );
+  double result( point1.lambdaModifier
+      + ( point1.lambdaModifier - point2.lambdaModifier ) / denominator * ( targetBitrate - point1.bitrate ) );
+  return result;
+}
+
+double guessLambdaModifier(
+    double initialAdjustmentParameter,
+    double targetBitrate,
+    const std::list< Point >& pointList,
+    double interDampeningFactor )
+{
+  assert( ( double )0.0 < interDampeningFactor );
+  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
+  {
+    preliminaryResult = incrementLambdaModifier( initialAdjustmentParameter, targetBitrate, pointList.back( ) );
+  }
+  else  // If there are at least two previous points, then we may be able to interpolate
+  {
+    std::list< Point >::const_reverse_iterator i( pointList.rbegin( ) );
+    Point point1 = *i;
+    ++i;
+    Point point2 = *i;
+    
+    // If the slope is either horizontal or vertical, we cannot interpolate
+    if( point1.lambdaModifier == point2.lambdaModifier || point1.bitrate == point2.bitrate )
+    {
+      preliminaryResult = incrementLambdaModifier( initialAdjustmentParameter, targetBitrate, pointList.back( ) );
+    }
+    else  // If the slope is not horizontal and not vertical, we can interpolate
+    {
+      preliminaryResult = polateLambdaModifier( targetBitrate, point1, point2 );
+    }
+  }
+  
+  double previousResult( pointList.back( ).lambdaModifier );
+  
+  // Apply "intra dampening"
+  {
+    double intermediate( std::log( ( double )1.0 + std::abs( preliminaryResult - previousResult ) / previousResult ) );
+    assert( ( double )0.0 <= intermediate );
+    if( ( preliminaryResult - previousResult ) < 0.0 )
+    {
+      preliminaryResult = previousResult * ( ( double )1.0 - intermediate );
+    }
+    else
+    {
+      preliminaryResult = previousResult * ( ( double )1.0 + intermediate );
+    }
+  }
+  
+  // Apply "inter dampening factor".  If necessary, reduce the factor until a positive result is acheived.
+  double result;
+  do
+  {
+    result = previousResult + interDampeningFactor * ( preliminaryResult - previousResult );
+    interDampeningFactor /= ( double )2.0;
+  } while( result <= ( double )0.0 );
+  return result;
+}
+
+namespace
+{
+  /// Extracts a single point at the given index from a full meta-log entry
+  Point pointFromFullMetaLogEntry( unsigned char index, const MetaLogEntry< std::vector< double > >& fullEntry )
+  {
+    Point result;
+    result.lambdaModifier = fullEntry.lambdaModifiers[ index ];
+    result.bitrate = fullEntry.bitrateVector[ index ];
+    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
+  /// \param cumulativeDelta The sum of the percentage changes of the Lambda-modifiers at the previous temporal layers
+  /// \return The calculated inter dampening factor
+  /// \pre cumulativeDelta must be non-negative
+  /// \pre parameter must be non-negative
+  double interDampeningFactor( double parameter, double cumulativeDelta )
+  {
+    assert( 0.0 <= cumulativeDelta );
+    assert( 0.0 <= parameter );
+    return ( double )1.0 / ( parameter * cumulativeDelta + ( double )1.0 );
+  }
+}
+
+std::vector< double > guessLambdaModifiers(
+    double initialAdjustmentParameter,
+    const std::vector< double > &targetBitrateVector,
+    const std::list< MetaLogEntry< std::vector< double > > >& metaLogEntryList )
+{
+  assert( !targetBitrateVector.empty( ) );
+  assert( !metaLogEntryList.empty( ) );
+  
+  double cumulativeDelta( 0.0 );
+  std::vector< double > resultVector;
+  for( unsigned char i( 0 ); i < targetBitrateVector.size( ); ++i )
+  {
+    // Populate pointList with up to two of the previous points
+    std::list< Point > pointList;
+    std::list< MetaLogEntry< std::vector< double > > >::const_reverse_iterator j( metaLogEntryList.rbegin( ) );
+    pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
+    ++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(
+        initialAdjustmentParameter,
+        targetBitrateVector[ i ],  // target bitrate
+        pointList,
+        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;
+}
+
+namespace
+{
+  /// Ignores all of the the characters up to and including a given character
+  /// \param i The active input stream
+  /// \param character The character to ignore up to
+  /// \throw MetaLogParseException if the stream goes bad before character is encountered or just after character is encountered
+  void ignoreUpTo( std::istream& i, char character )
+  {
+    while( i.good( ) && character != i.get( ) )
+      ;
+    if( !i.good( ) ) throw MetaLogParseException( );
+  }
+  
+  /// Parses a Lambda-modifier map
+  /// \param right The map to write the output to
+  void parseLambdaModifierMap( std::istream& left, std::map< unsigned char, double >& right )
+  {
+    for( ; ; )
+    {
+      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;
+      
+      // 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;
+      unsigned char index( ( unsigned char )indexLong );
+      
+      if( ' ' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      
+      // Parse the Lambda-modifier
+      double lambdaModifier;
+      left >> lambdaModifier;
+      if( lambdaModifier <= ( double )0.0 || ( !right.empty( ) && ( right.count( index ) != 0 || index <= right.rbegin( )->first ) ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      else
+      {
+        right[ index ] = lambdaModifier;
+      }
+      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( ) == ' ' )
+      {
+        left.ignore( );
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  
+  /// Extracts the indexes from the given maps
+  /// \return The set of indexes
+  std::set< unsigned char > indexSetFromMap( const std::map< unsigned char, double >& in )
+  {
+    std::set< unsigned char > result;
+    for( typename std::map< unsigned char, double >::const_iterator i( in.begin( ) ); i != in.end( ); ++i )
+    {
+      result.insert( i->first );
+    }
+    return result;
+  }
+}
+
+void guessLambdaModifiers(
+    std::ostream& o,
+    std::istream& initialAdjustmentParameterIstream,
+    std::istream& targetsIstream,
+    std::istream& metaLogIstream )
+{
+  // Parse the initialAdjustmentParameter
+  double initialAdjustmentParameter;
+  initialAdjustmentParameterIstream >> initialAdjustmentParameter;
+  if( initialAdjustmentParameterIstream.fail( ) || initialAdjustmentParameterIstream.good( ) )
+  {
+    throw InitialAdjustmentParameterParseException( );
+  }
+  
+  // Parse the targets
+  std::vector< double > targetVector;
+  parseBitrateVector( targetsIstream, targetVector );
+  if( targetVector.empty( ) || targetsIstream.fail( ) || targetsIstream.good( ) ) throw TargetsParseException( );
+  
+  // Parse the metalog
+  std::list< MetaLogEntry< std::map< unsigned char, double > > > metaLogEntryList;
+  do
+  {
+    // Parse the Lambda-modifiers
+    MetaLogEntry< std::map< unsigned char, double > > entry;
+    parseLambdaModifierMap( metaLogIstream, entry.lambdaModifiers );
+    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
+    
+    // Skip the ';'
+    if( ';' != metaLogIstream.get( ) ) throw MetaLogParseException( );
+    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
+    
+    // Parse the bitrates
+    parseBitrateVector( metaLogIstream, entry.bitrateVector );
+    if( metaLogIstream.fail( ) ) throw MetaLogParseException( );
+    metaLogEntryList.push_back( entry );
+    
+    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
+  
+  // 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( );
+  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( );
+  }
+  
+  // Initialize simplifiedMetaLogEntryList
+  std::list< MetaLogEntry< std::vector< double > > > simplifiedMetaLogEntryList;
+  for( std::list< MetaLogEntry< std::map< unsigned char, double > > >::const_iterator i( metaLogEntryList.begin( ) );
+      i != metaLogEntryList.end( );
+      ++i )
+  {
+    simplifiedMetaLogEntryList.push_back( MetaLogEntry< std::vector< double > >( ) );
+    for( std::map< unsigned char, double >::const_iterator j( i->lambdaModifiers.begin( ) ); j != i->lambdaModifiers.end( ); ++j )
+    {
+      simplifiedMetaLogEntryList.back( ).lambdaModifiers.push_back( j->second );
+    }
+    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( ) );
+  std::vector< double >::const_iterator resultIter( resultVector.begin( ) );
+  do
+  {
+    if( indexIter != firstIndexSet.begin( ) ) o << " ";
+    o << "-LM" << ( long )( *indexIter ) << " ";
+    o.setf( std::ostream::fixed, std::ostream::floatfield );
+    o.precision( 7 );
+    o << ( *resultIter );
+    
+    ++indexIter;
+    ++resultIter;
+  } while( indexIter != firstIndexSet.end( ) );
+  assert( resultIter == resultVector.end( ) );  // The index set and the result vector should be the same size
+}
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 341)
@@ -0,0 +1,148 @@
+/* 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-2012, 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 CALCULATE_LAMBDA_MODIFIER_H
+#define CALCULATE_LAMBDA_MODIFIER_H
+
+#include "RuntimeError.h"
+#include <vector>
+#include <map>
+#include <list>
+#include <set>
+#include <limits>
+
+/// Thrown if there is an error parsing the initial adjustment parameter
+class InitialAdjustmentParameterParseException: public RuntimeError
+{
+  public:
+    virtual ~InitialAdjustmentParameterParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing the initial-adjustment parameter"; }
+};
+
+/// Thrown if there is an error parsing the targets
+class TargetsParseException: public RuntimeError
+{
+  public:
+    virtual ~TargetsParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing targets"; }
+};
+
+/// Thrown if there is an error parsing the meta-log
+class MetaLogParseException: public RuntimeError
+{
+  public:
+    virtual ~MetaLogParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing meta log"; }
+};
+
+/// Thrown if there is a mismatch in the vector sizes or the Lambda-modifier indexes
+class MismatchedIndexesException: public RuntimeError
+{
+  public:
+    virtual ~MismatchedIndexesException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Mismatched vector sizes or lambda modifier indexes"; }
+};
+
+/// Full meta-log entry
+template< typename TLambdaModifier >
+struct MetaLogEntry
+{
+  TLambdaModifier lambdaModifiers;
+  std::vector< double > bitrateVector;
+};
+
+/// Contains a Lambda-modifier and bitrate for only a single index
+struct Point
+{
+  double lambdaModifier;
+  double bitrate;
+};
+
+/// Performs interpolation/extrapolation to guess a single Lambda-modifier
+/// \param target 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
+/// \return The interpolated Lambda-modifier guess
+/// \pre Both given points must contain only positive non-zero values for first and second
+/// \pre The given points must have different first values and different second values.  If either the first values are the same or the second values are the same, then we have either a vertical or horizontal slope, and thus, interpolation cannot be performed.
+double polateLambdaModifier( double targetBitrate, const Point& point1, const Point& point2 );
+
+/// Guesses a single Lambda-modifier
+/// \param initialAdjustmentParameter If interpolation/extrapolation cannot be performed, then this parameter is used in the "increment" process.
+/// \param targetBitrate The target bitrate value that this Lambda-modifier is trying to reach
+/// \param pointList The list of points that correspond with this index
+/// \param interDampeningFactor This factor is obtained based on guessed Lambda-modifiers for previous temporal layers.  In some cases, this factor will scale down the change of this Lambda-modifier so that we are not making too many severe Lambda-modifier changes for a single encoder run.
+/// \return The Lambda-modifier guess
+/// \pre pointList cannot be empty
+/// \pre interDampeningFactor must be greater than zero and less than or equal to 1 (0 < interDampeningFactor <= 1)
+double guessLambdaModifier(
+    double initialAdjustmentParameter,
+    double targetBitrate,
+    const std::list< Point >& pointList,
+    double interDampeningFactor );
+
+/// Guesses all of the Lambda-modifiers
+/// \param initialAdjustmentParameter If interpolation/extrapolation cannot be performed, then this parameter is used in the "increment" process.
+/// \param targetBitrateVector The target bitrate values that we are trying to reach
+/// \param metaLogEntryList All of the previously run Lambda-modifiers and their corresponding bitrates from the meta-log
+/// \return Vector containing all of the guessed Lambda-modifiers
+/// \pre targetBitrateVector cannot be empty
+/// \pre metaLogEntryList cannot be empty
+/// \pre The size of targetBitrateVector must be the same as the size of bitrateVector in every item in metaLogEntryList
+/// \pre The size of targetBitrateVector must be the same as the size of lambdaModifiers in every item in metaLogEntryList
+std::vector< double > guessLambdaModifiers(
+    double initialAdjustmentParameter,
+    const std::vector< double > &targetBitrateVector,
+    const std::list< MetaLogEntry< std::vector< double > > >& metaLogEntryList );
+
+/// Guesses all of the Lambda-modifiers
+/// This function performs all of the necessary input parsing.  It ends up calling the other guessLambdaModifiers overload to perform the actual calculations.
+/// \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 metaLogIstream The input stream that contains the meta-log
+/// \throw InitialAdjustmentParameterParseException if there is an error parsing the initial adjustment parameter
+/// \throw TargetsParseException if there is an error parsing the target bitrates
+/// \throw MetaLogParseException if there is an error parsing the meta-log
+/// \throw MismatchedIndexesException if there is a mismatch in the vector sizes or the Lambda-modifier indexes
+void guessLambdaModifiers(
+    std::ostream& o,
+    std::istream& initialAdjustmentParameterIstream,
+    std::istream& targetsIstream,
+    std::istream& metaLogIstream );
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 341)
@@ -0,0 +1,72 @@
+/* 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-2012, 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 "RuntimeError.h"
+#include "GuessLambdaModifiers.h"
+#include <iostream>
+
+class WrongNumberOfArgumentsException: public RuntimeError
+{
+  public:
+    virtual ~WrongNumberOfArgumentsException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Wrong number of arguments"; }
+};
+
+int main( int argc, char** ppArgv )
+{
+  try
+  {
+    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 )
+  {
+    std::cerr << e.what( ) << std::endl;
+  }
+  catch( ... )
+  {
+    std::cerr << "Unknown exception" << std::endl;
+  }
+  return 1;
+}
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/RuntimeError.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 341)
@@ -0,0 +1,76 @@
+/* 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-2012, 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 DIRECTORY_LIB_RUNTIME_ERROR_H
+#define DIRECTORY_LIB_RUNTIME_ERROR_H
+
+#include <sstream>
+#include <stdexcept>
+
+/// This class serves the same purpose as std::runtime_error, but it can be more convenient to use
+class RuntimeError: public std::runtime_error
+{
+  public:
+    RuntimeError( ): std::runtime_error( "" ), m_firstWhat( true ) { }
+    virtual ~RuntimeError( ) throw ( ) { }
+    
+    /// Implementation of the std::exception::what method
+    const char * what( ) const throw( )
+    {
+      if( m_firstWhat )
+      {
+        std::ostringstream o;
+        outputWhat( o );
+        m_what = o.str( );
+        m_firstWhat = false;
+      }
+      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
+    mutable std::string m_what;  ///< Contains the what string.  Populated by the first call to the what method.
+};
+
+/// Convenient formatted output operator that just outputs the what string
+inline std::ostream& operator<<( std::ostream& left, const RuntimeError& right )
+{
+  return left << right.what( );
+}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/encode.shl
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/encode.shl	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/encode.shl	(revision 341)
@@ -0,0 +1,151 @@
+# 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-2012, 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.
+
+# This files contains shell code that is common to both encodeCommand.sh and targetBitrates.sh.
+
+# Run this function to validate a "-option value" pair of arguments
+function checkDollarTwo {
+  if [[ "" == $2 ]] ; then
+    printf "An argument must follow $1.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+# If the second argument is empty (not provided), output an error message and the usage, and then exit
+function verifyProvided {
+  if [[ "" == $2 ]] ; then
+    printf "The $1 parameter must be provided.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyNotDirectory {
+  if [[ `printf "$2\n" | grep '/$'` != "" ]] ; then
+    printf "The $1 parameter cannot be a directory.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyDirectory {
+  if [[ "" == `printf "$2\n" | grep '/$'` ]] ; then
+    printf "The $1 parameter must be a directory.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyConfigurationIdentifier {
+  case $configurationIdentifier in
+    ldLC) ;;
+    raLC) ;;
+    inLC) ;;
+    ldHE) ;;
+    raHE) ;;
+    inHE) ;;
+    *)
+      printf "The provided $CONFIGURATION_IDENTIFIER_STRING is invalid.  It must be \"ldLC\", \"raLC\", \"inLC\", \"ldHE\", \"raHE\", or \"inHE\".\n" >&2
+      outputUsageAndExit
+      ;;
+  esac
+}
+
+function verifyQ {
+  case $1 in
+    22)  ;;
+    27)  ;;
+    32)  ;;
+    37)  ;;
+    *)
+      printf "The provided $Q_STRING, \"$1\", is invalid.  It must be \"22\", \"27\", \"32\", or \"37\".\n" >&2
+      outputUsageAndExit
+    ;;
+  esac
+}
+
+Q_OPTION="-q"
+EXECUTABLE_OPTION="-e"
+CONFIGURATION_IDENTIFIER_OPTION="-ci"
+OUTPUT_DIRECTORY_OPTION="-o"
+EXTRA_ARGUMENTS_OPTION="-ea"
+CONFIGURATION_PATH_OPTION="-cp"
+CONFIGURATION_DIRECTORY_OPTION="-cd"
+
+Q_STRING="q ($Q_OPTION)"
+CONFIGURATION_IDENTIFIER_STRING="configuration identifier ($CONFIGURATION_IDENTIFIER_OPTION)"
+INPUT_NAME_STRING="input name"
+OUTPUT_DIRECTORY_STRING="output directory ($OUTPUT_DIRECTORY_OPTION)"
+
+USAGE_INDENT="  "
+INPUT_NAME_USAGE_STRING=inputName
+CONFIGURATION_IDENTIFIER_USAGE_STRING=configurationIdentifier
+Q_USAGE_STRING=q
+OUTPUT_DIRECTORY_USAGE_STRING=outputDirectory
+EXTRA_ARGUMENTS_USAGE_STRING=extraArguments
+
+function outputConfigurationIdentifierUsage {
+  echo "${USAGE_INDENT}$CONFIGURATION_IDENTIFIER_USAGE_STRING specifies the configuration (ldHE, ldLC, raHE, raLC, inHE, or inLC)." >&2
+}
+
+function outputQUsage {
+  echo "${USAGE_INDENT}$Q_USAGE_STRING is the QP value (22, 27, 32, or 37)." >&2
+}
+
+function outputOutputDirectoryUsage {
+  echo "${USAGE_INDENT}$OUTPUT_DIRECTORY_USAGE_STRING is the directory that will contain the output log, YUV, and bin." >&2
+}
+
+function outputInputNameUsage {
+  echo "${USAGE_INDENT}$INPUT_NAME_USAGE_STRING is the name of the input sequence.  Must be one of the following:" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}NebutaFestival_2560x1600_60_10bit_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SteamLocomotiveTrain_2560x1600_60_10bit_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Traffic_2560x1600_30_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}PeopleOnStreet_2560x1600_30_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQTerrace_1920x1080_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrive_1920x1080_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Cactus_1920x1080_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Kimono1_1920x1080_24" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}ParkScene_1920x1080_24" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo1_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo3_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo4_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}RaceHorses_832x480_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQMall_832x480_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}PartyScene_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrill_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}RaceHorses_416x240_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQSquare_416x240_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BlowingBubbles_416x240_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballPass_416x240_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrillText_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Chinaspeed_1024x768_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SlideEditing_1280x720_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SlideShow_1280x720_20" >&2
+}
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/encodeCommand.sh
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 341)
@@ -0,0 +1,258 @@
+#! /bin/sh
+
+# 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-2012, 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.
+
+# Outputs a command to run the encoder for a given set of arguments.  The encoder typically requires a lot of arguments to run, so this script can be more convenient than running the encoder direcly because it automatically generates many of the arguments.
+
+# "Include" encode.shl which contains common shell script code related to encoding
+SUB_TOOLS_DIRECTORY=$(echo "$0" | sed -e 's/[^\/]*$//')
+. ${SUB_TOOLS_DIRECTORY}encode.shl
+
+USE_LOG_FILE_OPTION="-l"
+INPUT_DIRECTORY_OPTION="-id"
+NUM_FRAMES_OPTION="-f"
+
+function outputUsageAndExit {
+  local EXECUTABLE_USAGE_STRING=executable
+  local INPUT_DIRECTORY_USAGE_STRING=inputDirectory
+  local CONFIGURATION_PATH_USAGE_STRING=configurationPath
+  local CONFIGURATION_DIRECTORY_USAGE_STRING=configurationDirectory
+  local NUM_FRAMES_USAGE_STRING=numFrames
+  
+  echo "Usage: $0 $CONFIGURATION_IDENTIFIER_OPTION $CONFIGURATION_IDENTIFIER_USAGE_STRING ($CONFIGURATION_PATH_OPTION $CONFIGURATION_PATH_USAGE_STRING -or- $CONFIGURATION_DIRECTORY_OPTION $CONFIGURATION_DIRECTORY_USAGE_STRING) $Q_OPTION $Q_USAGE_STRING $EXECUTABLE_OPTION $EXECUTABLE_USAGE_STRING [$NUM_FRAMES_OPTION $NUM_FRAMES_USAGE_STRING] [$EXTRA_ARGUMENTS_OPTION $EXTRA_ARGUMENTS_USAGE_STRING] $OUTPUT_DIRECTORY_OPTION $OUTPUT_DIRECTORY_USAGE_STRING [$USE_LOG_FILE_OPTION] [$INPUT_DIRECTORY_OPTION $INPUT_DIRECTORY_USAGE_STRING] $INPUT_NAME_USAGE_STRING" >&2
+  outputConfigurationIdentifierUsage
+  echo "${USAGE_INDENT}$CONFIGURATION_PATH_USAGE_STRING is the path of the configuration file to use.  Either this or $CONFIGURATION_DIRECTORY_USAGE_STRING must be specified (but not both)." >&2
+  echo "${USAGE_INDENT}$CONFIGURATION_DIRECTORY_USAGE_STRING is the path of the directory that contains the configuration files.  The particular file will be chosen based on $CONFIGURATION_IDENTIFIER_USAGE_STRING.  Either this or $CONFIGURATION_PATH_USAGE_STRING must be specified (but not both)." >&2
+  outputQUsage
+  echo "${USAGE_INDENT}$EXECUTABLE_USAGE_STRING is the path of the encoder executable." >&2
+  echo "${USAGE_INDENT}$NUM_FRAMES_USAGE_STRING is the number of frames to encode.  If omitted, the entire sequence will be encoded." >&2
+  echo "${USAGE_INDENT}$EXTRA_ARGUMENTS_USAGE_STRING is any extra arguments that should be passed on to the encoder." >&2
+  outputOutputDirectoryUsage
+  echo "${USAGE_INDENT}If $USE_LOG_FILE_OPTION is specified, the encoder will output to a log file.  Otherwise it will output to the standard output." >&2
+  echo "${USAGE_INDENT}$INPUT_DIRECTORY_USAGE_STRING is the directory that contains the sequences.  The default value is the SEQUENCE_DIR environment variable." >&2
+  outputInputNameUsage
+  
+  exit 1
+}
+
+# Used to lookup the width, height, number of frames, and frame rate for a given sequence
+table=`printf "${table}\nNebutaFestival_2560x1600_60_10bit_crop          2560   1600   300        60"`
+table=`printf "${table}\nSteamLocomotiveTrain_2560x1600_60_10bit_crop    2560   1600   300        60"`
+table=`printf "${table}\nTraffic_2560x1600_30_crop                       2560   1600   150        30"`
+table=`printf "${table}\nPeopleOnStreet_2560x1600_30_crop                2560   1600   150        30"`
+table=`printf "${table}\nBQTerrace_1920x1080_60                          1920   1080   600        60"`
+table=`printf "${table}\nBasketballDrive_1920x1080_50                    1920   1080   500        50"`
+table=`printf "${table}\nCactus_1920x1080_50                             1920   1080   500        50"`
+table=`printf "${table}\nKimono1_1920x1080_24                            1920   1080   240        24"`
+table=`printf "${table}\nParkScene_1920x1080_24                          1920   1080   240        24"`
+table=`printf "${table}\nvidyo1_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nvidyo3_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nvidyo4_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nRaceHorses_832x480_30                            832    480   300        30"`
+table=`printf "${table}\nBQMall_832x480_60                                832    480   600        60"`
+table=`printf "${table}\nPartyScene_832x480_50                            832    480   500        50"`
+table=`printf "${table}\nBasketballDrill_832x480_50                       832    480   500        50"`
+table=`printf "${table}\nRaceHorses_416x240_30                            416    240   300        30"`
+table=`printf "${table}\nBQSquare_416x240_60                              416    240   600        60"`
+table=`printf "${table}\nBlowingBubbles_416x240_50                        416    240   500        50"`
+table=`printf "${table}\nBasketballPass_416x240_50                        416    240   500        50"`
+table=`printf "${table}\nBasketballDrillText_832x480_50                   832    480   500        50"`
+table=`printf "${table}\nChinaspeed_1024x768_30                          1024    768   500        30"`
+table=`printf "${table}\nSlideEditing_1280x720_30                        1280    720   300        30"`
+table=`printf "${table}\nSlideShow_1280x720_20                           1280    720   500        20"`
+
+EXECUTABLE_STRING="executable ($EXECUTABLE_OPTION)"
+INPUT_DIRECTORY_STRING="input directory ($INPUT_DIRECTORY_OPTION)"
+CONFIGURATION_PATH_STRING="configuration path ($CONFIGURATION_PATH_OPTION)"
+CONFIGURATION_DIRECTORY_STRING="configuration directory ($CONFIGURATION_DIRECTORY_OPTION)"
+
+inputDirectory="$SEQUENCE_DIR"  # The default input directory is taken from this environment variable
+
+# For every argument $1
+while [ "" != "$*" ] ; do
+  case $1 in
+    $USE_LOG_FILE_OPTION)
+      useLogFile=$1
+    ;;
+    -*)
+      checkDollarTwo "$1" "$2"
+      case $1 in
+        $EXECUTABLE_OPTION) executable=$2 ;;
+        $INPUT_DIRECTORY_OPTION) inputDirectory=$2 ;;
+        $EXTRA_ARGUMENTS_OPTION) extraArguments=$2 ;;
+        $Q_OPTION) q=$2 ;;
+        $OUTPUT_DIRECTORY_OPTION) outputDirectory=$2 ;;
+        $CONFIGURATION_IDENTIFIER_OPTION) configurationIdentifier=$2 ;;
+        $CONFIGURATION_PATH_OPTION) configurationPath=$2 ;;
+        $CONFIGURATION_DIRECTORY_OPTION) configurationDirectory=$2 ;;
+        $NUM_FRAMES_OPTION) numFrames=$2 ;;
+        *)
+          printf "You entered an invalid option: \"$1\".\n" >&2
+          outputUsageAndExit
+        ;;
+      esac
+      shift
+    ;;
+    *)
+      if [[ "" == $inputName ]] ; then
+        inputName=$1
+      else
+        printf "You entered too many arguments.\n" >&2
+        outputUsageAndExit
+      fi
+    ;;
+  esac
+  
+  shift
+done
+
+verifyProvided "$EXECUTABLE_STRING" "$executable"
+verifyNotDirectory "$EXECUTABLE_STRING" "$executable"
+
+verifyDirectory "$INPUT_DIRECTORY_STRING" "$inputDirectory"
+
+verifyProvided "$Q_STRING" "$q"
+verifyQ $q
+
+verifyProvided "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+verifyDirectory "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+
+verifyProvided "$CONFIGURATION_IDENTIFIER_STRING" "$configurationIdentifier"
+verifyConfigurationIdentifier "$configurationIdentifier"
+
+# Validate $configurationPath or $configurationDirectory
+if [[ $configurationPath != "" ]] ; then
+  verifyNotDirectory "$CONFIGURATION_PATH_STRING" "$configurationPath"
+else
+  if [[ "" == $configurationDirectory ]] ; then
+    printf "You must enter a $CONFIGURATION_PATH_STRING or $CONFIGURATION_DIRECTORY_STRING.\n" >&2
+    outputUsageAndExit
+  else
+    verifyDirectory "$CONFIGURATION_DIRECTORY_STRING" "$configurationDirectory"
+  fi
+fi
+
+verifyProvided "$INPUT_NAME_STRING" "$inputName"
+verifyNotDirectory "$INPUT_NAME_STRING" "$inputName"
+
+# If configurationPath is not already populated, populate it based on the configuration directory and the configuration identifier
+if [[ "" == $configurationPath ]] ; then
+  configurationPath="${configurationDirectory}encoder_"
+  case $configurationIdentifier in
+    ldLC) configurationPath="${configurationPath}lowdelay_loco" ;;
+    raLC) configurationPath="${configurationPath}randomaccess_loco" ;;
+    inLC) configurationPath="${configurationPath}intra_loco" ;;
+    ldHE) configurationPath="${configurationPath}lowdelay" ;;
+    raHE) configurationPath="${configurationPath}randomaccess" ;;
+    *)    configurationPath="${configurationPath}intra" ;;  # inHE
+  esac
+  configurationPath="${configurationPath}.cfg"
+fi
+
+# Validate the input name and populate masterLine which contains the line from the table for the given sequence
+masterLine=`printf "$table" | grep -i "^$inputName "`
+if [[ "" == $masterLine ]] ; then
+  printf "Invalid input name.\n" >&2
+  outputUsageAndExit
+fi
+
+# If numFrames is not yet initialized, initialize it by looking up the values in the table
+if [[ "" == $numFrames ]] ; then
+  numFrames=`printf -- "$masterLine" | awk '{ print $4 }'`
+fi
+
+# Initialize these variables by looking up the values in the table
+frameRate=`printf -- "$masterLine" | awk '{ print $5 }'`
+width=`printf -- "$masterLine" | awk '{ print $2 }'`
+height=`printf -- "$masterLine" | awk '{ print $3 }'`
+
+# Initialize intraPeriod
+case $configurationIdentifier in
+  ld*)
+    intraPeriod="-1"
+  ;;
+  ra*)
+    if [[ 20 == "$frameRate" ]] ; then
+      intraPeriod="16"
+    else
+      intraPeriod=$(expr "$frameRate" + 4)
+      intraPeriod=$(expr "$intraPeriod" / 8)
+      intraPeriod=$(expr "$intraPeriod" \* 8)
+    fi
+  ;;
+  in*)
+    intraPeriod="1"
+  ;;
+  *)
+    outputConfigurationIdentifierErrorAndExit
+  ;;
+esac
+
+# Initialize tenBit if the given sequence is 10-bit
+printf -- "$inputName" | grep -i '10bit' > /dev/null
+case $? in
+  0)  tenBit="--InputBitDepth=10 "
+    ;;
+  1)  ;;
+  *)  exit $?
+    ;;
+esac
+
+outputPathBegin="${outputDirectory}${inputName}_${configurationIdentifier}_q${q}"
+
+# Output the command
+printf -- "$executable "
+printf -- "-c $configurationPath "
+printf -- "-i $inputDirectory$inputName.yuv "
+printf -- "-f $numFrames "
+printf -- "-fr $frameRate "
+printf -- "-wdt $width "
+printf -- "-hgt $height "
+printf -- "-ip $intraPeriod "
+printf -- "$tenBit"
+if [[ $tenBit != "" ]] ; then
+  printf " "
+fi
+printf -- "$extraArguments"
+if [[ $extraArguments != "" ]] ; then
+  printf -- " "
+fi
+printf -- "-q $q "
+printf -- "-b $outputPathBegin.bin "
+printf -- "-o $outputPathBegin.yuv "
+if [[ "" != $useLogFile ]] ; then
+  printf -- "&> $outputPathBegin.log"
+fi
+printf "\n"
+
+exit 0
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/makefile
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/makefile	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/makefile	(revision 341)
@@ -0,0 +1,54 @@
+# 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-2012, 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.
+
+CPPFLAGS = -D NDEBUG -Wall -Wextra
+
+extractBitratesObjects = ExtractBitrates.o ExtractBitratesMain.o
+extractBitratesExecutable = extractBitrates.exe
+
+guessLambdaModifiersObjects = GuessLambdaModifiers.o GuessLambdaModifiersMain.o
+guessLambdaModifiersExecutable = guessLambdaModifiers.exe
+
+all: $(extractBitratesExecutable) $(guessLambdaModifiersExecutable)
+
+$(extractBitratesExecutable): $(extractBitratesObjects)
+	g++ -o $@ $(extractBitratesObjects)
+$(guessLambdaModifiersExecutable): $(guessLambdaModifiersObjects)
+	g++ -o $@ $(guessLambdaModifiersObjects)
+
+ExtractBitrates.o: ExtractBitrates.h RuntimeError.h
+ExtractBitratesMain.o: ExtractBitrates.h RuntimeError.h
+GuessLambdaModifiers.o: GuessLambdaModifiers.h RuntimeError.h
+GuessLambdaModifiersMain.o: GuessLambdaModifiers.h RuntimeError.h
+
+clean:
+	rm $(extractBitratesExecutable) $(extractBitratesObjects) $(guessLambdaModifiersExecutable) $(guessLambdaModifiersObjects)
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/targetBitrates.sh
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 341)
@@ -0,0 +1,409 @@
+#! /bin/sh
+
+# 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-2012, 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.
+
+
+SUB_TOOLS_DIRECTORY=$(echo "$0" | sed -e 's/[^\/]*$//')
+. ${SUB_TOOLS_DIRECTORY}encode.shl
+
+LAMBDA_MODIFIER_PREFIX="LM"
+
+RESUME_MODE_OPTION="-rm"
+TARGET_BITRATES_OPTION="-tb"
+INITIAL_LAMBDA_MODIFIERS_OPTION="-il"
+ENCODE_COMMAND_ARGS_OPTION="-ca"
+
+function outputUsageAndExit {
+  local TARGET_BITRATES_USAGE_STRING=targetBitrates
+  local INITIAL_LAMBDA_MODIFIERS_USAGE_STRING=initialLambdaModifiers
+  local ENCODE_COMMAND_ARGS_USAGE_STRING=encodeCommandArgs
+  
+  echo "Usage: $0 [$RESUME_MODE_OPTION] $CONFIGURATION_IDENTIFIER_OPTION $CONFIGURATION_IDENTIFIER_USAGE_STRING $Q_OPTION $Q_USAGE_STRING $TARGET_BITRATES_OPTION $TARGET_BITRATES_USAGE_STRING [$INITIAL_LAMBDA_MODIFIERS_OPTION $INITIAL_LAMBDA_MODIFIERS_USAGE_STRING] [$ENCODE_COMMAND_ARGS_OPTION $ENCODE_COMMAND_ARGS_USAGE_STRING] [$EXTRA_ARGUMENTS_OPTION $EXTRA_ARGUMENTS_USAGE_STRING] $OUTPUT_DIRECTORY_OPTION $OUTPUT_DIRECTORY_USAGE_STRING $INPUT_NAME_USAGE_STRING" >&2
+  echo "${USAGE_INDENT}$RESUME_MODE_OPTION engages resume mode which allows the user to resume an execution that was interrupted before completion."
+  outputConfigurationIdentifierUsage
+  outputQUsage
+  echo "${USAGE_INDENT}$TARGET_BITRATES_USAGE_STRING is the target bitrates.  For example: \"23:35 24:3473242 etc...\"." >&2
+  echo "${USAGE_INDENT}$INITIAL_LAMBDA_MODIFIERS_USAGE_STRING is the Lambda-modifiers to use for the first guess.  For example: \"$-{LAMBDA_MODIFIER_PREFIX}23 1e0 $-{LAMBDA_MODIFIER_PREFIX}24 0.98 etc...\"" >&2
+  echo "${USAGE_INDENT}$ENCODE_COMMAND_ARGS_USAGE_STRING is the extra arguments to be passed to encodeCommand.sh.  The common arguments that are available to both $0 and encodeCommand.sh should not be passed though this argument.  For example, don't pass $Q_OPTION here because it is an option of $0.  $EXECUTABLE_OPTION and ($CONFIGURATION_PATH_OPTION or $CONFIGURATION_DIRECTORY_OPTION) must be passed through this argument.  For example, \"$ENCODE_COMMAND_ARGS_OPTION '$EXECUTABLE_OPTION ~/bin/encode.exe $CONFIGURATION_DIRECTORY_OPTION ~/cfg/'\"." >&2
+  echo "${USAGE_INDENT}$EXTRA_ARGUMENTS_USAGE_STRING specifies extra arguments to be passed directly to the encoder (not to encodeCommand.sh)." >&2
+  outputOutputDirectoryUsage
+  outputInputNameUsage
+  
+  exit 1
+}
+
+NORMAL_MODE="NORMAL_MODE"
+RESUME_MODE="RESUME_MODE"
+mode="$NORMAL_MODE"
+
+# For every argument $1
+while [ "" != "$*" ] ; do
+  case $1 in
+    $RESUME_MODE_OPTION)
+      mode="$RESUME_MODE"
+    ;;
+    -*)
+      checkDollarTwo "$1" "$2"
+      case $1 in
+        $EXTRA_ARGUMENTS_OPTION) extraArguments=$2 ;;
+        $Q_OPTION) q=$2 ;;
+        $OUTPUT_DIRECTORY_OPTION) outputDirectory=$2 ;;
+        $CONFIGURATION_IDENTIFIER_OPTION) configurationIdentifier=$2 ;;
+        $TARGET_BITRATES_OPTION) targetBitrates=$2 ;;
+        $INITIAL_LAMBDA_MODIFIERS_OPTION) initialLambdaModifiers=$2 ;;
+        $ENCODE_COMMAND_ARGS_OPTION) encodeCommandArgs=$2 ;;
+        *)
+          printf "You entered an invalid option: \"$1\".\n" >&2
+          outputUsageAndExit
+        ;;
+      esac
+      shift
+    ;;
+    *)
+      if [[ "" == $inputName ]] ; then
+        inputName=$1
+      else
+        printf "You entered too many arguments.\n" >&2
+        outputUsageAndExit
+      fi
+    ;;
+  esac
+  
+  shift
+done
+
+verifyProvided "$Q_STRING" "$q"
+verifyQ $q
+
+verifyProvided "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+verifyDirectory "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+
+verifyProvided "$CONFIGURATION_IDENTIFIER_STRING" "$configurationIdentifier"
+verifyConfigurationIdentifier "$configurationIdentifier"
+
+verifyProvided "target bitrates ($TARGET_BITRATES_OPTION)" "$targetBitrates"
+verifyProvided "$INPUT_NAME_STRING" "$inputName"
+
+outputPathBegin="${outputDirectory}${inputName}_${configurationIdentifier}_q${q}"
+logPath="$outputPathBegin.log"
+metaLogPath="${outputPathBegin}_meta.log"
+
+TRUE=true
+
+# Outputs "$TRUE" if the given file exist.  Outputs nothing if the given file does not exist.  The first argument is the path to the supposed file.
+function doesFileExist {
+  ls $1 &> /dev/null
+  if [[ 0 == "$?" ]] ; then
+    echo "$TRUE"
+  fi
+}
+
+# Validate the mode (normal or resume) based on whether or not the meta-log file already exists
+if [[ "$TRUE" == "$(doesFileExist "$metaLogPath")" ]] ; then
+  if [[ "$NORMAL_MODE" == "$mode" ]] ; then
+    echo "$metaLogPath already exists.  Consider using resume-mode." >&2
+    outputUsageAndExit
+  else  # Resume-mode
+    cat "$metaLogPath"  # Output the pre-existing meta-log so we can resume where we left off
+  fi
+else  # Meta-log file does not exist
+  if [[ "$RESUME_MODE" == "$mode" ]] ; then
+    echo "$metaLogPath does not exist and resume-mode is enabled." >&2
+    outputUsageAndExit
+  fi
+fi
+
+# Outputs the number of elements in the given bitrate vector
+function bitrateVectorSize {
+  echo "$1" | sed -e 's/[^ ]//g' | wc -c | sed -e 's/^ *//'
+}
+
+# Initialize targetBitrateVectorSize
+targetBitrateVectorSize="$(bitrateVectorSize "$targetBitrates")"
+
+# Outputs the product of the two input values
+function multiply {
+  echo | awk "{print $1 * $2}"
+}
+
+# Extracts the bitrate at the given index from the given bitrate vector.  The first argument is the given index and the second argument in the given bitrate vector.
+function extractBitrateFromVector {
+  local localIndex=$(expr "$1" "+" "1")
+  echo "$2" | awk "{ print \$$localIndex }"
+}
+
+# Outputs a bitrate vector by multiplying the $targetBitrates vector by a given scalar.  The first argument is the given scalar.
+function populateBitrates {
+  local lI=0
+  local lResult=""
+  while true ; do
+    local lTargetBitrate=$(extractBitrateFromVector "$lI" "$targetBitrates")
+    if [[ "" == "$lTargetBitrate" ]] ; then
+      break;
+    fi
+    local lNew=$(multiply "$lTargetBitrate" "$1")
+    lResult="$lResult $lNew"
+    ((++lI))
+  done
+  echo "$lResult" | sed -e 's/^ //'
+}
+
+# Initialize the ranges
+outerRangeMins=$(populateBitrates "0.980")
+innerRangeMins=$(populateBitrates "0.985")
+innerRangeMaxs=$(populateBitrates "1.015")
+outerRangeMaxs=$(populateBitrates "1.020")
+
+# Outputs the given string to the meta-log (both the file and stdout) with no newline character.  The first argument is the string to output.
+function outputToMetaLogNoNewline {
+  toPrint=`echo $1 | sed -e 's/%/%%/g'`
+  printf -- "$toPrint"
+  printf -- "$toPrint" >> $metaLogPath
+}
+
+# Outputs the given string to the meta-log (both the file and stdout) with a newline character.  The first argument is the string to output.
+function outputToMetaLogWithNewline {
+  echo "$1"
+  echo "$1" >> $metaLogPath
+}
+
+# Extracts the Lambda-modifier at the given index from $lambdaModifiers.  The first argument is the given index.
+function extractLambdaModifier {
+  printf -- "$lambdaModifiers" | sed -e 's/^-//' | sed -e 's/ -/\
+/g' | grep "${LAMBDA_MODIFIER_PREFIX}$1 " | sed -e 's/^[^ ]* //'
+}
+
+# Outputs the given Lambda-modifier with a fixed number of decimal points.  The first argument is the given Lambda-modifier.
+function formatLambdaModifier {
+  printf "%.7f" "$1"
+}
+
+# Outputs $lambdaModifiers to the meta-log with proper formatting
+function outputLambdaModifiersToMetaLog {
+  local lI=0
+  local lLambdaModifier=$(extractLambdaModifier "$lI")
+  local lLambdaModifier=$(formatLambdaModifier "$lLambdaModifier")
+  local lOutput="-${LAMBDA_MODIFIER_PREFIX}$lI $lLambdaModifier"
+  while true ; do
+    ((++lI))
+    local lLambdaModifier=$(extractLambdaModifier "$lI")
+    if [[ "" == "$lLambdaModifier" ]] ; then
+      break
+    fi
+    local lLambdaModifier=$(formatLambdaModifier "$lLambdaModifier")
+    local lOutput="$lOutput -${LAMBDA_MODIFIER_PREFIX}$lI $lLambdaModifier"
+  done
+  outputToMetaLogNoNewline "$lOutput;"
+}
+
+# Initialize lambdaModifiers and output it to the meta-log
+if [[ "$RESUME_MODE" == "$mode" ]] ; then
+  if [[ "" == "$initialLambdaModifiers" ]] ; then  # If no initial lambda-modifiers provided, use default value
+    lambdaModifiers=$(tail -n 1 < "$metaLogPath" | sed -e 's/;$//')
+  else  # Initial lambda-modifiers provided
+    echo "You cannot use $RESUME_MODE and specify the initial lambda-modifiers.  In resume-mode, the lambda-modifiers will be retreived from the last line of the meta-log." >&2
+    outputUsageAndExit
+  fi
+else
+  if [[ "" == "$initialLambdaModifiers" ]] ; then  # If no initial lambda-modifiers provided, use default value
+    lambdaModifiers="-${LAMBDA_MODIFIER_PREFIX}0 1"
+    for (( i=1; i<"$targetBitrateVectorSize"; ++i )); do
+      lambdaModifiers="$lambdaModifiers -${LAMBDA_MODIFIER_PREFIX}${i} 1"
+    done
+  else  # Initial lambda-modifiers provided
+    lambdaModifiers="$initialLambdaModifiers"
+  fi
+  outputLambdaModifiersToMetaLog
+fi
+
+# Calculates the difference percentage between the given target bitrate and the given bitrate, appropriately formats this difference percentage, and then outputs it.  The first argument is the given target bitrate and the second argument is the given bitrate.
+function calculateAndFormatDifferencePercentage {
+  # Calculate the result and format it with the right number of decimal places
+  local result=$(echo | awk "{print 100*($2-$1)/$1}")
+  local result=$(printf "%.3f" "$result")
+  
+  # Separate the sign from the result
+  local sign=$(echo "$result" | sed -e 's/[^-]*$//')
+  if [[ "$sign" != "-" ]] ; then
+    local sign="+"
+  fi
+  local result=$(echo "$result" | sed -e 's/^-//')
+  
+  # Pad leading zereos to make two digits before the decimal point
+  if [[ 2 == $(echo "$result" | sed -e 's/\..*$//' | wc -c | sed -e 's/^ *//') ]] ; then
+    local result="0$result"
+  fi
+  
+  # Output the result including the sign and the percent sign
+  echo "${sign}${result}%"
+}
+
+# Outputs $TRUE i.f.f. the first argument is less than the second argument
+function lessOrEqual {
+  echo | awk "{ if($1 < $2) print \"$TRUE\" }"
+}
+
+# Outputs $TRUE i.f.f. the second argument is greater than the first argument and less than the third argument ($1 < $2 < $3)
+function isInRange {
+  if [[ "$TRUE" == $(lessOrEqual "$1" "$2") ]] ; then
+    if [[ "$TRUE" == $(lessOrEqual "$2" "$3") ]] ; then
+      echo "$TRUE"
+    fi
+  fi
+}
+
+# From the given bitrate vector, outputs the "bad" bitrates by filtering out the "good" bitrates.  The first argument is the index of the last good bitrate and the second argument is the given bitrate vector.  If the first argument is -1, then the given bitrate vector is outputted in its entirety.
+function filterOutGoodBitrates {
+  local result="$2"
+  for (( i=0; i<="$1"; ++i )); do
+    result=$(echo "$result" | sed -e 's/^[^ ]* //')
+  done
+  echo "$result"
+}
+
+# Outputs a given line from the given variable.  The first argument is the line number to output and the second argument is the given variable to extract the line from.
+function outputLine {
+  echo "$2" | head -n "$(expr "$1" + 1)" | tail -n 1
+}
+
+# Initialize iterationCount
+if [[ "$RESUME_MODE" == "$mode" ]] ; then
+  iterationCount=$(wc -l < "$metaLogPath" | sed -e 's/^ *//')
+else
+  iterationCount=0
+fi
+
+ITERATION_COUNT_LIMIT=50  # The number of attempts to make before giving up
+
+while true ; do  # The main loop
+  
+  # Run the encoder
+  sh ${SUB_TOOLS_DIRECTORY}encodeCommand.sh $inputName $encodeCommandArgs $CONFIGURATION_IDENTIFIER_OPTION $configurationIdentifier $Q_OPTION $q $OUTPUT_DIRECTORY_OPTION $outputDirectory -ea "$extraArguments $lambdaModifiers" | sh > $logPath
+  if [[ $? != 0 ]] ; then
+    printf "Unexpected exit status from encodeCommand.sh\n" >&2
+    exit 1
+  fi
+  
+  # Extract and output the bitrates
+  bitrates=`${SUB_TOOLS_DIRECTORY}extractBitrates.exe < $logPath`
+  outputToMetaLogNoNewline "$bitrates;"
+  
+  # Make sure that the index set of the extracted bitrates matches the index set of the target bitrates
+  if [[ "$targetBitrateVectorSize" != "$(bitrateVectorSize "$bitrates")" ]] ; then
+    echo "Index set from the extracted bitrates does not match the index set from the target bitrates" >&2
+    exit 1
+  fi
+  
+  # Calculate the bitrate difference percentages and output them to the meta-log
+  percentages="$(calculateAndFormatDifferencePercentage "$(extractBitrateFromVector "0" "$targetBitrates")" "$(extractBitrateFromVector "0" "$bitrates")")"
+  for (( i=1; i<"$targetBitrateVectorSize"; ++i )); do
+    percentages="$percentages $(calculateAndFormatDifferencePercentage "$(extractBitrateFromVector "$i" "$targetBitrates")" "$(extractBitrateFromVector "$i" "$bitrates")")"
+  done
+  outputToMetaLogNoNewline "$percentages;"
+  
+  # Initialize and output areBitratesSatismodifiery
+  areBitratesSatisfactory=yes
+  for (( i=0; ; ++i )) ; do
+    outerRangeMin=$(extractBitrateFromVector "$i" "$outerRangeMins")
+    bitrate=$(extractBitrateFromVector "$i" "$bitrates")
+    outerRangeMax=$(extractBitrateFromVector "$i" "$outerRangeMaxs")
+    if [[ "" == "$bitrate" ]] ; then
+      break
+    fi
+    if [[ $(isInRange "$outerRangeMin" "$bitrate" "$outerRangeMax") != "$TRUE" ]] ; then
+      areBitratesSatisfactory=no
+      break
+    fi
+  done
+  outputToMetaLogWithNewline "$areBitratesSatisfactory"
+  
+  # Exit if we are finished or if we have iterated too many times
+  if [[ yes == $areBitratesSatisfactory ]] ; then
+    mv "$logPath" "${outputPathBegin}_final.log"
+    exit 0
+  else
+    # Rename the deprecated log
+    countString="$iterationCount"
+    if [[ 1 == `printf -- "$countString" | wc -c | sed -e 's/^ *//'` ]] ; then
+      countString="0$countString"
+    fi
+    mv "$logPath" "${outputPathBegin}_dep${countString}.log"
+    
+    ((++iterationCount))
+    if [[ "$ITERATION_COUNT_LIMIT" == "$iterationCount" ]] ; then
+      outputToMetaLogWithNewline "Could not reach target bitrates"
+      exit 1
+    fi
+  fi
+  
+  filteredMetaLog=$(sed -e 's/;[^;]*$//' < $metaLogPath | sed -e 's/;[^;]*$//')
+  bitratesFromMetaLog=$(printf -- "$filteredMetaLog" | sed -e 's/^[^;]*;//')
+  
+  # Initialize goodIndex
+  goodIndex=-1
+  for (( i=0; i<"$targetBitrateVectorSize"; ++i )); do
+    innerRangeMin=$(extractBitrateFromVector "$i" "$innerRangeMins")
+    bitrate=$(extractBitrateFromVector "$i" "$bitrates")
+    innerRangeMax=$(extractBitrateFromVector "$i" "$innerRangeMaxs")
+    if [[ "$TRUE" == $(isInRange "$innerRangeMin" "$bitrate" "$innerRangeMax") ]] ; then
+      goodIndex="$i"
+    else
+      break
+    fi
+  done
+  
+  badBitrates=$(filterOutGoodBitrates "$goodIndex" "$bitratesFromMetaLog")
+  lambdaModifiersFromMetaLog=`printf -- "$filteredMetaLog" | sed -e 's/;[^;]*$//'`
+  badLambdaModifiers=`printf -- "$lambdaModifiersFromMetaLog" | sed -e "s/^.*-${LAMBDA_MODIFIER_PREFIX}$goodIndex [^ ]* //"`
+  lineCount=`printf -- "$badBitrates\n" | wc -l | sed -e 's/^ *//'`
+  
+  # Initialize guessLambdaModifiersIn
+  guessLambdaModifiersIn="$(outputLine 0 "$badLambdaModifiers");$(outputLine 0 "$badBitrates")"
+  for (( i=1; i<"$lineCount"; ++i )); do
+    guessLambdaModifiersIn="$(printf -- "$guessLambdaModifiersIn\n$(outputLine "$i" "$badLambdaModifiers");$(outputLine "$i" "$badBitrates")")"
+  done
+  
+  # Run guessLambdaModifiers
+  guessedLambdaModifiers=$(printf -- "$guessLambdaModifiersIn" | ${SUB_TOOLS_DIRECTORY}guessLambdaModifiers.exe "-.5" "$(filterOutGoodBitrates "$goodIndex" "$targetBitrates")")
+  if [[ $? != 0 ]] ; then
+    printf "Unexpected exit status from guessLambdaModifiers.exe\n" >&2
+    exit 1
+  fi
+  
+  # Initialize lambdaModifiers and output them to the meta-log
+  lastLambdaModifiersFromMetaLog=`printf -- "$filteredMetaLog" | tail -n 1 | sed -e "s/;[^;]*$//"`
+  goodLambdaModifiersFromMetaLog=`printf -- "$lastLambdaModifiersFromMetaLog" | tail -n 1 | sed -e "s/-${LAMBDA_MODIFIER_PREFIX}$(expr "$goodIndex" + 1).*$//"`
+  lambdaModifiers="${goodLambdaModifiersFromMetaLog}${guessedLambdaModifiers}"
+  outputLambdaModifiersToMetaLog
+  
+done
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/annexBbytecount.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/annexBbytecount.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/annexBbytecount.cpp	(revision 341)
@@ -0,0 +1,233 @@
+/* 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-2012, 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 <stdint.h>
+#include <cassert>
+#include <fstream>
+#include <sstream>
+#include <iostream>
+#include <string.h>
+
+#include "TLibDecoder/AnnexBread.h"
+
+using namespace std;
+
+static struct {
+  AnnexBStats expected;
+  unsigned data_len;
+  const char data[10];
+} tests[] = {
+  /* trivial cases: startcode, no payload */
+  {{0, 0, 3, 0, 0}, 3, {0,0,1}},
+  {{0, 1, 3, 0, 0}, 4, {0,0,0,1}},
+  {{2, 1, 3, 0, 0}, 6, {0,0,0,0,0,1}},
+  /* trivial cases: startcode, payload */
+  {{0, 0, 3, 1, 0}, 4, {0,0,1,2}},
+  {{0, 0, 3, 2, 0}, 5, {0,0,1,2,0}},
+  {{0, 0, 3, 3, 0}, 6, {0,0,1,2,0,0}},
+  {{0, 0, 3, 1, 3}, 7, {0,0,1,2,0,0,0}},
+  /* trivial cases: two nal units: extract the first */
+  {{0, 0, 3, 1, 0}, 8, {0,0,1,2,0,0,1,3}},
+  {{0, 0, 3, 1, 0}, 9, {0,0,1,2,0,0,0,1,3}},
+  {{0, 0, 3, 1, 1}, 10, {0,0,1,2,0,0,0,0,1,3}},
+  /* edge cases with EOF near start*/
+  {{0, 0, 0, 0, 0}, 0, {}},
+  {{1, 0, 0, 0, 0}, 1, {0}},
+  {{2, 0, 0, 0, 0}, 2, {0,0}},
+  {{3, 0, 0, 0, 0}, 3, {0,0,0}},
+};
+
+void selftest()
+{
+  /* test */
+  for (unsigned i = 0; i < sizeof(tests)/sizeof(*tests); i++)
+  {
+    istringstream in(string(tests[i].data, tests[i].data_len));
+    InputByteStream bs(in);
+
+    AnnexBStats actual = AnnexBStats();
+    vector<uint8_t> nalUnit;
+
+    byteStreamNALUnit(bs, nalUnit, actual);
+
+    cout << "Self-Test: " << i << ", {";
+    for (unsigned j = 0; j < tests[i].data_len; j++)
+    {
+      cout << hex << (unsigned int)tests[i].data[j] << dec;
+      if (j < tests[i].data_len-1)
+        cout << ",";
+    }
+    cout << "} ";
+
+    bool ok = true;
+#define VERIFY(a,b,m) \
+  if (a.m != b.m) { \
+    ok = false; \
+    cout << endl << "  MISSMATCH " #m << ", E(" << b.m << ") != " << a.m; \
+  }
+    VERIFY(actual, tests[i].expected, m_numLeadingZero8BitsBytes);
+    VERIFY(actual, tests[i].expected, m_numZeroByteBytes);
+    VERIFY(actual, tests[i].expected, m_numStartCodePrefixBytes);
+    VERIFY(actual, tests[i].expected, m_numBytesInNALUnit);
+    VERIFY(actual, tests[i].expected, m_numTrailingZero8BitsBytes);
+#undef VERIFY
+    if (ok)
+      cout << "OK";
+    cout << endl;
+  }
+}
+
+int main(int argc, char*argv[])
+{
+  selftest();
+
+  if (argc != 2)
+    return 0;
+
+  ifstream in(argv[1], ifstream::in | ifstream::binary);
+  InputByteStream bs(in);
+
+  AnnexBStats annexBStatsTotal = AnnexBStats();
+  AnnexBStats annexBStatsTotal_VCL = AnnexBStats();
+  AnnexBStats annexBStatsTotal_Filler = AnnexBStats();
+  AnnexBStats annexBStatsTotal_Other = AnnexBStats();
+  unsigned numNALUnits = 0;
+
+  cout << "NALUnits:" << endl;
+  while (!!in)
+  {
+    AnnexBStats annexBStatsSingle = AnnexBStats();
+    vector<uint8_t> nalUnit;
+
+    byteStreamNALUnit(bs, nalUnit, annexBStatsSingle);
+
+    int nal_unit_type = -1;
+    if (annexBStatsSingle.m_numBytesInNALUnit)
+    {
+      nal_unit_type = nalUnit[0] & 0x1f;
+    }
+
+    cout << " - NALU: #" << numNALUnits << " nal_unit_type:" << nal_unit_type << endl
+         << "   num_bytes(leading_zero_8bits): " << annexBStatsSingle.m_numLeadingZero8BitsBytes << endl
+         << "   num_bytes(zero_byte): " << annexBStatsSingle.m_numZeroByteBytes << endl
+         << "   num_bytes(start_code_prefix_one_3bytes): " << annexBStatsSingle.m_numStartCodePrefixBytes << endl
+         << "   NumBytesInNALunit: " << annexBStatsSingle.m_numBytesInNALUnit << endl
+         << "   num_bytes(trailing_zero_8bits): " << annexBStatsSingle.m_numTrailingZero8BitsBytes << endl
+         ;
+
+    annexBStatsTotal += annexBStatsSingle;
+    numNALUnits++;
+
+    if (!annexBStatsSingle.m_numBytesInNALUnit)
+      continue;
+
+    /* identify the NAL unit type and add stats to the correct
+     * accumulators */
+    switch (nalUnit[0] & 0x1f) {
+    case 1: case 2: case 3: case 4: case 5:
+      annexBStatsTotal_VCL += annexBStatsSingle;
+      break;
+    case 12:
+      annexBStatsTotal_Filler += annexBStatsSingle;
+      break;
+    default:
+      annexBStatsTotal_Other += annexBStatsSingle;
+    };
+  }
+
+  cout << "Summary: " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(VCL): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_VCL.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_VCL.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_VCL.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_VCL.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_VCL.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(Filler): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_Filler.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_Filler.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_Filler.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_Filler.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_Filler.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(Other): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_Other.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_Other.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_Other.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_Other.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_Other.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  /* The first such type of bitstream, called Type I bitstream, is a
+   * NAL unit stream containing only the VCL NAL units and filler data
+   * NAL units for all access units in the bitstream.
+   */
+  unsigned totalBytes_T1HRD = annexBStatsTotal_VCL.m_numBytesInNALUnit + annexBStatsTotal_Filler.m_numBytesInNALUnit;
+
+  /*The second type of bitstream, called a Type II bitstream,
+   * contains, in addition to the VCL NAL units and filler data NAL
+   * units for all access units in the bitstream, at least one of
+   * the following:
+   *  (a) additional non-VCL NAL units other than filler data NAL
+   *      units.
+   */
+  unsigned totalBytes_T2aHRD = annexBStatsTotal.m_numBytesInNALUnit;
+
+  /*  (b) all leading_zero_8bits, zero_byte,
+   *      start_code_prefix_one_3bytes, and trailing_zero_8bits syntax
+   *      elements that form a byte stream from the NAL unit stream (as
+   *      specified in Annex B)
+   */
+  unsigned totalBytes_T2abHRD = 0;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numLeadingZero8BitsBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numZeroByteBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numStartCodePrefixBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numBytesInNALUnit;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numTrailingZero8BitsBytes;
+
+  cout << "Totals (bytes):" << endl;
+  cout << "  Type1 HRD: " << totalBytes_T1HRD << endl;
+  cout << "  Type2 HRD: " << totalBytes_T2aHRD << endl;
+  cout << "  Type2b HRD: " << totalBytes_T2abHRD << endl;
+
+  return 0;
+}
Index: branches/HTM-6.2-dev1-Samsung/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 341)
@@ -0,0 +1,117 @@
+/* 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-2012, 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 <cstdlib>
+
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TAppCommon/program_options_lite.h"
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+int main(int argc, const char** argv)
+{
+  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;
+
+  po::Options opts;
+  opts.addOptions()
+  ("help", do_help, false, "this help text")
+  ("InputFile,i", filename_in, string(""), "input file to convert")
+  ("OutputFile,o", filename_out, string(""), "output file")
+  ("SourceWidth", width, 0u, "source picture width")
+  ("SourceHeight", height, 0u, "source picture height")
+  ("InputBitDepth", bitdepth_in, 8u, "bit-depth of input file")
+  ("OutputBitDepth", bitdepth_out, 8u, "bit-depth of output file")
+  ("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")
+  ;
+
+  po::setDefaults(opts);
+  po::scanArgv(opts, argc, argv);
+
+  if (argc == 1 || do_help)
+  {
+    /* argc == 1: no options have been specified */
+    po::doHelp(cout, opts);
+    return EXIT_FAILURE;
+  }
+
+  TVideoIOYuv input;
+  TVideoIOYuv output;
+
+  input.open((char*)filename_in.c_str(), false, bitdepth_in, bitdepth_out);
+  output.open((char*)filename_out.c_str(), true, bitdepth_out, bitdepth_out);
+
+  input.skipFrames(num_frames_skip, width, height);
+
+  TComPicYuv frame;
+  frame.create( width, height, 1, 1, 0 );
+
+  int pad[2] = {0, 0};
+
+  unsigned int num_frames_processed = 0;
+  while (!input.isEof()) 
+  {
+    if (! input.read(&frame, pad))
+    {
+      break;
+    }
+#if 0
+    Pel* img = frame.getLumaAddr();
+    for (int y = 0; y < height; y++) 
+    {
+      for (int x = 0; x < height; x++)
+        img[x] = 0;
+      img += frame.getStride();
+    }
+    img = frame.getLumaAddr();
+    img[0] = 1;
+#endif
+
+    output.write(&frame);
+    num_frames_processed++;
+    if (num_frames_processed == num_frames)
+      break;
+  }
+
+  input.close();
+  output.close();
+
+  return EXIT_SUCCESS;
+}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/TAppComCamPara.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 341)
@@ -0,0 +1,1511 @@
+/* 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-2011, 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 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 files
+#include "TAppComCamPara.h"
+
+
+#include <stdlib.h>
+#include <math.h>
+#include <errno.h>
+#include <assert.h>
+#include <vector>
+#include <iostream>
+#include <fstream>
+#include <algorithm>
+#include <functional>
+#include <string>
+
+
+
+Void
+TAppComCamPara::xCreateLUTs( UInt uiNumberSourceViews, UInt uiNumberTargetViews, Double****& radLUT, Int****& raiLUT, Double***& radShiftParams, Int64***& raiShiftParams )
+{
+  AOF( m_uiBitDepthForLUT == 8 );
+  AOF( radShiftParams == NULL && raiShiftParams == NULL && radLUT == NULL && raiLUT == NULL );
+
+  uiNumberSourceViews = Max( 1, uiNumberSourceViews );
+  uiNumberTargetViews = Max( 1, uiNumberTargetViews );
+
+  radShiftParams = new Double** [ uiNumberSourceViews ];
+  raiShiftParams = new Int64 ** [ uiNumberSourceViews ];
+  radLUT         = new Double***[ uiNumberSourceViews ];
+  raiLUT         = new Int   ***[ uiNumberSourceViews ];
+
+  for( UInt uiSourceView = 0; uiSourceView < uiNumberSourceViews; uiSourceView++ )
+  {
+    radShiftParams[ uiSourceView ] = new Double* [ uiNumberTargetViews ];
+    raiShiftParams[ uiSourceView ] = new Int64 * [ uiNumberTargetViews ];
+    radLUT        [ uiSourceView ] = new Double**[ uiNumberTargetViews ];
+    raiLUT        [ uiSourceView ] = new Int   **[ uiNumberTargetViews ];
+
+    for( UInt uiTargetView = 0; uiTargetView < uiNumberTargetViews; uiTargetView++ )
+    {
+      radShiftParams[ uiSourceView ][ uiTargetView ]      = new Double [ 2 ];
+      raiShiftParams[ uiSourceView ][ uiTargetView ]      = new Int64  [ 2 ];
+
+      radLUT        [ uiSourceView ][ uiTargetView ]      = new Double*[ 2 ];
+      radLUT        [ uiSourceView ][ uiTargetView ][ 0 ] = new Double [ 257 ];
+      radLUT        [ uiSourceView ][ uiTargetView ][ 1 ] = new Double [ 257 ];
+
+      raiLUT        [ uiSourceView ][ uiTargetView ]      = new Int*   [ 2 ];
+      raiLUT        [ uiSourceView ][ uiTargetView ][ 0 ] = new Int    [ 257 ];
+      raiLUT        [ uiSourceView ][ uiTargetView ][ 1 ] = new Int    [ 257 ];
+    }
+  }
+}
+
+Void
+TAppComCamPara::xCreate2dArray( UInt uiNum1Ids, UInt uiNum2Ids, Int**& raaiArray )
+{
+  AOT( raaiArray || uiNum1Ids == 0 || uiNum2Ids == 0 );
+  raaiArray = new Int* [ uiNum1Ids ];
+  for( UInt uiId1 = 0; uiId1 < uiNum1Ids; uiId1++ )
+  {
+    raaiArray[ uiId1 ] = new Int [ uiNum2Ids ];
+  }
+}
+
+
+Void
+TAppComCamPara::xInit2dArray( UInt uiNum1Ids, UInt uiNum2Ids, Int**& raaiArray, Int iValue )
+{
+  for( UInt uiId1 = 0; uiId1 < uiNum1Ids; uiId1++ )
+  {
+    for( UInt uiId2 = 0; uiId2 < uiNum2Ids; uiId2++ )
+    {
+      raaiArray[ uiId1 ][ uiId2 ] = iValue;
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::convertNumberString( Char* pchViewNumberString, std::vector<Int>& raiViewNumbers, Double dViewNumPrec )
+{
+  Bool bStringIsRange = false;
+  Int  iIdx           = 0;
+  std::vector<Double> adViewNumbers;
+
+  while( pchViewNumberString != 0 && pchViewNumberString[ iIdx ] != 0 )
+  {
+    if( pchViewNumberString[ iIdx ] == ':' )
+    {
+      bStringIsRange              = true;
+      pchViewNumberString[ iIdx ] = ' ';
+    }
+    iIdx++;
+  }
+
+  Char* pcNextStart = pchViewNumberString;
+  Char* pcEnd       = pcNextStart + iIdx;
+  Char* pcOldStart  = 0;
+
+  while( pcNextStart < pcEnd )
+  {
+    errno = 0;
+    adViewNumbers.push_back( ( strtod( pcNextStart, &pcNextStart ) ) );
+
+    if( errno == ERANGE || pcNextStart == pcOldStart )
+    {
+      std::cerr << "Error Parsing View Number String: `" << pchViewNumberString << "'" << std::endl;
+      AOT(true);
+      exit( EXIT_FAILURE );
+    };
+
+    while( pcNextStart < pcEnd && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;
+
+    pcOldStart = pcNextStart;
+  }
+
+  if( bStringIsRange )
+  {
+    if( adViewNumbers.size() != 3 )
+    {
+      std::cerr << "Error Parsing SynthViewNumbers: `" << pchViewNumberString << "'" << std::endl;
+      AOT(true);
+      exit( EXIT_FAILURE );
+    }
+
+    Double dRangeBegin = adViewNumbers[0];
+    Double dRangeStep  = adViewNumbers[1];
+    Double dRangeEnd   = adViewNumbers[2];
+
+    if( ( ( dRangeEnd - dRangeBegin > 0 ) != ( dRangeStep > 0 ) ) || dRangeStep == 0 )
+    {
+      std::cerr << "Error Parsing SynthViewNumbers: `" << pchViewNumberString << "'" << std::endl;
+      AOT(true);
+      exit( EXIT_FAILURE );
+    }
+
+    raiViewNumbers.clear();
+
+    Double dFac = ( dRangeBegin > dRangeEnd ? -1 : 1 );
+
+    for( Double dViewNumber = dRangeBegin; ( dViewNumber - dRangeEnd ) * dFac <= 0; dViewNumber += dRangeStep )
+    {
+      raiViewNumbers.push_back( (Int)( dViewNumber * dViewNumPrec ) );
+    }
+  }
+  else
+  {
+    for( UInt uiViewNum = 0; uiViewNum < adViewNumbers.size(); uiViewNum++ )
+    {
+      raiViewNumbers.push_back( (Int)( adViewNumbers[ uiViewNum ] * dViewNumPrec ) );
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::xReadCameraParameterFile( Char* pchCfgFileName )
+{
+  std::ifstream cCfgStream( pchCfgFileName, std::ifstream::in );
+  if( !cCfgStream )
+  {
+    std::cerr << "Failed to open camera parameter file: `" << pchCfgFileName << "'" << std::endl;
+    exit( EXIT_FAILURE );
+  }
+
+  Int iLineNumber = 0;
+  do
+  {
+    std::string cLine;
+    getline( cCfgStream, cLine );
+    iLineNumber++;
+
+    size_t iStart = cLine.find_first_not_of( " \t\n\r" );
+
+    if( iStart == std::string::npos )
+    {
+      continue;
+    }
+
+    if( cLine[iStart] == '#' )
+    {
+      continue;
+    }
+
+    Char* pcNextStart = (Char*) cLine.data();
+    Char* pcEnd = pcNextStart + cLine.length();
+
+    std::vector<Double> caNewLine;
+    caNewLine.clear();
+
+    Char* pcOldStart = 0;
+    while( pcNextStart < pcEnd )
+    {
+      errno = 0;
+      caNewLine.push_back( strtod( pcNextStart, &pcNextStart ) ) ;
+
+      if( errno == ERANGE || ( pcNextStart == pcOldStart ) )
+      {
+        std::cerr << "Failed reading config file: `" << pchCfgFileName << "' Error parsing double values in Line: " << iLineNumber << ' ' << std::endl;
+        assert( 0 );
+        exit( EXIT_FAILURE );
+      };
+      pcOldStart = pcNextStart;
+
+      while( ( pcNextStart < pcEnd ) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;
+    }
+
+    if ( ( caNewLine.size() != 2 ) && ( caNewLine.size() != 7 ) && ( caNewLine.size() != 6 ) && ( caNewLine.size() != 8 ) )
+    {
+      std::cerr << "Failed reading config file: `" << pchCfgFileName << "'" << std::endl;
+      std::cerr << "Invalid number of entries" << std::endl;
+      AOF(false);
+      exit( EXIT_FAILURE );
+    }
+    m_aadCameraParameters.push_back( caNewLine );
+  }
+  while( cCfgStream );
+}
+
+Void
+TAppComCamPara::xGetCodedCameraData( UInt uiSourceView, UInt uiTargetView, Bool bByIdx,  UInt uiFrame, Int& riScale, Int& riOffset, Int& riPrecision )
+{
+  if( bByIdx )
+  {
+    uiSourceView = m_aiBaseViews[ uiSourceView ];
+    uiTargetView = m_aiBaseViews[ uiTargetView ];
+  }
+
+  Int iFoundLine = -1;
+  for( UInt uiCurViewLine = 0; uiCurViewLine < m_aadCameraParameters.size(); uiCurViewLine++ )
+  {
+    if ( m_aadCameraParameters[uiCurViewLine].size() == 2 )
+      continue;
+
+    if(      ( (Int)( m_aadCameraParameters[ uiCurViewLine ][ 3 ] * m_dViewNumPrec ) == uiSourceView )
+          && ( (Int)( m_aadCameraParameters[ uiCurViewLine ][ 2 ] * m_dViewNumPrec ) == uiTargetView )
+      )
+    {
+      if( ( (UInt)m_aadCameraParameters[ uiCurViewLine ][ 0 ] <= uiFrame ) && ( (UInt)m_aadCameraParameters[ uiCurViewLine ][ 1 ] >= uiFrame ) )
+      {
+        if( iFoundLine != -1 )
+        {
+          std::cerr << "Error CameraParameters for SourceView " << (Double) uiSourceView / m_dViewNumPrec << " and Target View " << (Double) uiTargetView / m_dViewNumPrec << " and Frame " << uiFrame << " given multiple times."  << std::endl;
+          AOT(true);
+          exit( EXIT_FAILURE );
+        }
+        else
+        {
+          iFoundLine = uiCurViewLine;
+        }
+      }
+    }
+  }
+
+  if ( iFoundLine == -1 )
+  {
+    std::cerr << "Error CameraParameters for SourceView " << (Double) uiSourceView / m_dViewNumPrec << " and Target View " << (Double) uiTargetView / m_dViewNumPrec << " and Frame " << uiFrame << " not found."  << std::endl;
+    AOT(true);
+    exit( EXIT_FAILURE );
+  }
+
+  riScale     = (Int)( m_aadCameraParameters[ iFoundLine ][ 4 ] );
+  riOffset    = (Int)( m_aadCameraParameters[ iFoundLine ][ 5 ] );
+  riPrecision = (Int)( m_aadCameraParameters[ iFoundLine ][ 6 ] );
+}
+
+Bool
+TAppComCamPara::xGetCameraDataRow( Int iView, UInt uiFrame, UInt& ruiFoundLine )
+{
+  ruiFoundLine = -1;
+  for( UInt uiCurViewLine = 0; uiCurViewLine < m_aadCameraParameters.size(); uiCurViewLine++ )
+  {
+    if( (Int)( m_aadCameraParameters[ uiCurViewLine ][ 0 ] * m_dViewNumPrec ) == iView )
+    {
+      if( ( (UInt)m_aadCameraParameters[ uiCurViewLine ][ 1 ] <= uiFrame ) && ( (UInt)m_aadCameraParameters[ uiCurViewLine ][ 2 ] >= uiFrame ) )
+      {
+        if( ruiFoundLine != -1 )
+        {
+          std::cerr << "Error CameraParameters for View " << (Double) iView / m_dViewNumPrec << " and Frame " << uiFrame << " given multiple times."  << std::endl;
+          exit( EXIT_FAILURE );
+        }
+        else
+        {
+          ruiFoundLine = uiCurViewLine;
+        }
+      }
+    }
+  }
+  return ( ruiFoundLine == -1 );
+}
+
+
+Void
+TAppComCamPara::xGetSortedViewList( const std::vector<Int>& raiViews, std::vector<Int>& raiSortedViews, std::vector<Int>& raiId2SortedId, std::vector<Int>& raiSortedId2Id )
+{
+  AOF( raiViews.size() > 0 );
+  Int iNumViews   = (Int)raiViews.size();
+  raiId2SortedId  = std::vector<Int>( raiViews.size(), -1 );
+  raiSortedId2Id.clear();
+  raiSortedViews.clear();
+  for( Int iSortId = 0; iSortId < iNumViews; iSortId++ )
+  {
+    Int  iLeftMostBaseId = -1;
+    for( Int iBaseId = 0; iLeftMostBaseId == -1 && iBaseId < iNumViews; iBaseId++ )
+    {
+      if( raiId2SortedId[ iBaseId ] == -1 )
+      {
+        UInt   uiFoundLine   = -1;
+        xGetCameraDataRow( raiViews[ iBaseId ], 0, uiFoundLine );
+        AOT(   uiFoundLine  == -1 ); // something wrong
+        Double dXPos         = m_aadCameraParameters[ uiFoundLine ][ 4 ];
+        Double dZNear        = m_aadCameraParameters[ uiFoundLine ][ 6 ];
+        Double dZFar         = m_aadCameraParameters[ uiFoundLine ][ 7 ];
+        Double dSign         = ( dZFar > 0 ? 1.0 : -1.0 );
+        Bool   bLeftMost     = true;
+        AOF( dZNear * dZFar  > 0.0 ); // otherwise, z parameters are not correct
+
+        for( Int iTestBaseId = 0; bLeftMost && iTestBaseId < iNumViews; iTestBaseId++ )
+        {
+          if( iTestBaseId != iBaseId && raiId2SortedId[ iTestBaseId ] == -1 )
+          {
+            UInt   uiFoundLineTest  = -1;
+            xGetCameraDataRow( raiViews[ iTestBaseId ], 0, uiFoundLineTest );
+            AOT(   uiFoundLineTest == -1 ); // something wrong
+            Double dXPosTest        = m_aadCameraParameters[ uiFoundLineTest ][ 4 ];
+            Double dZNearTest       = m_aadCameraParameters[ uiFoundLineTest ][ 6 ];
+            Double dZFarTest        = m_aadCameraParameters[ uiFoundLineTest ][ 7 ];
+            AOF( dZNearTest * dZFarTest > 0.0 ); // otherwise, z parameters are not correct
+            AOF( dZNearTest * dSign     > 0.0 ); // otherwise, z parameters are not consistent
+            Double dDeltaXPos       = dSign * ( dXPosTest - dXPos );
+            bLeftMost               = ( bLeftMost && dDeltaXPos > 0.0 );
+          }
+        }
+        if( bLeftMost )
+        {
+          iLeftMostBaseId = iBaseId;
+        }
+      }
+    }
+    AOT( iLeftMostBaseId == -1 ); // something wrong
+    raiId2SortedId[ iLeftMostBaseId ] = iSortId;
+    raiSortedId2Id.push_back( iLeftMostBaseId );
+    raiSortedViews.push_back( raiViews[ iLeftMostBaseId ] );
+  }
+
+  // sanity check
+  if( iNumViews > 2 )
+  {
+    Int   iDeltaView  = gSign( raiSortedViews[ 1 ] - raiSortedViews[ 0 ] );
+    Bool  bOutOfOrder = false;
+    for(  Int  iSIdx  = 2; iSIdx < iNumViews; iSIdx++ )
+    {
+      bOutOfOrder = ( bOutOfOrder || iDeltaView * gSign( raiSortedViews[ iSIdx ] - raiSortedViews[ iSIdx - 1 ] ) < 0 );
+    }
+    if( bOutOfOrder )
+    {
+      std::cerr << "ERROR: View numbering must be strictly increasing or decreasing from left to right" << std::endl;
+      exit(EXIT_FAILURE);
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::xGetViewOrderIndices( const std::vector<Int>& raiId2SortedId, std::vector<Int>& raiVOIdx )
+{
+  AOF( raiId2SortedId.size() );
+  raiVOIdx  =      raiId2SortedId;
+  Int iSize = (Int)raiId2SortedId.size();
+  Int iOffs =      raiId2SortedId[ 0 ];
+  for( Int iIdx = 0; iIdx < iSize; iIdx++ )
+  {
+    raiVOIdx[ iIdx ] -= iOffs;
+  }
+}
+
+
+Bool
+TAppComCamPara::xGetCamParsChangeFlag()
+{
+  Bool bChangeDetected = false;
+  for( Int iBaseViewId = 0; !bChangeDetected && iBaseViewId < m_iNumberOfBaseViews; iBaseViewId++ )
+  {
+    if ( m_bSetupFromCoded )
+    {
+      for( Int iTargetViewId = 0; !bChangeDetected && iTargetViewId < m_iNumberOfBaseViews; iTargetViewId++ )
+      {
+        Int iTargetView = m_aiBaseViews[iTargetViewId];
+        Int iSourceView = m_aiBaseViews[iBaseViewId  ];
+
+        Int iS1 ,iSX;
+        Int iO1 ,iOX;
+        Int iP1 ,iPX;
+
+        if ( iSourceView == iTargetView )
+          continue;
+
+        xGetCodedCameraData( iSourceView, iTargetView, false, 0, iS1, iO1, iP1 );
+        for( UInt uiFrameId = m_uiFirstFrameId + 1; !bChangeDetected && uiFrameId <= m_uiLastFrameId; uiFrameId++ )
+        {
+          xGetCodedCameraData( iSourceView, iTargetView, false, uiFrameId, iSX, iOX, iPX );
+
+          if( iS1 != iSX || iO1 != iOX || iP1 != iPX )
+          {
+            bChangeDetected = true;
+          }
+        }
+      }
+    }
+    else
+    {
+    Int     iBaseView  = m_aiBaseViews[ iBaseViewId ];
+    Double  dFL1, dFLX;
+    Double  dCP1, dCPX;
+    Double  dCS1, dCSX;
+    Double  dZN1, dZNX;
+    Double  dZF1, dZFX;
+    Bool    bInterpolated;
+    xGetGeometryData( iBaseView, m_uiFirstFrameId, dFL1, dCP1, dCS1, bInterpolated );  AOT( bInterpolated );
+    xGetZNearZFar   ( iBaseView, m_uiFirstFrameId, dZN1, dZF1 );
+
+    for( UInt uiFrameId = m_uiFirstFrameId + 1; !bChangeDetected && uiFrameId <= m_uiLastFrameId; uiFrameId++ )
+    {
+      xGetGeometryData( iBaseView, uiFrameId, dFLX, dCPX, dCSX, bInterpolated );  AOT( bInterpolated );
+      xGetZNearZFar   ( iBaseView, uiFrameId, dZNX, dZFX );
+
+      if( dFL1 != dFLX || dCP1 != dCPX || dCS1 != dCSX || dZN1 != dZNX || dZF1 != dZFX )
+      {
+        bChangeDetected = true;
+      }
+    }
+  }
+  }
+  return bChangeDetected;
+}
+
+Int
+TAppComCamPara::xGetViewId( std::vector<Int> aiViewList, Int iBaseView )
+{
+  Int  iViewId = -1;
+  for( Int iId = 0; iId < (Int)aiViewList.size(); iId++ )
+  {
+    if( aiViewList[ iId ] == iBaseView )
+    {
+      iViewId = iId;
+      break;
+    }
+  }
+  AOT(   iViewId == -1 );
+  return iViewId;
+}
+
+Int
+TAppComCamPara::xGetBaseViewId( Int iBaseView )
+{
+  return xGetViewId( m_aiBaseViews, iBaseView );
+}
+
+
+Bool
+TAppComCamPara::xGetLeftRightView( Int iView, std::vector<Int> aiSortedViews, Int& riLeftView, Int& riRightView, Int& riLeftSortedViewIdx, Int& riRightSortedViewIdx )
+{
+  Bool bFoundLRView  = false;
+  Int  iLeftView     = -1;
+  Int  iRightView    = -1;
+  Int  iLeftViewIdx  = -1;
+  Int  iRightViewIdx = -1;
+  Bool bDecencdingVN = ( aiSortedViews.size() >= 2 && aiSortedViews[ 0 ] > aiSortedViews[ 1 ] );
+  Int  iFactor       = ( bDecencdingVN ? -1 : 1 );
+
+  for( Int iIdx = -1; iIdx < (Int)aiSortedViews.size(); iIdx++ )
+  {
+    if( iIdx == -1 )
+    {
+      if( ( aiSortedViews[ iIdx + 1 ] - iView ) * iFactor > 0  )
+      {
+        bFoundLRView  = false;
+        iLeftView     = -1;
+        iRightView    = aiSortedViews[ iIdx + 1 ];
+        iLeftViewIdx  = -1;
+        iRightViewIdx = iIdx + 1;
+        break;
+      }
+    }
+    else if ( iIdx == (Int)aiSortedViews.size() - 1 )
+    {
+      if( ( aiSortedViews[ iIdx ] - iView ) * iFactor < 0  )
+      {
+        bFoundLRView  = false;
+        iLeftView     = aiSortedViews[ iIdx ];
+        iRightView    = -1;
+        iLeftViewIdx  = iIdx;
+        iRightViewIdx = -1;
+        break;
+      }
+    }
+    else
+    {
+      if( ( ( aiSortedViews[ iIdx ] - iView ) * iFactor <= 0 ) && ( ( aiSortedViews[ iIdx + 1 ] - iView ) * iFactor >= 0 ) )
+      {
+        bFoundLRView  = true;
+        iLeftView     = aiSortedViews[ iIdx ];
+        iRightView    = aiSortedViews[ iIdx + 1 ];
+        iLeftViewIdx  = iIdx;
+        iRightViewIdx = iIdx + 1;
+        break;
+      }
+    }
+  }
+
+  if ( ( iView == iLeftView ) || ( iView == iRightView ) )
+  {
+    iLeftViewIdx  = ( iView == iLeftView ) ? iLeftViewIdx : iRightViewIdx;
+    iRightViewIdx = iLeftViewIdx;
+    iLeftView     = iView;
+    iRightView    = iView;
+    bFoundLRView  = false;
+  }
+
+  riLeftView           = iLeftView;
+  riRightView          = iRightView;
+  riLeftSortedViewIdx  = iLeftViewIdx;
+  riRightSortedViewIdx = iRightViewIdx;
+
+  return bFoundLRView;
+}
+
+
+Void
+TAppComCamPara::xGetPrevAndNextBaseView( Int iSourceViewNum, Int iTargetViewNum, Int& riPrevBaseViewNum, Int& riNextBaseViewNum )
+{
+  Int iLeftView;
+  Int iRightView;
+  Int iDummy;
+  xGetLeftRightView( iTargetViewNum, m_aiSortedBaseViews, iLeftView, iRightView, iDummy, iDummy );
+
+  if( iLeftView == iRightView )
+  {
+    riPrevBaseViewNum = iLeftView;
+    riNextBaseViewNum = iLeftView;
+  }
+  else
+  {
+    Bool bDecencdingVN   = ( m_aiSortedBaseViews.size() >= 2 && m_aiSortedBaseViews[ 0 ] > m_aiSortedBaseViews[ 1 ] );
+    Bool bNextViewIsLeft = ( bDecencdingVN ? ( iSourceViewNum < iTargetViewNum ) : ( iSourceViewNum > iTargetViewNum ) );
+    if ( bNextViewIsLeft )
+    {
+      riPrevBaseViewNum = iRightView;
+      riNextBaseViewNum = iLeftView;
+    }
+    else
+    {
+      riPrevBaseViewNum = iLeftView;
+      riNextBaseViewNum = iRightView;
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::xGetZNearZFar( Int iView, UInt uiFrame, Double& rdZNear, Double& rdZFar )
+{
+  UInt uiFoundLine = -1;
+  if( !xGetCameraDataRow( iView, uiFrame, uiFoundLine ) || !( m_aadCameraParameters[ uiFoundLine ].size() < 8 ) )
+  {
+    rdZNear = m_aadCameraParameters[ uiFoundLine ][ 6 ];
+    rdZFar  = m_aadCameraParameters[ uiFoundLine ][ 7 ];
+  }
+  else
+  {
+    std::cerr << "No ZNear or no ZFar for View " << (Double)iView / m_dViewNumPrec << " and Frame " << uiFrame << " given in CameraParameterFile" << std::endl;
+    exit( EXIT_FAILURE );
+  }
+}
+
+
+Void
+TAppComCamPara::xGetGeometryData( Int iView, UInt uiFrame, Double& rdFocalLength, Double& rdPosition, Double& rdCameraShift, Bool& rbInterpolated )
+{
+  UInt uiFoundLine = -1;
+  if ( !xGetCameraDataRow( iView, uiFrame, uiFoundLine ) )
+  {
+    AOT( m_aadCameraParameters[ uiFoundLine ].size() < 6 );
+    rbInterpolated = false;
+    rdFocalLength =  m_aadCameraParameters[ uiFoundLine ][ 3 ];
+    rdPosition    =  m_aadCameraParameters[ uiFoundLine ][ 4 ];
+    rdCameraShift =  m_aadCameraParameters[ uiFoundLine ][ 5 ];
+  }
+  else
+  {
+    UInt uiLeftViewLine;
+    UInt uiRightViewLine;
+    Int  iLeftView;
+    Int  iRightView;
+    Int  iDummy;
+
+    if( !xGetLeftRightView( iView, m_aiViewsInCfgFile, iLeftView, iRightView, iDummy, iDummy ) ||
+         xGetCameraDataRow( iLeftView,  uiFrame, uiLeftViewLine  )                             ||
+         xGetCameraDataRow( iRightView, uiFrame, uiRightViewLine )
+      )
+    {
+      std::cerr << "No Left or no Right View next to View " << (Double)iView / m_dViewNumPrec << " for Frame " << uiFrame << " given in CameraParameterFile" << std::endl;
+      AOT(true);
+      exit( EXIT_FAILURE );
+    }
+    AOT( m_aadCameraParameters[ uiLeftViewLine  ].size() < 6 );
+    AOT( m_aadCameraParameters[ uiRightViewLine ].size() < 6 );
+
+    // Linear Interpolation
+    Double dFactor = ( (Double)( iView - iLeftView ) ) / ( (Double)( iRightView - iLeftView ) );
+    rdFocalLength  = m_aadCameraParameters[ uiLeftViewLine ][ 3 ] + dFactor * ( m_aadCameraParameters[ uiRightViewLine ][ 3 ] - m_aadCameraParameters[ uiLeftViewLine ][ 3 ] );
+    rdPosition     = m_aadCameraParameters[ uiLeftViewLine ][ 4 ] + dFactor * ( m_aadCameraParameters[ uiRightViewLine ][ 4 ] - m_aadCameraParameters[ uiLeftViewLine ][ 4 ] );
+    rdCameraShift  = m_aadCameraParameters[ uiLeftViewLine ][ 5 ] + dFactor * ( m_aadCameraParameters[ uiRightViewLine ][ 5 ] - m_aadCameraParameters[ uiLeftViewLine ][ 5 ] );
+    rbInterpolated = true;
+  }
+}
+
+Bool
+TAppComCamPara::xGetShiftParameterReal( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bExternal, Bool bByIdx, Double& rdScale, Double& rdOffset )
+{
+  AOT( m_bSetupFromCoded );
+
+  Bool   bInterpolatedSource;
+  Double dMinDepthSource;
+  Double dMaxDepthSource;
+  Double dFocalLengthSource;
+  Double dPositionSource;
+  Double dIntersectionSource;
+
+  Bool   bInterpolatedTarget;
+  Double dPositionTarget;
+  Double dIntersectionTarget;
+  Double dFocalLengthTarget;
+
+  Int    iTargetViewNum;
+  Int    iSourceViewNum;
+
+  if( bByIdx )
+  {
+    iSourceViewNum = m_aiBaseViews[ uiSourceView ];
+    iTargetViewNum = ( bExternal ? m_aiSynthViews[ uiTargetView ] : m_aiBaseViews[ uiTargetView ] );
+  }
+  else
+  {
+    iSourceViewNum = (Int) uiSourceView;
+    iTargetViewNum = (Int) uiTargetView;
+  }
+
+  xGetGeometryData( iSourceViewNum, uiFrame, dFocalLengthSource, dPositionSource, dIntersectionSource, bInterpolatedSource );
+  xGetZNearZFar   ( iSourceViewNum, uiFrame, dMinDepthSource,    dMaxDepthSource );
+  xGetGeometryData( iTargetViewNum, uiFrame, dFocalLengthTarget, dPositionTarget, dIntersectionTarget, bInterpolatedTarget );
+
+  Double dFactor = dFocalLengthSource * ( dPositionTarget - dPositionSource );
+  rdScale        = dFactor * ( 1.0 / dMinDepthSource - 1.0 / dMaxDepthSource ) / (Double)( ( 1 << m_uiInputBitDepth ) - 1 );
+  rdOffset       = dFactor / dMaxDepthSource - dIntersectionTarget + dIntersectionSource;
+
+  return ( bInterpolatedSource || bInterpolatedTarget );
+}
+
+
+Void
+TAppComCamPara::xGetShiftParameterCoded( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bByIdx, Int& riScale, Int& riOffset )
+{
+  if ( m_bSetupFromCoded )
+  {
+    if ( uiSourceView == uiTargetView )
+    {
+      riScale  = 0;
+      riOffset = 0;
+      return;
+    }
+    Int iCamParsCodedPrecision;
+    xGetCodedCameraData( uiSourceView, uiTargetView,  bByIdx, uiFrame, riScale, riOffset, iCamParsCodedPrecision );
+
+    if ( m_bCamParsCodedPrecSet )
+    {
+      AOT( m_uiCamParsCodedPrecision != (UInt) iCamParsCodedPrecision );
+    }
+    else
+    {
+      m_uiCamParsCodedPrecision = (UInt) iCamParsCodedPrecision;
+      m_bCamParsCodedPrecSet    = true;
+    }
+  }
+  else
+  {
+  Double  dScale, dOffset;
+  Bool    bInterpolated = xGetShiftParameterReal( uiSourceView, uiTargetView, uiFrame, false, bByIdx, dScale, dOffset );
+  AOT(    bInterpolated ); // must be base view
+
+  Double  dMultOffset   = (Double)( 1 << ( m_uiCamParsCodedPrecision + 1 ) );
+  Double  dMultScale    = (Double)( 1 << ( m_uiCamParsCodedPrecision + 1 + m_uiInputBitDepth ) );
+  riOffset              = (Int)floor( dMultOffset * dOffset + .5 );
+  riScale               = (Int)floor( dMultScale  * dScale  + .5 );
+}
+
+}
+
+
+Void
+TAppComCamPara::xGetShiftParameterInt( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bExternal, Bool bByIdx, Int64& riScale, Int64& riOffset )
+{
+  Int    iTargetViewNum;
+  Int    iSourceViewNum;
+  Int    iPrevBaseViewNum;
+  Int    iNextBaseViewNum;
+  Int    iTargetViewRelNum;
+
+  if( bByIdx )
+  {
+
+    iSourceViewNum = m_aiBaseViews[ uiSourceView ];
+
+    if ( bExternal )
+    {
+      iTargetViewNum    = m_aiSynthViews      [ uiTargetView ];
+      iTargetViewRelNum = m_aiRelSynthViewsNum[ uiTargetView ];
+    }
+    else
+    {
+      iTargetViewNum    = m_aiBaseViews       [ uiTargetView ];
+      iTargetViewRelNum = m_aiBaseId2SortedId [ uiTargetView ] * ((Int) m_dViewNumPrec );
+    }
+  }
+  else
+  {
+    iSourceViewNum = (Int) uiSourceView;
+    iTargetViewNum = (Int) uiTargetView;
+
+    if ( bExternal )
+    {
+      iTargetViewRelNum = m_aiRelSynthViewsNum[ xGetViewId( m_aiSynthViews, (Int) uiTargetView )];
+    }
+    else
+    {
+      iTargetViewRelNum = m_aiBaseId2SortedId[ xGetBaseViewId( uiTargetView) ] * ((Int) m_dViewNumPrec );
+    }
+  }
+  xGetPrevAndNextBaseView( iSourceViewNum, iTargetViewNum, iPrevBaseViewNum, iNextBaseViewNum );
+  AOT( iPrevBaseViewNum == -1 ); // should not happen
+  AOT( iNextBaseViewNum == -1 ); // should not happen
+
+  Int iSrcId    = xGetBaseViewId( iSourceViewNum   );
+  Int iPrevId   = xGetBaseViewId( iPrevBaseViewNum );
+  Int iNextId   = xGetBaseViewId( iNextBaseViewNum );
+  AOF( m_aaiScaleAndOffsetSet[ iSrcId ][ iPrevId ] ); // coded scale and offset must be set
+  AOF( m_aaiScaleAndOffsetSet[ iSrcId ][ iNextId ] ); // coded scale and offset must be set
+
+  Int iNextBaseViewRelNum = m_aiBaseId2SortedId[ iNextId ] * ((Int) m_dViewNumPrec );
+  Int iPrevBaseViewRelNum = m_aiBaseId2SortedId[ iPrevId ] * ((Int) m_dViewNumPrec );
+
+  Int64 iPrevScale  = (Int64)m_aaiCodedScale [ iSrcId ][ iPrevId ];
+  Int64 iNextScale  = (Int64)m_aaiCodedScale [ iSrcId ][ iNextId ];
+  Int64 iPrevOffset = (Int64)m_aaiCodedOffset[ iSrcId ][ iPrevId ] << m_uiBitDepthForLUT;
+  Int64 iNextOffset = (Int64)m_aaiCodedOffset[ iSrcId ][ iNextId ] << m_uiBitDepthForLUT;
+
+  if( iPrevBaseViewNum == iNextBaseViewNum )
+  {
+    riScale   = iNextScale;
+    riOffset  = iNextOffset;
+  }
+  else
+  {
+    riScale   = Int64( iTargetViewRelNum    - iPrevBaseViewRelNum ) * iNextScale;
+    riScale  += Int64( iNextBaseViewRelNum  - iTargetViewRelNum   ) * iPrevScale;
+    riOffset  = Int64( iTargetViewRelNum   - iPrevBaseViewRelNum ) * iNextOffset;
+    riOffset += Int64( iNextBaseViewRelNum - iTargetViewRelNum   ) * iPrevOffset;
+    Int64 iD  = Int64( iNextBaseViewRelNum - iPrevBaseViewRelNum );
+    Int64 iSA = ( riScale  > 0 ? iD / 2 : -iD / 2 );
+    Int64 iOA = ( riOffset > 0 ? iD / 2 : -iD / 2 );
+    riScale   = ( riScale  + iSA  ) / iD;
+    riOffset  = ( riOffset + iOA  ) / iD;
+  }
+}
+
+
+Void
+TAppComCamPara::xSetCodedScaleOffset( UInt uiFrame )
+{
+  for( UInt uiSourceId = 0; uiSourceId < m_iNumberOfBaseViews; uiSourceId++ )
+  {
+    for( UInt uiTargetId = 0; uiTargetId < m_iNumberOfBaseViews; uiTargetId++ )
+    {
+      Int iScale, iOffset;
+      xGetShiftParameterCoded( uiSourceId, uiTargetId, uiFrame, true, iScale, iOffset );
+      m_aaiCodedScale        [ uiSourceId ][ uiTargetId ] = iScale;
+      m_aaiCodedOffset       [ uiSourceId ][ uiTargetId ] = iOffset;
+      m_aaiScaleAndOffsetSet [ uiSourceId ][ uiTargetId ] = 1;
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::xSetShiftParametersAndLUT( UInt uiNumberSourceViews, UInt uiNumberTargetViews, UInt uiFrame, Bool bExternalReference , Double****& radLUT, Int****& raiLUT, Double***& radShiftParams, Int64***& raiShiftParams )
+{
+  if( uiNumberSourceViews <= 1 || uiNumberTargetViews == 0 )
+  {
+    return;
+  }
+  AOF( radShiftParams != NULL && raiShiftParams != NULL && radLUT != NULL && raiLUT != NULL );
+  AOF( m_uiBitDepthForLUT == 8 );
+
+  Int     iLog2DivLuma   = m_uiBitDepthForLUT + m_uiCamParsCodedPrecision + 1 - m_iLog2Precision;   AOF( iLog2DivLuma > 0 );
+  Int     iLog2DivChroma = iLog2DivLuma + 1;
+  Double  dMaxDispDev    = 0.0;
+  Double  dMaxRndDispDvL = 0.0;
+  Double  dMaxRndDispDvC = 0.0;
+  for( UInt uiSourceView = 0; uiSourceView < uiNumberSourceViews; uiSourceView++ )
+  {
+    for( UInt uiTargetView = 0; uiTargetView < uiNumberTargetViews; uiTargetView++ )
+    {
+
+      // integer-valued scale and offset
+      Int64 iScale, iOffset;
+      xGetShiftParameterInt ( uiSourceView, uiTargetView, uiFrame, bExternalReference, true, iScale, iOffset );
+      raiShiftParams[ uiSourceView][ uiTargetView ][ 0 ] = iScale;
+      raiShiftParams[ uiSourceView][ uiTargetView ][ 1 ] = iOffset;
+
+      // offsets including rounding offsets
+      Int64 iOffsetLuma   = iOffset + ( ( 1 << iLog2DivLuma   ) >> 1 );
+      Int64 iOffsetChroma = iOffset + ( ( 1 << iLog2DivChroma ) >> 1 );
+
+      // real-valued scale and offset
+      Double dScale, dOffset;
+
+      if ( m_bSetupFromCoded )
+      {
+        dScale  = (Double) iScale  / (( Double ) ( 1 << iLog2DivLuma ));
+        dOffset = (Double) iOffset / (( Double ) ( 1 << iLog2DivLuma ));
+      }
+      else
+      {
+        xGetShiftParameterReal( uiSourceView, uiTargetView, uiFrame, bExternalReference, true, dScale, dOffset );
+      }
+
+      radShiftParams[ uiSourceView][ uiTargetView ][ 0 ] = dScale;
+      radShiftParams[ uiSourceView][ uiTargetView ][ 1 ] = dOffset;
+
+      for( UInt uiDepthValue = 0; uiDepthValue < 256; uiDepthValue++ )
+      {
+        // real-valued look-up tables
+        Double  dShiftLuma      = ( (Double)uiDepthValue * dScale + dOffset ) * Double( 1 << m_iLog2Precision );
+        Double  dShiftChroma    = dShiftLuma / 2;
+        radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ uiDepthValue ] = dShiftLuma;
+        radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ uiDepthValue ] = dShiftChroma;
+
+        // integer-valued look-up tables
+        Int64   iTempScale      = (Int64)uiDepthValue * iScale;
+        Int64   iTestScale      = ( iTempScale + iOffset       );   // for checking accuracy of camera parameters
+        Int64   iShiftLuma      = ( iTempScale + iOffsetLuma   ) >> iLog2DivLuma;
+        Int64   iShiftChroma    = ( iTempScale + iOffsetChroma ) >> iLog2DivChroma;
+        raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ uiDepthValue ] = (Int)iShiftLuma;
+        raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ uiDepthValue ] = (Int)iShiftChroma;
+
+        // maximum deviation
+        dMaxDispDev     = Max( dMaxDispDev,    fabs( Double( (Int) iTestScale   ) - dShiftLuma * Double( 1 << iLog2DivLuma ) ) / Double( 1 << iLog2DivLuma ) );
+        dMaxRndDispDvL  = Max( dMaxRndDispDvL, fabs( Double( (Int) iShiftLuma   ) - dShiftLuma   ) );
+        dMaxRndDispDvC  = Max( dMaxRndDispDvC, fabs( Double( (Int) iShiftChroma ) - dShiftChroma ) );
+      }
+
+      radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 256 ] = radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 255 ];
+      radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 256 ] = radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 255 ];
+      raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 256 ] = raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 255 ];
+      raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 256 ] = raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 255 ];
+    }
+  }
+
+  // check maximum deviation
+  Double  dMaxAllowedDispDev    =       Double( 1 << m_iLog2Precision ) / Double( 1 << m_uiCamParsCodedPrecision );       //  counting only the impact of camera parameter rounding
+  Double  dMaxAllowedRndDispDvL = 0.5 + Double( 1 << m_iLog2Precision ) / Double( 1 << m_uiCamParsCodedPrecision );       // final rounding and impact of camera parameter rounding
+  Double  dMaxAllowedRndDispDvC = 0.5 + Double( 1 << m_iLog2Precision ) / Double( 1 << m_uiCamParsCodedPrecision ) / 2.0; // final rounding and impact of camera parameter rounding
+
+  if( ( dMaxDispDev >= dMaxAllowedDispDev || dMaxRndDispDvL >= dMaxAllowedRndDispDvL || dMaxRndDispDvC >= dMaxAllowedRndDispDvC ) && !m_bSetupFromCoded )
+  {
+    std::cout << "Warning: Something wrong with the accuracy of coded camera parameters:" << std::endl;
+    if( dMaxDispDev    >= dMaxAllowedDispDev    )
+    {
+      std::cout << "   max disparity difference is " << dMaxDispDev    << " (allowed: " << dMaxAllowedDispDev    << ")" << std::endl;
+    }
+    if( dMaxRndDispDvL >= dMaxAllowedRndDispDvL )
+    {
+      std::cout << "   max rnd luma   disp diff is " << dMaxRndDispDvL << " (allowed: " << dMaxAllowedRndDispDvL << ")" << std::endl;
+    }
+    if( dMaxRndDispDvC >= dMaxAllowedRndDispDvC )
+    {
+      std::cout << "   max rnd chroma disp diff is " << dMaxRndDispDvC << " (allowed: " << dMaxAllowedRndDispDvC << ")" << std::endl;
+    }
+  }
+}
+
+Void
+TAppComCamPara::xSetShiftParametersAndLUT( UInt uiFrame )
+{
+  xInit2dArray             ( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiScaleAndOffsetSet, 0 );
+  xSetCodedScaleOffset     (                                                          uiFrame );
+  xSetShiftParametersAndLUT( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  uiFrame, false, m_adBaseViewShiftLUT,  m_aiBaseViewShiftLUT,  m_adBaseViewShiftParameter,  m_aiBaseViewShiftParameter  );
+  xSetShiftParametersAndLUT( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfSynthViews, uiFrame, true,  m_adSynthViewShiftLUT, m_aiSynthViewShiftLUT, m_adSynthViewShiftParameter, m_aiSynthViewShiftParameter );
+};
+
+
+Void
+TAppComCamPara::xGetCameraShifts( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Double& rdCamPosShift, Double& rdPicPosShift )
+{
+  Double  dDummy, dCamPosSource, dCamPosTarget, dPicPosSource, dPicPosTarget;
+  Bool    bInterpolatedSource, bInterpolatedTarget;
+  Int     iTargetViewNum = m_aiBaseViews[ uiTargetView ];
+  Int     iSourceViewNum = m_aiBaseViews[ uiSourceView ];
+
+  xGetGeometryData( iSourceViewNum, uiFrame, dDummy, dCamPosSource, dPicPosSource, bInterpolatedSource );
+  xGetGeometryData( iTargetViewNum, uiFrame, dDummy, dCamPosTarget, dPicPosTarget, bInterpolatedTarget );
+  AOT( bInterpolatedSource || bInterpolatedTarget );
+
+  rdCamPosShift =  ( dCamPosTarget - dCamPosSource );
+  rdPicPosShift = -( dPicPosTarget - dPicPosSource ); // to be consistent
+}
+
+
+Void
+TAppComCamPara::xSetPdmConversionParams()
+{
+  AOF( m_aiViewOrderIndex[ 0 ] == 0 );
+  if ( m_bSetupFromCoded || m_iNumberOfBaseViews    <  2 )
+  {
+    return;
+  }
+
+  //--- determine (virtual) camera parameter shift between view order index 1 and base view (view order index 0) ---
+  Double        dCamPosShift, dPicPosShift;
+  Int           iMinVOI       = (1<<30);
+  Int           iMinAbsVOI    = (1<<30);
+  Int           iMinAbsVOIId  = 0;
+  for( Int iBaseId = 1; iBaseId < m_iNumberOfBaseViews; iBaseId++ )
+  {
+    Int iAbsVOI = ( m_aiViewOrderIndex[ iBaseId ] < 0 ? -m_aiViewOrderIndex[ iBaseId ] : m_aiViewOrderIndex[ iBaseId ] );
+    if( iAbsVOI < iMinAbsVOI )
+    {
+      iMinVOI      = m_aiViewOrderIndex[ iBaseId ];
+      iMinAbsVOI   = iAbsVOI;
+      iMinAbsVOIId = iBaseId;
+    }
+  }
+  AOF( iMinAbsVOIId != 0 && iMinAbsVOI != 0 );
+  xGetCameraShifts( 0, iMinAbsVOIId, m_uiFirstFrameId, dCamPosShift, dPicPosShift );
+  Double  dCamPosShiftVOI01     = dCamPosShift / Double( iMinVOI );
+
+  //--- determine maximum absolute camera position shift, precision, and base scale ---
+  Double  dMaxAbsCamPosShift = 0.0;
+  for( Int iTargetId = 1; iTargetId < m_iNumberOfBaseViews; iTargetId++ )
+  {
+    for( Int iBaseId = 0; iBaseId < iTargetId; iBaseId++ )
+    {
+      xGetCameraShifts( (UInt)iBaseId, (UInt)iTargetId, m_uiFirstFrameId, dCamPosShift, dPicPosShift );
+      dCamPosShift        = ( dCamPosShift < 0.0                ? -dCamPosShift : dCamPosShift       );
+      dMaxAbsCamPosShift  = ( dCamPosShift > dMaxAbsCamPosShift ?  dCamPosShift : dMaxAbsCamPosShift );
+    }
+  }
+  Int     iPrecision  = 0;
+#if 0 // enabling this lines might be reasonable, but produces different results for the 2 view and 3 view test cases
+  Double  dEpsilon    = 1e-15;
+  Double  dAbsCamPosShiftVOI01  = ( dCamPosShiftVOI01 < 0.0 ? -dCamPosShiftVOI01 : dCamPosShiftVOI01 );
+  Double  dShiftRatio = dMaxAbsCamPosShift / dAbsCamPosShiftVOI01 - dEpsilon;
+  for( ; (Double)( 1 << iPrecision ) < dShiftRatio; iPrecision++ );
+#endif
+  Int     iPrecShift  = iPrecision + PDM_INTER_CALC_SHIFT + PDM_VIRT_DEPTH_PRECISION - 2;
+  AOF(    iPrecShift  < PDM_INTERNAL_CALC_BIT_DEPTH );
+  Int     iScaleVOI01 = 1 << iPrecShift;
+  m_iPdmPrecision     = iPrecision;
+
+  //--- loop over target views ---
+  for( Int iTargetId = 1; iTargetId < m_iNumberOfBaseViews; iTargetId++ )
+  {
+    // set scale and offset parameters for other views
+    for( Int iBaseId = 0; iBaseId < iTargetId; iBaseId++ )
+    {
+      xGetCameraShifts( (UInt)iBaseId, (UInt)iTargetId, m_uiFirstFrameId, dCamPosShift, dPicPosShift );
+      Double  dScale      = Double( iScaleVOI01 ) * dCamPosShiftVOI01 / dCamPosShift;
+      Int     iDiv        = m_aiViewOrderIndex[ iTargetId ] - m_aiViewOrderIndex[ iBaseId ];
+      Int     iAdd        = ( iDiv > 0 ? iDiv / 2 : -iDiv / 2 );
+      Int     iScalePred  = ( iScaleVOI01 + iAdd ) / iDiv;
+      Double  dFactor     = dScale / (Double)iScalePred * pow( 2.0, PDM_LOG4_SCALE_DENOMINATOR );
+      Int     iNominator  = (Int)floor( dFactor + .5 );
+      Int     iNomDelta   = iNominator - ( 1 << PDM_LOG4_SCALE_DENOMINATOR );
+      Int     iScale      = Int( ( (Int64)iNominator * (Int64)iScalePred + (Int64)( ( 1 << PDM_LOG4_SCALE_DENOMINATOR ) >> 1 ) ) >> PDM_LOG4_SCALE_DENOMINATOR );
+      Double  dOffset     = -dPicPosShift * Double( iScale ) * pow( 2.0, 2 - PDM_OFFSET_SHIFT );
+      Int     iOffset     = (Int)floor( dOffset + .5 );
+
+      m_aaiPdmScaleNomDelta [ iTargetId ][ iBaseId ]  = iNomDelta;
+      m_aaiPdmOffset        [ iTargetId ][ iBaseId ]  = iOffset;
+    }
+  }
+}
+
+
+
+TAppComCamPara::TAppComCamPara()
+{
+  m_dViewNumPrec              = VIEW_NUM_PREC;  // fixed
+  m_iLog2Precision            = -1;
+  m_uiInputBitDepth           = 0;
+  m_uiBitDepthForLUT          = 8;              // fixed
+  m_uiFirstFrameId            = 0;
+  m_uiLastFrameId             = 0;
+
+  m_iNumberOfBaseViews        = -1;
+  m_iNumberOfSynthViews       = -1;
+
+  m_uiCamParsCodedPrecision   = 0;
+  m_bCamParsVaryOverTime      = true;
+
+  m_aaiCodedScale             = 0;
+  m_aaiCodedOffset            = 0;
+  m_aaiScaleAndOffsetSet      = 0;
+
+  m_iPdmPrecision             = 0;
+  m_aaiPdmScaleNomDelta       = 0;
+  m_aaiPdmOffset              = 0;
+
+  m_adBaseViewShiftParameter  = 0;
+  m_aiBaseViewShiftParameter  = 0;
+  m_adSynthViewShiftParameter = 0;
+  m_aiSynthViewShiftParameter = 0;
+
+  m_adBaseViewShiftLUT        = 0;
+  m_aiBaseViewShiftLUT        = 0;
+  m_adSynthViewShiftLUT       = 0;
+  m_aiSynthViewShiftLUT       = 0;
+
+  m_bSetupFromCoded           = false;
+  m_bCamParsCodedPrecSet      = false;
+
+
+}
+
+
+TAppComCamPara::~TAppComCamPara()
+{
+  xDeleteArray( m_adBaseViewShiftParameter,  m_iNumberOfBaseViews, m_iNumberOfBaseViews     );
+  xDeleteArray( m_aiBaseViewShiftParameter,  m_iNumberOfBaseViews, m_iNumberOfBaseViews     );
+  xDeleteArray( m_adBaseViewShiftLUT,        m_iNumberOfBaseViews, m_iNumberOfBaseViews,  2 );
+  xDeleteArray( m_aiBaseViewShiftLUT,        m_iNumberOfBaseViews, m_iNumberOfBaseViews,  2 );
+
+  xDeleteArray( m_adSynthViewShiftParameter, m_iNumberOfBaseViews, Max(1,m_iNumberOfSynthViews));
+  xDeleteArray( m_aiSynthViewShiftParameter, m_iNumberOfBaseViews, Max(1,m_iNumberOfSynthViews));
+  xDeleteArray( m_adSynthViewShiftLUT,       m_iNumberOfBaseViews, Max(1,m_iNumberOfSynthViews), 2 );
+  xDeleteArray( m_aiSynthViewShiftLUT,       m_iNumberOfBaseViews, Max(1,m_iNumberOfSynthViews), 2 );
+
+  xDeleteArray( m_aaiCodedScale,             m_iNumberOfBaseViews );
+  xDeleteArray( m_aaiCodedOffset,            m_iNumberOfBaseViews );
+  xDeleteArray( m_aaiScaleAndOffsetSet,      m_iNumberOfBaseViews );
+
+  xDeleteArray( m_aaiPdmScaleNomDelta,       m_iNumberOfBaseViews );
+  xDeleteArray( m_aaiPdmOffset,              m_iNumberOfBaseViews );
+}
+
+Void
+TAppComCamPara::xSetupBaseViewsFromCoded()
+{
+  //===== get and sort views given in camera parameter file and set list of base views and related arrays =====
+  // get left-right order and coding order from cfg-file
+  std::vector<Int> aiViewOrderIdx;   // Left Right Order
+  std::vector<Int> aiViewId ;        // Coding     Order
+
+  Int iMinViewOrderIdx = MAX_INT;
+  for( UInt uiRow = 0; uiRow < m_aadCameraParameters.size(); uiRow++ )
+  {
+    if (m_aadCameraParameters[uiRow].size() != 2 )
+      break;
+
+    Int iViewOrderIdx  = (Int)( m_aadCameraParameters[ uiRow ][ 1 ] );
+    iMinViewOrderIdx   = Min( iViewOrderIdx, iMinViewOrderIdx );
+
+    aiViewOrderIdx     .push_back( iViewOrderIdx );
+    aiViewId           .push_back( (Int) m_aadCameraParameters[ uiRow ][ 0 ]  );
+  }
+
+  // create base view numbers
+  AOT( aiViewId.size() != aiViewOrderIdx.size() );
+  m_iNumberOfBaseViews = (Int) aiViewId.size();
+  for (Int iCurBaseView = 0; iCurBaseView < m_iNumberOfBaseViews; iCurBaseView++ )
+  {
+    aiViewOrderIdx[iCurBaseView] = ( aiViewOrderIdx[iCurBaseView] - iMinViewOrderIdx);
+    m_aiBaseViews      .push_back(  aiViewOrderIdx[iCurBaseView] * ( (Int) m_dViewNumPrec) );
+    m_aiBaseId2SortedId.push_back( iCurBaseView );
+    m_aiBaseSortedId2Id.push_back( iCurBaseView );
+
+  }
+
+  m_iNumberOfBaseViews = (Int) m_aiBaseViews.size();
+
+  std::vector<Int> aiSortedViewOrderIdx = aiViewOrderIdx;
+
+  // sort base views according to View Order Idx
+  m_aiSortedBaseViews = m_aiBaseViews;
+  for (Int iCurBaseView = 1; iCurBaseView < m_iNumberOfBaseViews; iCurBaseView++ )
+  {
+    Int iCurViewOrder = aiSortedViewOrderIdx[iCurBaseView];
+    for (Int iCurSearchPos = iCurBaseView; iCurSearchPos >= 0; iCurSearchPos-- )
+    {
+      if ( iCurViewOrder < aiSortedViewOrderIdx[iCurSearchPos] )
+      {
+        Int iTempViewId = m_aiSortedBaseViews[iCurSearchPos];
+        m_aiSortedBaseViews[iCurSearchPos] = m_aiSortedBaseViews[iCurBaseView];
+        m_aiSortedBaseViews[iCurBaseView ] = iTempViewId;
+
+        Int iTempViewOrderIdx = aiSortedViewOrderIdx[iCurSearchPos];
+        aiSortedViewOrderIdx[iCurSearchPos] = aiSortedViewOrderIdx[iCurBaseView];
+        aiSortedViewOrderIdx[iCurBaseView ] = iTempViewOrderIdx;
+
+        Int iTempPos = m_aiBaseSortedId2Id[iCurSearchPos];
+        m_aiBaseSortedId2Id[iCurSearchPos] = m_aiBaseSortedId2Id[iCurBaseView];
+        m_aiBaseSortedId2Id[iCurBaseView] = iTempPos;
+        iCurBaseView--;
+      }
+    }
+  }
+
+  for (Int iCurBaseView = 0; iCurBaseView < m_iNumberOfBaseViews; iCurBaseView++ )
+  {
+    m_aiBaseId2SortedId[m_aiBaseSortedId2Id[iCurBaseView]] = iCurBaseView;
+  }
+
+  m_aiViewsInCfgFile = m_aiSortedBaseViews;
+
+  // check
+  if( m_aiViewsInCfgFile.size() < 2 )
+  {
+    std::cerr << "Failed reading camera parameter file" << std::endl;
+    std::cerr << "At least two views must be given" << std::endl;
+    AOT(true);
+    exit( EXIT_FAILURE );
+  }
+
+  // translate coding order to view order
+  for( UInt uiRow = 0; uiRow < m_aadCameraParameters.size(); uiRow++ )
+{
+    if (m_aadCameraParameters[uiRow].size() == 2 )
+      continue;
+
+    m_aadCameraParameters[ uiRow ][ 2 ] = (Double) aiViewOrderIdx[ xGetViewId( aiViewId, (Int) m_aadCameraParameters[ uiRow ][ 2 ] ) ];
+    m_aadCameraParameters[ uiRow ][ 3 ] = (Double) aiViewOrderIdx[ xGetViewId( aiViewId, (Int) m_aadCameraParameters[ uiRow ][ 3 ] ) ];
+  }
+}
+
+Void TAppComCamPara::xSetupBaseViews( Char* pchBaseViewNumbers, UInt uiNumBaseViews )
+  {
+    // init list
+    std::vector<Int> aiViewsInCfg;
+    for( UInt uiRow = 0; uiRow < m_aadCameraParameters.size(); uiRow++ )
+    {
+      aiViewsInCfg.push_back( (Int)( m_aadCameraParameters[ uiRow ][ 0 ] * m_dViewNumPrec ) );
+    }
+    // remove duplicated items
+    std::sort( aiViewsInCfg.begin(), aiViewsInCfg.end() );
+    std::vector<Int>::iterator cIterNewEnd = std::unique( aiViewsInCfg.begin(), aiViewsInCfg.end() );
+    aiViewsInCfg.erase( cIterNewEnd, aiViewsInCfg.end() );
+    // sort (from left to right)
+    std::vector<Int> aiDummyI2SI, aiDummySI2I;
+    xGetSortedViewList( aiViewsInCfg, m_aiViewsInCfgFile, aiDummyI2SI, aiDummySI2I );
+    // check
+    if( m_aiViewsInCfgFile.size() < 2 )
+    {
+    std::cerr << "Failed reading config file" << std::endl;
+      std::cerr << "At least two views must be given" << std::endl;
+      exit( EXIT_FAILURE );
+    }
+
+
+
+  //===== set list of base views and related arrays =====
+  if( pchBaseViewNumbers == 0 )
+  {
+    std::cerr << "BaseViewCameraNumbers must be given" << std::endl;
+    exit( EXIT_FAILURE );
+  };
+
+  convertNumberString( pchBaseViewNumbers, m_aiBaseViews, m_dViewNumPrec  );
+  while( (UInt)m_aiBaseViews.size() > uiNumBaseViews )
+  {
+    m_aiBaseViews.pop_back();
+  }
+  xGetSortedViewList( m_aiBaseViews, m_aiSortedBaseViews, m_aiBaseId2SortedId, m_aiBaseSortedId2Id );
+  m_iNumberOfBaseViews = (Int)m_aiBaseViews.size();
+}
+
+
+Void
+TAppComCamPara::init( UInt   uiNumBaseViews,
+                      UInt   uiInputBitDepth,
+                      UInt   uiCodedCamParsPrecision,
+                      UInt   uiStartFrameId,
+                      UInt   uiNumFrames,
+                      Char*  pchCfgFileName,
+                      Char*  pchBaseViewNumbers,
+                      Char*  pchSynthViewNumbers,
+                      std::vector<Int>* paiSynthViewNumbers,
+                      Int    iLog2Precision )
+{
+  //===== set miscellaneous variables =====
+  m_uiInputBitDepth         = uiInputBitDepth;
+  m_uiFirstFrameId          = uiStartFrameId;
+  m_uiLastFrameId           = uiStartFrameId + uiNumFrames - 1;
+  m_uiCamParsCodedPrecision = uiCodedCamParsPrecision;
+  m_iLog2Precision          = iLog2Precision;
+#if HHI_INTERVIEW_SKIP
+  m_iCurrentFrameId         = 0 ;
+#endif
+
+  xReadCameraParameterFile( pchCfgFileName );
+
+  m_bSetupFromCoded         = ( m_aadCameraParameters[ 0 ].size() == 2 );
+
+  if ( m_bSetupFromCoded )
+  {
+    std::cout << "Detected decoded camera parameter file. Overwriting base view settings from cfg file. " << std::endl;
+    xSetupBaseViewsFromCoded();
+  }
+  else
+  {
+    xSetupBaseViews( pchBaseViewNumbers, uiNumBaseViews );
+  }
+
+  //===== set list of external (virtual) views =====
+  m_aiSynthViews.clear();
+
+  if( pchSynthViewNumbers != 0 || paiSynthViewNumbers != 0)
+  {
+    std::vector<Int> aiTmpSynthViews;
+
+    AOT( ( pchSynthViewNumbers != NULL ) && ( paiSynthViewNumbers != NULL ) );
+
+    if ( pchSynthViewNumbers != NULL )
+    {
+      convertNumberString( pchSynthViewNumbers, aiTmpSynthViews, m_dViewNumPrec );
+    }
+    else
+    {
+      aiTmpSynthViews = (*paiSynthViewNumbers);
+    }
+
+    for( UInt uiSId = 0; uiSId < (UInt)aiTmpSynthViews.size(); uiSId++ )
+    {
+
+      Int iViewNumPrec        = (Int) m_dViewNumPrec;
+      Int iLeftBaseViewIdx    =   aiTmpSynthViews[ uiSId ]                        / iViewNumPrec;
+      Int iRightBaseViewIdx   = ( aiTmpSynthViews[ uiSId ] + (iViewNumPrec - 1) ) / iViewNumPrec;
+
+      if ( iLeftBaseViewIdx < 0 || iRightBaseViewIdx >= m_iNumberOfBaseViews )
+      {
+        std::cerr << "SynthViewCameraNumbers must be greater and equal to 0 and smaller than number of base views" << std::endl;
+        AOT(true);
+        exit( EXIT_FAILURE );
+      }
+
+      Int64  iLeftBaseViewRelNum = iLeftBaseViewIdx  * iViewNumPrec;
+      Int64 iRightBaseViewRelNum = iRightBaseViewIdx * iViewNumPrec;
+
+      Int64 iDiffBaseViewRelNum  = iRightBaseViewRelNum - iLeftBaseViewRelNum;
+
+      Int64 iSynthViewRelNum     = aiTmpSynthViews[ uiSId ];
+      Int64 iLeftBaseNum         = m_aiSortedBaseViews[ iLeftBaseViewIdx  ];
+      Int64 iRightBaseNum        = m_aiSortedBaseViews[ iRightBaseViewIdx ];
+      Int64 iDiffBaseNum         = iRightBaseNum - iLeftBaseNum;
+      Int64 iSynthViewNum;
+
+      if ( iDiffBaseViewRelNum != 0)
+      {
+        AOT( (Int) iDiffBaseViewRelNum != iViewNumPrec );
+        Int iFact = iDiffBaseNum > 0 ? 1 : -1;
+        iSynthViewNum = iLeftBaseNum + ( iDiffBaseNum * ( iSynthViewRelNum - iLeftBaseViewRelNum ) + (iViewNumPrec >> 1) * iFact ) / ( iViewNumPrec );
+      }
+      else
+      {
+        iSynthViewNum = iLeftBaseNum;
+      }
+
+      m_aiRelSynthViewsNum.push_back(  aiTmpSynthViews[ uiSId ] );
+      m_aiSynthViews      .push_back(  (Int) iSynthViewNum  );
+    }
+  }
+  m_iNumberOfSynthViews = (Int)m_aiSynthViews.size();
+
+
+  //===== set derived parameters =====
+  xGetViewOrderIndices( m_aiBaseId2SortedId, m_aiViewOrderIndex );
+  m_bCamParsVaryOverTime = xGetCamParsChangeFlag();
+
+
+  //===== create arrays =====
+  xCreateLUTs   ( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_adBaseViewShiftLUT,  m_aiBaseViewShiftLUT,  m_adBaseViewShiftParameter,  m_aiBaseViewShiftParameter  );
+  xCreateLUTs   ( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfSynthViews, m_adSynthViewShiftLUT, m_aiSynthViewShiftLUT, m_adSynthViewShiftParameter, m_aiSynthViewShiftParameter );
+  xCreate2dArray( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiCodedScale           );
+  xCreate2dArray( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiCodedOffset          );
+  xCreate2dArray( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiScaleAndOffsetSet    );
+  xInit2dArray  ( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiScaleAndOffsetSet, 0 );
+
+  xCreate2dArray( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiPdmScaleNomDelta     );
+  xCreate2dArray( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiPdmOffset            );
+
+  //===== init disparity to virtual depth conversion parameters =====
+  xSetPdmConversionParams();
+
+  //===== init arrays for first frame =====
+  xSetShiftParametersAndLUT( m_uiFirstFrameId );
+}
+
+
+Void
+TAppComCamPara::check( Bool bCheckViewRange, Bool bCheckFrameRange )
+{
+  if( bCheckFrameRange )
+  {
+    Double dDummy;
+
+    for( UInt uiBaseView = 0; uiBaseView < m_aiBaseViews.size(); uiBaseView++ )
+    {
+      if ( m_bSetupFromCoded )
+      {
+        for( UInt uiTargetView = 0; uiTargetView < m_aiBaseViews.size(); uiTargetView++ )
+        {
+          if ( uiTargetView == uiBaseView )
+            continue;
+
+          for( UInt uiFrame = m_uiFirstFrameId; uiFrame <= m_uiLastFrameId; uiFrame++ )
+          {
+            Int iDummy;
+
+            xGetCodedCameraData( uiBaseView, uiTargetView, true , uiFrame, iDummy, iDummy, iDummy );
+          }
+        }
+      }
+      else
+      {
+      for( UInt uiFrame = m_uiFirstFrameId; uiFrame <= m_uiLastFrameId; uiFrame++ )
+      {
+        Bool bInterpolatedCur;
+        xGetGeometryData( m_aiBaseViews[ uiBaseView ], uiFrame, dDummy, dDummy, dDummy, bInterpolatedCur );
+        xGetZNearZFar   ( m_aiBaseViews[ uiBaseView ], uiFrame, dDummy, dDummy );
+
+        if( bInterpolatedCur )
+        {
+          std::cerr << "Error: CameraParameters for BaseView " << (Double)m_aiBaseViews[ uiBaseView ] / m_dViewNumPrec << " and Frame " << uiFrame << " not defined. "  << std::endl;
+          exit( EXIT_FAILURE );
+        }
+      }
+
+      }
+    }
+
+    for( UInt uiERView = 0; uiERView < m_aiSynthViews.size() && !m_bSetupFromCoded; uiERView++ )
+    {
+      Bool bInterpolated = false;
+      for( UInt uiFrame = m_uiFirstFrameId; uiFrame <= m_uiLastFrameId; uiFrame++ )
+      {
+        Bool bInterpolatedCur;
+        xGetGeometryData( m_aiSynthViews[ uiERView ], uiFrame, dDummy, dDummy, dDummy, bInterpolatedCur );
+        bInterpolated |= bInterpolatedCur;
+      }
+      if( bInterpolated )
+      {
+        std::cout << "Interpolating Camera Parameters for View " << (Double)m_aiSynthViews[ uiERView ] / m_dViewNumPrec << std::endl;
+      }
+    }
+  }
+
+  if( bCheckViewRange )
+  {
+    Bool bAllExist = true;
+    for( Int iSynthViewIdx = 0; iSynthViewIdx < m_iNumberOfSynthViews; iSynthViewIdx++ )
+    {
+      Bool bIsBaseView;
+      Int  iDummy;
+      Bool bExist = getLeftRightBaseView( iSynthViewIdx, iDummy, iDummy, iDummy, bIsBaseView );
+      bAllExist  &= ( bExist || bIsBaseView );
+    }
+    if( !bAllExist )
+    {
+      std::cerr << "SynthViewNumbers must be within the range of BaseViewNumbers"  << std::endl;
+      exit( EXIT_FAILURE );
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::update( UInt uiFrameId )
+{
+
+  m_iCurrentFrameId = uiFrameId;
+  m_bCamParsCodedPrecSet = false;
+
+  if ( m_bCamParsVaryOverTime )
+  {
+    xSetShiftParametersAndLUT( m_uiFirstFrameId + uiFrameId );
+  }
+}
+
+#if SAIT_VSO_EST_A0033
+Void
+TAppComCamPara::xSetDispCoeff( UInt uiFrameId, Int iViewIdx )
+{
+  UInt uiFrame = m_uiFirstFrameId + uiFrameId;
+  Int  iSourceViewNum = m_aiBaseViews[ iViewIdx ];
+  Double dBaseLine = 0.0;
+  Double dFL1, dCS1, dCP1, dZN1, dZF1; 
+  Bool bInterpolated;
+  double dPos[3];
+
+  if( m_iNumberOfBaseViews == 3 )
+  {
+    xGetGeometryData( m_aiBaseViews[0], uiFrame, dFL1, dPos[0], dCS1, bInterpolated );
+    xGetGeometryData( m_aiBaseViews[1], uiFrame, dFL1, dPos[1], dCS1, bInterpolated );
+    xGetGeometryData( m_aiBaseViews[2], uiFrame, dFL1, dPos[2], dCS1, bInterpolated );
+
+    xGetGeometryData( iSourceViewNum, uiFrame, dFL1, dCP1, dCS1, bInterpolated );
+    xGetZNearZFar   ( iSourceViewNum, uiFrame, dZN1, dZF1 );
+
+    dBaseLine = ( Max( dPos[0], Max( dPos[1], dPos[2] ) ) - Min( dPos[0], Min( dPos[1], dPos[2] ) ) ) / 2.0;
+  }
+  else if( m_iNumberOfBaseViews == 2 )
+  {
+    xGetGeometryData( m_aiBaseViews[0], uiFrame, dFL1, dPos[0], dCS1, bInterpolated );
+    xGetGeometryData( m_aiBaseViews[1], uiFrame, dFL1, dPos[1], dCS1, bInterpolated );
+
+    xGetGeometryData( iSourceViewNum, uiFrame, dFL1, dCP1, dCS1, bInterpolated );
+    xGetZNearZFar   ( iSourceViewNum, uiFrame, dZN1, dZF1 );
+
+    dBaseLine = dPos[0] - dPos[1];
+  }
+
+
+  m_dDispCoeff = fabs( dFL1 * ( dBaseLine / 2.0 ) / 255.0 * ( 1.0/dZN1 - 1.0/dZF1 ) );
+}
+#endif
+
+Bool
+TAppComCamPara::getLeftRightBaseView( Int iSynthViewIdx, Int &riLeftViewIdx, Int &riRightViewIdx, Int &riRelDistToLeft, Bool& rbIsBaseView )
+{
+  Int    iLeftSortedViewIdx, iRightSortedViewIdx, iDummy;
+  Bool   bExist  = xGetLeftRightView( m_aiSynthViews[ iSynthViewIdx ], m_aiSortedBaseViews, iDummy, iDummy, iLeftSortedViewIdx, iRightSortedViewIdx );
+  rbIsBaseView   = ( iLeftSortedViewIdx == iRightSortedViewIdx && iLeftSortedViewIdx != -1 );
+
+  Int iLeftViewIdx  = ( iLeftSortedViewIdx  != -1 ? m_aiBaseSortedId2Id[ iLeftSortedViewIdx  ] : -1 );
+  Int iRightViewIdx = ( iRightSortedViewIdx != -1 ? m_aiBaseSortedId2Id[ iRightSortedViewIdx ] : -1 );
+
+  if ( iLeftSortedViewIdx != -1 && iRightSortedViewIdx != -1 )
+  {
+    riRelDistToLeft = getRelDistLeft(  iSynthViewIdx, iLeftViewIdx, iRightViewIdx);
+  }
+  else
+  {
+    riRelDistToLeft = -1;
+  }
+
+  riLeftViewIdx  = iLeftViewIdx;
+  riRightViewIdx = iRightViewIdx;
+
+  return bExist;
+}
+
+Int TAppComCamPara::getRelDistLeft( Int iSynthViewIdx, Int iLeftViewIdx, Int iRightViewIdx )
+{
+  //GT: Get normalized distance
+  Int iLeftViewDist  = abs ( m_aiBaseId2SortedId[ iLeftViewIdx  ] * ((Int) m_dViewNumPrec) - m_aiRelSynthViewsNum [ iSynthViewIdx ]);
+  Int iRightViewDist = abs ( m_aiBaseId2SortedId[ iRightViewIdx ] * ((Int) m_dViewNumPrec) - m_aiRelSynthViewsNum [ iSynthViewIdx ]);
+  Int64 iDistSum = iLeftViewDist + iRightViewDist;
+  return (iDistSum == 0) ? (1 << (REN_VDWEIGHT_PREC -1) ) : (Int) (( (((Int64) iLeftViewDist ) << REN_VDWEIGHT_PREC ) + (iDistSum >> 1) )  / iDistSum );
+}
+
+Int
+TAppComCamPara::synthRelNum2Idx( Int iRelNum )
+{
+  return xGetViewId(m_aiRelSynthViewsNum, iRelNum );
+}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/TAppComCamPara.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/TAppComCamPara.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/TAppComCamPara.h	(revision 341)
@@ -0,0 +1,289 @@
+/* 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-2011, 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 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 __TAPPCOMCAMPARA__
+#define __TAPPCOMCAMPARA__
+
+// Include files
+#include "../../Lib/TLibCommon/CommonDef.h"
+#include <vector>
+
+
+#define LOG10_VIEW_NUM_PREC         5  // Precision of view numbering
+#define VIEW_NUM_PREC               pow( 10.0, (Int)LOG10_VIEW_NUM_PREC )
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TAppComCamPara
+{
+private:
+  // camera parameter data
+  std::vector< std::vector<Double> >  m_aadCameraParameters;  ///< buffer for double values from file
+
+  // miscellaneous variables
+  Double              m_dViewNumPrec;                         ///< factor for camera number to create integer representation
+  Int                 m_iLog2Precision;                       ///< shift precision in LUT
+  UInt                m_uiInputBitDepth;                      ///< bit depth of input depth maps
+  UInt                m_uiBitDepthForLUT;                     ///< bit depth used for table look-up
+  UInt                m_uiFirstFrameId;                       ///< first frame id
+  UInt                m_uiLastFrameId;                        ///< last frame id
+  UInt                m_iCurrentFrameId;                      ///< currently set frame id
+
+  Bool                m_bSetupFromCoded;                      ///< setup from coded parameter file
+  Bool                m_bCamParsCodedPrecSet;                 ///< Coded Cam Para precision set for current frame;
+
+#if SAIT_VSO_EST_A0033
+  Double              m_dDispCoeff;
+#endif
+
+  // view lists
+  std::vector<Int>    m_aiViewsInCfgFile;                     ///< views for which parameters are specified in cfg file (from left to right)
+  std::vector<Int>    m_aiSynthViews;                         ///< View numbers of External ViewReferences
+  std::vector<Int>    m_aiRelSynthViewsNum;                   ///< Relative view numbers of External ViewReferences
+  std::vector<Int>    m_aiBaseViews;                          ///< View numbers of Base View References (in coding order)
+  std::vector<Int>    m_aiSortedBaseViews;                    ///< View numbers of Base View References (from left to right)
+  std::vector<Int>    m_aiBaseId2SortedId;                    ///< mapping from coding order to left-right order for base views
+  std::vector<Int>    m_aiBaseSortedId2Id;                    ///< mapping from left-right order to coding order for base views
+  Int                 m_iNumberOfBaseViews;                   ///< number of base views
+  Int                 m_iNumberOfSynthViews;                  ///< number of synthesized views
+
+  // SPS and slice header related variables
+  std::vector<Int>    m_aiViewOrderIndex;                     ///< list of view order indices
+  UInt                m_uiCamParsCodedPrecision;              ///< precision for coding of camera parameters (x: max error in disparity is 2^(-x) luma samples)
+  Bool                m_bCamParsVaryOverTime;                 ///< flag specifying whether camera parameters vary for given frame numbers
+  Int**               m_aaiCodedScale;                        ///< array of coded scaling parameters [RefView][TargetView]
+  Int**               m_aaiCodedOffset;                       ///< array of coded offset  parameters [RefView][TargetView]
+  Int**               m_aaiScaleAndOffsetSet;                 ///< array indicating whether scale and offset have been set
+
+  // parameters for virtual depth map generation
+  Int                 m_iPdmPrecision;                        ///< additional precision for disparity - virtual depth conversion
+  Int**               m_aaiPdmScaleNomDelta;                  ///< [TargetView][RefView] delta for nominator of scale factor
+  Int**               m_aaiPdmOffset;                         ///< [TargetView][RefView] offset parameter
+
+  // scale and offset parameters
+  Double***           m_adBaseViewShiftParameter;             ///< ShiftParameters between BaseViews e.g. [2][1][0] shift scale from view 2 to view 1; [2][1][1] shift offset from view 2 to view 1
+  Int64 ***           m_aiBaseViewShiftParameter;             ///< ShiftParameters between BaseViews e.g. [2][1][0] shift scale from view 2 to view 1; [2][1][1] shift offset from view 2 to view 1     /* do we need 64 bit? */
+  Double***           m_adSynthViewShiftParameter;            ///< ShiftParameters between BaseViews and ERViews e.g. [2][1][0] shift scale from base view 2 to er view 1;
+  Int64 ***           m_aiSynthViewShiftParameter;            ///< ShiftParameters between BaseViews and ERViews e.g. [2][1][0] shift scale from base view 2 to er view 1;    /* do we need 64 bit? */
+
+  // look-up tables
+  Double****          m_adBaseViewShiftLUT;                    ///< Disparity LUT
+  Int****             m_aiBaseViewShiftLUT;                    ///< Disparity LUT
+  Double****          m_adSynthViewShiftLUT;                   ///< Disparity LUT
+  Int****             m_aiSynthViewShiftLUT;                   ///< Disparity LUT
+
+protected:
+  // create and delete arrays
+  Void                    xCreateLUTs   ( UInt uiNumberSourceViews, UInt uiNumberTargetViews, Double****& radLUT, Int****& raiLUT, Double***& radShiftParams, Int64***& raiShiftParams );
+  Void                    xCreate2dArray( UInt uiNum1Ids, UInt uiNum2Ids, Int**& raaiArray );
+  Void                    xInit2dArray  ( UInt uiNum1Ids, UInt uiNum2Ids, Int**& raaiArray, Int iValue );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize1, UInt uiSize2, UInt uiSize3 );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize1, UInt uiSize2 );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize );
+
+  // functions for reading, initialization, sorting, getting data, etc.
+  Void  xReadCameraParameterFile  ( Char* pchCfgFileName );
+  Bool  xGetCameraDataRow         ( Int iView, UInt uiFrame, UInt& ruiFoundLine );
+
+  Void  xGetSortedViewList        ( const std::vector<Int>& raiViews, std::vector<Int>& raiSortedViews, std::vector<Int>& raiId2SortedId, std::vector<Int>& raiSortedId2Id );
+  Void  xGetViewOrderIndices      ( const std::vector<Int>& raiId2SortedId, std::vector<Int>& raiVOIdx );
+  Bool  xGetCamParsChangeFlag     ();
+  Int   xGetBaseViewId            ( Int iBaseView );
+  Int   xGetViewId                 ( std::vector<Int> aiViewList, Int iBaseView );
+
+  Bool  xGetLeftRightView         ( Int iView, std::vector<Int> aiSortedViews, Int& riLeftView, Int& riRightView, Int& riLeftSortedViewIdx, Int& riRightSortedViewIdx );
+  Void  xGetPrevAndNextBaseView   ( Int iSourceViewNum, Int iTargetViewNum, Int& riPrevBaseViewNum, Int& riNextBaseViewNum );
+  Void  xGetZNearZFar             ( Int iView, UInt uiFrame, Double& rdZNear, Double& rdZFar );
+  Void  xGetGeometryData          ( Int dView, UInt uiFrame, Double& rdFocalLength, Double& rdPosition, Double& rdCameraShift, Bool& rbInterpolated );
+  Void  xSetupBaseViewsFromCoded  ();
+  Void  xSetupBaseViews           ( Char* pchBaseViewNumbers, UInt uiNumBaseViews );
+
+  // functions for getting and setting scales and offsets
+  Bool  xGetShiftParameterReal    ( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bExternal, Bool bByIdx, Double& rdScale, Double& rdOffset );
+  Void  xGetShiftParameterCoded   ( UInt uiSourceView, UInt uiTargetView, UInt uiFrame,                 Bool bByIdx, Int&    riScale, Int&    riOffset );
+  Void  xGetShiftParameterInt     ( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bExternal, Bool bByIdx, Int64&  riScale, Int64&  riOffset );
+  Void  xGetCodedCameraData       ( UInt uiSourceView, UInt uiTargetView, Bool bByIdx,  UInt uiFrame, Int& riScale, Int& riOffset, Int& riPrecision );
+
+  Void  xSetCodedScaleOffset      ( UInt uiFrame );
+  Void  xSetShiftParametersAndLUT ( UInt uiNumViewDim1, UInt uiNumViewDim2, UInt uiFrame, Bool bExternalReference, Double****& radLUT, Int****& raiLUT, Double***& radShiftParams, Int64***& raiShiftParams );
+  Void  xSetShiftParametersAndLUT ( UInt uiFrame );
+
+  // getting conversion parameters for disparity to virtual depth conversion
+  Void  xGetCameraShifts          ( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Double& rdCamPosShift, Double& rdPicPosShift );
+  Void  xSetPdmConversionParams   ();
+
+public:
+  // constructor and destructor
+  TAppComCamPara();
+  ~TAppComCamPara();
+
+  // initialization, check, and and update
+  Void init   ( UInt    uiNumBaseViews,
+                UInt    uiInputBitDepth,
+                UInt    uiCodedCamParsPrecision,
+                UInt    uiStartFrameId,
+                UInt    uiNumFrames,
+                Char*   pchCfgFileName,
+                Char*   pchBaseViewNumbers,
+                Char*   pchSynthViewNumbers,
+                std::vector<Int>* paiSynthViewNumbers,
+                Int     iLog2Precision );
+
+  Void init   ( UInt    uiInputBitDepth,
+                UInt    uiStartFrameId,
+                UInt    uiNumFrames,
+                Char*   pchCfgFileName,
+                Char*   pchSynthViewNumbers,
+                std::vector<Int>* paiSynthViewNumbers,
+                Int     iLog2Precision
+              );
+
+
+
+  Void check  ( Bool    bCheckViewRange,
+                Bool    bCheckFrameRange );
+  Void update ( UInt    uiFrameId );
+
+  // miscellaneous functions
+
+  Int                 synthRelNum2Idx           ( Int iRelNum );
+  Bool getLeftRightBaseView( Int iSynthViewIdx, Int &riLeftViewIdx, Int &riRightViewIdx, Int &riRelDistToLeft, Bool& rbIsBaseView );
+  Int                 getRelDistLeft            ( Int iSynthViewIdx, Int   iLeftViewIdx, Int iRightViewIdx );
+  UInt                getCurFrameId             ()  { return m_iCurrentFrameId;   }
+  static Void         convertNumberString       ( Char* pchViewNumberString, std::vector<Int>& raiViewNumbers, Double dViewNumPrec );
+
+#if SAIT_VSO_EST_A0033
+  Void xSetDispCoeff( UInt uiStartFrameId, Int iViewIdx );
+  Double getDispCoeff() { return m_dDispCoeff; }
+#endif
+
+  // function for getting parameters and parameter arrays
+  std::vector<Int>&   getBaseViewNumbers        ()  { return m_aiBaseViews;       }
+  std::vector<Int>&   getSortedBaseViewNumbers  ()  { return m_aiSortedBaseViews; }
+  std::vector<Int>&   getSynthViewNumbers       ()  { return m_aiSynthViews;      }
+  std::vector<Int>&   getRelSynthViewNumbers    ()  { return m_aiRelSynthViewsNum;}
+
+  std::vector<Int>&   getBaseId2SortedId        ()   { return m_aiBaseId2SortedId; }
+  std::vector<Int>&   getBaseSortedId2Id        ()   { return m_aiBaseSortedId2Id; }
+
+
+  Double***           getBaseViewShiftParameterD()  { return         m_adBaseViewShiftParameter;  }
+  Int***              getBaseViewShiftParameterI()  { return (Int***)m_aiBaseViewShiftParameter;  }
+
+  Double****          getSynthViewShiftLUTD     ()  { return m_adSynthViewShiftLUT;  }
+  Double****          getBaseViewShiftLUTD      ()  { return m_adBaseViewShiftLUT;   }
+  Int****             getSynthViewShiftLUTI     ()  { return m_aiSynthViewShiftLUT;  }
+  Int****             getBaseViewShiftLUTI      ()  { return m_aiBaseViewShiftLUT;   }
+
+  Bool                getVaryingCameraParameters()  { return m_bCamParsVaryOverTime;    }
+  UInt                getCamParsCodedPrecision  ()  { return m_uiCamParsCodedPrecision; }
+  std::vector<Int>&   getViewOrderIndex         ()  { return m_aiViewOrderIndex;        }
+  Int**               getCodedScale             ()  { return m_aaiCodedScale;           }
+  Int**               getCodedOffset            ()  { return m_aaiCodedOffset;          }
+
+  // parameters for virtual depth map generation
+  Int                 getPdmPrecision           ()  { return m_iPdmPrecision;           }
+  Int**               getPdmScaleNomDelta       ()  { return m_aaiPdmScaleNomDelta;     }
+  Int**               getPdmOffset              ()  { return m_aaiPdmOffset;            }
+};
+
+
+
+
+
+template <class T>
+Void TAppComCamPara::xDeleteArray( T*& rpt, UInt uiSize1, UInt uiSize2, UInt uiSize3 )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize1; uiK++ )
+    {
+      for( UInt uiL = 0; uiL < uiSize2; uiL++ )
+      {
+        for( UInt uiM = 0; uiM < uiSize3; uiM++ )
+        {
+          delete[] rpt[ uiK ][ uiL ][ uiM ];
+        }
+        delete[] rpt[ uiK ][ uiL ];
+      }
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+template <class T>
+Void TAppComCamPara::xDeleteArray( T*& rpt, UInt uiSize1, UInt uiSize2 )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize1; uiK++ )
+    {
+      for( UInt uiL = 0; uiL < uiSize2; uiL++ )
+      {
+        delete[] rpt[ uiK ][ uiL ];
+      }
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+template <class T>
+Void TAppComCamPara::xDeleteArray( T*& rpt, UInt uiSize )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize; uiK++ )
+    {
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+
+#endif // __TAPPCOMCAMPARA__
+
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/program_options_lite.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/program_options_lite.cpp	(revision 341)
@@ -0,0 +1,497 @@
+/* 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-2012, 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 <stdlib.h>
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+#include "program_options_lite.h"
+
+using namespace std;
+
+//! \ingroup TAppCommon
+//! \{
+
+namespace df
+{
+  namespace program_options_lite
+  {
+    
+    Options::~Options()
+    {
+      for(Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); it++)
+      {
+        delete *it;
+      }
+    }
+    
+    void Options::addOption(OptionBase *opt)
+    {
+      Names* names = new Names();
+      names->opt = opt;
+      string& opt_string = opt->opt_string;
+      
+      size_t opt_start = 0;
+      for (size_t opt_end = 0; opt_end != string::npos;)
+      {
+        opt_end = opt_string.find_first_of(',', opt_start);
+        bool force_short = 0;
+        if (opt_string[opt_start] == '-')
+        {
+          opt_start++;
+          force_short = 1;
+        }
+        string opt_name = opt_string.substr(opt_start, opt_end - opt_start);
+        if (force_short || opt_name.size() == 1)
+        {
+          names->opt_short.push_back(opt_name);
+          opt_short_map[opt_name].push_back(names);
+        }
+        else
+        {
+          names->opt_long.push_back(opt_name);
+          opt_long_map[opt_name].push_back(names);
+        }
+        opt_start += opt_end + 1;
+      }
+      opt_list.push_back(names);
+    }
+
+    /* Helper method to initiate adding options to Options */
+    OptionSpecific Options::addOptions()
+    {
+      return OptionSpecific(*this);
+    }
+    
+    static void setOptions(Options::NamesPtrList& opt_list, const string& value)
+    {
+      /* multiple options may be registered for the same name:
+       *   allow each to parse value */
+      for (Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); ++it)
+      {
+        (*it)->opt->parse(value);
+      }
+    }
+
+    static const char spaces[41] = "                                        ";
+    
+    /* format help text for a single option:
+     * using the formatting: "-x, --long",
+     * if a short/long option isn't specified, it is not printed
+     */
+    static void doHelpOpt(ostream& out, const Options::Names& entry, unsigned pad_short = 0)
+    {
+      pad_short = min(pad_short, 8u);
+
+      if (!entry.opt_short.empty())
+      {
+        unsigned pad = max((int)pad_short - (int)entry.opt_short.front().size(), 0);
+        out << "-" << entry.opt_short.front();
+        if (!entry.opt_long.empty())
+        {
+          out << ", ";
+        }
+        out << &(spaces[40 - pad]);
+      }
+      else
+      {
+        out << "   ";
+        out << &(spaces[40 - pad_short]);
+      }
+
+      if (!entry.opt_long.empty())
+      {
+        out << "--" << entry.opt_long.front();
+      }
+    }
+    
+    /* format the help text */
+    void doHelp(ostream& out, Options& opts, unsigned columns)
+    {
+      const unsigned pad_short = 3;
+      /* first pass: work out the longest option name */
+      unsigned max_width = 0;
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+        ostringstream line(ios_base::out);
+        doHelpOpt(line, **it, pad_short);
+        max_width = max(max_width, (unsigned) line.tellp());
+      }
+
+      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
+       *  - if the option text is longer than opt_width, place the help
+       *    text at opt_width on the next line.
+       */
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+        ostringstream line(ios_base::out);
+        line << "  ";
+        doHelpOpt(line, **it, pad_short);
+
+        const string& opt_desc = (*it)->opt->opt_desc;
+        if (opt_desc.empty())
+        {
+          /* no help text: output option, skip further processing */
+          cout << line.str() << endl;
+          continue;
+        }
+        size_t currlength = size_t(line.tellp());
+        if (currlength > opt_width)
+        {
+          /* if option text is too long (and would collide with the
+           * help text, split onto next line */
+          line << endl;
+          currlength = 0;
+        }
+        /* split up the help text, taking into account new lines,
+         *   (add opt_width of padding to each new line) */
+        for (size_t newline_pos = 0, cur_pos = 0; cur_pos != string::npos; currlength = 0)
+        {
+          /* print any required padding space for vertical alignment */
+          line << &(spaces[40 - opt_width + currlength]);
+          newline_pos = opt_desc.find_first_of('\n', newline_pos);
+          if (newline_pos != string::npos)
+          {
+            /* newline found, print substring (newline needn't be stripped) */
+            newline_pos++;
+            line << opt_desc.substr(cur_pos, newline_pos - cur_pos);
+            cur_pos = newline_pos = newline_pos;
+            continue;
+          }
+          if (cur_pos + desc_width > opt_desc.size())
+          {
+            /* no need to wrap text, remainder is less than avaliable width */
+            line << opt_desc.substr(cur_pos);
+            break;
+          }
+          /* find a suitable point to split text (avoid spliting in middle of word) */
+          size_t split_pos = opt_desc.find_last_of(' ', cur_pos + desc_width);
+          if (split_pos != string::npos)
+          {
+            /* eat up multiple space characters */
+            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;
+          if (bad_split)
+          {
+            split_pos = cur_pos + desc_width;
+          }
+          line << opt_desc.substr(cur_pos, split_pos - cur_pos);
+          
+          /* eat up any space for the start of the next line */
+          if (!bad_split)
+          {
+            split_pos = opt_desc.find_first_not_of(' ', split_pos);
+          }
+          cur_pos = newline_pos = split_pos;
+          
+          if (cur_pos >= opt_desc.size())
+          {
+            break;
+          }
+          line << endl;
+        }
+
+        cout << line.str() << endl;
+      }
+    }
+    
+    bool storePair(Options& opts, bool allow_long, bool allow_short, const string& name, const string& value)
+    {
+      bool found = false;
+      Options::NamesMap::iterator opt_it;
+      if (allow_long)
+      {
+        opt_it = opts.opt_long_map.find(name);
+        if (opt_it != opts.opt_long_map.end())
+        {
+          found = true;
+        }
+      }
+      
+      /* check for the short list */
+      if (allow_short && !(found && allow_long))
+      {
+        opt_it = opts.opt_short_map.find(name);
+        if (opt_it != opts.opt_short_map.end())
+        {
+          found = true;
+        }
+      }
+
+      if (!found)
+      {
+        /* not found */
+        cerr << "Unknown option: `" << name << "' (value:`" << value << "')" << endl;
+        return false;
+      }
+
+      setOptions((*opt_it).second, value);
+      return true;
+    }
+    
+    bool storePair(Options& opts, const string& name, const string& value)
+    {
+      return storePair(opts, true, true, name, value);
+    }
+    
+    /**
+     * returns number of extra arguments consumed
+     */
+    unsigned parseGNU(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* gnu style long options can take the forms:
+       *  --option=arg
+       *  --option arg
+       */
+      string arg(argv[0]);
+      size_t arg_opt_start = arg.find_first_not_of('-');
+      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)
+      {
+        /* no argument found => argument in argv[1] (maybe) */
+        /* xxx, need to handle case where option isn't required */
+#if 0
+        /* commented out, to return to true GNU style processing
+        * where longopts have to include an =, otherwise they are
+        * booleans */
+        if (argc == 1)
+          return 0; /* run out of argv for argument */
+        extra_argc_consumed = 1;
+#endif
+        if(!storePair(opts, true, false, option, "1"))
+        {
+          return 0;
+        }
+      }
+      else
+      {
+        /* argument occurs after option_sep */
+        string val = arg.substr(arg_opt_sep + 1);
+        storePair(opts, true, false, option, val);
+      }
+
+      return extra_argc_consumed;
+    }
+
+    unsigned parseSHORT(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* short options can take the forms:
+       *  --option arg
+       *  -option arg
+       */
+      string arg(argv[0]);
+      size_t arg_opt_start = arg.find_first_not_of('-');
+      string option = arg.substr(arg_opt_start);
+      /* lookup option */
+
+      /* argument in argv[1] */
+      /* xxx, need to handle case where option isn't required */
+      if (argc == 1)
+      {
+        cerr << "Not processing option without argument `" << option << "'" << endl;
+        return 0; /* run out of argv for argument */
+      }
+      storePair(opts, false, true, option, string(argv[1]));
+
+      return 1;
+    }
+    
+    list<const char*>
+    scanArgv(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* a list for anything that didn't get handled as an option */
+      list<const char*> non_option_arguments;
+
+      for(unsigned i = 1; i < argc; i++)
+      {
+        if (argv[i][0] != '-')
+        {
+          non_option_arguments.push_back(argv[i]);
+          continue;
+        }
+
+        if (argv[i][1] == 0)
+        {
+          /* a lone single dash is an argument (usually signifying stdin) */
+          non_option_arguments.push_back(argv[i]);
+          continue;
+        }
+
+        if (argv[i][1] != '-')
+        {
+          /* handle short (single dash) options */
+#if 0
+          i += parsePOSIX(opts, argc - i, &argv[i]);
+#else
+          i += parseSHORT(opts, argc - i, &argv[i]);
+#endif
+          continue;
+        }
+
+        if (argv[i][2] == 0)
+        {
+          /* 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]);
+      }
+
+      return non_option_arguments;
+    }
+    
+    void scanLine(Options& opts, string& line)
+    {
+      /* strip any leading whitespace */
+      size_t start = line.find_first_not_of(" \t\n\r");
+      if (start == string::npos)
+      {
+        /* blank line */
+        return;
+      }
+      if (line[start] == '#')
+      {
+        /* comment line */
+        return;
+      }
+      /* look for first whitespace or ':' after the option end */
+      size_t option_end = line.find_first_of(": \t\n\r",start);
+      string option = line.substr(start, option_end - start);
+
+      /* look for ':', eat up any whitespace first */
+      start = line.find_first_not_of(" \t\n\r", option_end);
+      if (start == string::npos)
+      {
+        /* error: badly formatted line */
+        return;
+      }
+      if (line[start] != ':')
+      {
+        /* error: badly formatted line */
+        return;
+      }
+
+      /* look for start of value string -- eat up any leading whitespace */
+      start = line.find_first_not_of(" \t\n\r", ++start);
+      if (start == string::npos)
+      {
+        /* error: badly formatted line */
+        return;
+      }
+
+      /* extract the value part, which may contain embedded spaces
+       * by searching for a word at a time, until we hit a comment or end of line */
+      size_t value_end = start;
+      do
+      {
+        if (line[value_end] == '#')
+        {
+          /* rest of line is a comment */
+          value_end--;
+          break;
+        }
+        value_end = line.find_first_of(" \t\n\r", value_end);
+        /* consume any white space, incase there is another word.
+         * any trailing whitespace will be removed shortly */
+        value_end = line.find_first_not_of(" \t\n\r", value_end);
+      }
+      while (value_end != string::npos);
+      /* strip any trailing space from value*/
+      value_end = line.find_last_not_of(" \t\n\r", value_end);
+
+      string value;
+      if (value_end >= start)
+      {
+        value = line.substr(start, value_end +1 - start);
+      }
+      else
+      {
+        /* error: no value */
+        return;
+      }
+
+      /* store the value in option */
+      storePair(opts, true, false, option, value);
+    }
+
+    void scanFile(Options& opts, istream& in)
+    {
+      do
+      {
+        string line;
+        getline(in, line);
+        scanLine(opts, line);
+      }
+      while(!!in);
+    }
+
+    /* for all options in opts, set their storage to their specified
+     * default value */
+    void setDefaults(Options& opts)
+    {
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+        (*it)->opt->setDefault();
+      }
+    }
+
+    void parseConfigFile(Options& opts, const string& filename)
+    {
+      ifstream cfgstream(filename.c_str(), ifstream::in);
+      if (!cfgstream)
+      {
+        cerr << "Failed to open config file: `" << filename << "'" << endl;
+        exit(EXIT_FAILURE);
+      }
+      scanFile(opts, cfgstream);
+    }
+
+  };
+};
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/program_options_lite.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TAppCommon/program_options_lite.h	(revision 341)
@@ -0,0 +1,378 @@
+/* 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-2012, 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 <iostream>
+#include <sstream>
+#include <string>
+#include <vector>
+#include <list>
+#include <map>
+#include <stdlib.h>
+#include <errno.h>
+#include <cstring>
+#include <math.h>
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+//! \ingroup TAppCommon
+//! \{
+
+
+namespace df
+{
+  namespace program_options_lite
+  {
+    struct Options;
+    
+    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);
+    void setDefaults(Options& opts);
+    void parseConfigFile(Options& opts, const std::string& filename);
+    bool storePair(Options& opts, const std::string& name, const std::string& value);
+    
+    /** OptionBase: Virtual base class for storing information relating to a
+     * specific option This base class describes common elements.  Type specific
+     * information should be stored in a derived class. */
+    struct OptionBase
+    {
+      OptionBase(const std::string& name, const std::string& desc)
+      : opt_string(name), opt_desc(desc)
+      {};
+      
+      virtual ~OptionBase() {}
+      
+      /* parse argument arg, to obtain a value for the option */
+      virtual void parse(const std::string& arg) = 0;
+      /* set the argument to the default value */
+      virtual void setDefault() = 0;
+      
+      std::string opt_string;
+      std::string opt_desc;
+    };
+    
+    /** Type specific option storage */
+    template<typename T>
+    struct Option : public OptionBase
+    {
+      Option(const std::string& name, T& storage, T default_val, const std::string& desc)
+      : OptionBase(name, desc), opt_storage(storage), opt_default_val(default_val)
+      {}
+      
+      void parse(const std::string& arg);
+      
+      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)
+    {
+      std::istringstream arg_ss (arg,std::istringstream::in);
+      arg_ss >> opt_storage;
+    }
+    
+    /* string parsing is specialized -- copy the whole string, not just the
+     * first word */
+    template<>
+    inline void
+    Option<std::string>::parse(const std::string& arg)
+    {
+      opt_storage = arg;
+    }
+    
+    template<>
+    inline void
+      Option<char*>::parse(const std::string& arg)
+    {
+      opt_storage = arg.empty() ? NULL : strdup(arg.c_str()) ;
+    }
+
+    template<>
+    inline void
+      Option< std::vector<char*> >::parse(const std::string& arg)
+    {
+      opt_storage.clear(); 
+
+      char* pcStart = (char*) arg.data();      
+      char* pcEnd = strtok (pcStart," ");
+
+      while (pcEnd != NULL)
+      {
+        size_t uiStringLength = pcEnd - pcStart;
+        char* pcNewStr = (char*) malloc( uiStringLength + 1 );
+        strncpy( pcNewStr, pcStart, uiStringLength); 
+        pcNewStr[uiStringLength] = '\0'; 
+        pcStart = pcEnd+1; 
+        pcEnd = strtok (NULL, " ,.-");
+        opt_storage.push_back( pcNewStr ); 
+      }      
+    }
+
+
+    template<>    
+    inline void
+      Option< std::vector<double> >::parse(const std::string& arg)
+    {
+      char* pcNextStart = (char*) arg.data();
+      char* pcEnd = pcNextStart + arg.length();
+
+      char* pcOldStart = 0; 
+
+      size_t iIdx = 0; 
+
+      while (pcNextStart < pcEnd)
+      {
+        errno = 0; 
+
+        if ( iIdx < opt_storage.size() )
+        {
+          opt_storage[iIdx] = strtod(pcNextStart, &pcNextStart);
+        }
+        else
+        {
+          opt_storage.push_back( strtod(pcNextStart, &pcNextStart)) ;
+        }
+        iIdx++; 
+
+        if ( errno == ERANGE || (pcNextStart == pcOldStart) )
+        {
+          std::cerr << "Error Parsing Doubles: `" << arg << "'" << std::endl;
+          exit(EXIT_FAILURE);    
+        };   
+        while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
+        pcOldStart = pcNextStart; 
+
+      }
+    }
+
+    template<>
+    inline void
+      Option< std::vector<int> >::parse(const std::string& arg)
+    {
+      opt_storage.clear();
+
+
+      char* pcNextStart = (char*) arg.data();
+      char* pcEnd = pcNextStart + arg.length();
+
+      char* pcOldStart = 0; 
+
+      size_t iIdx = 0; 
+
+
+      while (pcNextStart < pcEnd)
+      {
+
+        if ( iIdx < opt_storage.size() )
+        {
+          opt_storage[iIdx] = (int) strtol(pcNextStart, &pcNextStart,10);
+        }
+        else
+        {
+          opt_storage.push_back( (int) strtol(pcNextStart, &pcNextStart,10)) ;
+        }
+        iIdx++; 
+        if ( errno == ERANGE || (pcNextStart == pcOldStart) )
+        {
+          std::cerr << "Error Parsing Integers: `" << arg << "'" << std::endl;
+          exit(EXIT_FAILURE);
+        };   
+        while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
+        pcOldStart = pcNextStart;
+      }
+    }
+
+
+    template<>
+    inline void
+      Option< std::vector<bool> >::parse(const std::string& arg)
+    {
+      char* pcNextStart = (char*) arg.data();
+      char* pcEnd = pcNextStart + arg.length();
+
+      char* pcOldStart = 0; 
+
+      size_t iIdx = 0; 
+
+      while (pcNextStart < pcEnd)
+      {
+        if ( iIdx < opt_storage.size() )
+        {
+          opt_storage[iIdx] = (strtol(pcNextStart, &pcNextStart,10) != 0);
+        }
+        else
+        {
+          opt_storage.push_back(strtol(pcNextStart, &pcNextStart,10) != 0) ;
+        }
+        iIdx++; 
+
+        if ( errno == ERANGE || (pcNextStart == pcOldStart) )
+        {
+          std::cerr << "Error Parsing Bools: `" << arg << "'" << std::endl;
+          exit(EXIT_FAILURE);
+        };   
+        while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
+        pcOldStart = pcNextStart;
+      }
+    }
+
+    /** Option class for argument handling using a user provided function */
+    struct OptionFunc : public OptionBase
+    {
+      typedef void (Func)(Options&, const std::string&);
+      
+      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 setDefault()
+      {
+        return;
+      }
+      
+    private:
+      Options& parent;
+      void (*func)(Options&, const std::string&);
+    };
+    
+    class OptionSpecific;
+    struct Options
+    {
+      ~Options();
+      
+      OptionSpecific addOptions();
+      
+      struct Names
+      {
+        Names() : opt(0) {};
+        ~Names()
+        {
+          if (opt)
+            delete opt;
+        }
+        std::list<std::string> opt_long;
+        std::list<std::string> opt_short;
+        OptionBase* opt;
+      };
+
+      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
+    {
+    public:
+      OptionSpecific(Options& parent_) : parent(parent_) {}
+      
+      /**
+       * Add option described by name to the parent Options list,
+       *   with storage for the option's value
+       *   with default_val as the default value
+       *   with desc as an optional help description
+       */
+      template<typename T>
+      OptionSpecific&
+      operator()(const std::string& name, T& storage, T default_val, const std::string& desc = "")
+      {
+        parent.addOption(new Option<T>(name, storage, default_val, desc));
+        return *this;
+      }
+      
+      template<typename T>
+      OptionSpecific&
+        operator()(const std::string& name, std::vector<T>& storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
+      {
+        std::string cNameBuffer;
+        std::string cDescriptionBuffer;
+
+        cNameBuffer       .resize( name.size() + 10 );
+        cDescriptionBuffer.resize( desc.size() + 10 );
+
+        storage.resize(uiMaxNum);
+        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
+        {
+          // isn't there are sprintf function for string??
+          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
+          sprintf((char*) cDescriptionBuffer.c_str(),desc.c_str(),uiK,uiK);
+
+          parent.addOption(new Option<T>( cNameBuffer, (storage[uiK]), default_val, cDescriptionBuffer ));
+        }
+
+        return *this;
+      }
+
+      /**
+       * Add option described by name to the parent Options list,
+       *   with desc as an optional help description
+       * instead of storing the value somewhere, a function of type
+       * OptionFunc::Func is called.  It is upto this function to correctly
+       * handle evaluating the option's value.
+       */
+      OptionSpecific&
+      operator()(const std::string& name, OptionFunc::Func *func, const std::string& desc = "")
+      {
+        parent.addOption(new OptionFunc(name, parent, func, desc));
+        return *this;
+      }
+    private:
+      Options& parent;
+    };
+    
+  }; /* namespace: program_options_lite */
+}; /* namespace: df */
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/AccessUnit.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/AccessUnit.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/AccessUnit.h	(revision 341)
@@ -0,0 +1,69 @@
+/* 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-2012, 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     AccessUnit.h
+ \brief    Access Unit class (header)
+ */
+
+#pragma once
+
+#include <list>
+#include "NAL.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * An AccessUnit is a list of one or more NAL units, according to the
+ * working draft.  All NAL units within the object belong to the same
+ * access unit.
+ *
+ * NALUnits held in the AccessUnit list are in EBSP format.  Attempting
+ * to insert an OutputNALUnit into the access unit will automatically cause
+ * the nalunit to have its headers written and anti-emulation performed.
+ *
+ * The AccessUnit owns all pointers stored within.  Destroying the
+ * AccessUnit will delete all contained objects.
+ */
+class AccessUnit : public std::list<NALUnitEBSP*>
+{
+public:
+  ~AccessUnit()
+  {
+    for (AccessUnit::iterator it = this->begin(); it != this->end(); it++)
+      delete *it;
+  }
+};
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/CommonDef.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/CommonDef.h	(revision 341)
@@ -0,0 +1,521 @@
+/* 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-2012, 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     CommonDef.h
+    \brief    Defines constants, macros and tool parameters
+*/
+
+#ifndef __COMMONDEF__
+#define __COMMONDEF__
+
+#include <algorithm>
+
+#if _MSC_VER > 1000
+// disable "signed and unsigned mismatch"
+#pragma warning( disable : 4018 )
+// disable bool coercion "performance warning"
+#pragma warning( disable : 4800 )
+#endif // _MSC_VER > 1000
+#include "TypeDef.h"
+
+#include <stdio.h>
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Version information
+// ====================================================================================================================
+
+#define HM_VERSION        "6.1"
+#define NV_VERSION        "6.2"                  ///< Current software version
+
+// ====================================================================================================================
+// Platform information
+// ====================================================================================================================
+
+#ifdef __GNUC__
+#define NVM_COMPILEDBY  "[GCC %d.%d.%d]", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__
+#ifdef __IA64__
+#define NVM_ONARCH    "[on 64-bit] "
+#else
+#define NVM_ONARCH    "[on 32-bit] "
+#endif
+#endif
+
+#ifdef __INTEL_COMPILER
+#define NVM_COMPILEDBY  "[ICC %d]", __INTEL_COMPILER
+#elif  _MSC_VER
+#define NVM_COMPILEDBY  "[VS %d]", _MSC_VER
+#endif
+
+#ifndef NVM_COMPILEDBY
+#define NVM_COMPILEDBY "[Unk-CXX]"
+#endif
+
+#ifdef _WIN32
+#define NVM_ONOS        "[Windows]"
+#elif  __linux
+#define NVM_ONOS        "[Linux]"
+#elif  __CYGWIN__
+#define NVM_ONOS        "[Cygwin]"
+#elif __APPLE__
+#define NVM_ONOS        "[Mac OS X]"
+#else
+#define NVM_ONOS "[Unk-OS]"
+#endif
+
+#define NVM_BITS          "[%d bit] ", (sizeof(void*) == 8 ? 64 : 32) ///< used for checking 64-bit O/S
+
+#ifndef NULL
+#define NULL              0
+#endif
+
+// ====================================================================================================================
+// Common constants
+// ====================================================================================================================
+
+#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                 4           ///< max. value of multiple reference frames
+#define MAX_NUM_REF_LC              8           ///< max. value of combined reference frames
+
+#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_DOUBLE                  1.7e+308    ///< max. value of double-type value
+
+#define MIN_QP                      0
+#define MAX_QP                      51
+
+#define NOT_VALID                   -1
+
+// ====================================================================================================================
+// 3D constants
+// ====================================================================================================================
+#define MAX_VIEW_NUM                10
+
+#if ( H3D_IVMP || H3D_IVRP )
+#define DEPTH_MAP_GENERATION        1
+#define PDM_REMOVE_DEPENDENCE       1      //bug-fix for DMDV JCT2-A0095
+#else
+#define DEPTH_MAP_GENERATION        0
+#endif
+
+//>>>>> generation and usage of virtual prediction depth maps >>>>>
+#define PDM_ONE_DEPTH_PER_PU              1         // use only a single depth for a prediction unit (in update)
+#define PDM_NO_INTER_UPDATE               1         // no update for inter (but not inter-view) predicted blocks
+#define PDM_MERGE_POS                     0         // position of pdm in merge list (0..4)
+
+#if H3D_IVMP&!H3D_NBDV
+#define PDM_AMVP_POS                      0         // position of pdm in amvp list  (0..3)
+#else
+#define PDM_AMVP_POS                      2         // position of pdm in amvp list  (0..3)
+#endif
+#define PDM_OUTPUT_PRED_DEPTH_MAP         0         // output prediction depth map (for debugging)
+
+#define PDM_INTERNAL_CALC_BIT_DEPTH       31        // bit depth for internal calculations (32 - 1 for signed values)
+#define PDM_BITDEPTH_VIRT_DEPTH           15        // bit depth for virtual depth storage (16 - 1 for signed values)
+#define PDM_LOG2_MAX_ABS_NORMAL_DISPARITY 8         // maximum absolute normal disparity = 256 (for setting accuracy)
+#define PDM_VIRT_DEPTH_PRECISION          4         // must be greater than or equal to 2 (since MVs are given in quarter-pel units)
+
+#define PDM_INTER_CALC_SHIFT              ( PDM_INTERNAL_CALC_BIT_DEPTH - PDM_BITDEPTH_VIRT_DEPTH )         // avoids overflow
+#define PDM_LOG4_SCALE_DENOMINATOR        ( PDM_LOG2_MAX_ABS_NORMAL_DISPARITY + PDM_VIRT_DEPTH_PRECISION )  // accuracy of scaling factor
+#define PDM_OFFSET_SHIFT                  ( PDM_LOG2_MAX_ABS_NORMAL_DISPARITY )                             // accuracy of offset
+
+#define PDM_MAX_ABS_VIRT_DEPTH            (  ( 1 << PDM_BITDEPTH_VIRT_DEPTH ) - 1 )
+#define PDM_UNDEFINED_DEPTH               ( -( 1 << PDM_BITDEPTH_VIRT_DEPTH )     )
+
+#define PDM_USE_FOR_IVIEW                 1
+#define PDM_USE_FOR_INTER                 2
+#define PDM_USE_FOR_MERGE                 4
+
+#define PDM_SUBSAMPLING_EXP               2         // subsampling factor is 2^PDM_SUBSAMPLING_EXP
+#define PDM_SUB_SAMP_EXP_X(Pdm)           ((Pdm)==1?PDM_SUBSAMPLING_EXP:0)
+#define PDM_SUB_SAMP_EXP_Y(Pdm)           ((Pdm)==1?PDM_SUBSAMPLING_EXP:0)
+//<<<<< generation and usage of virtual prediction depth maps <<<<<
+
+#define OUTPUT_RESIDUAL_PICTURES          0         // output residual pictures (for debugging)
+
+#define STD_CAM_PARAMETERS_PRECISION 5        ///< quarter luma sample accuarcy for derived disparities (as default)
+
+#define LOG2_DISP_PREC_LUT           2          ///< log2 of disparity precision used in integer disparity LUTs
+
+// ====================================================================================================================
+// VPS constants
+// ====================================================================================================================
+#if QC_MVHEVC_B0046
+#define MAX_LAYER_NUM                     MAX_VIEW_NUM
+#endif
+#if VIDYO_VPS_INTEGRATION
+#define MAX_LAYER_NUM                     MAX_VIEW_NUM
+#define VPS_EXTENSION_TYPE_MULTI_VIEW     0
+#endif
+
+// ====================================================================================================================
+// Macro functions
+// ====================================================================================================================
+extern UInt g_uiIBDI_MAX;
+
+/** clip x, such that 0 <= x <= #g_uiIBDI_MAX */
+template <typename T> inline T Clip(T x) { return std::min<T>(T(g_uiIBDI_MAX), 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
+
+#define DATA_ALIGN                  1                                                                 ///< use 32-bit aligned malloc/free
+#if     DATA_ALIGN && _WIN32 && ( _MSC_VER > 1300 )
+#define xMalloc( type, len )        _aligned_malloc( sizeof(type)*(len), 32 )
+#define xFree( ptr )                _aligned_free  ( ptr )
+#else
+#define xMalloc( type, len )        malloc   ( sizeof(type)*(len) )
+#define xFree( ptr )                free     ( ptr )
+#endif
+
+#define FATAL_ERROR_0(MESSAGE, EXITCODE)                      \
+{                                                             \
+  printf(MESSAGE);                                            \
+  exit(EXITCODE);                                             \
+}
+
+#define ROF( exp )            \
+{                             \
+  if( !( exp ) )              \
+{                           \
+  assert( 0 );              \
+  return -1;                \
+}                           \
+}
+
+#define ROT( exp )            \
+{                             \
+  if( ( exp ) )               \
+{                           \
+  assert( 0 );              \
+  return -1;                \
+}                           \
+}
+
+#define ROFS( exp )           \
+{                             \
+  if( !( exp ) )              \
+{                           \
+  return -1;                \
+}                           \
+}
+
+#define ROTS( exp )           \
+{                             \
+  if( ( exp ) )               \
+{                           \
+  return -1;                \
+}                           \
+}
+
+#define ROFR( exp, retVal )   \
+{                             \
+  if( !( exp ) )              \
+{                           \
+  assert( 0 );              \
+  return retVal;            \
+}                           \
+}
+
+#define ROTR( exp, retVal )   \
+{                             \
+  if( ( exp ) )               \
+{                           \
+  assert( 0 );              \
+  return retVal;            \
+}                           \
+}
+
+#define ROFRS( exp, retVal )  \
+{                             \
+  if( !( exp ) )              \
+{                           \
+  return retVal;            \
+}                           \
+}
+
+#define ROTRS( exp, retVal )  \
+{                             \
+  if( ( exp ) )               \
+{                           \
+  return retVal;            \
+}                           \
+}
+
+#define ROFV( exp )           \
+{                             \
+  if( !( exp ) )              \
+{                           \
+  assert( 0 );              \
+  return;                   \
+}                           \
+}
+
+#define ROTV( exp )           \
+{                             \
+  if( ( exp ) )               \
+{                           \
+  assert( 0 );              \
+  return;                   \
+}                           \
+}
+
+#define ROFVS( exp )          \
+{                             \
+  if( !( exp ) )              \
+{                           \
+  return;                   \
+}                           \
+}
+
+#define ROTVS( exp )          \
+{                             \
+  if( ( exp ) )               \
+{                           \
+  return;                   \
+}                           \
+}
+
+#define RNOK( exp )                   \
+{                                     \
+  const ErrVal nMSysRetVal = ( exp ); \
+  if( 0 != nMSysRetVal )              \
+{                                   \
+  assert( 0 );                      \
+  return nMSysRetVal;               \
+}                                   \
+}
+
+#define RNOKR( exp, retVal )        \
+{                                   \
+  if( 0 != ( exp ) )                \
+{                                 \
+  assert( 0 );                    \
+  return retVal;                  \
+}                                 \
+}
+
+#define RNOKS( exp )                  \
+{                                     \
+  const ErrVal nMSysRetVal = ( exp ); \
+  if( 0 != nMSysRetVal )              \
+{                                   \
+  return nMSysRetVal;               \
+}                                   \
+}
+
+#define RNOKRS( exp, retVal )       \
+{                                   \
+  if( 0 != ( exp ) )                \
+{                                 \
+  return retVal;                  \
+}                                 \
+}
+
+#define RNOKV( exp )                \
+{                                   \
+  if( 0 != ( exp ) )                \
+{                                 \
+  assert( 0 );                    \
+  return;                         \
+}                                 \
+}
+
+#define RNOKVS( exp )               \
+{                                   \
+  if( 0 != ( exp ) )                \
+{                                 \
+  return;                         \
+}                                 \
+}
+
+#define ANOK( exp )                 \
+{                                   \
+  if( 0 != ( exp ) )                \
+{                                 \
+  assert( 0 );                    \
+}                                 \
+}
+
+#define AOF( exp )                  \
+{                                   \
+  if( !( exp ) )                    \
+{                                 \
+  assert( 0 );                    \
+}                                 \
+}
+
+#define AOT( exp )            \
+{                             \
+  if( ( exp ) )               \
+{                           \
+  assert( 0 );              \
+}                           \
+}
+
+template <typename T>
+__inline T gSign(const T& t)
+{
+  if( t == 0 )
+    return T(0);
+  else
+    return (t < 0) ? T(-1) : T(1);
+}
+
+#define Max(x, y)                   ((x)>(y)?(x):(y))                                                 ///< max of (x, y)
+#define Min(x, y)                   ((x)<(y)?(x):(y))                                                 ///< min of (x, y)
+#define Median(a,b,c)               ((a)>(b)?(a)>(c)?(b)>(c)?(b):(c):(a):(b)>(c)?(a)>(c)?(a):(c):(b)) ///< 3-point median
+#define Clip(x)                     ( Min(g_uiIBDI_MAX, Max( 0, (x)) ) )                              ///< clip with bit-depth range
+#define Clip3( MinVal, MaxVal, a)   ( ((a)<(MinVal)) ? (MinVal) : (((a)>(MaxVal)) ? (MaxVal) :(a)) )  ///< general min/max clip
+#define RemoveBitIncrement(x)       ( (x + ( (1 << g_uiBitIncrement) >> 1 )) >> g_uiBitIncrement )     ///< Remove Bit increment
+
+#if SAIT_VSO_EST_A0033
+#define ROUND(a)  (((a) < 0)? (int)((a) - 0.5) : (int)((a) + 0.5))
+#endif
+
+// ====================================================================================================================
+// Coding tool configuration
+// ====================================================================================================================
+
+// AMVP: advanced motion vector prediction
+#define AMVP_MAX_NUM_CANDS          2           ///< max number of final candidates
+#if H3D_IVMP
+#define AMVP_MAX_NUM_CANDS_MEM      4           ///< max number of candidates
+#else
+#define AMVP_MAX_NUM_CANDS_MEM      3           ///< max number of candidates
+#endif
+// MERGE
+#define MRG_MAX_NUM_CANDS           5
+#if H3D_IVMP
+#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                  8           ///< 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
+
+// IBDI range restriction for skipping clip
+#define IBDI_NOCLIP_RANGE           0           ///< restrict max. value after IBDI to skip clip
+
+// Early-skip threshold (encoder)
+#define EARLY_SKIP_THRES            1.50        ///< if RD < thres*avg[BestSkipRD]
+
+#define MAX_NUM_REF_PICS 16
+
+
+enum NalUnitType
+{
+  NAL_UNIT_UNSPECIFIED_0 = 0,
+  NAL_UNIT_CODED_SLICE,
+#if QC_REM_IDV_B0046
+  NAL_UNIT_RESERVED,
+#else
+  NAL_UNIT_CODED_SLICE_IDV,
+#endif
+  NAL_UNIT_CODED_SLICE_TLA,
+  NAL_UNIT_CODED_SLICE_CRA,
+  NAL_UNIT_CODED_SLICE_IDR,
+  NAL_UNIT_SEI,
+  NAL_UNIT_SPS,
+  NAL_UNIT_PPS,
+  NAL_UNIT_ACCESS_UNIT_DELIMITER,
+  NAL_UNIT_RESERVED_10,
+  NAL_UNIT_RESERVED_11,
+  NAL_UNIT_FILLER_DATA,
+  NAL_UNIT_RESERVED_13,
+  NAL_UNIT_APS,
+  NAL_UNIT_RESERVED_15,
+  NAL_UNIT_RESERVED_16,
+  NAL_UNIT_RESERVED_17,
+  NAL_UNIT_RESERVED_18,
+  NAL_UNIT_RESERVED_19,
+  NAL_UNIT_RESERVED_20,
+  NAL_UNIT_RESERVED_21,
+  NAL_UNIT_RESERVED_22,
+  NAL_UNIT_RESERVED_23,
+  NAL_UNIT_UNSPECIFIED_24,
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  NAL_UNIT_VPS,
+#else
+  NAL_UNIT_UNSPECIFIED_25,
+#endif
+  NAL_UNIT_UNSPECIFIED_26,
+  NAL_UNIT_UNSPECIFIED_27,
+  NAL_UNIT_UNSPECIFIED_28,
+  NAL_UNIT_UNSPECIFIED_29,
+  NAL_UNIT_UNSPECIFIED_30,
+  NAL_UNIT_UNSPECIFIED_31,
+  NAL_UNIT_INVALID,
+};
+
+//PICYUV
+#define PICYUV_PAD         16
+
+//RENDERER
+#define REN_LUMA_MARGIN   ( g_uiMaxCUWidth + PICYUV_PAD )
+#define REN_VDWEIGHT_PREC  8
+#define REN_IS_FILLED     ( 1 << REN_VDWEIGHT_PREC )
+#define REN_USED_PEL       g_uiIBDI_MAX
+#define REN_UNUSED_PEL     0
+#define REN_IS_HOLE        0
+
+
+typedef Int64 PicOrderCnt;
+
+//! \}
+
+#endif // end of #ifndef  __COMMONDEF__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel.cpp	(revision 341)
@@ -0,0 +1,129 @@
+/* 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-2012, 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     ContextModel.cpp
+    \brief    context model class
+*/
+
+#include <algorithm>
+
+#include "ContextModel.h"
+
+using namespace std;
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - initialize context model with respect to QP and initialization value
+ .
+ \param  qp         input QP value
+ \param  initValue  8 bit initialization value
+ */
+Void ContextModel::init( Int qp, Int initValue )
+{
+  qp = Clip3(0, 51, qp);
+
+  Int  slope      = (initValue>>4)*5 - 45;
+  Int  offset     = ((initValue&15)<<3)-16;
+  Int  initState  =  min( max( 1, ( ( ( slope * qp ) >> 4 ) + offset ) ), 126 );
+  UInt mpState    = (initState >= 64 );
+  m_ucState       = ( (mpState? (initState - 64):(63 - initState)) <<1) + mpState;
+}
+
+const UChar ContextModel::m_aucNextStateMPS[ 128 ] =
+{
+  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, 58, 59, 60, 61, 62, 63, 64, 65,
+  66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
+  82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
+  98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
+  114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 124, 125, 126, 127
+};
+
+const UChar ContextModel::m_aucNextStateLPS[ 128 ] =
+{
+  1, 0, 0, 1, 2, 3, 4, 5, 4, 5, 8, 9, 8, 9, 10, 11,
+  12, 13, 14, 15, 16, 17, 18, 19, 18, 19, 22, 23, 22, 23, 24, 25,
+  26, 27, 26, 27, 30, 31, 30, 31, 32, 33, 32, 33, 36, 37, 36, 37,
+  38, 39, 38, 39, 42, 43, 42, 43, 44, 45, 44, 45, 46, 47, 48, 49,
+  48, 49, 50, 51, 52, 53, 52, 53, 54, 55, 54, 55, 56, 57, 58, 59,
+  58, 59, 60, 61, 60, 61, 60, 61, 62, 63, 64, 65, 64, 65, 66, 67,
+  66, 67, 66, 67, 68, 69, 68, 69, 70, 71, 70, 71, 70, 71, 72, 73,
+  72, 73, 72, 73, 74, 75, 74, 75, 74, 75, 76, 77, 76, 77, 126, 127
+};
+
+#if FAST_BIT_EST
+UChar ContextModel::m_nextState[128][2];
+
+Void ContextModel::buildNextStateTable()
+{
+  for (Int i = 0; i < 128; i++)
+  {
+    for (Int j = 0; j < 2; j++)
+    {
+      m_nextState[i][j] = ((i&1) == j) ? m_aucNextStateMPS[i] : m_aucNextStateLPS[i];
+    }
+  }
+}
+#endif
+
+const Int ContextModel::m_entropyBits[128] =
+{
+#if FAST_BIT_EST
+  // Corrected table, most notably for last state
+  0x07b23, 0x085f9, 0x074a0, 0x08cbc, 0x06ee4, 0x09354, 0x067f4, 0x09c1b, 0x060b0, 0x0a62a, 0x05a9c, 0x0af5b, 0x0548d, 0x0b955, 0x04f56, 0x0c2a9,
+  0x04a87, 0x0cbf7, 0x045d6, 0x0d5c3, 0x04144, 0x0e01b, 0x03d88, 0x0e937, 0x039e0, 0x0f2cd, 0x03663, 0x0fc9e, 0x03347, 0x10600, 0x03050, 0x10f95,
+  0x02d4d, 0x11a02, 0x02ad3, 0x12333, 0x0286e, 0x12cad, 0x02604, 0x136df, 0x02425, 0x13f48, 0x021f4, 0x149c4, 0x0203e, 0x1527b, 0x01e4d, 0x15d00,
+  0x01c99, 0x166de, 0x01b18, 0x17017, 0x019a5, 0x17988, 0x01841, 0x18327, 0x016df, 0x18d50, 0x015d9, 0x19547, 0x0147c, 0x1a083, 0x0138e, 0x1a8a3,
+  0x01251, 0x1b418, 0x01166, 0x1bd27, 0x01068, 0x1c77b, 0x00f7f, 0x1d18e, 0x00eda, 0x1d91a, 0x00e19, 0x1e254, 0x00d4f, 0x1ec9a, 0x00c90, 0x1f6e0,
+  0x00c01, 0x1fef8, 0x00b5f, 0x208b1, 0x00ab6, 0x21362, 0x00a15, 0x21e46, 0x00988, 0x2285d, 0x00934, 0x22ea8, 0x008a8, 0x239b2, 0x0081d, 0x24577,
+  0x007c9, 0x24ce6, 0x00763, 0x25663, 0x00710, 0x25e8f, 0x006a0, 0x26a26, 0x00672, 0x26f23, 0x005e8, 0x27ef8, 0x005ba, 0x284b5, 0x0055e, 0x29057,
+  0x0050c, 0x29bab, 0x004c1, 0x2a674, 0x004a7, 0x2aa5e, 0x0046f, 0x2b32f, 0x0041f, 0x2c0ad, 0x003e7, 0x2ca8d, 0x003ba, 0x2d323, 0x0010c, 0x3bfbb
+#else
+  0x08000, 0x08000, 0x076da, 0x089a0, 0x06e92, 0x09340, 0x0670a, 0x09cdf, 0x06029, 0x0a67f, 0x059dd, 0x0b01f, 0x05413, 0x0b9bf, 0x04ebf, 0x0c35f,
+  0x049d3, 0x0ccff, 0x04546, 0x0d69e, 0x0410d, 0x0e03e, 0x03d22, 0x0e9de, 0x0397d, 0x0f37e, 0x03619, 0x0fd1e, 0x032ee, 0x106be, 0x02ffa, 0x1105d,
+  0x02d37, 0x119fd, 0x02aa2, 0x1239d, 0x02836, 0x12d3d, 0x025f2, 0x136dd, 0x023d1, 0x1407c, 0x021d2, 0x14a1c, 0x01ff2, 0x153bc, 0x01e2f, 0x15d5c,
+  0x01c87, 0x166fc, 0x01af7, 0x1709b, 0x0197f, 0x17a3b, 0x0181d, 0x183db, 0x016d0, 0x18d7b, 0x01595, 0x1971b, 0x0146c, 0x1a0bb, 0x01354, 0x1aa5a,
+  0x0124c, 0x1b3fa, 0x01153, 0x1bd9a, 0x01067, 0x1c73a, 0x00f89, 0x1d0da, 0x00eb7, 0x1da79, 0x00df0, 0x1e419, 0x00d34, 0x1edb9, 0x00c82, 0x1f759,
+  0x00bda, 0x200f9, 0x00b3c, 0x20a99, 0x00aa5, 0x21438, 0x00a17, 0x21dd8, 0x00990, 0x22778, 0x00911, 0x23118, 0x00898, 0x23ab8, 0x00826, 0x24458,
+  0x007ba, 0x24df7, 0x00753, 0x25797, 0x006f2, 0x26137, 0x00696, 0x26ad7, 0x0063f, 0x27477, 0x005ed, 0x27e17, 0x0059f, 0x287b6, 0x00554, 0x29156,
+  0x0050e, 0x29af6, 0x004cc, 0x2a497, 0x0048d, 0x2ae35, 0x00451, 0x2b7d6, 0x00418, 0x2c176, 0x003e2, 0x2cb15, 0x003af, 0x2d4b5, 0x0037f, 0x2de55
+#endif
+};
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel.h	(revision 341)
@@ -0,0 +1,113 @@
+/* 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-2012, 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     ContextModel.h
+    \brief    context model class (header)
+*/
+
+#ifndef __CONTEXT_MODEL__
+#define __CONTEXT_MODEL__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// context model class
+class ContextModel
+{
+public:
+#if CABAC_INIT_FLAG
+  ContextModel  ()                        { m_ucState = 0; m_binsCoded = 0; }
+#else
+  ContextModel  ()                        { m_ucState = 0;             }
+#endif
+  ~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 )
+  {
+    m_ucState = m_nextState[m_ucState][binVal];
+  }
+  static Void buildNextStateTable();
+  static Int getEntropyBitsTrm( Int val ) { return m_entropyBits[126 ^ val]; }
+#endif
+#if CABAC_INIT_FLAG
+  Void setBinsCoded(UInt val)   { m_binsCoded = val;  }
+  UInt getBinsCoded()           { return m_binsCoded;   }
+#endif
+  
+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 ];
+#if FAST_BIT_EST
+  static UChar m_nextState[128][2];
+#endif
+#if CABAC_INIT_FLAG
+  UInt          m_binsCoded;
+#endif
+};
+
+//! \}
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 341)
@@ -0,0 +1,124 @@
+/* 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-2012, 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     ContextModel3DBuffer.cpp
+    \brief    context model 3D buffer class
+*/
+
+#include "ContextModel3DBuffer.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+ContextModel3DBuffer::ContextModel3DBuffer( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX, ContextModel *basePtr, Int &count )
+: m_sizeX  ( uiSizeX )
+, m_sizeXY ( uiSizeX * uiSizeY )
+, m_sizeXYZ( uiSizeX * uiSizeY * uiSizeZ )
+{
+  // allocate 3D buffer
+  m_contextModel = basePtr;
+  count += m_sizeXYZ;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * Initialize 3D buffer with respect to slicetype, QP and given initial probability table
+ *
+ * \param  eSliceType      slice type
+ * \param  iQp             input QP value
+ * \param  psCtxModel      given probability table
+ */
+Void ContextModel3DBuffer::initBuffer( SliceType sliceType, Int qp, UChar* ctxModel )
+{
+  ctxModel += sliceType * m_sizeXYZ;
+  
+  for ( Int n = 0; n < m_sizeXYZ; n++ )
+  {
+    m_contextModel[ n ].init( qp, ctxModel[ n ] );
+#if CABAC_INIT_FLAG
+    m_contextModel[ n ].setBinsCoded( 0 );
+#endif
+  }
+}
+
+#if CABAC_INIT_FLAG
+/**
+ * Calculate the cost of choosing a probability table based on the current probability of CABAC at encoder
+ *
+ * \param  sliceType      slice type
+ * \param  qp             input QP value
+ * \param  ctxModel      given probability table
+ */
+UInt ContextModel3DBuffer::calcCost( SliceType sliceType, Int qp, UChar* ctxModel )
+{
+  UInt cost = 0;
+  ctxModel += sliceType * m_sizeXYZ;
+
+  for ( Int n = 0; n < m_sizeXYZ; n++ )
+  {
+    ContextModel tmpContextModel;
+    tmpContextModel.init( qp, ctxModel[ n ] );
+
+    // 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};
+
+    Double probLPS          = aStateToProbLPS[ m_contextModel[ n ].getState() ];
+    Double prob0, prob1;
+    if (m_contextModel[ n ].getMps()==1)
+    {
+      prob0 = probLPS;
+      prob1 = 1.0-prob0;
+    }
+    else
+    {
+      prob1 = probLPS;
+      prob0 = 1.0-prob1;
+    }
+
+    if (m_contextModel[ n ].getBinsCoded()>0)
+    {
+      cost += (UInt) (prob0 * tmpContextModel.getEntropyBits( 0 ) + prob1 * tmpContextModel.getEntropyBits( 1 ));
+    }
+  }
+
+  return cost;
+}
+#endif
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 341)
@@ -0,0 +1,100 @@
+/* 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-2012, 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     ContextModel3DBuffer.h
+    \brief    context model 3D buffer class (header)
+*/
+
+#ifndef _HM_CONTEXT_MODEL_3DBUFFER_H_
+#define _HM_CONTEXT_MODEL_3DBUFFER_H_
+
+#include <stdio.h>
+#include <assert.h>
+#include <memory.h>
+
+#include "CommonDef.h"
+#include "ContextModel.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// context model 3D buffer class
+class ContextModel3DBuffer
+{
+protected:
+  ContextModel* m_contextModel; ///< array of context models
+  const UInt    m_sizeX;        ///< X size of 3D buffer
+  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 )
+  {
+    return  m_contextModel[ uiZ * m_sizeXY + uiY * m_sizeX + uiX ];
+  }
+  ContextModel* get( UInt uiZ, UInt uiY )
+  {
+    return &m_contextModel[ uiZ * m_sizeXY + uiY * m_sizeX ];
+  }
+  ContextModel* get( UInt uiZ )
+  {
+    return &m_contextModel[ uiZ * m_sizeXY ];
+  }
+  
+  // initialization & copy functions
+  Void initBuffer( SliceType eSliceType, Int iQp, UChar* ctxModel );          ///< initialize 3D buffer by slice type & QP
+  
+#if CABAC_INIT_FLAG
+  UInt calcCost( SliceType sliceType, Int qp, UChar* ctxModel );      ///< determine cost of choosing a probability table based on current probabilities
+#endif
+  /** copy from another buffer
+   * \param src buffer to copy from
+   */
+  Void copyFrom( ContextModel3DBuffer* src )
+  {
+    assert( m_sizeXYZ == src->m_sizeXYZ );
+    ::memcpy( m_contextModel, src->m_contextModel, sizeof(ContextModel) * m_sizeXYZ );
+  }
+};
+
+//! \}
+
+#endif // _HM_CONTEXT_MODEL_3DBUFFER_H_
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextTables.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/ContextTables.h	(revision 341)
@@ -0,0 +1,619 @@
+/* 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-2012, 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     ContextTables.h
+    \brief    Defines constants and tables for SBAC
+    \todo     number of context models is not matched to actual use, should be fixed
+*/
+
+#ifndef __CONTEXTTABLES__
+#define __CONTEXTTABLES__
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define MAX_NUM_CTX_MOD             512       ///< maximum number of supported contexts
+
+#define NUM_SPLIT_FLAG_CTX            3       ///< number of context models for split flag
+#define NUM_SKIP_FLAG_CTX             3       ///< number of context models for skip flag
+
+#if LGE_ILLUCOMP_B0045
+#define NUM_IC_FLAG_CTX               3       ///< number of context models for illumination compensation flag
+#endif
+
+#define NUM_MERGE_FLAG_EXT_CTX        1       ///< number of context models for merge flag of merge extended
+#define NUM_MERGE_IDX_EXT_CTX         1       ///< number of context models for merge index of merge extended
+
+#if H3D_IVRP
+#define NUM_RES_PRED_FLAG_CTX         4       ///< number of context for residual prediction flag
+#endif
+
+#define NUM_ALF_CTRL_FLAG_CTX         1       ///< number of context models for ALF control flag
+#define NUM_PART_SIZE_CTX             4       ///< number of context models for partition size
+#define NUM_CU_AMP_CTX                1       ///< number of context models for partition size (AMP)
+#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_CHROMA_PRED_CTX           2       ///< number of context models for intra prediction (chroma)
+#define NUM_INTER_DIR_CTX             4       ///< number of context models for inter prediction direction
+#define NUM_MV_RES_CTX                2       ///< number of context models for motion vector difference
+
+#define NUM_REF_NO_CTX                4       ///< number of context models for reference index
+#define NUM_TRANS_SUBDIV_FLAG_CTX     10      ///< number of context models for transform subdivision flags
+#define NUM_QT_CBF_CTX                5       ///< 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              48      ///< 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       21      ///< number of context models for chroma sig flag
+#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
+
+#define NUM_MVP_IDX_CTX               2       ///< number of context models for MVP index
+
+#define NUM_ALF_FLAG_CTX              1       ///< number of context models for ALF flag
+#define NUM_ALF_UVLC_CTX              2       ///< number of context models for ALF UVLC (filter length)
+#define NUM_ALF_SVLC_CTX              3       ///< number of context models for ALF SVLC (filter coeff.)
+
+#define NUM_SAO_FLAG_CTX              1       ///< number of context models for SAO flag
+#define NUM_SAO_UVLC_CTX              2       ///< number of context models for SAO UVLC
+#define NUM_SAO_SVLC_CTX              3       ///< number of context models for SAO SVLC
+#define NUM_SAO_RUN_CTX               3       ///< number of context models for AO SVLC (filter coeff.)
+#define NUM_SAO_MERGE_LEFT_FLAG_CTX   3       ///< number of context models for AO SVLC (filter coeff.)
+#define NUM_SAO_MERGE_UP_FLAG_CTX     1       ///< number of context models for AO SVLC (filter coeff.)
+#define NUM_SAO_TYPE_IDX_CTX          2       ///< number of context models for AO SVLC (filter coeff.)
+#define CNU                          154      ///< dummy initialization value for unused context models 'Context model Not Used'
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#define NUM_DMM_FLAG_CTX              1       ///< number of context models for DMM flag
+#define NUM_DMM_MODE_CTX              1       ///< number of context models for DMM mode
+#if LGE_DMM3_SIMP_C0044
+#define NUM_DMM_DATA_CTX              4       ///< number of context models for DMM data
+#else
+#define NUM_DMM_DATA_CTX              3       ///< number of context models for DMM data
+#endif
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+#define NUM_EDGE_INTRA_CTX            1
+#if LGE_EDGE_INTRA_DELTA_DC
+#define NUM_EDGE_INTRA_DELTA_DC_CTX   2 // one for Delta_DC flag, another for Delta_DC value
+#endif
+#endif
+
+#if RWTH_SDC_DLT_B0036
+#define SDC_NUM_FLAG_CTX                 3
+#define SDC_NUM_RESIDUAL_FLAG_CTX        1
+#define SDC_NUM_SIGN_FLAG_CTX            1
+#define SDC_NUM_RESIDUAL_CTX             10
+
+#define SDC_NUM_PRED_MODE_CTX            5
+#endif
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// initial probability for split flag
+static const UChar 
+INIT_SPLIT_FLAG[3][NUM_SPLIT_FLAG_CTX] =  
+{
+  { 139,  141,  157, }, 
+  { 107,  139,  126, }, 
+  { 107,  139,  126, }, 
+};
+
+static const UChar 
+INIT_SKIP_FLAG[3][NUM_SKIP_FLAG_CTX] =  
+{
+  { CNU,  CNU,  CNU, }, 
+  { 197,  185,  201, }, 
+  { 197,  185,  201, }, 
+};
+
+#if LGE_ILLUCOMP_B0045
+static const UChar 
+INIT_IC_FLAG[3][NUM_IC_FLAG_CTX] =  
+{
+  { CNU,  CNU,  CNU, }, 
+  { 197,  185,  201, }, 
+  { 197,  185,  201, }, 
+};
+#endif
+
+static const UChar 
+INIT_ALF_CTRL_FLAG[3][NUM_ALF_CTRL_FLAG_CTX] = 
+{
+  { 200, }, 
+  { 139, }, 
+  { 169, }, 
+};
+
+static const UChar 
+INIT_MERGE_FLAG_EXT[3][NUM_MERGE_FLAG_EXT_CTX] = 
+{
+  { CNU, }, 
+  { 110, }, 
+  { 154, }, 
+};
+
+static const UChar 
+INIT_MERGE_IDX_EXT[3][NUM_MERGE_IDX_EXT_CTX] =  
+{
+  { CNU, }, 
+  { 122, }, 
+  { 137, }, 
+};
+
+#if H3D_IVRP
+static const UChar
+INIT_RES_PRED_FLAG[3][NUM_RES_PRED_FLAG_CTX] =
+{
+    { CNU, CNU, CNU, CNU },
+    { 154, 154, 154, 154 },
+    { 154, 154, 154, 154 },
+};
+#endif
+
+static const UChar 
+INIT_PART_SIZE[3][NUM_PART_SIZE_CTX] =  
+{
+  { 184,  CNU,  CNU,  CNU, }, 
+  { 154,  139,  CNU,  CNU, }, 
+  { 154,  139,  CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_CU_AMP_POS[3][NUM_CU_AMP_CTX] =  
+{
+  { CNU, }, 
+  { 154, }, 
+  { 154, }, 
+};
+
+static const UChar 
+INIT_PRED_MODE[3][NUM_PRED_MODE_CTX] = 
+{
+  { CNU, }, 
+  { 149, }, 
+  { 134, }, 
+};
+
+static const UChar 
+INIT_INTRA_PRED_MODE[3][NUM_ADI_CTX] = 
+{
+  { 184, }, 
+  { 154, }, 
+  { 183, }, 
+};
+
+static const UChar 
+INIT_CHROMA_PRED_MODE[3][NUM_CHROMA_PRED_CTX] = 
+{
+  {  63,  139, }, 
+  { 152,  139, }, 
+  { 152,  139, }, 
+};
+
+static const UChar 
+INIT_INTER_DIR[3][NUM_INTER_DIR_CTX] = 
+{
+  { CNU,  CNU,  CNU,  CNU, }, 
+#if CABAC_INIT_FLAG
+  {  95,   79,   63,   31, }, 
+#else
+  { CNU,  CNU,  CNU,  CNU, }, 
+#endif
+  {  95,   79,   63,   31, }, 
+};
+
+static const UChar 
+INIT_MVD[3][NUM_MV_RES_CTX] =  
+{
+  { CNU,  CNU, }, 
+  { 140,  198, }, 
+  { 169,  198, }, 
+};
+
+static const UChar 
+INIT_REF_PIC[3][NUM_REF_NO_CTX] =  
+{
+  { CNU,  CNU,  CNU,  CNU, }, 
+  { 153,  153,  139,  CNU, }, 
+  { 153,  153,  168,  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] =  
+{
+  { 111,  141,  CNU,  CNU,  CNU,   94,  138,  182,  CNU,  CNU, }, 
+  { 153,  111,  CNU,  CNU,  CNU,  149,  107,  167,  CNU,  CNU, }, 
+  { 153,  111,  CNU,  CNU,  CNU,  149,   92,  167,  CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_QT_ROOT_CBF[3][NUM_QT_ROOT_CBF_CTX] = 
+{
+  { CNU, }, 
+  {  79, }, 
+  {  79, }, 
+};
+
+static const UChar 
+INIT_LAST[3][2*NUM_CTX_LAST_FLAG_XY] =  
+{
+  { 110,  110,  124,  110,  140,  111,  125,  111,  127,  111,  111,  156,  127,  127,  111, 
+    108,  123,   63,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, 
+  }, 
+  { 125,  110,   94,  110,  125,  110,  125,  111,  111,  110,  139,  111,  111,  111,  125,  
+    108,  123,  108,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,
+  }, 
+  { 125,  110,  124,  110,  125,  110,  125,  111,  111,  110,  139,  111,  111,  111,  125, 
+    108,  123,   93,  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] =  
+{
+  {  91,  171,  
+    134,  141, 
+  }, 
+  { 121,  140, 
+    61,  154, 
+  }, 
+  { 121,  140,  
+    61,  154, 
+  }, 
+};
+
+static const UChar 
+INIT_SIG_FLAG[3][NUM_SIG_FLAG_CTX] = 
+{
+  { 141,  111,  125,  110,  110,   94,  124,  108,  124,  125,  139,  124,   63,  139,  168,  138,  107,  123,   92,  111,  141,  107,  125,  141,  179,  153,  125,  140,  139,  182,  123,   47,  153,  182,  137,  149,  192,  152,  224,  136,   31,  136,   74,  140,  141,  136,  139,  111, }, 
+  { 170,  154,  139,  153,  139,  123,  123,   63,  153,  168,  153,  152,   92,  152,  152,  137,  122,   92,   61,  155,  185,  166,  183,  140,  136,  153,  154,  155,  153,  123,   63,   61,  167,  153,  167,  136,  149,  107,  136,  121,  122,   91,  149,  170,  185,  151,  183,  140, }, 
+  { 170,  154,  139,  153,  139,  123,  123,   63,  124,  139,  153,  152,   92,  152,  152,  137,  137,   92,   61,  170,  185,  166,  183,  140,  136,  153,  154,  155,  153,  138,  107,   61,  167,  153,  167,  136,  121,  122,  136,  121,  122,   91,  149,  170,  170,  151,  183,  140, }, 
+};
+
+static const UChar 
+INIT_ONE_FLAG[3][NUM_ONE_FLAG_CTX] = 
+{
+  { 140,   92,  137,  138,  140,  152,  138,  139,  153,   74,  149,   92,  139,  107,  122,  152,  140,  179,  166,  182,  140,  227,  122,  197, }, 
+  { 154,  196,  196,  167,  154,  152,  167,  182,  182,  134,  149,  136,  153,  121,  136,  137,  169,  194,  166,  167,  154,  167,  137,  182, }, 
+  { 154,  196,  167,  167,  154,  152,  167,  182,  182,  134,  149,  136,  153,  121,  136,  122,  169,  208,  166,  167,  154,  152,  167,  182, }, 
+};
+
+static const UChar 
+INIT_ABS_FLAG[3][NUM_ABS_FLAG_CTX] =  
+{
+  { 138,  153,  136,  167,  152,  152, }, 
+  { 107,  167,   91,  122,  107,  167, }, 
+  { 107,  167,   91,  107,  107,  167, }, 
+};
+
+static const UChar 
+INIT_MVP_IDX[3][NUM_MVP_IDX_CTX] =  
+{
+  { CNU,  CNU, }, 
+  { 168,  CNU, }, 
+  { 168,  CNU, }, 
+};
+
+static const UChar 
+INIT_ALF_FLAG[3][NUM_ALF_FLAG_CTX] = 
+{
+  { 153, }, 
+  { 153, }, 
+  { 153, }, 
+};
+
+static const UChar 
+INIT_ALF_UVLC[3][NUM_ALF_UVLC_CTX] = 
+{
+  { 140,  154, }, 
+  { 154,  154, }, 
+  { 154,  154, }, 
+};
+
+static const UChar 
+INIT_ALF_SVLC[3][NUM_ALF_SVLC_CTX] =  
+{
+  { 187,  154,  159, }, 
+  { 141,  154,  189, }, 
+  { 141,  154,  159, }, 
+};
+
+static const UChar 
+INIT_SAO_FLAG[3][NUM_SAO_FLAG_CTX] =  
+{
+  { 154, }, 
+  { 153, }, 
+  { 153, }, 
+};
+
+static const UChar 
+INIT_SAO_UVLC[3][NUM_SAO_UVLC_CTX] =  
+{
+  { 143,  140, }, 
+  { 185,  140, }, 
+  { 200,  140, }, 
+};
+
+static const UChar 
+INIT_SAO_SVLC[3][NUM_SAO_SVLC_CTX] = 
+{
+  { 247,  154,  244, }, 
+  { 215,  154,  169, }, 
+  { 215,  154,  169, }, 
+};
+
+static const UChar 
+INIT_SAO_MERGE_LEFT_FLAG[3][NUM_SAO_MERGE_LEFT_FLAG_CTX] = 
+{
+  { 153,  153,  153, }, 
+  { 153,  153,  153, }, 
+  { 153,  153,  153, }, 
+};
+
+static const UChar 
+INIT_SAO_MERGE_UP_FLAG[3][NUM_SAO_MERGE_UP_FLAG_CTX] = 
+{
+  { 175, }, 
+  { 153, }, 
+  { 153, }, 
+};
+
+static const UChar 
+INIT_SAO_TYPE_IDX[3][NUM_SAO_TYPE_IDX_CTX] = 
+{
+  { 160,  140, }, 
+  { 185,  140, }, 
+  { 200,  140, }, 
+};
+
+static const UChar 
+INIT_TRANS_SUBDIV_FLAG[3][NUM_TRANS_SUBDIV_FLAG_CTX] = 
+{
+{ CNU,  224,  167,  122,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, }, 
+{ CNU,  124,  138,   94,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, }, 
+{ CNU,  153,  138,  138,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, }, 
+};
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+static const UChar
+INIT_DMM_FLAG[3][NUM_DMM_FLAG_CTX] =
+{
+  {
+    CNU
+  },
+  {
+    CNU
+  },
+  {
+    CNU
+  }
+};
+
+static const UChar
+INIT_DMM_MODE[3][NUM_DMM_MODE_CTX] =
+{
+  {
+    CNU
+  },
+  {
+    CNU
+  },
+  {
+    CNU
+  }
+};
+
+static const UChar
+INIT_DMM_DATA[3][NUM_DMM_DATA_CTX] = 
+{
+#if LGE_DMM3_SIMP_C0044
+  {
+    CNU, CNU, CNU, CNU
+  },
+  {
+    CNU, CNU, CNU, CNU
+  },
+  {
+    CNU, CNU, CNU, CNU
+  }
+#else
+  {
+    CNU, CNU, CNU
+  },
+  {
+    CNU, CNU, CNU
+  },
+  {
+    CNU, CNU, CNU
+  }
+#endif
+};
+
+#if LGE_EDGE_INTRA_A0070
+static const Short
+INIT_EDGE_INTRA[3][NUM_EDGE_INTRA_CTX] =
+{
+  {
+    CNU
+  },
+  {
+    CNU
+  },
+  {
+    CNU
+  }
+};
+
+#if LGE_EDGE_INTRA_DELTA_DC
+static const Short
+INIT_EDGE_INTRA_DELTA_DC[3][NUM_EDGE_INTRA_DELTA_DC_CTX] =
+{
+  {
+    CNU, CNU
+  },
+  {
+    CNU, CNU
+  },
+  {
+    CNU, CNU
+  }
+};
+#endif
+#endif
+
+#endif
+
+#if RWTH_SDC_DLT_B0036
+static const Short INIT_SDC_FLAG[3][SDC_NUM_FLAG_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  }
+};
+
+static const Short INIT_SDC_RESIDUAL_FLAG[3][3*SDC_NUM_RESIDUAL_FLAG_CTX][2] =
+{
+  {
+    { -5, 35 },
+    { -0, 56 },
+    { -0, 56 }
+    
+  },
+  {
+    { -5, 35 },
+    { -0, 56 },
+    { -0, 56 }
+  },
+  {
+    { -5, 35 },
+    { -0, 56 },
+    { -0, 56 }
+  }
+};
+
+static const Short INIT_SDC_SIGN_FLAG[3][3*SDC_NUM_SIGN_FLAG_CTX][2] =
+{
+  {
+    { -1, 56 },
+    { -4, 55 },
+    { -4, 55 }
+  },
+  {
+    { -1, 56 },
+    { -4, 55 },
+    { -4, 55 }
+  },
+  {
+    { -1, 56 },
+    { -4, 55 },
+    { -4, 55 }
+  }
+};
+
+static const Short INIT_SDC_RESIDUAL[3][3*SDC_NUM_RESIDUAL_CTX][2] =
+{
+  {
+    { -1, 64 }, {  2, 64 }, {  6, 67 }, {  8, 61 }, {  7, 47 }, { 10, 33 }, { 12, 14 }, { 33, -13 }, { 12, 14 }, { 33, -13 },
+    {  2, 66 }, { -0, 63 }, {  1, 64 }, {  6, 65 }, {  7, 59 }, { 12, 50 }, { 14, 27 }, { -0, -17 }, { 14, 27 }, { -0, -17 },
+    {  2, 66 }, { -0, 63 }, {  1, 64 }, {  6, 65 }, {  7, 59 }, { 12, 50 }, { 14, 27 }, { -0, -17 }, { 14, 27 }, { -0, -17 }
+  },
+  {
+    { -1, 64 }, {  2, 64 }, {  6, 67 }, {  8, 61 }, {  7, 47 }, { 10, 33 }, { 12, 14 }, { 33, -13 }, { 12, 14 }, { 33, -13 },
+    {  2, 66 }, { -0, 63 }, {  1, 64 }, {  6, 65 }, {  7, 59 }, { 12, 50 }, { 14, 27 }, { -0, -17 }, { 14, 27 }, { -0, -17 },
+    {  2, 66 }, { -0, 63 }, {  1, 64 }, {  6, 65 }, {  7, 59 }, { 12, 50 }, { 14, 27 }, { -0, -17 }, { 14, 27 }, { -0, -17 }
+  },
+  {
+    { -1, 64 }, {  2, 64 }, {  6, 67 }, {  8, 61 }, {  7, 47 }, { 10, 33 }, { 12, 14 }, { 33, -13 }, { 12, 14 }, { 33, -13 },
+    {  2, 66 }, { -0, 63 }, {  1, 64 }, {  6, 65 }, {  7, 59 }, { 12, 50 }, { 14, 27 }, { -0, -17 }, { 14, 27 }, { -0, -17 },
+    {  2, 66 }, { -0, 63 }, {  1, 64 }, {  6, 65 }, {  7, 59 }, { 12, 50 }, { 14, 27 }, { -0, -17 }, { 14, 27 }, { -0, -17 }
+  }
+};
+
+static const Short INIT_SDC_PRED_MODE[3][3*SDC_NUM_PRED_MODE_CTX][2] =
+{
+  {
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 },
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 },
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 }
+  },
+  {
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 },
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 },
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 }
+  },
+  {
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 },
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 },
+    {  9, 85 }, { -4, 60 }, {  4, 70 }, {  4, 70 }, {  4, 70 }
+  }
+};
+#endif
+
+//! \}
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/NAL.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/NAL.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/NAL.h	(revision 341)
@@ -0,0 +1,113 @@
+/* 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-2012, 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
+
+#include <vector>
+#include <sstream>
+#include "CommonDef.h"
+
+class TComOutputBitstream;
+
+/**
+ * Represents a single NALunit header and the associated RBSPayload
+ */
+struct NALUnit
+{
+  NalUnitType m_nalUnitType; ///< nal_unit_type
+  Bool        m_nalRefFlag;  ///< nal_ref_flag
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  unsigned    m_layerId;
+  unsigned    m_temporalId;  ///< temporal_id
+#else
+  Int         m_viewId;      ///< view_id
+  Bool        m_isDepth;     ///< is_depth
+  unsigned    m_temporalId;  ///< temporal_id
+#endif
+
+  /** construct an NALunit structure with given header values. */
+  NALUnit(
+    NalUnitType nalUnitType,
+    Bool        nalRefFlag,
+#if !VIDYO_VPS_INTEGRATION & !QC_MVHEVC_B0046    
+    Int         viewId,
+    Bool        isDepth,
+#else
+    unsigned    layerId,
+#endif
+    unsigned       temporalId = 0)
+    :m_nalUnitType (nalUnitType)
+    ,m_nalRefFlag  (nalRefFlag)
+#if !VIDYO_VPS_INTEGRATION & !QC_MVHEVC_B0046
+    ,m_viewId      (viewId)
+    ,m_isDepth     (isDepth)
+#else
+    ,m_layerId     (layerId)
+#endif
+    ,m_temporalId  (temporalId)
+  {}
+
+  /** default constructor - no initialization; must be perfomed by user */
+  NALUnit() {}
+
+  /** returns true if the NALunit is a slice NALunit */
+  bool isSlice()
+  {
+    return m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR
+#if !QC_REM_IDV_B0046    
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDV
+#endif
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TLA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE;
+  }
+};
+
+struct OutputNALUnit;
+
+/**
+ * A single NALunit, with complete payload in EBSP format.
+ */
+struct NALUnitEBSP : public NALUnit
+{
+  std::ostringstream m_nalUnitData;
+
+  /**
+   * convert the OutputNALUnit #nalu# into EBSP format by writing out
+   * the NALUnit header, then the rbsp_bytes including any
+   * emulation_prevention_three_byte symbols.
+   */
+  NALUnitEBSP(OutputNALUnit& nalu);
+};
+//! \}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/SEI.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/SEI.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/SEI.h	(revision 341)
@@ -0,0 +1,114 @@
+/* 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-2012, 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
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * Abstract class representing an SEI message with lightweight RTTI.
+ */
+class SEI
+{
+public:
+  enum PayloadType
+  {
+    USER_DATA_UNREGISTERED = 5,
+    PICTURE_DIGEST = 256,
+  };
+  
+  SEI() {}
+  virtual ~SEI() {}
+  
+  virtual PayloadType payloadType() const = 0;
+};
+
+class SEIuserDataUnregistered : public SEI
+{
+public:
+  PayloadType payloadType() const { return USER_DATA_UNREGISTERED; }
+
+  SEIuserDataUnregistered()
+    : userData(0)
+    {}
+
+  virtual ~SEIuserDataUnregistered()
+  {
+    delete userData;
+  }
+
+  unsigned char uuid_iso_iec_11578[16];
+  unsigned userDataLength;
+  unsigned char *userData;
+};
+
+class SEIpictureDigest : public SEI
+{
+public:
+  PayloadType payloadType() const { return PICTURE_DIGEST; }
+
+  SEIpictureDigest() {}
+  virtual ~SEIpictureDigest() {}
+  
+  enum Method
+  {
+    MD5,
+    RESERVED,
+  } method;
+
+  unsigned char digest[16];
+};
+
+/**
+ * A structure to collate all SEI messages.  This ought to be replaced
+ * with a list of std::list<SEI*>.  However, since there is only one
+ * user of the SEI framework, this will do initially */
+class SEImessages
+{
+public:
+  SEImessages()
+    : user_data_unregistered(0)
+    , picture_digest(0)
+    {}
+
+  ~SEImessages()
+  {
+    delete user_data_unregistered;
+    delete picture_digest;
+  }
+
+  SEIuserDataUnregistered* user_data_unregistered;
+  SEIpictureDigest* picture_digest;
+};
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp	(revision 341)
@@ -0,0 +1,2284 @@
+/* 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-2012, 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     TComAdaptiveLoopFilter.cpp
+    \brief    adaptive loop filter class
+*/
+
+#include "TComAdaptiveLoopFilter.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibCommon
+//! \{
+
+
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+Int TComAdaptiveLoopFilter::weightsShape1Sym[ALF_MAX_NUM_COEF+1] = 
+{ 
+              2,
+              2,
+           2, 2, 2,
+  2, 2, 2, 2, 1, 
+              1
+};
+Int* TComAdaptiveLoopFilter::weightsTabShapes[NUM_ALF_FILTER_SHAPE] =
+{
+  weightsShape1Sym
+};
+Int TComAdaptiveLoopFilter::m_sqrFiltLengthTab[NUM_ALF_FILTER_SHAPE] =
+{
+  ALF_FILTER_LEN
+};
+Int depthIntShape1Sym[ALF_MAX_NUM_COEF+1] = 
+{
+              6,
+              7,
+           7, 8, 7,
+  5, 6, 7, 8, 9, 
+              9  
+};
+Int* pDepthIntTabShapes[NUM_ALF_FILTER_SHAPE] =
+{ 
+  depthIntShape1Sym
+};
+
+Int kTableShape1[ALF_MAX_NUM_COEF+1] = 
+{      
+              2,
+              3,
+           3, 4, 3,
+  1, 2, 3, 4, 1, 
+              3
+};
+Int* kTableTabShapes[NUM_ALF_FILTER_SHAPE] =
+{ 
+  kTableShape1
+};
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+const AlfCUCtrlInfo& AlfCUCtrlInfo::operator= (const AlfCUCtrlInfo& src)
+{
+  this->cu_control_flag = src.cu_control_flag;
+  this->alf_max_depth   = src.alf_max_depth;
+  this->num_alf_cu_flag = src.num_alf_cu_flag;
+  this->alf_cu_flag     = src.alf_cu_flag;
+  return *this;
+}
+
+/// AlfCUCtrlInfo
+Void AlfCUCtrlInfo::reset()
+{
+  cu_control_flag= 0;
+  num_alf_cu_flag= 0;
+  alf_max_depth = 0;
+  alf_cu_flag.clear();
+}
+
+/// ALFParam
+const ALFParam& ALFParam::operator= (const ALFParam& src)
+{
+  if(this->componentID < 0)
+  {
+    this->create(src.componentID);
+  }
+  this->copy(src);
+  return *this;
+}
+
+Void ALFParam::create(Int cID)
+{
+  const Int numCoef = ALF_MAX_NUM_COEF;
+
+  this->componentID       = cID;
+  this->alf_flag          = 0;
+  this->filters_per_group = 1; // this value keeps 1 for chroma componenet
+  this->startSecondFilter = -1;
+  this->predMethod        = -1;
+  this->minKStart         = -1;
+  this->filterPattern     = NULL;
+  this->nbSPred           = NULL;
+  this->kMinTab           = NULL;
+  this->coeffmulti        = NULL;
+  this->filter_shape      = 0;
+  this->num_coeff         = numCoef;
+
+  switch(cID)
+  {
+  case ALF_Y:
+    {
+      this->coeffmulti = new Int*[NO_VAR_BINS];
+      for(Int i=0; i< NO_VAR_BINS; i++)
+      {
+        this->coeffmulti[i] = new Int[numCoef];
+        ::memset(this->coeffmulti[i], 0, sizeof(Int)*numCoef);
+      }
+      this->filterPattern = new Int[NO_VAR_BINS];
+      ::memset(this->filterPattern, 0, sizeof(Int)*NO_VAR_BINS);
+
+      this->nbSPred       = new Int[NO_VAR_BINS];
+      ::memset(this->nbSPred, 0, sizeof(Int)*NO_VAR_BINS);
+
+      this->kMinTab       = new Int[42];
+    }
+    break;
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      this->coeffmulti = new Int*[1];
+      this->coeffmulti[0] = new Int[numCoef];
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+Void ALFParam::destroy()
+{
+  if(this->componentID >=0)
+  {
+    switch(this->componentID)
+    {
+    case ALF_Y:
+      {
+        for(Int i=0; i< NO_VAR_BINS; i++)
+        {
+          delete[] this->coeffmulti[i];
+        }
+        delete[] this->coeffmulti;
+        delete[] this->filterPattern;
+        delete[] this->nbSPred;
+        delete[] this->kMinTab;
+      }
+      break;
+    case ALF_Cb:
+    case ALF_Cr:
+      {
+        delete[] this->coeffmulti[0];
+        delete[] this->coeffmulti;
+      }
+      break;
+    default:
+      {
+        printf("Not a legal component ID\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+
+  }
+}
+
+Void ALFParam::copy(const ALFParam& src)
+{
+  const Int numCoef = ALF_MAX_NUM_COEF;
+
+  this->componentID       = src.componentID;
+  this->alf_flag          = src.alf_flag;
+  if(this->alf_flag == 1)
+  {
+    this->filters_per_group = src.filters_per_group;
+    this->filter_shape      = src.filter_shape;
+    this->num_coeff         = src.num_coeff;
+
+    switch(this->componentID)
+    {
+    case ALF_Cb:
+    case ALF_Cr:
+      {
+        ::memcpy(this->coeffmulti[0], src.coeffmulti[0], sizeof(Int)*numCoef);
+      }
+      break;
+    case ALF_Y:
+      {
+        this->startSecondFilter = src.startSecondFilter;
+        this->predMethod        = src.predMethod;
+        this->minKStart         = src.minKStart;
+        ::memcpy(this->filterPattern, src.filterPattern, sizeof(Int)*NO_VAR_BINS);
+        ::memcpy(this->nbSPred, src.nbSPred, sizeof(Int)*NO_VAR_BINS);
+        ::memcpy(this->kMinTab, src.kMinTab, sizeof(Int)*42);
+
+        for(Int i=0; i< (Int)NO_VAR_BINS; i++)
+        {
+          ::memcpy(this->coeffmulti[i], src.coeffmulti[i], sizeof(Int)*numCoef);
+        }
+
+      }
+      break;
+    default:
+      {
+        printf("not a legal component ID\n");
+        assert(0);
+        exit(-1);
+      }
+
+    }
+  }
+  else
+  {
+    //reset
+    this->filters_per_group = 0;
+    this->filter_shape      = 0;
+    this->num_coeff         = 0;
+  }
+}
+
+/// AlfUnitParam
+AlfUnitParam::AlfUnitParam()
+{
+  this->mergeType = ALF_MERGE_DISABLED;
+  this->isEnabled = false;
+  this->isNewFilt = false;
+  this->storedFiltIdx = -1;
+  this->alfFiltParam = NULL;
+
+}
+
+
+
+const AlfUnitParam& AlfUnitParam::operator= (const AlfUnitParam& src)
+{
+  this->mergeType = src.mergeType;
+  this->isEnabled = src.isEnabled;
+  this->isNewFilt = src.isNewFilt;
+  this->storedFiltIdx = src.storedFiltIdx;
+  this->alfFiltParam = src.alfFiltParam; // just a pointer assignment and no additional memory allocation
+
+  return *this;
+}
+
+Bool AlfUnitParam::operator == (const AlfUnitParam& cmp)
+{
+  if( isEnabled != cmp.isEnabled)
+  {
+    return false;
+  }
+
+  //enable flags are the same
+  if(!isEnabled)
+  {
+    return true;
+  }
+
+  //both enabled
+  assert(alfFiltParam->alf_flag == 1);
+
+  const Int numCoef = ALF_MAX_NUM_COEF;
+  ALFParam* cmpAlfParam = cmp.alfFiltParam;
+
+  if(alfFiltParam->componentID == ALF_Y)
+  {
+    if(alfFiltParam->filters_per_group != cmpAlfParam->filters_per_group)
+    {
+      return false;
+    }
+    if(alfFiltParam->predMethod != cmpAlfParam->predMethod)
+    {
+      return false;
+    }
+    if(alfFiltParam->minKStart != cmpAlfParam->minKStart)
+    {
+      return false;
+    }
+    if(alfFiltParam->filters_per_group == 2)
+    {
+      if(alfFiltParam->startSecondFilter != cmpAlfParam->startSecondFilter)
+      {
+        return false;
+      }
+    }
+    if (alfFiltParam->filters_per_group > 1)
+    {
+      for (Int i=0; i<NO_VAR_BINS; i++)
+      {
+        if (alfFiltParam->filterPattern[i] != cmpAlfParam->filterPattern[i])
+        {
+          return false;
+        } 
+      }
+    }      
+    for (Int i=0; i<alfFiltParam->filters_per_group; i++)
+    {
+      if (alfFiltParam->nbSPred[i] != cmpAlfParam->nbSPred[i])
+      {
+        return false;
+      } 
+    }
+  }
+  for(Int f=0; f< alfFiltParam->filters_per_group; f++)
+  {
+    for(Int i=0; i< numCoef; i++)
+    {
+      if(alfFiltParam->coeffmulti[f][i] != cmpAlfParam->coeffmulti[f][i])
+      {
+        return false;
+      }
+    }
+  }
+
+  return true;
+}
+
+
+/// AlfParamSet
+Void AlfParamSet::init()
+{
+  destroy(); 
+  create();
+}
+
+Void AlfParamSet::releaseALFParam()
+{
+  for(Int c=0; c< NUM_ALF_COMPONENT; c++)
+  {
+    if(alfUnitParam[c] != NULL)
+    {
+      for(Int n=0; n< numLCU; n++)
+      {
+        if(alfUnitParam[c][n].alfFiltParam != NULL)
+        {
+          delete alfUnitParam[c][n].alfFiltParam;
+          alfUnitParam[c][n].alfFiltParam = NULL;
+        }
+      }
+    }
+  }
+
+}
+
+Void AlfParamSet::createALFParam()
+{
+  for(Int c=0; c< NUM_ALF_COMPONENT; c++)
+  {
+    for(Int n=0; n< numLCU; n++)
+    {
+      alfUnitParam[c][n].alfFiltParam = new ALFParam(c);
+    }
+  }
+}
+
+/** Create ALF parameter set
+ * \param [in] width number of LCU in width
+ * \param [in] height number of LCU in height
+ * \param [in] num number of LCU in one picture
+ */
+Void AlfParamSet::create(Int width, Int height, Int num)
+{
+  numLCU = num;
+  numLCUInHeight = height;
+  numLCUInWidth  = width;
+
+  for(Int c=0; c< NUM_ALF_COMPONENT; c++)
+  {
+    isEnabled[c] = false;
+    isUniParam[c]= false;
+    if(num !=0)
+    {
+      alfUnitParam[c] = new AlfUnitParam[num];
+    }
+    else
+    {
+      alfUnitParam[c] = NULL;
+    }
+  }
+
+}
+
+Void AlfParamSet::destroy()
+{
+  for(Int c=0; c< NUM_ALF_COMPONENT; c++)
+  {
+    if(alfUnitParam[c] != NULL)
+    {
+      delete[] alfUnitParam[c];
+      alfUnitParam[c] = NULL;
+    }
+  }
+}
+
+
+
+
+
+TComAdaptiveLoopFilter::TComAdaptiveLoopFilter()
+{
+  m_pcTempPicYuv = NULL;
+  m_iSGDepth     = 0;
+  m_pcPic        = NULL;
+  m_ppSliceAlfLCUs = NULL;
+  m_pvpAlfLCU    = NULL;
+  m_pvpSliceTileAlfLCU = NULL;
+  for(Int c=0; c< NUM_ALF_COMPONENT; c++)
+  {
+    m_alfFiltInfo[c] = NULL;
+  }
+  m_varImg = NULL;
+  m_filterCoeffSym = NULL;
+
+}
+
+Void TComAdaptiveLoopFilter:: xError(const char *text, int code)
+{
+  fprintf(stderr, "%s\n", text);
+  exit(code);
+}
+
+Void TComAdaptiveLoopFilter:: no_mem_exit(const char *where)
+{
+  char errortext[200];
+  sprintf(errortext, "Could not allocate memory: %s",where);
+  xError (errortext, 100);
+}
+
+Void TComAdaptiveLoopFilter::initMatrix_Pel(Pel ***m2D, int d1, int d2)
+{
+  int i;
+  
+  if(!(*m2D = (Pel **) calloc(d1, sizeof(Pel *))))
+  {
+    FATAL_ERROR_0("initMatrix_Pel: memory allocation problem\n", -1);
+  }
+  if(!((*m2D)[0] = (Pel *) calloc(d1 * d2, sizeof(Pel))))
+  {
+    FATAL_ERROR_0("initMatrix_Pel: memory allocation problem\n", -1);
+  }
+  
+  for(i = 1; i < d1; i++)
+  {
+    (*m2D)[i] = (*m2D)[i-1] + d2;
+  }
+}
+
+Void TComAdaptiveLoopFilter::initMatrix_int(int ***m2D, int d1, int d2)
+{
+  int i;
+  
+  if(!(*m2D = (int **) calloc(d1, sizeof(int *))))
+  {
+    FATAL_ERROR_0("initMatrix_int: memory allocation problem\n", -1);
+  }
+  if(!((*m2D)[0] = (int *) calloc(d1 * d2, sizeof(int))))
+  {
+    FATAL_ERROR_0("initMatrix_int: memory allocation problem\n", -1);
+  }
+  
+  for(i = 1; i < d1; i++)
+  {
+    (*m2D)[i] = (*m2D)[i-1] + d2;
+  }
+}
+
+Void TComAdaptiveLoopFilter::destroyMatrix_int(int **m2D)
+{
+  if(m2D)
+  {
+    if(m2D[0])
+    {
+      free(m2D[0]);
+    }
+    else
+    {
+      FATAL_ERROR_0("destroyMatrix_int: memory free problem\n", -1);
+    }
+    free(m2D);
+  } 
+  else
+  {
+    FATAL_ERROR_0("destroyMatrix_int: memory free problem\n", -1);
+  }
+}
+
+Void TComAdaptiveLoopFilter::destroyMatrix_Pel(Pel **m2D)
+{
+  if(m2D)
+  {
+    if(m2D[0])
+    {
+      free(m2D[0]);
+    }
+    else
+    {
+      FATAL_ERROR_0("destroyMatrix_Pel: memory free problem\n", -1);
+    }
+    free(m2D);
+  } 
+  else
+  {
+    FATAL_ERROR_0("destroyMatrix_Pel: memory free problem\n", -1);
+  }
+}
+
+Void TComAdaptiveLoopFilter::initMatrix_double(double ***m2D, int d1, int d2)
+{
+  int i;
+  
+  if(!(*m2D = (double **) calloc(d1, sizeof(double *))))
+  {
+    FATAL_ERROR_0("initMatrix_double: memory allocation problem\n", -1);
+  }
+  if(!((*m2D)[0] = (double *) calloc(d1 * d2, sizeof(double))))
+  {
+    FATAL_ERROR_0("initMatrix_double: memory allocation problem\n", -1);
+  }
+  
+  for(i = 1; i < d1; i++)
+  {
+    (*m2D)[i] = (*m2D)[i-1] + d2;
+  }
+}
+
+Void TComAdaptiveLoopFilter::initMatrix3D_double(double ****m3D, int d1, int d2, int d3)
+{
+  int  j;
+  
+  if(!((*m3D) = (double ***) calloc(d1, sizeof(double **))))
+  {
+    FATAL_ERROR_0("initMatrix3D_double: memory allocation problem\n", -1);
+  }
+  
+  for(j = 0; j < d1; j++)
+  {
+    initMatrix_double((*m3D) + j, d2, d3);
+  }
+}
+
+
+Void TComAdaptiveLoopFilter::initMatrix4D_double(double *****m4D, int d1, int d2, int d3, int d4)
+{
+  int  j;
+  
+  if(!((*m4D) = (double ****) calloc(d1, sizeof(double ***))))
+  {
+    FATAL_ERROR_0("initMatrix4D_double: memory allocation problem\n", -1);
+  }
+  
+  for(j = 0; j < d1; j++)
+  {
+    initMatrix3D_double((*m4D) + j, d2, d3, d4);
+  }
+}
+
+
+Void TComAdaptiveLoopFilter::destroyMatrix_double(double **m2D)
+{
+  if(m2D)
+  {
+    if(m2D[0])
+    {
+      free(m2D[0]);
+    }
+    else
+    {
+      FATAL_ERROR_0("destroyMatrix_double: memory free problem\n", -1);
+    }
+    free(m2D);
+  } 
+  else
+  {
+    FATAL_ERROR_0("destroyMatrix_double: memory free problem\n", -1);
+  }
+}
+
+Void TComAdaptiveLoopFilter::destroyMatrix3D_double(double ***m3D, int d1)
+{
+  int i;
+  
+  if(m3D)
+  {
+    for(i = 0; i < d1; i++)
+    {
+      destroyMatrix_double(m3D[i]);
+    }
+    free(m3D);
+  } 
+  else
+  {
+    FATAL_ERROR_0("destroyMatrix3D_double: memory free problem\n", -1);
+  }
+}
+
+
+Void TComAdaptiveLoopFilter::destroyMatrix4D_double(double ****m4D, int d1, int d2)
+{
+  int  j;
+  
+  if(m4D)
+  {
+    for(j = 0; j < d1; j++)
+    {
+      destroyMatrix3D_double(m4D[j], d2);
+    }
+    free(m4D);
+  } 
+  else
+  {
+    FATAL_ERROR_0("destroyMatrix4D_double: memory free problem\n", -1);
+  }
+}
+
+Void TComAdaptiveLoopFilter::create( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth )
+{
+  destroy();
+  if ( !m_pcTempPicYuv )
+  {
+    m_pcTempPicYuv = new TComPicYuv;
+    m_pcTempPicYuv->create( iPicWidth, iPicHeight, uiMaxCUWidth, uiMaxCUHeight, uiMaxCUDepth );
+  }
+  m_img_height = iPicHeight;
+  m_img_width = iPicWidth;
+  initMatrix_Pel(&(m_varImg), m_img_height, m_img_width);
+  initMatrix_int(&m_filterCoeffSym, NO_VAR_BINS, ALF_MAX_NUM_COEF);
+  UInt uiNumLCUsInWidth   = m_img_width  / uiMaxCUWidth;
+  UInt uiNumLCUsInHeight  = m_img_height / uiMaxCUHeight;
+
+  uiNumLCUsInWidth  += ( m_img_width % uiMaxCUWidth ) ? 1 : 0;
+  uiNumLCUsInHeight += ( m_img_height % uiMaxCUHeight ) ? 1 : 0;
+
+  m_uiNumCUsInFrame = uiNumLCUsInWidth* uiNumLCUsInHeight; 
+
+  m_numLCUInPicWidth = uiNumLCUsInWidth;
+  m_numLCUInPicHeight= uiNumLCUsInHeight;
+  m_lcuHeight = uiMaxCUHeight;
+  m_lineIdxPadBot = m_lcuHeight - 4 - 3; // DFRegion, Vertical Taps
+  m_lineIdxPadTop = m_lcuHeight - 4; // DFRegion
+
+  m_lcuHeightChroma = m_lcuHeight>>1;
+  m_lineIdxPadBotChroma = m_lcuHeightChroma - 2 - 3; // DFRegion, Vertical Taps
+  m_lineIdxPadTopChroma = m_lcuHeightChroma - 2 ; // DFRegion
+
+  createLCUAlfInfo();
+}
+
+Void TComAdaptiveLoopFilter::destroy()
+{
+  if ( m_pcTempPicYuv )
+  {
+    m_pcTempPicYuv->destroy();
+    delete m_pcTempPicYuv;
+    m_pcTempPicYuv = NULL;
+  }
+  if(m_varImg != NULL)
+  {
+    destroyMatrix_Pel( m_varImg );
+    m_varImg = NULL;
+  }
+  if(m_filterCoeffSym != NULL)
+  {
+    destroyMatrix_int(m_filterCoeffSym);
+    m_filterCoeffSym = NULL;
+  }
+  destroyLCUAlfInfo();
+
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------
+// interface function for actual ALF process
+// --------------------------------------------------------------------------------------------------------------------
+
+/** ALF reconstruction process for one picture
+ * \param [in, out] pcPic the decoded/filtered picture (input: decoded picture; output filtered picture)
+ * \param [in] vAlfCUCtrlParam ALF CU-on/off control parameters
+ * \param [in] isAlfCoefInSlice ALF coefficient in slice (true) or ALF coefficient in APS (false) 
+ */
+Void TComAdaptiveLoopFilter::ALFProcess(TComPic* pcPic, std::vector<AlfCUCtrlInfo>& vAlfCUCtrlParam, Bool isAlfCoefInSlice)
+{
+  TComPicYuv* pcPicYuvRec    = pcPic->getPicYuvRec();
+  TComPicYuv* pcPicYuvExtRec = m_pcTempPicYuv;
+  pcPicYuvRec   ->copyToPic          ( pcPicYuvExtRec );
+  pcPicYuvExtRec->setBorderExtension ( false );
+  pcPicYuvExtRec->extendPicBorder    ();
+
+  Int lumaStride   = pcPicYuvExtRec->getStride();
+  Int chromaStride = pcPicYuvExtRec->getCStride();
+
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    Pel* pDec         = getPicBuf(pcPicYuvExtRec, compIdx);
+    Pel* pRest        = getPicBuf(pcPicYuvRec, compIdx);
+    Int  stride       = (compIdx == ALF_Y)?(lumaStride):(chromaStride);
+    Int  formatShift = (compIdx == ALF_Y)?(0):(1);
+
+    ALFParam** alfLCUParamComp = m_alfFiltInfo[compIdx];
+
+    if(!isEnabledComponent(alfLCUParamComp))
+    {
+      continue;
+    }
+
+    switch(compIdx)
+    {
+    case ALF_Cb:
+    case ALF_Cr:
+      {
+        recALF(compIdx, alfLCUParamComp, pDec, pRest, stride, formatShift, NULL, false);
+      }
+      break;
+    case ALF_Y:
+      {
+        std::vector<AlfCUCtrlInfo>* alfCUCtrlParam = NULL;
+        if(!isAlfCoefInSlice)
+        {
+          alfCUCtrlParam = &vAlfCUCtrlParam;
+          assignAlfOnOffControlFlags(pcPic, *alfCUCtrlParam);
+        }
+
+        memset(&m_varImg[0][0], 0, sizeof(Pel)*(m_img_height*m_img_width));
+
+        //calcOneRegionVar(m_varImg, pDec, stride, false, 0, m_img_height, 0, m_img_width);
+        recALF(compIdx, alfLCUParamComp, pDec, pRest, stride, formatShift, alfCUCtrlParam, true);
+      }
+      break;
+    default:
+      {
+        printf("Not a legal component ID for ALF\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+
+}
+
+/** Check the filter process of one component is enable
+ * \param [in] alfLCUParam ALF parameters
+ */
+Bool TComAdaptiveLoopFilter::isEnabledComponent(ALFParam** alfLCUParam)
+{
+  Bool isEnabled = false;
+  for(Int n=0; n< m_uiNumCUsInFrame; n++)
+  {
+    if(alfLCUParam[n]->alf_flag == 1)
+    {
+      isEnabled = true;
+      break;
+    }
+  }
+  return isEnabled;
+}
+
+
+/** ALF Reconstruction for each component
+ * \param [in] compIdx color component index
+ * \param [in] alfLCUParams alf parameters 
+ * \param [in] pDec decoded picture
+ * \param [in, out] pRest filtered picture
+ * \param [in] stride picture stride in memory
+ * \param [in] formatShift luma component (false) or chroma component (1)
+ * \param [in] alfCUCtrlParam ALF CU-on/off control parameters 
+ * \param [in] caculateBAIdx calculate BA filter index (true) or BA filter index array is ready (false)
+ */
+Void TComAdaptiveLoopFilter::recALF(Int compIdx, ALFParam** alfLCUParams,Pel* pDec, Pel* pRest, Int stride, Int formatShift
+                                  , std::vector<AlfCUCtrlInfo>* alfCUCtrlParam //default: NULL
+                                  , Bool caculateBAIdx //default: false
+                                    )
+{
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    if(!m_pcPic->getValidSlice(s))
+    {
+      continue;
+    }
+    Int numTilesInSlice = (Int)m_pvpSliceTileAlfLCU[s].size();
+    for(Int t=0; t< numTilesInSlice; t++)
+    {
+      std::vector<AlfLCUInfo*> & vpAlfLCU = m_pvpSliceTileAlfLCU[s][t];
+      Pel* pSrc = pDec;
+
+      if(m_bUseNonCrossALF)
+      {
+        pSrc = getPicBuf(m_pcSliceYuvTmp, compIdx);
+        copyRegion(vpAlfLCU, pSrc, pDec, stride, formatShift);
+        extendRegionBorder(vpAlfLCU, pSrc, stride, formatShift);
+      }
+
+      Bool isOnOffCtrlEnabled = (alfCUCtrlParam == NULL)?(false):(  (*alfCUCtrlParam)[s].cu_control_flag == 1 );
+
+      if(isOnOffCtrlEnabled)
+      {
+        assert(compIdx == ALF_Y);
+        filterRegionCUControl(alfLCUParams, vpAlfLCU, pSrc, pRest, stride, caculateBAIdx);
+      }
+      else
+      {
+        filterRegion(compIdx, alfLCUParams, vpAlfLCU, pSrc, pRest, stride, formatShift, caculateBAIdx);
+      }
+    } //tile
+  } //slice
+}
+
+
+/** assign ALC CU-On/Off Control parameters
+ * \param [in, out] pcPic picture data
+ * \param [in] vAlfCUCtrlParam ALF CU-on/off control parameters
+ */
+Void TComAdaptiveLoopFilter::assignAlfOnOffControlFlags(TComPic* pcPic, std::vector<AlfCUCtrlInfo>& vAlfCUCtrlParam)
+{
+  if(m_uiNumSlicesInPic == 1)
+  {
+    AlfCUCtrlInfo* pcAlfCtrlParam = &(vAlfCUCtrlParam[0]);
+    if(pcAlfCtrlParam->cu_control_flag)
+    {
+      UInt idx = 0;
+      for(UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++)
+      {
+        TComDataCU *pcCU = pcPic->getCU(uiCUAddr);
+        setAlfCtrlFlags(pcAlfCtrlParam, pcCU, 0, 0, idx);
+      }
+    }
+  }
+  else
+  {
+    transferCtrlFlagsFromAlfParam(vAlfCUCtrlParam);
+  }
+
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/** 
+ \param filter         filter coefficient
+ \param filterLength   filter length
+ \param isChroma       1: chroma, 0: luma
+ */
+Void TComAdaptiveLoopFilter::checkFilterCoeffValue( Int *filter, Int filterLength, Bool isChroma )
+{
+#if LCUALF_QP_DEPENDENT_BITS
+  Int alfPrecisionBit = getAlfPrecisionBit( m_alfQP );
+
+  Int maxValueNonCenter = 1 * (1 << alfPrecisionBit) - 1;
+  Int minValueNonCenter = 0 - 1 * (1 << alfPrecisionBit);
+
+  Int maxValueCenter    = 2 * (1 << alfPrecisionBit) - 1;
+#else
+  Int maxValueNonCenter = 1 * (1 << ALF_NUM_BIT_SHIFT) - 1;
+  Int minValueNonCenter = 0 - 1 * (1 << ALF_NUM_BIT_SHIFT);
+
+  Int maxValueCenter    = 2 * (1 << ALF_NUM_BIT_SHIFT) - 1;
+#endif
+  Int minValueCenter    = 0 ; 
+
+  for(Int i = 0; i < filterLength-1; i++)
+  {
+    filter[i] = Clip3(minValueNonCenter, maxValueNonCenter, filter[i]);
+  }
+
+  filter[filterLength-1] = Clip3(minValueCenter, maxValueCenter, filter[filterLength-1]);
+}
+
+
+static Pel Clip_post(int high, int val)
+{
+  return (Pel)(((val > high)? high: val));
+}
+
+
+Void TComAdaptiveLoopFilter::setAlfCtrlFlags(AlfCUCtrlInfo* pAlfParam, TComDataCU *pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt &idx)
+{
+  TComPic* pcPic = pcCU->getPic();
+  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (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 uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  
+  if( ( uiRPelX >= pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  {
+    UInt uiIdx = uiAbsPartIdx;
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
+    {
+      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+      
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        setAlfCtrlFlags(pAlfParam, pcCU, uiIdx, uiDepth+1, idx);
+      }
+      uiIdx += uiQNumParts;
+    }
+    
+    return;
+  }
+  
+  if( uiDepth <= pAlfParam->alf_max_depth || pcCU->isFirstAbsZorderIdxInDepth(uiAbsPartIdx, pAlfParam->alf_max_depth))
+  {
+    if (uiDepth > pAlfParam->alf_max_depth)
+    {
+      pcCU->setAlfCtrlFlagSubParts(pAlfParam->alf_cu_flag[idx], uiAbsPartIdx, pAlfParam->alf_max_depth);
+    }
+    else
+    {
+      pcCU->setAlfCtrlFlagSubParts(pAlfParam->alf_cu_flag[idx], uiAbsPartIdx, uiDepth );
+    }
+    idx++;
+  }
+}
+
+/** Initialize the variables for one ALF LCU
+ * \param rAlfLCU to-be-initialized ALF LCU
+ * \param sliceID slice index
+ * \param tileID tile index
+ * \param pcCU CU data pointer
+ * \param maxNumSUInLCU maximum number of SUs in one LCU
+ */
+Void TComAdaptiveLoopFilter::InitAlfLCUInfo(AlfLCUInfo& rAlfLCU, Int sliceID, Int tileID, TComDataCU* pcCU, UInt maxNumSUInLCU)
+{
+  //pcCU
+  rAlfLCU.pcCU     = pcCU;
+  //sliceID
+  rAlfLCU.sliceID = sliceID;
+  //tileID
+  rAlfLCU.tileID  = tileID;
+
+  //numSGU, vpAlfBLock;
+  std::vector<NDBFBlockInfo>& vNDBFBlock = *(pcCU->getNDBFilterBlocks());
+  rAlfLCU.vpAlfBlock.clear();
+  rAlfLCU.numSGU = 0;
+  for(Int i=0; i< vNDBFBlock.size(); i++)
+  {
+    if( vNDBFBlock[i].sliceID == sliceID)
+    {
+      rAlfLCU.vpAlfBlock.push_back( &(vNDBFBlock[i])  );
+      rAlfLCU.numSGU ++;
+    }
+  }
+  //startSU
+  rAlfLCU.startSU = rAlfLCU.vpAlfBlock.front()->startSU;
+  //endSU
+  rAlfLCU.endSU   = rAlfLCU.vpAlfBlock.back()->endSU;
+  //bAllSUsInLCUInSameSlice
+  rAlfLCU.bAllSUsInLCUInSameSlice = (rAlfLCU.startSU == 0)&&( rAlfLCU.endSU == maxNumSUInLCU -1);
+}
+
+/** create and initialize variables for picture ALF processing
+ * \param pcPic picture-level data pointer
+ * \param numSlicesInPic number of slices in picture
+ */
+Void TComAdaptiveLoopFilter::createPicAlfInfo(TComPic* pcPic, Int numSlicesInPic, Int alfQP)
+{
+  m_uiNumSlicesInPic = numSlicesInPic;
+  m_iSGDepth         = pcPic->getSliceGranularityForNDBFilter();
+
+  m_bUseNonCrossALF = ( pcPic->getIndependentSliceBoundaryForNDBFilter() || pcPic->getIndependentTileBoundaryForNDBFilter());
+  m_pcPic = pcPic;
+
+  m_isNonCrossSlice = pcPic->getIndependentSliceBoundaryForNDBFilter(); 
+  m_suWidth = pcPic->getMinCUWidth();
+  m_suHeight= pcPic->getMinCUHeight();
+  m_alfQP = alfQP; 
+    m_ppSliceAlfLCUs = new AlfLCUInfo*[m_uiNumSlicesInPic];
+    m_pvpAlfLCU = new std::vector< AlfLCUInfo* >[m_uiNumSlicesInPic];
+    m_pvpSliceTileAlfLCU = new std::vector< std::vector< AlfLCUInfo* > >[m_uiNumSlicesInPic];
+
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      m_ppSliceAlfLCUs[s] = NULL;
+      if(!pcPic->getValidSlice(s))
+      {
+        continue;
+      }
+
+      std::vector< TComDataCU* >& vSliceLCUPointers = pcPic->getOneSliceCUDataForNDBFilter(s);
+      Int                         numLCU           = (Int)vSliceLCUPointers.size();
+
+      //create Alf LCU info
+      m_ppSliceAlfLCUs[s] = new AlfLCUInfo[numLCU];
+      for(Int i=0; i< numLCU; i++)
+      {
+        TComDataCU* pcCU       = vSliceLCUPointers[i];
+        if(pcCU->getPic()==0)
+        {
+          continue;
+        }
+        Int         currTileID = pcPic->getPicSym()->getTileIdxMap(pcCU->getAddr());
+
+        InitAlfLCUInfo(m_ppSliceAlfLCUs[s][i], s, currTileID, pcCU, pcPic->getNumPartInCU());
+      }
+
+      //distribute Alf LCU info pointers to slice container
+      std::vector< AlfLCUInfo* >&    vpSliceAlfLCU     = m_pvpAlfLCU[s]; 
+      vpSliceAlfLCU.reserve(numLCU);
+      vpSliceAlfLCU.resize(0);
+      std::vector< std::vector< AlfLCUInfo* > > &vpSliceTileAlfLCU = m_pvpSliceTileAlfLCU[s];
+      Int prevTileID = -1;
+      Int numValidTilesInSlice = 0;
+
+      for(Int i=0; i< numLCU; i++)
+      {
+        AlfLCUInfo* pcAlfLCU = &(m_ppSliceAlfLCUs[s][i]);
+
+        //container of Alf LCU pointers for slice processing
+        vpSliceAlfLCU.push_back( pcAlfLCU);
+
+        if(pcAlfLCU->tileID != prevTileID)
+        {
+          if(prevTileID == -1 || pcPic->getIndependentTileBoundaryForNDBFilter())
+          {
+            prevTileID = pcAlfLCU->tileID;
+            numValidTilesInSlice ++;
+            vpSliceTileAlfLCU.resize(numValidTilesInSlice);
+          }
+        }
+        //container of Alf LCU pointers for tile processing 
+        vpSliceTileAlfLCU[numValidTilesInSlice-1].push_back(pcAlfLCU);
+      }
+
+      assert( vpSliceAlfLCU.size() == numLCU);
+    }
+ 
+    if(m_bUseNonCrossALF)
+    {
+      m_pcSliceYuvTmp = pcPic->getYuvPicBufferForIndependentBoundaryProcessing();
+    }
+
+}
+
+/** Destroy ALF slice units
+ */
+Void TComAdaptiveLoopFilter::destroyPicAlfInfo()
+{
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      if(m_ppSliceAlfLCUs[s] != NULL)
+      {
+        delete[] m_ppSliceAlfLCUs[s];
+        m_ppSliceAlfLCUs[s] = NULL;
+      }
+    }
+    delete[] m_ppSliceAlfLCUs;
+    m_ppSliceAlfLCUs = NULL;
+
+    delete[] m_pvpAlfLCU;
+    m_pvpAlfLCU = NULL;
+
+    delete[] m_pvpSliceTileAlfLCU;
+    m_pvpSliceTileAlfLCU = NULL;
+}
+
+
+/** Copy ALF CU control flags from ALF parameters for slices
+ * \param [in] vAlfParamSlices ALF CU control parameters
+ */
+Void TComAdaptiveLoopFilter::transferCtrlFlagsFromAlfParam(std::vector<AlfCUCtrlInfo>& vAlfParamSlices)
+{
+  assert(m_uiNumSlicesInPic == vAlfParamSlices.size());
+
+  for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    AlfCUCtrlInfo& rAlfParam = vAlfParamSlices[s];
+    transferCtrlFlagsFromAlfParamOneSlice( m_pvpAlfLCU[s], 
+      (rAlfParam.cu_control_flag ==1)?true:false, 
+      rAlfParam.alf_max_depth, 
+      rAlfParam.alf_cu_flag
+      );
+  }
+}
+/** Copy ALF CU control flags from ALF CU control parameters for one slice
+ * \param [in] vpAlfLCU ALF LCU data container 
+ * \param [in] bCUCtrlEnabled true for ALF CU control enabled
+ * \param [in] iAlfDepth ALF CU control depth
+ * \param [in] vCtrlFlags ALF CU control flags
+ */
+Void TComAdaptiveLoopFilter::transferCtrlFlagsFromAlfParamOneSlice(std::vector< AlfLCUInfo* > &vpAlfLCU, Bool bCUCtrlEnabled, Int iAlfDepth, std::vector<UInt>& vCtrlFlags)
+{
+
+  if(!bCUCtrlEnabled)
+  {
+    for(Int idx=0; idx< vpAlfLCU.size(); idx++)
+    {
+      AlfLCUInfo& cAlfLCU = *(vpAlfLCU[idx]);
+      if(cAlfLCU.pcCU==0)
+      {
+        return;
+      }
+      if( cAlfLCU.bAllSUsInLCUInSameSlice)
+      {
+        cAlfLCU.pcCU->setAlfCtrlFlagSubParts(1, 0, 0);
+      }
+      else
+      {
+        for(UInt uiCurrSU= cAlfLCU.startSU; uiCurrSU<= cAlfLCU.endSU; uiCurrSU++)
+        {
+          cAlfLCU.pcCU->setAlfCtrlFlag(uiCurrSU, 1);
+        }
+      }
+    }
+    return;
+  }
+
+  UInt uiNumCtrlFlags = 0;
+  for(Int idx=0; idx< vpAlfLCU.size(); idx++)
+  {
+    AlfLCUInfo& cAlfLCU = *(vpAlfLCU[idx]);
+
+    if(cAlfLCU.pcCU==NULL)
+    {
+      continue;
+    }
+    uiNumCtrlFlags += (UInt)getCtrlFlagsFromAlfParam(&cAlfLCU, iAlfDepth, &(vCtrlFlags[uiNumCtrlFlags]) );
+  }
+}
+
+/** Copy region pixels
+ * \param vpAlfLCU ALF LCU data container
+ * \param pPicDst destination picture buffer
+ * \param pPicSrc source picture buffer
+ * \param stride stride size of picture buffer
+ * \param formatShift region size adjustment according to component size
+ */
+Void TComAdaptiveLoopFilter::copyRegion(std::vector< AlfLCUInfo* > &vpAlfLCU, Pel* pPicDst, Pel* pPicSrc, Int stride, Int formatShift)
+{
+  Int extSize = 4;
+  Int posX, posY, width, height, offset;
+  Pel *pPelDst, *pPelSrc;
+  
+  for(Int idx =0; idx < vpAlfLCU.size(); idx++)
+  {
+    AlfLCUInfo& cAlfLCU = *(vpAlfLCU[idx]);
+    for(Int n=0; n < cAlfLCU.numSGU; n++)
+    {
+      NDBFBlockInfo& rSGU = cAlfLCU[n];
+
+      posX     = (Int)(rSGU.posX   >> formatShift);
+      posY     = (Int)(rSGU.posY   >> formatShift);
+      width    = (Int)(rSGU.width  >> formatShift);
+      height   = (Int)(rSGU.height >> formatShift);
+      offset   = ( (posY- extSize) * stride)+ (posX -extSize);
+      pPelDst  = pPicDst + offset;    
+      pPelSrc  = pPicSrc + offset;    
+
+      for(Int j=0; j< (height + (extSize<<1)); j++)
+      {
+        ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*(width + (extSize<<1)));
+        pPelDst += stride;
+        pPelSrc += stride;
+      }
+    }
+  }
+}
+
+/** Extend region boundary 
+ * \param [in] vpAlfLCU ALF LCU data container
+ * \param [in,out] pPelSrc picture buffer
+ * \param [in] stride stride size of picture buffer
+ * \param [in] formatShift region size adjustment according to component size
+ */
+Void TComAdaptiveLoopFilter::extendRegionBorder(std::vector< AlfLCUInfo* > &vpAlfLCU, Pel* pPelSrc, Int stride, Int formatShift)
+{
+  UInt extSize = 4;
+  UInt width, height;
+  UInt posX, posY;
+  Pel* pPel;
+  Bool* pbAvail;
+  for(Int idx = 0; idx < vpAlfLCU.size(); idx++)
+  {
+    AlfLCUInfo& rAlfLCU = *(vpAlfLCU[idx]);
+    for(Int n =0; n < rAlfLCU.numSGU; n++)
+    {
+      NDBFBlockInfo& rSGU = rAlfLCU[n];
+      if(rSGU.allBordersAvailable)
+      {
+        continue;
+      }
+      posX     = rSGU.posX >> formatShift;
+      posY     = rSGU.posY >> formatShift;
+      width    = rSGU.width >> formatShift;
+      height   = rSGU.height >> formatShift;
+      pbAvail  = rSGU.isBorderAvailable;    
+      pPel     = pPelSrc + (posY * stride)+ posX;    
+      extendBorderCoreFunction(pPel, stride, pbAvail, width, height, extSize);
+    }
+  }
+}
+
+/** Core function for extending slice/tile boundary 
+ * \param [in, out] pPel processing block pointer
+ * \param [in] stride picture buffer stride
+ * \param [in] pbAvail neighboring blocks availabilities
+ * \param [in] width block width
+ * \param [in] height block height
+ * \param [in] extSize boundary extension size
+ */
+Void TComAdaptiveLoopFilter::extendBorderCoreFunction(Pel* pPel, Int stride, Bool* pbAvail, UInt width, UInt height, UInt extSize)
+{
+  Pel* pPelDst;
+  Pel* pPelSrc;
+  Int i, j;
+
+  for(Int pos =0; pos < NUM_SGU_BORDER; pos++)
+  {
+    if(pbAvail[pos])
+    {
+      continue;
+    }
+
+    switch(pos)
+    {
+    case SGU_L:
+      {
+        pPelDst = pPel - extSize;
+        pPelSrc = pPel;
+        for(j=0; j< height; j++)
+        {
+          for(i=0; i< extSize; i++)
+          {
+            pPelDst[i] = *pPelSrc;
+          }
+          pPelDst += stride;
+          pPelSrc += stride;
+        }
+      }
+      break;
+    case SGU_R:
+      {
+        pPelDst = pPel + width;
+        pPelSrc = pPelDst -1;
+        for(j=0; j< height; j++)
+        {
+          for(i=0; i< extSize; i++)
+          {
+            pPelDst[i] = *pPelSrc;
+          }
+          pPelDst += stride;
+          pPelSrc += stride;
+        }
+
+      }
+      break;
+    case SGU_T:
+      {
+        pPelSrc = pPel;
+        pPelDst = pPel - stride;
+        for(j=0; j< extSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*width);
+          pPelDst -= stride;
+        }
+      }
+      break;
+    case SGU_B:
+      {
+        pPelDst = pPel + height*stride;
+        pPelSrc = pPelDst - stride;
+        for(j=0; j< extSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*width);
+          pPelDst += stride;
+        }
+
+      }
+      break;
+    case SGU_TL:
+      {
+        if( (!pbAvail[SGU_T]) && (!pbAvail[SGU_L]))
+        {
+          pPelSrc = pPel  - extSize;
+          pPelDst = pPelSrc - stride;
+          for(j=0; j< extSize; j++)
+          {
+            ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*extSize);
+            pPelDst -= stride;
+          }         
+        }
+      }
+      break;
+    case SGU_TR:
+      {
+        if( (!pbAvail[SGU_T]) && (!pbAvail[SGU_R]))
+        {
+          pPelSrc = pPel + width;
+          pPelDst = pPelSrc - stride;
+          for(j=0; j< extSize; j++)
+          {
+            ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*extSize);
+            pPelDst -= stride;
+          }
+
+        }
+
+      }
+      break;
+    case SGU_BL:
+      {
+        if( (!pbAvail[SGU_B]) && (!pbAvail[SGU_L]))
+        {
+          pPelDst = pPel + height*stride; pPelDst-= extSize;
+          pPelSrc = pPelDst - stride;
+          for(j=0; j< extSize; j++)
+          {
+            ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*extSize);
+            pPelDst += stride;
+          }
+
+        }
+      }
+      break;
+    case SGU_BR:
+      {
+        if( (!pbAvail[SGU_B]) && (!pbAvail[SGU_R]))
+        {
+          pPelDst = pPel + height*stride; pPelDst += width;
+          pPelSrc = pPelDst - stride;
+          for(j=0; j< extSize; j++)
+          {
+            ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*extSize);
+            pPelDst += stride;
+          }
+        }
+      }
+      break;
+    default:
+      {
+        printf("Not a legal neighboring availability\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+/** Assign ALF on/off-control flags from ALF parameters to CU data
+ * \param [in] pcAlfLCU processing ALF LCU data pointer
+ * \param [in] alfDepth ALF on/off-control depth
+ * \param [in] pFlags on/off-control flags buffer in ALF parameters
+ */
+Int TComAdaptiveLoopFilter::getCtrlFlagsFromAlfParam(AlfLCUInfo* pcAlfLCU, Int alfDepth, UInt* pFlags)
+{
+
+  const UInt startSU               = pcAlfLCU->startSU;
+  const UInt endSU                 = pcAlfLCU->endSU;
+  const Bool bAllSUsInLCUInSameSlice = pcAlfLCU->bAllSUsInLCUInSameSlice;
+  const UInt maxNumSUInLCU         = m_pcPic->getNumPartInCU();
+
+  TComDataCU* pcCU = pcAlfLCU->pcCU;
+  Int   numCUCtrlFlags = 0;
+
+  UInt  currSU, CUDepth, setDepth, ctrlNumSU;
+  UInt  alfFlag;
+
+  currSU = startSU;
+  if( bAllSUsInLCUInSameSlice ) 
+  {
+    while(currSU < maxNumSUInLCU)
+    {
+      //depth of this CU
+      CUDepth = pcCU->getDepth(currSU);
+
+      //choose the min. depth for ALF
+      setDepth   = (alfDepth < CUDepth)?(alfDepth):(CUDepth);
+      ctrlNumSU = maxNumSUInLCU >> (setDepth << 1);
+
+      alfFlag= pFlags[numCUCtrlFlags];
+
+      pcCU->setAlfCtrlFlagSubParts(alfFlag, currSU, (UInt)setDepth);
+
+      numCUCtrlFlags++;
+      currSU += ctrlNumSU;
+    }
+    return numCUCtrlFlags;
+  }
+
+
+  UInt  LCUX    = pcCU->getCUPelX();
+  UInt  LCUY    = pcCU->getCUPelY();
+
+  Bool  bFirst, bValidCU;
+  UInt  idx, LPelXSU, TPelYSU;
+
+  bFirst= true;
+  while(currSU <= endSU)
+  {
+    //check picture boundary
+    while(!( LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ] < m_img_width  ) || 
+          !( LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ] < m_img_height )
+      )
+    {
+      currSU++;
+      if(currSU >= maxNumSUInLCU || currSU > endSU)
+      {
+        break;
+      }
+    }
+
+    if(currSU >= maxNumSUInLCU || currSU > endSU)
+    {
+      break;
+    }
+
+    //depth of this CU
+    CUDepth = pcCU->getDepth(currSU);
+
+    //choose the min. depth for ALF
+    setDepth   = (alfDepth < CUDepth)?(alfDepth):(CUDepth);
+    ctrlNumSU = maxNumSUInLCU >> (setDepth << 1);
+
+    if(bFirst)
+    {
+      if(currSU !=0 )
+      {
+        currSU = ((UInt)(currSU/ctrlNumSU))* ctrlNumSU;
+      }
+      bFirst = false;
+    }
+
+    //alf flag for this CU
+    alfFlag= pFlags[numCUCtrlFlags];
+
+    bValidCU = false;
+    for(idx = currSU; idx < currSU + ctrlNumSU; idx++)
+    {
+      if(idx < startSU || idx > endSU)
+      {
+        continue;
+      }
+
+      LPelXSU   = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[idx] ];
+      TPelYSU   = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[idx] ];
+
+      if( !( LPelXSU < m_img_width )  || !( TPelYSU < m_img_height )  )
+      {
+        continue;
+      }
+
+      bValidCU = true;
+      pcCU->setAlfCtrlFlag(idx, alfFlag);
+    }
+
+    if(bValidCU)
+    {
+      numCUCtrlFlags++;
+    }
+
+    currSU += ctrlNumSU;
+  }
+
+  return numCUCtrlFlags;
+}
+
+/** reconstruct ALF luma coefficient
+ * \param [in] alfLCUParam ALF parameters 
+ * \param [out] filterCoeff reconstructed luma coefficients
+ */
+Void TComAdaptiveLoopFilter::reconstructLumaCoefficients(ALFParam* alfLCUParam, Int** filterCoeff)
+{
+  Int sum, coeffPred, ind;
+#if LCUALF_QP_DEPENDENT_BITS
+  Int alfPrecisionBit = getAlfPrecisionBit( m_alfQP );
+#endif
+  const Int* filtMag = NULL;
+  filtMag = weightsTabShapes[0];
+
+  // Undo intra-filter prediction
+  for(ind = 0; ind < alfLCUParam->filters_per_group; ind++)
+  {
+    sum = 0;
+
+    for(Int i = 0; i < alfLCUParam->num_coeff-2; i++)
+    {
+      sum += (filtMag[i] * alfLCUParam->coeffmulti[ind][i]);
+      filterCoeff[ind][i] = alfLCUParam->coeffmulti[ind][i];
+    }
+
+    if(alfLCUParam->nbSPred[ind] == 0)
+    {
+      if((alfLCUParam->predMethod==0)|(ind==0))
+      {
+#if LCUALF_QP_DEPENDENT_BITS
+        coeffPred = ((1<<alfPrecisionBit)-sum) >> 2;
+#else
+        coeffPred = ((1<<ALF_NUM_BIT_SHIFT)-sum) >> 2;
+#endif
+      }
+      else
+      {
+        coeffPred = (0-sum) >> 2;
+      }
+
+      filterCoeff[ind][alfLCUParam->num_coeff-2] = coeffPred + alfLCUParam->coeffmulti[ind][alfLCUParam->num_coeff-2];
+    }
+    else
+    {
+      filterCoeff[ind][alfLCUParam->num_coeff-2] = alfLCUParam->coeffmulti[ind][alfLCUParam->num_coeff-2];
+    }
+
+    sum += filtMag[alfLCUParam->num_coeff-2] * filterCoeff[ind][alfLCUParam->num_coeff-2];
+
+    if((alfLCUParam->predMethod==0)|(ind==0))
+    {
+#if LCUALF_QP_DEPENDENT_BITS
+      coeffPred = (1<<alfPrecisionBit)-sum;
+#else
+      coeffPred = (1<<ALF_NUM_BIT_SHIFT)-sum;
+#endif
+    }
+    else
+    {
+      coeffPred = -sum;
+    }
+
+    filterCoeff[ind][alfLCUParam->num_coeff-1] = coeffPred + alfLCUParam->coeffmulti[ind][alfLCUParam->num_coeff-1];
+  }
+
+
+  // Undo inter-filter prediction
+  for(ind = 1; ind < alfLCUParam->filters_per_group; ind++)
+  {
+    if(alfLCUParam->predMethod)
+    {
+      // Prediction
+      for(Int i = 0; i < alfLCUParam->num_coeff; i++)
+      {
+        filterCoeff[ind][i] = (int)(filterCoeff[ind][i] + filterCoeff[ind - 1][i]);
+      }
+    }
+  }
+
+}
+
+
+/** reconstruct ALF chroma coefficient
+ * \param [in] alfLCUParam ALF parameters 
+ * \param [out] filterCoeff reconstructed chroma coefficients
+ */
+Void TComAdaptiveLoopFilter::reconstructChromaCoefficients(ALFParam* alfLCUParam, Int** filterCoeff)
+{
+  Int sum = 0;
+  Int i, coeffPred;
+  const Int* filtMag = NULL;
+  filtMag = weightsTabShapes[0];
+
+  for(i=0; i<alfLCUParam->num_coeff-1; i++)
+  {
+    sum += (filtMag[i] * alfLCUParam->coeffmulti[0][i]);
+    filterCoeff[0][i] = alfLCUParam->coeffmulti[0][i];
+  }
+
+#if LCUALF_QP_DEPENDENT_BITS
+  Int alfPrecisionBit = getAlfPrecisionBit( m_alfQP );
+  coeffPred = (1<<alfPrecisionBit) - sum;
+#else
+  coeffPred = (1<<ALF_NUM_BIT_SHIFT) - sum;
+#endif
+  filterCoeff[0][alfLCUParam->num_coeff-1] = coeffPred + alfLCUParam->coeffmulti[0][alfLCUParam->num_coeff-1];
+}
+
+
+/** reconstruct ALF coefficient
+ * \param [in] compIdx component index
+ * \param [in] alfLCUParam ALF parameters 
+ * \param [out] filterCoeff reconstructed coefficients
+ * \param [out] varIndTab the merged groups in block-based adaptation mode
+ */
+Void TComAdaptiveLoopFilter::reconstructCoefInfo(Int compIdx, ALFParam* alfLCUParam, Int** filterCoeff, Int* varIndTab)
+{
+  switch(compIdx)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      alfLCUParam->filters_per_group = 1;
+      reconstructChromaCoefficients(alfLCUParam, filterCoeff);
+    }
+    break;
+  case ALF_Y:
+    {
+      ::memset(varIndTab, 0, NO_VAR_BINS * sizeof(Int));
+      if(alfLCUParam->filters_per_group > 1)
+      {
+        for(Int i = 1; i < NO_VAR_BINS; ++i)
+        {
+          if(alfLCUParam->filterPattern[i])
+          {
+            varIndTab[i] = varIndTab[i-1] + 1;
+          }
+          else
+          {
+            varIndTab[i] = varIndTab[i-1];
+          }
+        }
+      }
+      reconstructLumaCoefficients(alfLCUParam, filterCoeff);
+    }
+    break;
+  default:
+    {
+      printf("not legal component ID for ALF\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+}
+
+
+/** filter process with CU-On/Off control
+ * \param [in] alfLCUParam ALF parameters 
+ * \param [in] regionLCUInfo ALF CU-on/off control parameters 
+ * \param [in] pDec decoded picture
+ * \param [out] pRest filtered picture
+ * \param [in] stride picture stride in memory
+ * \param [in] caculateBAIdx calculate BA filter index (true) or BA filter index array is ready (false)
+ */
+Void TComAdaptiveLoopFilter::filterRegionCUControl(ALFParam** alfLCUParams, std::vector<AlfLCUInfo*>& regionLCUInfo, Pel* pDec, Pel* pRest, Int stride, Bool caculateBAIdx)
+{
+  Int ypos, xpos, currSU, startSU, endSU, lcuX, lcuY;
+  Int yposEnd, xposEnd;
+
+  for(Int i=0; i< (Int)regionLCUInfo.size(); i++)
+  {
+    AlfLCUInfo& alfLCUinfo = *(regionLCUInfo[i]); 
+    TComDataCU* pcCU = alfLCUinfo.pcCU;
+    Int addr = pcCU->getAddr();
+
+    ALFParam* alfParam = alfLCUParams[addr];
+
+    if(alfParam->alf_flag == 1)
+    {
+      lcuX    = pcCU->getCUPelX();
+      lcuY    = pcCU->getCUPelY();
+
+      if(caculateBAIdx)
+      {
+        xposEnd = lcuX + g_uiMaxCUWidth;
+        yposEnd = lcuY + g_uiMaxCUHeight;
+
+        if(xposEnd > m_img_width)
+        {
+          xposEnd = m_img_width;
+        }
+
+        if(yposEnd > m_img_height)
+        {
+          yposEnd = m_img_height;
+        }
+
+        calcOneRegionVar(m_varImg, pDec, stride, (alfParam->filters_per_group == 1), lcuY, yposEnd, lcuX, xposEnd);        
+      }
+
+      //reconstruct ALF coefficients & related parameters 
+      reconstructCoefInfo(ALF_Y, alfParam, m_filterCoeffSym, m_varIndTab);
+
+      startSU = alfLCUinfo.startSU;
+      endSU   = alfLCUinfo.endSU;
+
+
+      for(currSU= startSU; currSU<= endSU; currSU++)
+      {
+        xpos  = lcuX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+        ypos  = lcuY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+        if( !( xpos < m_img_width )  || !( ypos < m_img_height )  )
+        {
+          continue;
+        }
+
+        if(pcCU->getAlfCtrlFlag(currSU))
+        {
+          filterOneCompRegion(pRest, pDec, stride, false, ypos, ypos+m_suHeight, xpos, xpos+m_suWidth, m_filterCoeffSym, m_varIndTab, m_varImg);
+        }
+      }
+
+    } //alf_flag == 1
+  }
+
+}
+
+
+/** filter process without CU-On/Off control
+ * \param [in] alfLCUParam ALF parameters 
+ * \param [in] regionLCUInfo ALF CU-on/off control parameters 
+ * \param [in] pDec decoded picture
+ * \param [out] pRest filtered picture
+ * \param [in] stride picture stride in memory
+ * \param [in] formatShift luma component (0) or chroma component (1)
+ * \param [in] caculateBAIdx calculate BA filter index (true) or BA filter index array is ready (false)
+ */
+Void TComAdaptiveLoopFilter::filterRegion(Int compIdx, ALFParam** alfLCUParams, std::vector<AlfLCUInfo*>& regionLCUInfo, Pel* pDec, Pel* pRest, Int stride, Int formatShift, Bool caculateBAIdx)
+{
+  Int height, width;
+  Int ypos, xpos,  lcuX, lcuY;
+  Int yposEnd, xposEnd;
+
+  for(Int i=0; i< regionLCUInfo.size(); i++)
+  {
+    AlfLCUInfo& alfLCUinfo = *(regionLCUInfo[i]); 
+    TComDataCU* pcCU = alfLCUinfo.pcCU;
+    Int addr = pcCU->getAddr();
+
+    ALFParam* alfParam = alfLCUParams[addr];
+
+    if(alfParam->alf_flag == 1)
+    {
+      lcuX    = pcCU->getCUPelX();
+      lcuY    = pcCU->getCUPelY();
+
+      if(caculateBAIdx)
+      {
+        assert(compIdx == ALF_Y);
+
+        xposEnd = lcuX + g_uiMaxCUWidth;
+        yposEnd = lcuY + g_uiMaxCUHeight;
+
+        if(xposEnd > m_img_width)
+        {
+          xposEnd = m_img_width;
+        }
+
+        if(yposEnd > m_img_height)
+        {
+          yposEnd = m_img_height;
+        }
+
+        calcOneRegionVar(m_varImg, pDec, stride, (alfParam->filters_per_group == 1), lcuY, yposEnd, lcuX, xposEnd);        
+      }
+
+      //reconstruct ALF coefficients & related parameters 
+      reconstructCoefInfo(compIdx, alfParam, m_filterCoeffSym, m_varIndTab);
+
+      //filtering process
+      for(Int j=0; j< alfLCUinfo.numSGU; j++)
+      {
+        ypos    = (Int)(alfLCUinfo[j].posY   >> formatShift);
+        xpos    = (Int)(alfLCUinfo[j].posX   >> formatShift);
+        height = (Int)(alfLCUinfo[j].height >> formatShift);
+        width  = (Int)(alfLCUinfo[j].width  >> formatShift);
+
+        filterOneCompRegion(pRest, pDec, stride, (compIdx!=ALF_Y), ypos, ypos+height, xpos, xpos+width, m_filterCoeffSym, m_varIndTab, m_varImg);
+      }
+    } //alf_flag == 1
+  }
+}
+
+
+/** predict chroma center coefficient
+ * \param [in] coeff ALF chroma coefficient
+ * \param [in] numCoef number of chroma coefficients
+ */
+Void TComAdaptiveLoopFilter::predictALFCoeffChroma(Int* coeff, Int numCoef)
+{
+  Int sum=0;
+  for(Int i=0; i< numCoef-1;i++)
+  {
+    sum += (2* coeff[i]);
+  }
+
+#if LCUALF_QP_DEPENDENT_BITS 
+  Int alfPrecisionBit = getAlfPrecisionBit( m_alfQP );
+  Int pred = (1<<alfPrecisionBit) - (sum);
+#else
+  Int pred = (1<<ALF_NUM_BIT_SHIFT) - (sum);
+#endif
+  coeff[numCoef-1] = coeff[numCoef-1] - pred;
+}
+
+/** filtering pixels
+ * \param [out] imgRes filtered picture
+ * \param [in] imgPad decoded picture 
+ * \param [in] stride picture stride in memory
+ * \param [in] isChroma chroma component (true) or luma component (false)
+ * \param [in] yPos y position of the top-left pixel in one to-be-filtered region
+ * \param [in] yPosEnd y position of the right-bottom pixel in one to-be-filtered region
+ * \param [in] xPos x position of the top-left pixel in one to-be-filtered region
+ * \param [in] xPosEnd x position of the right-bottom pixel in one to-be-filtered region
+ * \param [in] filterSet filter coefficients
+ * \param [in] mergeTable the merged groups in block-based adaptation mode
+ * \param [in] varImg BA filter index array 
+ */
+Void TComAdaptiveLoopFilter::filterOneCompRegion(Pel *imgRes, Pel *imgPad, Int stride, Bool isChroma
+                                                , Int yPos, Int yPosEnd, Int xPos, Int xPosEnd
+                                                , Int** filterSet, Int* mergeTable, Pel** varImg
+                                                )
+{
+#if LCUALF_QP_DEPENDENT_BITS  
+  Int alfPrecisionBit = getAlfPrecisionBit( m_alfQP );
+  Int numBitsMinus1   = alfPrecisionBit;
+  Int offset          = (1<<(alfPrecisionBit-1));
+#else
+  static Int numBitsMinus1= (Int)ALF_NUM_BIT_SHIFT;
+  static Int offset       = (1<<( (Int)ALF_NUM_BIT_SHIFT-1));
+#endif
+  static Int shiftHeight  = (Int)(log((double)VAR_SIZE_H)/log(2.0));
+  static Int shiftWidth   = (Int)(log((double)VAR_SIZE_W)/log(2.0));
+
+  Pel *imgPad1,*imgPad2,*imgPad3, *imgPad4, *imgPad5, *imgPad6;
+  Pel *var = varImg[yPos>>shiftHeight] + (xPos>>shiftWidth);;
+  Int i, j, pixelInt;
+  Int *coef = NULL;
+
+  coef    = filterSet[0];
+  imgPad += (yPos*stride);
+  imgRes += (yPos*stride);
+
+  Int yLineInLCU;
+  Int paddingLine;
+  //Int varInd = 0;
+  Int lcuHeight     = isChroma ? m_lcuHeightChroma     : m_lcuHeight;
+  Int lineIdxPadBot = isChroma ? m_lineIdxPadBotChroma : m_lineIdxPadBot;
+  Int lineIdxPadTop = isChroma ? m_lineIdxPadTopChroma : m_lineIdxPadTop;
+  Int img_height    = isChroma ? m_img_height>>1       : m_img_height;
+
+  for(i= yPos; i< yPosEnd; i++)
+  {
+    yLineInLCU = i % lcuHeight;
+
+    if(isChroma && yLineInLCU == 0 && i>0)
+    {
+      paddingLine = yLineInLCU + 2;
+      imgPad1 = imgPad + stride;
+      imgPad2 = imgPad - stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;
+    }
+    else if(yLineInLCU<lineIdxPadBot || i-yLineInLCU+lcuHeight >= img_height)
+    {
+      imgPad1 = imgPad +   stride;
+      imgPad2 = imgPad -   stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = imgPad + 3*stride;
+      imgPad6 = imgPad - 3*stride;
+    }
+    else if (yLineInLCU<lineIdxPadTop)
+    {
+      paddingLine = - yLineInLCU + lineIdxPadTop - 1;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + min(paddingLine, 1)*stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + min(paddingLine, 2)*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + min(paddingLine, 3)*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - 3*stride;
+    }
+    else
+    {
+      paddingLine = yLineInLCU - lineIdxPadTop ;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - min(paddingLine, 1)*stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + 2*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - min(paddingLine, 2)*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;
+    } 
+
+    if(!isChroma)
+    {
+      var = varImg[i>>shiftHeight] + (xPos>>shiftWidth);
+    }
+
+    for(j= xPos; j< xPosEnd ; j++)
+    {
+      if (!isChroma && j % VAR_SIZE_W==0) 
+      {
+        coef = filterSet[mergeTable[*(var++)]];
+      }
+
+      pixelInt  = coef[0]* (imgPad5[j  ] + imgPad6[j  ]);
+
+      pixelInt += coef[1]* (imgPad3[j  ] + imgPad4[j  ]);
+
+      pixelInt += coef[2]* (imgPad1[j-1] + imgPad2[j+1]);
+      pixelInt += coef[3]* (imgPad1[j  ] + imgPad2[j  ]);
+      pixelInt += coef[4]* (imgPad1[j+1] + imgPad2[j-1]);
+
+      pixelInt += coef[5]* (imgPad[j+4] + imgPad[j-4]);
+      pixelInt += coef[6]* (imgPad[j+3] + imgPad[j-3]);
+      pixelInt += coef[7]* (imgPad[j+2] + imgPad[j-2]);
+      pixelInt += coef[8]* (imgPad[j+1] + imgPad[j-1]);
+      pixelInt += coef[9]* (imgPad[j  ]);
+
+      pixelInt=(Int)((pixelInt+offset) >> numBitsMinus1);
+      imgRes[j] = Clip( pixelInt );
+    }
+
+    imgPad += stride;
+    imgRes += stride;
+  }  
+}
+
+#if LCUALF_QP_DEPENDENT_BITS
+/** filtering pixels
+ * \param [in] qp quantization parameter
+ */
+Int  TComAdaptiveLoopFilter::getAlfPrecisionBit(Int qp)
+{
+  Int alfPrecisionBit = 8;
+
+  if (qp < ALF_QP1)
+  {
+    alfPrecisionBit = 8;
+  }
+  else if (qp < ALF_QP2)
+  {
+    alfPrecisionBit = 7;
+  }
+  else if (qp < ALF_QP3)
+  {
+    alfPrecisionBit = 6;
+  }
+  else
+  {
+    alfPrecisionBit = 5;
+  }
+
+  return alfPrecisionBit;
+}
+#endif
+
+/** filtering pixels
+ * \param [out] imgYvar BA filter index array
+ * \param [in] imgYpad decoded picture 
+ * \param [in] stride picture stride in memory
+ * \param [in] isOnlyOneGroup only one filter is used (true) or multiple filters are used (false)
+ * \param [in] yPos y position of the top-left pixel in one to-be-filtered region
+ * \param [in] yPosEnd y position of the right-bottom pixel in one to-be-filtered region
+ * \param [in] xPos x position of the top-left pixel in one to-be-filtered region
+ * \param [in] xPosEnd x position of the right-bottom pixel in one to-be-filtered region
+ */
+Void TComAdaptiveLoopFilter::calcOneRegionVar(Pel **imgYvar, Pel *imgYpad, Int stride, Bool isOnlyOneGroup, Int yPos, Int yPosEnd, Int xPos, Int xPosEnd)
+{
+
+  static Int shiftH = (Int)(log((double)VAR_SIZE_H)/log(2.0));
+  static Int shiftW = (Int)(log((double)VAR_SIZE_W)/log(2.0));
+  static Int varMax = (Int)NO_VAR_BINS-1;  
+  static Int th[NO_VAR_BINS] = {0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5}; 
+  static Int avgVarTab[3][6] = { {0,  1,  2,  3,  4,  5,},
+  {0,  6,  7,  8,  9, 10,},
+  {0, 11, 12, 13, 14, 15}   };
+
+  Int i, j, avgVar, vertical, horizontal, direction, yOffset;
+  Pel *imgYPadCur, *imgYPadUp, *imgYPadDown;
+
+  if (isOnlyOneGroup)
+  {
+    for(i = yPos; i < yPosEnd; i=i+4)
+    {
+      for(j = xPos; j < xPosEnd; j=j+4)
+      {
+        imgYvar[i>>shiftH][j>>shiftW] = 0;
+      }
+    }
+    return;
+  }
+
+  for(i = yPos; i < yPosEnd; i=i+4)
+  {
+    yOffset     = (i*stride) + stride;
+    imgYPadCur  = &imgYpad[yOffset];
+    imgYPadUp   = &imgYpad[yOffset + stride];
+    imgYPadDown = &imgYpad[yOffset - stride];
+
+    for(j = xPos; j < xPosEnd; j=j+4)
+    {
+      // Compute at sub-sample by 2
+      vertical   =  abs((imgYPadCur[j+1]<<1) - imgYPadDown[j+1] - imgYPadUp [j+1]);
+      horizontal =  abs((imgYPadCur[j+1]<<1) - imgYPadCur [j+2] - imgYPadCur[j  ]);
+
+      vertical   += abs((imgYPadCur[j+2]<<1) - imgYPadDown[j+2] - imgYPadUp [j+2]);
+      horizontal += abs((imgYPadCur[j+2]<<1) - imgYPadCur [j+3] - imgYPadCur[j+1]);
+
+      vertical   += abs((imgYPadCur[j+1+stride]<<1) - imgYPadDown[j+1+stride] - imgYPadUp [j+1+stride]);
+      horizontal += abs((imgYPadCur[j+1+stride]<<1) - imgYPadCur [j+2+stride] - imgYPadCur[j+stride  ]);
+
+      vertical   += abs((imgYPadCur[j+2+stride]<<1) - imgYPadDown[j+2+stride] - imgYPadUp [j+2+stride]);
+      horizontal += abs((imgYPadCur[j+2+stride]<<1) - imgYPadCur [j+3+stride] - imgYPadCur[j+1+stride]);
+
+      direction = 0;
+      if (vertical > 2*horizontal) 
+      {
+        direction = 1; //vertical
+      }
+      if (horizontal > 2*vertical)
+      {
+        direction = 2; //horizontal
+      }
+
+      avgVar = (vertical + horizontal) >> 2;
+      avgVar = (Pel) Clip_post( varMax, avgVar>>(g_uiBitIncrement+1) );
+      avgVar = th[avgVar];
+      avgVar = avgVarTab[direction][avgVar];
+      imgYvar[i>>shiftH][j>>shiftW] = avgVar;
+    }
+  }
+}
+
+
+Void TComAdaptiveLoopFilter::resetLCUAlfInfo()
+{
+  //reset to all off
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      m_alfFiltInfo[compIdx][n]->alf_flag = 0;
+    }
+  }
+
+}
+
+Void TComAdaptiveLoopFilter::createLCUAlfInfo()
+{
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    m_alfFiltInfo[compIdx] = new ALFParam*[m_uiNumCUsInFrame];
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      m_alfFiltInfo[compIdx][n] = new ALFParam(compIdx);
+    }
+  }
+
+  resetLCUAlfInfo();
+}
+
+Void TComAdaptiveLoopFilter::destroyLCUAlfInfo()
+{
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    if(m_alfFiltInfo[compIdx] != NULL)
+    {
+      for(Int n=0; n< m_uiNumCUsInFrame; n++)
+      {
+        delete m_alfFiltInfo[compIdx][n];
+      }
+      delete[] m_alfFiltInfo[compIdx];
+      m_alfFiltInfo[compIdx] = NULL;
+    }
+  }
+}
+
+Pel* TComAdaptiveLoopFilter::getPicBuf(TComPicYuv* pPicYuv, Int compIdx)
+{
+  Pel* pBuf = NULL;
+  switch(compIdx)
+  {
+  case ALF_Y:
+    {
+      pBuf = pPicYuv->getLumaAddr();
+    }
+    break;
+  case ALF_Cb:
+    {
+      pBuf = pPicYuv->getCbAddr();
+    }
+    break;
+  case ALF_Cr:
+    {
+      pBuf = pPicYuv->getCrAddr();
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID for ALF\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.
+ */
+Void TComAdaptiveLoopFilter::PCMLFDisableProcess (TComPic* pcPic)
+{
+  xPCMRestoration(pcPic);
+}
+
+/** Picture-level PCM restoration. 
+ * \param pcPic picture (TComPic) pointer
+ * \returns Void
+ */
+Void TComAdaptiveLoopFilter::xPCMRestoration(TComPic* pcPic)
+{
+  Bool  bPCMFilter = (pcPic->getSlice(0)->getSPS()->getUsePCM() && pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag())? true : false;
+
+#if LOSSLESS_CODING
+  if(bPCMFilter || pcPic->getSlice(0)->getSPS()->getUseLossless())
+#else
+  if(bPCMFilter)
+#endif
+  {
+    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
+ */
+Void TComAdaptiveLoopFilter::xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth )
+{
+  TComPic* pcPic     = pcCU->getPic();
+  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts   = uiCurNumParts>>2;
+
+  // go to sub-CU
+  if( pcCU->getDepth(uiAbsZorderIdx) > uiDepth )
+  {
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      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() ) )
+        xPCMCURestoration( pcCU, uiAbsZorderIdx, uiDepth+1 );
+    }
+    return;
+  }
+
+  // restore PCM samples
+#if LOSSLESS_CODING 
+  if ((pcCU->getIPCMFlag(uiAbsZorderIdx)) || pcCU->isLosslessCoded( uiAbsZorderIdx))
+#else
+  if (pcCU->getIPCMFlag(uiAbsZorderIdx))
+#endif
+  {
+    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
+ */
+Void TComAdaptiveLoopFilter::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 LOSSLESS_CODING 
+    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) )
+    {
+      uiPcmLeftShiftBit = 0;
+    }
+    else
+#endif
+    {
+        uiPcmLeftShiftBit = g_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+    }
+  }
+  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 LOSSLESS_CODING 
+    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) )
+    {
+      uiPcmLeftShiftBit = 0;
+    }
+    else
+#endif
+    {
+      uiPcmLeftShiftBit = g_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+    }
+  }
+
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piSrc[uiX] = (piPcm[uiX] << uiPcmLeftShiftBit);
+    }
+    piPcm += uiWidth;
+    piSrc += uiStride;
+  }
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h	(revision 341)
@@ -0,0 +1,269 @@
+/* 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-2012, 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     TComAdaptiveLoopFilter.h
+    \brief    adaptive loop filter class (header)
+*/
+
+#ifndef __TCOMADAPTIVELOOPFILTER__
+#define __TCOMADAPTIVELOOPFILTER__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+  #define LCUALF_QP_DEPENDENT_BITS    1  
+
+#define ALF_FILTER_LEN       10
+#define ALF_MAX_NUM_COEF     ALF_FILTER_LEN    //!< maximum number of filter coefficients
+#define MAX_SQR_FILT_LENGTH   41                                      //!< ((max_horizontal_tap * max_vertical_tap) / 2 + 1) = ((11 * 5) / 2 + 1)
+
+#if LCUALF_QP_DEPENDENT_BITS
+#define ALF_QP1               28 
+#define ALF_QP2               34 
+#define ALF_QP3               39 
+#else
+#define ALF_NUM_BIT_SHIFT     8                                       ///< bit shift parameter for quantization of ALF param.
+#endif
+
+#define VAR_SIZE_H            4
+#define VAR_SIZE_W            4
+#define NO_VAR_BINS           16 
+#define NO_FILTERS            16
+#define MAX_SCAN_VAL          13
+#define MAX_EXP_GOLOMB        16
+
+
+
+/// Luma/Chroma component ID
+enum ALFComponentID
+{
+  ALF_Y = 0,
+  ALF_Cb,
+  ALF_Cr,
+  NUM_ALF_COMPONENT
+};
+/// ALF LCU merge type
+enum ALFLCUMergeType
+{
+  ALF_MERGE_DISABLED = 0,
+  ALF_MERGE_UP,
+  ALF_MERGE_LEFT,
+  ALF_MERGE_FIRST,
+  NUM_ALF_MERGE_TYPE
+};
+///
+/// Filter shape
+///
+enum ALFFilterShape
+{
+  ALF_CROSS9x7_SQUARE3x3 = 0,
+  NUM_ALF_FILTER_SHAPE
+};
+
+extern Int* kTableTabShapes[NUM_ALF_FILTER_SHAPE];
+extern Int depthIntShape1Sym[ALF_MAX_NUM_COEF+1];
+extern Int *pDepthIntTabShapes[NUM_ALF_FILTER_SHAPE];
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// ALF CU control parameters
+struct AlfCUCtrlInfo
+{
+  Int  cu_control_flag;                    //!< slice-level ALF CU control enabled/disabled flag 
+  UInt num_alf_cu_flag;                    //!< number of ALF CU control flags
+  UInt alf_max_depth;                      //!< ALF CU control depth
+  std::vector<UInt> alf_cu_flag;           //!< ALF CU control flags (container)
+
+  const AlfCUCtrlInfo& operator= (const AlfCUCtrlInfo& src);  //!< "=" operator
+  AlfCUCtrlInfo():cu_control_flag(0), num_alf_cu_flag(0), alf_max_depth(0) {} //!< constructor
+  Void reset();
+};
+
+
+///
+/// LCU-based ALF processing info
+///
+struct AlfLCUInfo
+{
+  TComDataCU* pcCU;            //!< TComDataCU pointer
+  Int         sliceID;        //!< slice ID
+  Int         tileID;         //!< tile ID
+  UInt        numSGU;        //!< number of slice granularity blocks 
+  UInt        startSU;       //!< starting SU z-scan address in LCU
+  UInt        endSU;         //!< ending SU z-scan address in LCU
+  Bool        bAllSUsInLCUInSameSlice; //!< true: all SUs in this LCU belong to same slice
+  std::vector<NDBFBlockInfo*> vpAlfBlock; //!< container for filter block pointers
+
+  NDBFBlockInfo& operator[] (Int idx) { return *( vpAlfBlock[idx]); } //!< [] operator
+  AlfLCUInfo():pcCU(NULL), sliceID(0), tileID(0), numSGU(0), startSU(0), endSU(0), bAllSUsInLCUInSameSlice(false) {} //!< constructor
+};
+
+
+///
+/// adaptive loop filter class
+///
+class TComAdaptiveLoopFilter
+{
+
+protected: //protected member variables
+
+  // filter shape information
+  static Int weightsShape1Sym[ALF_MAX_NUM_COEF+1];
+  static Int *weightsTabShapes[NUM_ALF_FILTER_SHAPE];
+  static Int m_sqrFiltLengthTab[NUM_ALF_FILTER_SHAPE];
+
+  // temporary buffer
+  TComPicYuv*   m_pcTempPicYuv;                          ///< temporary picture buffer for ALF processing
+  TComPicYuv* m_pcSliceYuvTmp;    //!< temporary picture buffer pointer when non-across slice boundary ALF is enabled
+
+
+  //filter coefficients buffer
+  Int **m_filterCoeffSym;
+
+  //classification
+  Int      m_varIndTab[NO_VAR_BINS];
+  Pel** m_varImg;
+
+  //parameters
+  Int   m_img_height;
+  Int   m_img_width;
+  Bool  m_bUseNonCrossALF;       //!< true for performing non-cross slice boundary ALF
+  UInt  m_uiNumSlicesInPic;      //!< number of slices in picture
+  Int   m_iSGDepth;              //!< slice granularity depth
+  UInt  m_uiNumCUsInFrame;
+
+  Int m_lcuHeight;
+  Int m_lineIdxPadBot;
+  Int m_lineIdxPadTop;
+
+  Int m_lcuHeightChroma;
+  Int m_lineIdxPadBotChroma;
+  Int m_lineIdxPadTopChroma;
+
+  //slice
+  TComPic* m_pcPic;
+  AlfLCUInfo** m_ppSliceAlfLCUs;
+  std::vector< AlfLCUInfo* > *m_pvpAlfLCU;
+  std::vector< std::vector< AlfLCUInfo* > > *m_pvpSliceTileAlfLCU;
+
+  Int m_suWidth;
+  Int m_suHeight;
+  Int m_numLCUInPicWidth;
+  Int m_numLCUInPicHeight;
+  ALFParam** m_alfFiltInfo[NUM_ALF_COMPONENT];
+  Bool m_isNonCrossSlice;
+  Int m_alfQP;
+
+private: //private member variables
+
+
+protected: //protected methods
+
+  Void createLCUAlfInfo();
+  Void destroyLCUAlfInfo();
+  Pel* getPicBuf(TComPicYuv* pPicYuv, Int compIdx);
+  Void predictALFCoeffChroma(Int* coeff, Int numCoef= ALF_MAX_NUM_COEF);
+  Void assignAlfOnOffControlFlags(TComPic* pcPic, std::vector<AlfCUCtrlInfo>& vAlfCUCtrlParam);
+  Void recALF(Int compIdx, ALFParam** alfLCUParams, Pel* pDec, Pel* pRest, Int stride, Int formatShift, std::vector<AlfCUCtrlInfo>* alfCUCtrlParam, Bool caculateBAIdx);
+  Void reconstructCoefInfo(Int compIdx, ALFParam* alfLCUParam, Int** filterCoeff, Int* varIndTab= NULL);
+  Void reconstructLumaCoefficients(ALFParam* alfLCUParam, Int** filterCoeff);
+  Void reconstructChromaCoefficients(ALFParam* alfLCUParam, Int** filterCoeff);
+  Void filterRegion(Int compIdx, ALFParam** alfLCUParams, std::vector<AlfLCUInfo*>& regionLCUInfo, Pel* pDec, Pel* pRest, Int stride, Int formatShift, Bool caculateBAIdx);
+  Void filterRegionCUControl(ALFParam** alfLCUParams, std::vector<AlfLCUInfo*>& regionLCUInfo, Pel* pDec, Pel* pRest, Int stride, Bool caculateBAIdx);
+  Bool isEnabledComponent(ALFParam** alfLCUParam);
+  Int  getAlfPrecisionBit(Int qp);
+  Void filterOneCompRegion(Pel *imgRes, Pel *imgPad, Int stride, Bool isChroma, Int yPos, Int yPosEnd, Int xPos, Int xPosEnd, Int** filterSet, Int* mergeTable, Pel** varImg);  
+  Void calcOneRegionVar(Pel **imgYvar, Pel *imgYpad, Int stride, Bool isOnlyOneGroup, Int yPos, Int yPosEnd, Int xPos, Int xPosEnd);
+
+
+  Void InitAlfLCUInfo(AlfLCUInfo& rAlfLCU, Int sliceID, Int tileID, TComDataCU* pcCU, UInt maxNumSUInLCU);
+  Void checkFilterCoeffValue( Int *filter, Int filterLength, Bool isChroma );
+  Void setAlfCtrlFlags(AlfCUCtrlInfo* pAlfParam, TComDataCU *pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt &idx);
+  Void transferCtrlFlagsFromAlfParam(std::vector<AlfCUCtrlInfo>& vAlfParamSlices); //!< Copy ALF CU control flags from ALF parameters for slices  
+  Void transferCtrlFlagsFromAlfParamOneSlice(std::vector<AlfLCUInfo*> &vpAlfLCU, Bool bCUCtrlEnabled, Int iAlfDepth, std::vector<UInt>& vCtrlFlags); //!< Copy ALF CU control flags from ALF parameter for one slice
+  Void extendBorderCoreFunction(Pel* pPel, Int stride, Bool* pbAvail, UInt width, UInt height, UInt extSize); //!< Extend slice boundary border  
+  Void copyRegion(std::vector<AlfLCUInfo*> &vpAlfLCU, Pel* pPicDst, Pel* pPicSrc, Int stride, Int formatShift = 0);
+  Void extendRegionBorder(std::vector<AlfLCUInfo*> &vpAlfLCU, Pel* pPelSrc, Int stride, Int formatShift = 0);
+  Int  getCtrlFlagsFromAlfParam(AlfLCUInfo* pcAlfLCU, Int iAlfDepth, UInt* puiFlags);
+
+  Void xPCMRestoration        (TComPic* pcPic);
+  Void xPCMCURestoration      (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth);
+  Void xPCMSampleRestoration  (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
+
+public: //public methods, interface functions
+
+  TComAdaptiveLoopFilter();
+  virtual ~TComAdaptiveLoopFilter() {}
+
+  Void create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
+  Void destroy ();
+
+  Void ALFProcess          (TComPic* pcPic, std::vector<AlfCUCtrlInfo>& vAlfCUCtrlParam, Bool isAlfCoefInSlice);
+  Void resetLCUAlfInfo     ();
+  Int  getNumLCUInPicWidth ()  {return m_numLCUInPicWidth;}
+  Int  getNumLCUInPicHeight() {return m_numLCUInPicHeight;}
+
+  ALFParam*** getAlfLCUParam() {return m_alfFiltInfo;}
+  Int  getNumCUsInPic()  {return m_uiNumCUsInFrame;} //!< get number of LCU in picture for ALF process
+  Void createPicAlfInfo (TComPic* pcPic, Int uiNumSlicesInPic = 1, Int alfQP = 26);
+  Void destroyPicAlfInfo();
+
+  Void PCMLFDisableProcess    ( TComPic* pcPic);                        ///< interface function for ALF process 
+
+protected: //memory allocation
+  Void destroyMatrix_Pel(Pel **m2D);
+  Void destroyMatrix_int(int **m2D);
+  Void initMatrix_int(int ***m2D, int d1, int d2);
+  Void initMatrix_Pel(Pel ***m2D, int d1, int d2);
+  Void destroyMatrix4D_double(double ****m4D, int d1, int d2);
+  Void destroyMatrix3D_double(double ***m3D, int d1);
+  Void destroyMatrix_double(double **m2D);
+  Void initMatrix4D_double(double *****m4D, int d1, int d2, int d3, int d4);
+  Void initMatrix3D_double(double ****m3D, int d1, int d2, int d3);
+  Void initMatrix_double(double ***m2D, int d1, int d2);
+  Void no_mem_exit(const char *where);
+  Void xError(const char *text, int code);
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitCounter.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitCounter.h	(revision 341)
@@ -0,0 +1,71 @@
+/* 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-2012, 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     TComBitCounter.h
+    \brief    Class for counting bits (header)
+*/
+
+#ifndef __COMBITCOUNTER__
+#define __COMBITCOUNTER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TComBitStream.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// class for counting bits
+class TComBitCounter : public TComBitIf
+{
+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; }
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitStream.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitStream.cpp	(revision 341)
@@ -0,0 +1,347 @@
+/* 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-2012, 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     TComBitStream.cpp
+    \brief    class for handling bitstream
+*/
+
+#include <stdint.h>
+#include <vector>
+#include "TComBitStream.h"
+#include <string.h>
+#include <memory.h>
+
+using namespace std;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComOutputBitstream::TComOutputBitstream()
+{
+  m_fifo = new vector<uint8_t>;
+  clear();
+  m_puiTileMarkerLocation     = new UInt[MAX_MARKER_PER_NALU];
+  m_uiTileMarkerLocationCount = 0;
+}
+
+TComOutputBitstream::~TComOutputBitstream()
+{
+  delete m_fifo;
+  delete [] m_puiTileMarkerLocation;
+}
+
+TComInputBitstream::TComInputBitstream(std::vector<uint8_t>* buf)
+{
+  m_fifo = buf;
+  m_fifo_idx = 0;
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+  m_puiTileMarkerLocation     = new UInt[MAX_MARKER_PER_NALU];
+  m_uiTileMarkerLocationCount = 0;
+  m_numBitsRead = 0;
+}
+
+TComInputBitstream::~TComInputBitstream()
+{
+  delete [] m_puiTileMarkerLocation;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+char* TComOutputBitstream::getByteStream() const
+{
+  return (char*) &m_fifo->front();
+}
+
+unsigned int TComOutputBitstream::getByteStreamLength()
+{
+  return unsigned(m_fifo->size());
+}
+
+void TComOutputBitstream::clear()
+{
+  m_fifo->clear();
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+  m_uiTileMarkerLocationCount = 0;
+}
+
+Void TComOutputBitstream::write   ( UInt uiBits, UInt uiNumberOfBits )
+{
+  assert( uiNumberOfBits <= 32 );
+
+  /* any modulo 8 remainder of num_total_bits cannot be written this time,
+   * and will be held until next time. */
+  unsigned num_total_bits = uiNumberOfBits + m_num_held_bits;
+  unsigned next_num_held_bits = num_total_bits % 8;
+
+  /* form a byte aligned word (write_bits), by concatenating any held bits
+   * with the new bits, discarding the bits that will form the next_held_bits.
+   * eg: H = held bits, V = n new bits        /---- next_held_bits
+   * len(H)=7, len(V)=1: ... ---- HHHH HHHV . 0000 0000, next_num_held_bits=0
+   * len(H)=7, len(V)=2: ... ---- HHHH HHHV . V000 0000, next_num_held_bits=1
+   * if total_bits < 8, the value of v_ is not used */
+  unsigned char next_held_bits = uiBits << (8 - next_num_held_bits);
+
+  if (!(num_total_bits >> 3))
+  {
+    /* insufficient bits accumulated to write out, append new_held_bits to
+     * current held_bits */
+    /* NB, this requires that v only contains 0 in bit positions {31..n} */
+    m_held_bits |= next_held_bits;
+    m_num_held_bits = next_num_held_bits;
+    return;
+  }
+
+  /* topword serves to justify held_bits to align with the msb of uiBits */
+  unsigned topword = (uiNumberOfBits - next_num_held_bits) & ~((1 << 3) -1);
+  unsigned int write_bits = (m_held_bits << topword) | (uiBits >> next_num_held_bits);
+
+  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);
+  }
+
+  m_held_bits = next_held_bits;
+  m_num_held_bits = next_num_held_bits;
+}
+
+Void TComOutputBitstream::writeAlignOne()
+{
+  unsigned int num_bits = getNumBitsUntilByteAligned();
+  write((1 << num_bits) - 1, num_bits);
+  return;
+}
+
+Void TComOutputBitstream::writeAlignZero()
+{
+  if (0 == m_num_held_bits)
+    return;
+  m_fifo->push_back(m_held_bits);
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+}
+
+/**
+ - add substream to the end of the current bitstream
+ .
+ \param  pcSubstream  substream to be added
+ */
+Void   TComOutputBitstream::addSubstream( TComOutputBitstream* pcSubstream )
+{
+  UInt uiNumBits = pcSubstream->getNumberOfWrittenBits();
+
+  const vector<uint8_t>& rbsp = pcSubstream->getFIFO();
+  for (vector<uint8_t>::const_iterator it = rbsp.begin(); it != rbsp.end();)
+  {
+    write(*it++, 8);
+  }
+  if (uiNumBits&0x7)
+  {
+    write(pcSubstream->getHeldBits()>>(8-(uiNumBits&0x7)), uiNumBits&0x7);
+  }
+}
+
+/**
+ * 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
+ * avoid the overrun.
+ */
+Void TComInputBitstream::pseudoRead ( UInt uiNumberOfBits, UInt& ruiBits )
+{
+  unsigned int saved_num_held_bits = m_num_held_bits;
+  unsigned char saved_held_bits = m_held_bits;
+  unsigned int saved_fifo_idx = m_fifo_idx;
+
+  unsigned num_bits_to_read = min(uiNumberOfBits, getNumBitsLeft());
+  read(num_bits_to_read, ruiBits);
+  ruiBits <<= (uiNumberOfBits - num_bits_to_read);
+
+  m_fifo_idx = saved_fifo_idx;
+  m_held_bits = saved_held_bits;
+  m_num_held_bits = saved_num_held_bits;
+}
+
+
+Void TComInputBitstream::read (UInt uiNumberOfBits, UInt& ruiBits)
+{
+  assert( uiNumberOfBits <= 32 );
+  
+  m_numBitsRead += uiNumberOfBits;
+
+  /* NB, bits are extracted from the MSB of each byte. */
+  unsigned retval = 0;
+  if (uiNumberOfBits <= m_num_held_bits)
+  {
+    /* n=1, len(H)=7:   -VHH HHHH, shift_down=6, mask=0xfe
+     * n=3, len(H)=7:   -VVV HHHH, shift_down=4, mask=0xf8
+     */
+    retval = m_held_bits >> (m_num_held_bits - uiNumberOfBits);
+    retval &= ~(0xff << uiNumberOfBits);
+    m_num_held_bits -= uiNumberOfBits;
+    ruiBits = retval;
+    return;
+  }
+
+  /* all num_held_bits will go into retval
+   *   => need to mask leftover bits from previous extractions
+   *   => align retval with top of extracted word */
+  /* n=5, len(H)=3: ---- -VVV, mask=0x07, shift_up=5-3=2,
+   * n=9, len(H)=3: ---- -VVV, mask=0x07, shift_up=9-3=6 */
+  uiNumberOfBits -= m_num_held_bits;
+  retval = m_held_bits & ~(0xff << m_num_held_bits);
+  retval <<= uiNumberOfBits;
+
+  /* number of whole bytes that need to be loaded to form retval */
+  /* n=32, len(H)=0, load 4bytes, shift_down=0
+   * n=32, len(H)=1, load 4bytes, shift_down=1
+   * n=31, len(H)=1, load 4bytes, shift_down=1+1
+   * n=8,  len(H)=0, load 1byte,  shift_down=0
+   * n=8,  len(H)=3, load 1byte,  shift_down=3
+   * n=5,  len(H)=1, load 1byte,  shift_down=1+3
+   */
+  unsigned aligned_word = 0;
+  unsigned num_bytes_to_load = (uiNumberOfBits - 1) >> 3;
+  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++];
+  }
+
+  /* resolve remainder bits */
+  unsigned next_num_held_bits = (32 - uiNumberOfBits) % 8;
+
+  /* copy required part of aligned_word into retval */
+  retval |= aligned_word >> next_num_held_bits;
+
+  /* store held bits */
+  m_num_held_bits = next_num_held_bits;
+  m_held_bits = aligned_word;
+
+  ruiBits = retval;
+}
+
+/**
+ * insert the contents of the bytealigned (and flushed) bitstream src
+ * into this at byte position pos.
+ */
+void TComOutputBitstream::insertAt(const TComOutputBitstream& src, unsigned pos)
+{
+  unsigned 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 ()
+{
+  UInt uiBits = 0;
+
+  while ( ( getNumBitsLeft() > 0 ) && (getNumBitsUntilByteAligned()!=0) )
+  {
+    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;
+  this->m_uiTileMarkerLocationCount = src.m_uiTileMarkerLocationCount;
+  for (Int uiIdx=0; uiIdx<m_uiTileMarkerLocationCount; uiIdx++)
+  {
+    this->m_puiTileMarkerLocation[uiIdx] = src.m_puiTileMarkerLocation[uiIdx];
+  }
+
+  return *this;
+}
+
+/**
+ - extract substream from the current bitstream
+ .
+ \param  pcBitstream  bitstream which contains substreams
+ \param  uiNumBits    number of bits to transfer
+ */
+TComInputBitstream *TComInputBitstream::extractSubstream( UInt uiNumBits )
+{
+  UInt uiNumBytes = uiNumBits/8;
+  std::vector<uint8_t>* buf = new std::vector<uint8_t>;
+  UInt uiByte;
+  for (UInt ui = 0; ui < uiNumBytes; ui++)
+  {
+    read(8, uiByte);
+    buf->push_back(uiByte);
+  }
+  if (uiNumBits&0x7)
+  {
+    uiByte = 0;
+    read(uiNumBits&0x7, uiByte);
+    uiByte <<= 8-(uiNumBits&0x7);
+    buf->push_back(uiByte);
+  }
+#if !OL_FLUSH_ALIGN
+  buf->push_back(0); // The final chunk might not start byte aligned.
+#endif
+  return new TComInputBitstream(buf);
+}
+
+/**
+ - delete internal fifo
+ */
+Void TComInputBitstream::deleteFifo()
+{
+  delete m_fifo;
+  m_fifo = NULL;
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitStream.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComBitStream.h	(revision 341)
@@ -0,0 +1,233 @@
+/* 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-2012, 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     TComBitStream.h
+    \brief    class for handling bitstream (header)
+*/
+
+#ifndef __COMBITSTREAM__
+#define __COMBITSTREAM__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdint.h>
+#include <vector>
+#include <stdio.h>
+#include <assert.h>
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// pure virtual class for basic bit handling
+class TComBitIf
+{
+public:
+  virtual Void        writeAlignOne         () {};
+  virtual Void        writeAlignZero        () {};
+  virtual Void        write                 ( UInt uiBits, UInt uiNumberOfBits )  = 0;
+  virtual Void        resetBits             ()                                    = 0;
+  virtual UInt getNumberOfWrittenBits() const = 0;
+  virtual ~TComBitIf() {}
+};
+
+/**
+ * Model of a writable bitstream that accumulates bits to produce a
+ * bytestream.
+ */
+class TComOutputBitstream : public TComBitIf
+{
+  /**
+   * FIFO for storage of bytes.  Use:
+   *  - fifo.push_back(x) to append words
+   *  - fifo.clear() to empty the FIFO
+   *  - &fifo.front() to get a pointer to the data array.
+   *    NB, this pointer is only valid until the next push_back()/clear()
+   */
+  std::vector<uint8_t> *m_fifo;
+
+  unsigned int m_num_held_bits; /// number of bits not flushed to bytestream.
+  unsigned char m_held_bits; /// the bits held and not flushed to bytestream.
+                             /// this value is always msb-aligned, bigendian.
+  UInt m_uiTileMarkerLocationCount;
+  UInt *m_puiTileMarkerLocation;
+
+public:
+  // create / destroy
+  TComOutputBitstream();
+  ~TComOutputBitstream();
+
+  // interface for encoding
+  /**
+   * append uiNumberOfBits least significant bits of uiBits to
+   * the current bitstream
+   */
+  Void        write           ( UInt uiBits, UInt uiNumberOfBits );
+
+  /** insert one bits until the bitstream is byte-aligned */
+  Void        writeAlignOne   ();
+
+  /** insert zero bits until the bitstream is byte-aligned */
+  Void        writeAlignZero  ();
+
+  /** this function should never be called */
+  void resetBits() { assert(0); }
+
+  // utility functions
+
+  /**
+   * Return a pointer to the start of the byte-stream buffer.
+   * Pointer is valid until the next write/flush/reset call.
+   * NB, data is arranged such that subsequent bytes in the
+   * bytestream are stored in ascending addresses.
+   */
+  char* getByteStream() const;
+
+  /**
+   * Return the number of valid bytes available from  getByteStream()
+   */
+  unsigned int getByteStreamLength();
+
+  /**
+   * Reset all internal state.
+   */
+  Void clear();
+
+  /**
+   * returns the number of bits that need to be written to
+   * achieve byte alignment.
+   */
+  Int getNumBitsUntilByteAligned() { return (8 - m_num_held_bits) & 0x7; }
+
+  /**
+   * Return the number of bits that have been written since the last clear()
+   */
+  unsigned getNumberOfWrittenBits() const { return unsigned(m_fifo->size()) * 8 + m_num_held_bits; }
+
+  void insertAt(const TComOutputBitstream& src, unsigned pos);
+
+  /**
+   * Return a reference to the internal fifo
+   */
+  std::vector<uint8_t>& getFIFO() { return *m_fifo; }
+
+  UChar getHeldBits  ()          { return m_held_bits;          }
+
+  TComOutputBitstream& operator= (const TComOutputBitstream& src);
+  UInt  getTileMarkerLocationCount   ( )                     { return m_uiTileMarkerLocationCount   ; }
+  Void  setTileMarkerLocationCount   ( UInt i )              { m_uiTileMarkerLocationCount = i      ; }  
+  UInt  getTileMarkerLocation        ( UInt i)               { return m_puiTileMarkerLocation[i]    ; }
+  Void  setTileMarkerLocation        ( UInt i, UInt uiLOC )  { m_puiTileMarkerLocation[i] = uiLOC   ; }
+  /** Return a reference to the internal fifo */
+  std::vector<uint8_t>& getFIFO() const { return *m_fifo; }
+
+  Void          addSubstream    ( TComOutputBitstream* pcSubstream );
+};
+
+/**
+ * Model of an input bitstream that extracts bits from a predefined
+ * bytestream.
+ */
+class TComInputBitstream
+{
+  std::vector<uint8_t> *m_fifo; /// FIFO for storage of complete bytes
+
+protected:
+  unsigned int m_fifo_idx; /// Read index into m_fifo
+
+  unsigned int m_num_held_bits;
+  unsigned char m_held_bits;
+  UInt m_uiTileMarkerLocationCount;
+  UInt *m_puiTileMarkerLocation;
+  UInt  m_numBitsRead;
+
+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();
+
+  // interface for decoding
+  Void        pseudoRead      ( UInt uiNumberOfBits, UInt& ruiBits );
+  Void        read            ( UInt uiNumberOfBits, UInt& ruiBits );
+#if !OL_FLUSH_ALIGN
+  Void        readByte        ( UInt &ruiBits )
+  {
+    // More expensive, but reads "bytes" that are not aligned.
+    read(8, ruiBits);
+  }
+#else
+  Void        readByte        ( UInt &ruiBits )
+  {
+    assert(m_fifo_idx < m_fifo->size());
+    ruiBits = (*m_fifo)[m_fifo_idx++];
+  }
+#endif // OL_FLUSH && !OL_FLUSH_ALIGN
+
+  Void        readOutTrailingBits ();
+  UChar getHeldBits  ()          { return m_held_bits;          }
+  TComOutputBitstream& operator= (const TComOutputBitstream& src);
+  UInt  getTileMarkerLocationCount   ( )                     { return m_uiTileMarkerLocationCount   ; }
+  Void  setTileMarkerLocationCount   ( UInt i )              { m_uiTileMarkerLocationCount = i      ; }  
+  UInt  getTileMarkerLocation        ( UInt i)               { return m_puiTileMarkerLocation[i]    ; }
+  Void  setTileMarkerLocation        ( UInt i, UInt uiLOC )  { m_puiTileMarkerLocation[i] = uiLOC   ; }
+  UInt  getByteLocation              ( )                     { return m_fifo_idx                    ; }
+
+  // Peek at bits in word-storage. Used in determining if we have completed reading of current bitstream and therefore slice in LCEC.
+  UInt        peekBits (UInt uiBits) { unsigned tmp; pseudoRead(uiBits, tmp); return tmp; }
+
+  // utility functions
+  unsigned read(unsigned numberOfBits) { UInt tmp; read(numberOfBits, tmp); return tmp; }
+  UInt     readByte() { UInt tmp; readByte( tmp ); return tmp; }
+  unsigned getNumBitsUntilByteAligned() { return m_num_held_bits & (0x7); }
+  unsigned getNumBitsLeft() { return 8*((unsigned)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.
+#if !OL_FLUSH_ALIGN
+  Void                backupByte() { m_fifo_idx--; }
+#endif
+  UInt  getNumBitsRead() { return m_numBitsRead; }
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 341)
@@ -0,0 +1,123 @@
+/* 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-2012, 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     TComCABACTables.cpp
+ *  \brief    static class for CABAC tables
+ */
+
+#include "TComCABACTables.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+const UChar TComCABACTables::sm_aucLPSTable[64][4] =
+{
+  { 128, 176, 208, 240},
+  { 128, 167, 197, 227},
+  { 128, 158, 187, 216},
+  { 123, 150, 178, 205},
+  { 116, 142, 169, 195},
+  { 111, 135, 160, 185},
+  { 105, 128, 152, 175},
+  { 100, 122, 144, 166},
+  {  95, 116, 137, 158},
+  {  90, 110, 130, 150},
+  {  85, 104, 123, 142},
+  {  81,  99, 117, 135},
+  {  77,  94, 111, 128},
+  {  73,  89, 105, 122},
+  {  69,  85, 100, 116},
+  {  66,  80,  95, 110},
+  {  62,  76,  90, 104},
+  {  59,  72,  86,  99},
+  {  56,  69,  81,  94},
+  {  53,  65,  77,  89},
+  {  51,  62,  73,  85},
+  {  48,  59,  69,  80},
+  {  46,  56,  66,  76},
+  {  43,  53,  63,  72},
+  {  41,  50,  59,  69},
+  {  39,  48,  56,  65},
+  {  37,  45,  54,  62},
+  {  35,  43,  51,  59},
+  {  33,  41,  48,  56},
+  {  32,  39,  46,  53},
+  {  30,  37,  43,  50},
+  {  29,  35,  41,  48},
+  {  27,  33,  39,  45},
+  {  26,  31,  37,  43},
+  {  24,  30,  35,  41},
+  {  23,  28,  33,  39},
+  {  22,  27,  32,  37},
+  {  21,  26,  30,  35},
+  {  20,  24,  29,  33},
+  {  19,  23,  27,  31},
+  {  18,  22,  26,  30},
+  {  17,  21,  25,  28},
+  {  16,  20,  23,  27},
+  {  15,  19,  22,  25},
+  {  14,  18,  21,  24},
+  {  14,  17,  20,  23},
+  {  13,  16,  19,  22},
+  {  12,  15,  18,  21},
+  {  12,  14,  17,  20},
+  {  11,  14,  16,  19},
+  {  11,  13,  15,  18},
+  {  10,  12,  15,  17},
+  {  10,  12,  14,  16},
+  {   9,  11,  13,  15},
+  {   9,  11,  12,  14},
+  {   8,  10,  12,  14},
+  {   8,   9,  11,  13},
+  {   7,   9,  11,  12},
+  {   7,   9,  10,  12},
+  {   7,   8,  10,  11},
+  {   6,   8,   9,  11},
+  {   6,   7,   9,  10},
+  {   6,   7,   8,   9},
+  {   2,   2,   2,   2}
+};
+
+const UChar TComCABACTables::sm_aucRenormTable[32] =
+{
+  6,  5,  4,  4,
+  3,  3,  3,  3,
+  2,  2,  2,  2,
+  2,  2,  2,  2,
+  1,  1,  1,  1,
+  1,  1,  1,  1,
+  1,  1,  1,  1,
+  1,  1,  1,  1
+};
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComCABACTables.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComCABACTables.h	(revision 341)
@@ -0,0 +1,60 @@
+/* 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-2012, 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     TComCABACTables.h
+    \brief    static class for CABAC tables
+*/
+
+#ifndef __TCOM_CABAC_TABLES__
+#define __TCOM_CABAC_TABLES__
+
+#include "TLibCommon/CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * \brief static class for CABAC tables
+ */
+
+class TComCABACTables
+{
+public:
+  const static UChar  sm_aucLPSTable[64][4];
+  const static UChar  sm_aucRenormTable[32];
+};
+
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDataCU.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDataCU.cpp	(revision 341)
@@ -0,0 +1,7827 @@
+/* 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-2012, 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     TComDataCU.cpp
+    \brief    CU data structure
+    \todo     not all entities are documented
+*/
+
+#include "TComDataCU.h"
+#include "TComPic.h"
+#include "TComDepthMapGenerator.h"
+#include "TComResidualGenerator.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#if ADAPTIVE_QP_SELECTION
+Int * TComDataCU::m_pcGlbArlCoeffY  = NULL;
+Int * TComDataCU::m_pcGlbArlCoeffCb = NULL;
+Int * TComDataCU::m_pcGlbArlCoeffCr = NULL;
+#endif
+
+#if MERL_VSP_C0152
+
+#define CHECK_ADD_YET(pcCURef,uiIdx,vspIdx) && !( (pcCURef)->getVSPIndex(uiIdx) == vspIdx && bVspMvZeroDone[vspIdx-1] )
+
+inline Void TComDataCU::xInheritVspMode( TComDataCU* pcCURef, UInt uiIdx, Bool* bVspMvZeroDone, Int iCount, Int* iVSPIndexTrue, TComMvField* pcMvFieldNeighbours, DisInfo* pDInfo )
+{
+  Int vspIdx = (Int) pcCURef->getVSPIndex(uiIdx);
+  if( vspIdx != 0 )
+  {
+    Int idx = vspIdx - 1;
+    bVspMvZeroDone[idx] = true;
+    iVSPIndexTrue [idx] = iCount;
+
+    // no need to reset Inter Dir
+
+    // set MV using checked disparity
+    if (vspIdx < 4)
+    {
+      pcMvFieldNeighbours[ iCount<<1].setMvField ( pDInfo->m_acMvCand[0],  NOT_VALID );
+      if ( pcCURef->getSlice()->isInterB() )
+      {
+         pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField ( pDInfo->m_acMvCand[0],  NOT_VALID );
+      }
+    }
+  }
+}
+
+inline Bool TComDataCU::xAddVspMergeCand( UChar ucVspMergePos, Int vspIdx, Bool* bVspMvZeroDone, UInt uiDepth, Bool* abCandIsInter, Int& iCount,
+                                          UChar* puhInterDirNeighbours, TComMvField* pcMvFieldNeighbours, Int* iVSPIndexTrue, Int mrgCandIdx, DisInfo* pDInfo )
+{
+#if MERL_VSP_C0152_BugFix_ForNoDepthCase
+  TComPic* pRefPicBaseDepth = NULL;
+  pRefPicBaseDepth = getSlice()->getRefPicBaseDepth();
+  if(ucVspMergePos == VSP_MERGE_POS && pRefPicBaseDepth) //VSP can be used only when depth is used as input
+#else
+  if( ucVspMergePos == VSP_MERGE_POS )
+#endif
+  if( ucVspMergePos == VSP_MERGE_POS )
+  {
+    Int idx = vspIdx - 1;
+    {
+      if( getSlice()->getSPS()->getViewId() != 0 && bVspMvZeroDone[idx] == false )
+      {
+        {
+          abCandIsInter [iCount] = true;
+          bVspMvZeroDone[idx] = true;
+
+          // get Inter Dir
+          Int iInterDir = ((getSlice()->getNumRefIdx(REF_PIC_LIST_0) > 0 && getSlice()->getNumRefIdx(REF_PIC_LIST_1) > 0) ? 3 :
+            (getSlice()->getNumRefIdx(REF_PIC_LIST_0) > 0 ? 1 : 2));
+          puhInterDirNeighbours[iCount] = iInterDir; // The direction information does not matter
+          // get Mv using checked disparity vector
+          if (vspIdx < 4) // spatial
+          {
+            pcMvFieldNeighbours[iCount<<1].setMvField(pDInfo->m_acMvCand[0], NOT_VALID );
+            if ( getSlice()->isInterB() )
+            {
+              pcMvFieldNeighbours[(iCount<<1)+1].setMvField( pDInfo->m_acMvCand[0], NOT_VALID );
+            }
+          }
+          iVSPIndexTrue[idx] = iCount;
+          if ( mrgCandIdx == iCount )
+          {
+            return false;
+          }
+          iCount ++;
+        }
+      }
+    }
+  }
+  return true;
+}
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComDataCU::TComDataCU()
+{
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  m_puhDepth           = NULL;
+#if HHI_MPI
+  m_piTextureModeDepth = NULL;
+#endif
+  
+  m_pePartSize         = NULL;
+#if HHI_INTERVIEW_SKIP
+  m_pbRenderable       = NULL;
+#endif
+  m_pePredMode         = NULL;
+  m_puiAlfCtrlFlag     = NULL;
+  m_puiTmpAlfCtrlFlag  = NULL;
+  m_puhWidth           = NULL;
+  m_puhHeight          = NULL;
+  m_phQP               = NULL;
+  m_pbMergeFlag        = NULL;
+#if LGE_ILLUCOMP_B0045
+  m_pbICFlag           = NULL;
+#endif
+  m_puhMergeIndex      = NULL;
+#if MERL_VSP_C0152
+  m_piVSPIndex         = NULL;
+#endif
+  m_puhLumaIntraDir    = NULL;
+  m_puhChromaIntraDir  = NULL;
+  m_puhInterDir        = NULL;
+  m_puhTrIdx           = NULL;
+#if NSQT_MOD2
+  m_nsqtPartIdx        = NULL;
+#endif
+  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  
+  m_ArlCoeffIsAliasedAllocation = false;
+  m_pcArlCoeffY        = NULL;
+  m_pcArlCoeffCb       = NULL;
+  m_pcArlCoeffCr       = NULL;
+#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_bDecSubCu          = false;
+  m_uiSliceStartCU        = 0;
+  m_uiEntropySliceStartCU = 0;
+
+#if HHI_DMM_WEDGE_INTRA
+  m_puiWedgeFullTabIdx       = NULL;
+  m_piWedgeFullDeltaDC1      = NULL;
+  m_piWedgeFullDeltaDC2      = NULL;
+
+  m_puiWedgePredDirTabIdx    = NULL;
+  m_piWedgePredDirDeltaDC1   = NULL;
+  m_piWedgePredDirDeltaDC2   = NULL;
+  m_piWedgePredDirDeltaEnd   = NULL;
+#endif
+#if HHI_DMM_PRED_TEX
+  m_puiWedgePredTexTabIdx    = NULL;
+#if LGE_DMM3_SIMP_C0044
+  m_puiWedgePredTexIntraTabIdx = NULL;
+#endif
+  m_piWedgePredTexDeltaDC1   = NULL;
+  m_piWedgePredTexDeltaDC2   = NULL;
+
+  m_piContourPredTexDeltaDC1 = NULL;
+  m_piContourPredTexDeltaDC2 = NULL;
+#endif
+#if H3D_IVRP
+  m_pbResPredAvailable = NULL;
+  m_pbResPredFlag      = NULL;
+#endif
+#if LGE_EDGE_INTRA_A0070
+  m_pucEdgeCode         = NULL;
+  m_pucEdgeNumber       = NULL;
+  m_pucEdgeStartPos     = NULL;
+  m_pbEdgeLeftFirst     = NULL;
+  m_pbEdgePartition     = NULL;
+#if LGE_EDGE_INTRA_DELTA_DC
+  m_piEdgeDeltaDC0      = NULL;
+  m_piEdgeDeltaDC1      = NULL;
+#endif
+#endif
+#if RWTH_SDC_DLT_B0036
+  m_pbSDCFlag           = NULL;
+  m_apSegmentDCOffset[0] = NULL;
+  m_apSegmentDCOffset[1] = NULL;
+#endif
+}
+
+TComDataCU::~TComDataCU()
+{
+}
+
+Void TComDataCU::create(UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+#if ADAPTIVE_QP_SELECTION
+                        , Bool bGlobalRMARLBuffer
+#endif                                              
+                        )
+{
+  m_bDecSubCu = bDecSubCu;
+  
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  m_uiNumPartition     = uiNumPartition;
+  m_unitSize = unitSize;
+  
+  if ( !bDecSubCu )
+  {
+    m_phQP               = (Char*     )xMalloc(Char,     uiNumPartition);
+    m_puhDepth           = (UChar*    )xMalloc(UChar,    uiNumPartition);
+#if HHI_MPI
+    m_piTextureModeDepth = (Int*      )xMalloc(Int,      uiNumPartition);
+#endif
+    m_puhWidth           = (UChar*    )xMalloc(UChar,    uiNumPartition);
+    m_puhHeight          = (UChar*    )xMalloc(UChar,    uiNumPartition);
+    m_pePartSize         = new Char[ uiNumPartition ];
+#if HHI_INTERVIEW_SKIP
+    m_pbRenderable        = (Bool*  )xMalloc(Bool,   uiNumPartition);
+#endif
+    memset( m_pePartSize, SIZE_NONE,uiNumPartition * sizeof( *m_pePartSize ) );
+    m_pePredMode         = new Char[ uiNumPartition ];
+    
+#if RWTH_SDC_DLT_B0036
+    m_pbSDCFlag          = (Bool*  )xMalloc(Bool,   uiNumPartition);
+    m_apSegmentDCOffset[0] = (Pel*)xMalloc(Pel, uiNumPartition);
+    m_apSegmentDCOffset[1] = (Pel*)xMalloc(Pel, uiNumPartition);
+#endif
+    
+    m_puiAlfCtrlFlag     = new Bool[ uiNumPartition ];
+    
+    m_pbMergeFlag        = (Bool*  )xMalloc(Bool,   uiNumPartition);
+#if LGE_ILLUCOMP_B0045
+    m_pbICFlag           = (Bool*  )xMalloc(Bool,   uiNumPartition);
+#endif
+    m_puhMergeIndex      = (UChar* )xMalloc(UChar,  uiNumPartition);
+#if MERL_VSP_C0152
+    m_piVSPIndex         = (Char*  )xMalloc(Char,   uiNumPartition);
+#endif
+#if H3D_IVRP
+    m_pbResPredAvailable = (Bool*  )xMalloc(Bool,   uiNumPartition);
+    m_pbResPredFlag      = (Bool*  )xMalloc(Bool,   uiNumPartition);
+#endif
+    m_puhLumaIntraDir    = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhChromaIntraDir  = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhInterDir        = (UChar* )xMalloc(UChar,  uiNumPartition);
+    
+    m_puhTrIdx           = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_nsqtPartIdx        = (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);
+    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
+    
+    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 );
+    
+#if HHI_DMM_WEDGE_INTRA
+    m_puiWedgeFullTabIdx       = (UInt*)xMalloc(UInt, uiNumPartition);
+    m_piWedgeFullDeltaDC1      = (Int* )xMalloc(Int,  uiNumPartition);
+    m_piWedgeFullDeltaDC2      = (Int* )xMalloc(Int,  uiNumPartition);
+
+    m_puiWedgePredDirTabIdx    = (UInt*)xMalloc(UInt, uiNumPartition);
+    m_piWedgePredDirDeltaDC1   = (Int* )xMalloc(Int,  uiNumPartition);
+    m_piWedgePredDirDeltaDC2   = (Int* )xMalloc(Int,  uiNumPartition);
+    m_piWedgePredDirDeltaEnd   = (Int* )xMalloc(Int,  uiNumPartition);
+#endif
+#if HHI_DMM_PRED_TEX
+    m_puiWedgePredTexTabIdx    = (UInt*)xMalloc(UInt, uiNumPartition);
+#if LGE_DMM3_SIMP_C0044
+    m_puiWedgePredTexIntraTabIdx    = (UInt*)xMalloc(UInt, uiNumPartition);
+#endif
+    m_piWedgePredTexDeltaDC1   = (Int* )xMalloc(Int,  uiNumPartition);
+    m_piWedgePredTexDeltaDC2   = (Int* )xMalloc(Int,  uiNumPartition);
+
+    m_piContourPredTexDeltaDC1 = (Int* )xMalloc(Int,  uiNumPartition);
+    m_piContourPredTexDeltaDC2 = (Int* )xMalloc(Int,  uiNumPartition);
+#endif
+#if LGE_EDGE_INTRA_A0070
+    m_pucEdgeCode       = (UChar*)xMalloc(UChar, uiNumPartition * LGE_EDGE_INTRA_MAX_EDGE_NUM_PER_4x4);
+    m_pucEdgeNumber     = (UChar*)xMalloc(UChar, uiNumPartition);
+    m_pucEdgeStartPos   = (UChar*)xMalloc(UChar, uiNumPartition);
+    m_pbEdgeLeftFirst   = (Bool*) xMalloc(Bool,  uiNumPartition);
+    m_pbEdgePartition   = (Bool*) xMalloc(Bool,  uiNumPartition * 16);
+#if LGE_EDGE_INTRA_DELTA_DC
+    m_piEdgeDeltaDC0    = (Int* ) xMalloc(Int,   uiNumPartition);
+    m_piEdgeDeltaDC1    = (Int* ) xMalloc(Int,   uiNumPartition);
+#endif
+#endif
+  }
+  else
+  {
+    m_acCUMvField[0].setNumPartition(uiNumPartition );
+    m_acCUMvField[1].setNumPartition(uiNumPartition );
+  }
+  
+  m_uiSliceStartCU        = (UInt*  )xMalloc(UInt, uiNumPartition);
+  m_uiEntropySliceStartCU = (UInt*  )xMalloc(UInt, uiNumPartition);
+  
+  // create pattern memory
+  m_pcPattern            = (TComPattern*)xMalloc(TComPattern, 1);
+  
+  // create motion vector fields
+  
+  m_pcCUAboveLeft      = NULL;
+  m_pcCUAboveRight     = NULL;
+  m_pcCUAbove          = NULL;
+  m_pcCULeft           = NULL;
+  
+  m_apcCUColocated[0]  = NULL;
+  m_apcCUColocated[1]  = 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 HHI_MPI
+    if ( m_piTextureModeDepth ) { xFree(m_piTextureModeDepth);  m_piTextureModeDepth= NULL; }
+#endif
+    if ( m_puhWidth           ) { xFree(m_puhWidth);            m_puhWidth          = NULL; }
+    if ( m_puhHeight          ) { xFree(m_puhHeight);           m_puhHeight         = NULL; }
+    if ( m_pePartSize         ) { delete[] m_pePartSize;        m_pePartSize        = NULL; }
+#if HHI_INTERVIEW_SKIP
+    if ( m_pbRenderable        ) { xFree(m_pbRenderable);         m_pbRenderable       = NULL; }
+#endif
+    if ( m_pePredMode         ) { delete[] m_pePredMode;        m_pePredMode        = NULL; }
+#if RWTH_SDC_DLT_B0036
+    if ( m_pbSDCFlag          ) { xFree(m_pbSDCFlag);      m_pbSDCFlag    = NULL; }
+    if ( m_apSegmentDCOffset[0]          ) { xFree(m_apSegmentDCOffset[0]);      m_apSegmentDCOffset[0]    = NULL; }
+    if ( m_apSegmentDCOffset[1]          ) { xFree(m_apSegmentDCOffset[1]);      m_apSegmentDCOffset[1]    = NULL; }
+#endif
+    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_puiAlfCtrlFlag     ) { delete[] m_puiAlfCtrlFlag;    m_puiAlfCtrlFlag    = NULL; }
+    if ( m_puhInterDir        ) { xFree(m_puhInterDir);         m_puhInterDir       = NULL; }
+    if ( m_pbMergeFlag        ) { xFree(m_pbMergeFlag);         m_pbMergeFlag       = NULL; }
+#if LGE_ILLUCOMP_B0045
+    if ( m_pbICFlag           ) { xFree(m_pbICFlag);            m_pbICFlag          = NULL; }
+#endif
+#if MERL_VSP_C0152
+    if ( m_piVSPIndex         ) { xFree(m_piVSPIndex);          m_piVSPIndex        = NULL; }
+#endif
+    if ( m_puhMergeIndex      ) { xFree(m_puhMergeIndex);       m_puhMergeIndex     = NULL; }
+#if H3D_IVRP
+    if ( m_pbResPredAvailable ) { xFree(m_pbResPredAvailable);  m_pbResPredAvailable= NULL; }
+    if ( m_pbResPredFlag      ) { xFree(m_pbResPredFlag);       m_pbResPredFlag     = 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_nsqtPartIdx        ) { xFree(m_nsqtPartIdx);         m_nsqtPartIdx       = 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; }
+#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 HHI_DMM_WEDGE_INTRA
+    if ( m_puiWedgeFullTabIdx       ) { xFree(m_puiWedgeFullTabIdx      ); m_puiWedgeFullTabIdx       = NULL; }
+    if ( m_piWedgeFullDeltaDC1      ) { xFree(m_piWedgeFullDeltaDC1     ); m_piWedgeFullDeltaDC1      = NULL; }
+    if ( m_piWedgeFullDeltaDC2      ) { xFree(m_piWedgeFullDeltaDC2     ); m_piWedgeFullDeltaDC2      = NULL; }
+
+    if ( m_puiWedgePredDirTabIdx    ) { xFree(m_puiWedgePredDirTabIdx   ); m_puiWedgePredDirTabIdx    = NULL; }
+    if ( m_piWedgePredDirDeltaEnd   ) { xFree(m_piWedgePredDirDeltaEnd  ); m_piWedgePredDirDeltaEnd   = NULL; }
+    if ( m_piWedgePredDirDeltaDC1   ) { xFree(m_piWedgePredDirDeltaDC1  ); m_piWedgePredDirDeltaDC1   = NULL; }
+    if ( m_piWedgePredDirDeltaDC2   ) { xFree(m_piWedgePredDirDeltaDC2  ); m_piWedgePredDirDeltaDC2   = NULL; }
+#endif
+#if HHI_DMM_PRED_TEX
+    if ( m_puiWedgePredTexTabIdx    ) { xFree(m_puiWedgePredTexTabIdx   ); m_puiWedgePredTexTabIdx    = NULL; }
+#if LGE_DMM3_SIMP_C0044
+    if ( m_puiWedgePredTexIntraTabIdx ) { xFree(m_puiWedgePredTexIntraTabIdx); m_puiWedgePredTexIntraTabIdx    = NULL; }
+#endif
+    if ( m_piWedgePredTexDeltaDC1   ) { xFree(m_piWedgePredTexDeltaDC1  ); m_piWedgePredTexDeltaDC1   = NULL; }
+    if ( m_piWedgePredTexDeltaDC2   ) { xFree(m_piWedgePredTexDeltaDC2  ); m_piWedgePredTexDeltaDC2   = NULL; }
+
+    if ( m_piContourPredTexDeltaDC1 ) { xFree(m_piContourPredTexDeltaDC1); m_piContourPredTexDeltaDC1 = NULL; }
+    if ( m_piContourPredTexDeltaDC2 ) { xFree(m_piContourPredTexDeltaDC2); m_piContourPredTexDeltaDC2 = NULL; }
+#endif    
+#if LGE_EDGE_INTRA_A0070
+  if ( m_pbEdgeLeftFirst  ) { xFree(m_pbEdgeLeftFirst);   m_pbEdgeLeftFirst = NULL; }
+  if ( m_pucEdgeStartPos  ) { xFree(m_pucEdgeStartPos);   m_pucEdgeStartPos = NULL; }
+  if ( m_pucEdgeNumber    ) { xFree(m_pucEdgeNumber);     m_pucEdgeNumber   = NULL; }
+  if ( m_pucEdgeCode      ) { xFree(m_pucEdgeCode);       m_pucEdgeCode     = NULL; }
+  if ( m_pbEdgePartition    ) { xFree(m_pbEdgePartition); m_pbEdgePartition = NULL; }
+#if LGE_EDGE_INTRA_DELTA_DC
+  if ( m_piEdgeDeltaDC0     ) { xFree(m_piEdgeDeltaDC0);  m_piEdgeDeltaDC0  = NULL; }
+  if ( m_piEdgeDeltaDC1     ) { xFree(m_piEdgeDeltaDC1);  m_piEdgeDeltaDC1  = NULL; }
+#endif
+#endif
+    m_acCUMvField[0].destroy();
+    m_acCUMvField[1].destroy();
+    
+  }
+  
+  m_pcCUAboveLeft       = NULL;
+  m_pcCUAboveRight      = NULL;
+  m_pcCUAbove           = NULL;
+  m_pcCULeft            = NULL;
+  
+  m_apcCUColocated[0]   = NULL;
+  m_apcCUColocated[1]   = NULL;
+
+  if( m_uiSliceStartCU )
+  {
+    xFree(m_uiSliceStartCU);
+    m_uiSliceStartCU=NULL;
+  }
+  if(m_uiEntropySliceStartCU )
+  {
+    xFree(m_uiEntropySliceStartCU);
+    m_uiEntropySliceStartCU=NULL;
+  }
+}
+
+const NDBFBlockInfo& NDBFBlockInfo::operator= (const NDBFBlockInfo& src)
+{
+  this->tileID = src.tileID;
+  this->sliceID= src.sliceID;
+  this->startSU= src.startSU;
+  this->endSU  = src.endSU;
+  this->widthSU= src.widthSU;
+  this->heightSU=src.heightSU;
+  this->posX   = src.posX;
+  this->posY   = src.posY;
+  this->width  = src.width;
+  this->height = src.height;
+  ::memcpy(this->isBorderAvailable, src.isBorderAvailable, sizeof(Bool)*((Int)NUM_SGU_BORDER));
+  this->allBordersAvailable = src.allBordersAvailable;
+
+  return *this;
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// Initialization
+// --------------------------------------------------------------------------------------------------------------------
+
+/**
+ - 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
+ */
+Void TComDataCU::initCU( TComPic* pcPic, UInt iCUAddr )
+{
+  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_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+  m_uiNumPartition     = pcPic->getNumPartInCU();
+  m_numSucIPCM       = 0;
+  m_lastCUSucIPCMFlag   = false;
+
+  for(int i=0; i<pcPic->getNumPartInCU(); i++) 
+  {
+    if(pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr)*pcPic->getNumPartInCU()+i>=getSlice()->getSliceCurStartCUAddr())
+    {
+      m_uiSliceStartCU[i]=getSlice()->getSliceCurStartCUAddr();
+    }
+    else
+    {
+      m_uiSliceStartCU[i]=pcPic->getCU(getAddr())->m_uiSliceStartCU[i];
+    }
+  }
+  for(int i=0; i<pcPic->getNumPartInCU(); i++) 
+  {
+    if(pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr)*pcPic->getNumPartInCU()+i>=getSlice()->getEntropySliceCurStartCUAddr())
+    {
+      m_uiEntropySliceStartCU[i]=getSlice()->getEntropySliceCurStartCUAddr();
+    }
+    else
+    {
+      m_uiEntropySliceStartCU[i]=pcPic->getCU(getAddr())->m_uiEntropySliceStartCU[i];
+    }
+  }
+
+  Int partStartIdx = getSlice()->getEntropySliceCurStartCUAddr() - 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_pePartSize[ui] = pcFrom->getPartitionSize(ui);
+    m_pePredMode[ui] = pcFrom->getPredictionMode(ui);
+    m_puhDepth[ui] = pcFrom->getDepth(ui);
+#if HHI_MPI
+    m_piTextureModeDepth[ui] = pcFrom->getTextureModeDepth(ui);
+#endif
+#if RWTH_SDC_DLT_B0036
+    m_pbSDCFlag[ui] = pcFrom->getSDCFlag(ui);
+#endif
+    m_puhWidth  [ui] = pcFrom->getWidth(ui);
+    m_puhHeight [ui] = pcFrom->getHeight(ui);
+    m_puhTrIdx  [ui] = pcFrom->getTransformIdx(ui);
+    m_nsqtPartIdx[ui] = pcFrom->getNSQTPartIdx(ui);
+    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_puiAlfCtrlFlag[ui]=pcFrom->m_puiAlfCtrlFlag[ui];
+    m_pbMergeFlag[ui]=pcFrom->m_pbMergeFlag[ui];
+#if LGE_ILLUCOMP_B0045
+    m_pbICFlag[ui]=pcFrom->m_pbICFlag[ui];
+#endif
+    m_puhMergeIndex[ui]=pcFrom->m_puhMergeIndex[ui];
+#if MERL_VSP_C0152
+    m_piVSPIndex[ui] = pcFrom->m_piVSPIndex[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];
+  }
+  
+  Int firstElement = max<Int>( partStartIdx, 0 );
+  numElements = m_uiNumPartition - firstElement;
+  
+  if ( numElements > 0 )
+  {
+    memset( m_pePartSize        + firstElement, SIZE_NONE,                numElements * sizeof( *m_pePartSize ) );
+    memset( m_pePredMode        + firstElement, MODE_NONE,                numElements * sizeof( *m_pePredMode ) );
+    memset( m_puhDepth          + firstElement, 0,                        numElements * sizeof( *m_puhDepth ) );
+#if HHI_MPI
+    memset( m_piTextureModeDepth+ firstElement,-1,                        numElements * sizeof( *m_piTextureModeDepth ) );
+#endif
+#if RWTH_SDC_DLT_B0036
+    memset( m_pbSDCFlag        + firstElement,     0,                     numElements * sizeof( *m_pbSDCFlag ) );
+    memset( m_apSegmentDCOffset[0]        + firstElement,     0,                     numElements * sizeof( *m_apSegmentDCOffset[0] ) );
+    memset( m_apSegmentDCOffset[1]        + firstElement,     0,                     numElements * sizeof( *m_apSegmentDCOffset[1] ) );
+#endif
+    memset( m_puhTrIdx          + firstElement, 0,                        numElements * sizeof( *m_puhTrIdx ) );
+    memset( m_nsqtPartIdx       + firstElement, 0,                        numElements * sizeof( *m_nsqtPartIdx) );
+    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_puiAlfCtrlFlag    + firstElement, false,                    numElements * sizeof( *m_puiAlfCtrlFlag ) );
+    memset( m_pbMergeFlag       + firstElement, false,                    numElements * sizeof( *m_pbMergeFlag ) );
+#if LGE_ILLUCOMP_B0045
+    memset( m_pbICFlag          + firstElement, false,                    numElements * sizeof( *m_pbICFlag ) );
+#endif
+    memset( m_puhMergeIndex     + firstElement, 0,                        numElements * sizeof( *m_puhMergeIndex ) );
+#if MERL_VSP_C0152
+    memset( m_piVSPIndex        + firstElement, 0,                        numElements * sizeof( *m_piVSPIndex ) );
+#endif
+    memset( m_puhLumaIntraDir   + firstElement, 2,                        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 ) );
+
+#if HHI_DMM_WEDGE_INTRA
+    memset( m_puiWedgeFullTabIdx       + firstElement, 0, sizeof( UInt ) * numElements );
+    memset( m_piWedgeFullDeltaDC1      + firstElement, 0, sizeof( Int  ) * numElements );
+    memset( m_piWedgeFullDeltaDC2      + firstElement, 0, sizeof( Int  ) * numElements );
+
+    memset( m_puiWedgePredDirTabIdx    + firstElement, 0, sizeof( UInt ) * numElements );
+    memset( m_piWedgePredDirDeltaDC1   + firstElement, 0, sizeof( Int  ) * numElements );
+    memset( m_piWedgePredDirDeltaDC2   + firstElement, 0, sizeof( Int  ) * numElements );
+    memset( m_piWedgePredDirDeltaEnd   + firstElement, 0, sizeof( Int  ) * numElements );
+#endif
+#if HHI_DMM_PRED_TEX
+    memset( m_puiWedgePredTexTabIdx    + firstElement, 0, sizeof( UInt ) * numElements );
+#if LGE_DMM3_SIMP_C0044
+    memset( m_puiWedgePredTexIntraTabIdx + firstElement, 0, sizeof( UInt ) * numElements );
+#endif
+    memset( m_piWedgePredTexDeltaDC1   + firstElement, 0, sizeof( Int  ) * numElements );
+    memset( m_piWedgePredTexDeltaDC2   + firstElement, 0, sizeof( Int  ) * numElements );
+
+    memset( m_piContourPredTexDeltaDC1 + firstElement, 0, sizeof( Int  ) * numElements );
+    memset( m_piContourPredTexDeltaDC2 + firstElement, 0, sizeof( Int  ) * numElements );
+#endif 
+#if HHI_INTERVIEW_SKIP
+    memset (m_pbRenderable             + firstElement, false, sizeof( Bool ) * numElements) ;
+#endif
+#if H3D_IVRP
+    memset( m_pbResPredAvailable       + firstElement, 0    , sizeof( Bool ) * numElements );
+    memset( m_pbResPredFlag            + firstElement, 0    , sizeof( Bool ) * numElements );
+#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 );
+#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];
+    }
+  }
+
+  // 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 
+*/
+Void TComDataCU::initEstData( UInt uiDepth, Int qp )
+{
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU+ui >= getSlice()->getEntropySliceCurStartCUAddr())
+    {
+#if HHI_INTERVIEW_SKIP
+      m_pbRenderable[ui]=  0 ;
+#endif
+      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;
+#if HHI_MPI
+      m_piTextureModeDepth[ui] = -1;
+#endif
+      m_nsqtPartIdx[ui] = 0;
+      m_pePartSize[ui] = SIZE_NONE;
+      m_pePredMode[ui] = MODE_NONE;
+      m_pbIPCMFlag[ui] = 0;
+      m_phQP[ui] = qp;
+      m_puiAlfCtrlFlag[ui]= false;
+      m_pbMergeFlag[ui] = 0;
+#if LGE_ILLUCOMP_B0045
+      m_pbICFlag[ui]    = false;
+#endif
+      m_puhMergeIndex[ui] = 0;
+#if MERL_VSP_C0152
+      m_piVSPIndex[ui] = 0;
+#endif
+#if H3D_IVRP
+      m_pbResPredAvailable[ui] = 0;
+      m_pbResPredFlag[ui]      = 0;
+#endif
+      m_puhLumaIntraDir[ui] = 2;
+      m_puhChromaIntraDir[ui] = 0;
+      m_puhInterDir[ui] = 0;
+      m_puhCbf[0][ui] = 0;
+      m_puhCbf[1][ui] = 0;
+      m_puhCbf[2][ui] = 0;
+#if HHI_DMM_WEDGE_INTRA
+    m_puiWedgeFullTabIdx      [ui] = 0;
+    m_piWedgeFullDeltaDC1     [ui] = 0;
+    m_piWedgeFullDeltaDC2     [ui] = 0;
+
+    m_puiWedgePredDirTabIdx   [ui] = 0;
+    m_piWedgePredDirDeltaDC1  [ui] = 0;
+    m_piWedgePredDirDeltaDC2  [ui] = 0;
+    m_piWedgePredDirDeltaEnd  [ui] = 0;
+#endif
+#if HHI_DMM_PRED_TEX
+    m_puiWedgePredTexTabIdx   [ui] = 0;
+#if LGE_DMM3_SIMP_C0044
+    m_puiWedgePredTexIntraTabIdx [ui] = 0;
+#endif
+    m_piWedgePredTexDeltaDC1  [ui] = 0;
+    m_piWedgePredTexDeltaDC2  [ui] = 0;
+
+    m_piContourPredTexDeltaDC1[ui] = 0;
+    m_piContourPredTexDeltaDC2[ui] = 0;
+#endif 
+#if RWTH_SDC_DLT_B0036
+    m_pbSDCFlag[ui] = false;
+    m_apSegmentDCOffset[0][ui] = 0;
+    m_apSegmentDCOffset[1][ui] = 0;
+#endif
+    }
+  }
+
+  UInt uiTmp = uhWidth*uhHeight;
+
+  if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU >= getSlice()->getEntropySliceCurStartCUAddr())
+  {
+    m_acCUMvField[0].clearMvField();
+    m_acCUMvField[1].clearMvField();
+    uiTmp = uhWidth*uhHeight;
+    
+    memset( m_pcTrCoeffY,    0, uiTmp * sizeof( *m_pcTrCoeffY    ) );
+#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 ) );
+  }
+}
+
+
+// initialize Sub partition
+Void TComDataCU::initSubCU( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp )
+{
+  assert( uiPartUnitIdx<4 );
+
+  UInt uiPartOffset = ( pcCU->getTotalNumPart()>>2 )*uiPartUnitIdx;
+
+  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_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+  m_uiNumPartition     = pcCU->getTotalNumPart() >> 2;
+
+  m_numSucIPCM       = 0;
+  m_lastCUSucIPCMFlag   = false;
+
+  Int iSizeInUchar = sizeof( UChar  ) * m_uiNumPartition;
+  Int iSizeInBool  = sizeof( Bool   ) * m_uiNumPartition;
+#if MERL_VSP_C0152
+  Int iSizeInChar  = sizeof( Char   ) * m_uiNumPartition;
+#endif
+
+  Int sizeInChar = sizeof( Char  ) * m_uiNumPartition;
+  memset( m_phQP,              qp,  sizeInChar );
+
+  memset( m_puiAlfCtrlFlag,     0, iSizeInBool );
+  memset( m_pbMergeFlag,        0, iSizeInBool  );
+#if LGE_ILLUCOMP_B0045
+  memset( m_pbICFlag,           0, iSizeInBool  );
+#endif
+#if HHI_INTERVIEW_SKIP
+  memset( m_pbRenderable,        0, iSizeInBool  );
+#endif
+  memset( m_puhMergeIndex,      0, iSizeInUchar );
+#if MERL_VSP_C0152
+  memset( m_piVSPIndex,         0, iSizeInChar );
+#endif
+#if H3D_IVRP
+  memset( m_pbResPredAvailable, 0, iSizeInBool  );
+  memset( m_pbResPredFlag,      0, iSizeInBool  );
+#endif
+  memset( m_puhLumaIntraDir,    2, iSizeInUchar );
+  memset( m_puhChromaIntraDir,  0, iSizeInUchar );
+  memset( m_puhInterDir,        0, iSizeInUchar );
+  memset( m_puhTrIdx,           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 );
+#if HHI_MPI
+  memset( m_piTextureModeDepth, -1, sizeof( Int ) * m_uiNumPartition );
+#endif
+
+#if HHI_DMM_WEDGE_INTRA
+  memset( m_puiWedgeFullTabIdx,       0, sizeof( UInt ) * m_uiNumPartition );
+  memset( m_piWedgeFullDeltaDC1,      0, sizeof( Int  ) * m_uiNumPartition );
+  memset( m_piWedgeFullDeltaDC2,      0, sizeof( Int  ) * m_uiNumPartition );
+
+  memset( m_puiWedgePredDirTabIdx,    0, sizeof( UInt ) * m_uiNumPartition );
+  memset( m_piWedgePredDirDeltaDC1,   0, sizeof( Int  ) * m_uiNumPartition );
+  memset( m_piWedgePredDirDeltaDC2,   0, sizeof( Int  ) * m_uiNumPartition );
+  memset( m_piWedgePredDirDeltaEnd,   0, sizeof( Int  ) * m_uiNumPartition );
+#endif
+#if HHI_DMM_PRED_TEX
+  memset( m_puiWedgePredTexTabIdx,    0, sizeof( UInt ) * m_uiNumPartition );
+#if LGE_DMM3_SIMP_C0044
+  memset( m_puiWedgePredTexIntraTabIdx, 0, sizeof( UInt ) * m_uiNumPartition );
+#endif
+  memset( m_piWedgePredTexDeltaDC1,   0, sizeof( Int  ) * m_uiNumPartition );
+  memset( m_piWedgePredTexDeltaDC2,   0, sizeof( Int  ) * m_uiNumPartition );
+
+  memset( m_piContourPredTexDeltaDC1, 0, sizeof( Int  ) * m_uiNumPartition );
+  memset( m_piContourPredTexDeltaDC2, 0, sizeof( Int  ) * m_uiNumPartition );
+#endif   
+#if RWTH_SDC_DLT_B0036
+  memset( m_pbSDCFlag,     0, sizeof(Bool) * m_uiNumPartition  );
+  memset( m_apSegmentDCOffset[0],     0, sizeof(Pel) * m_uiNumPartition);
+  memset( m_apSegmentDCOffset[1],     0, sizeof(Pel) * m_uiNumPartition);
+#endif
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  memset( m_puhWidth,          uhWidth,  iSizeInUchar );
+  memset( m_puhHeight,         uhHeight, iSizeInUchar );
+  memset( m_pbIPCMFlag,        0, iSizeInBool  );
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    m_pePartSize[ui] = SIZE_NONE;
+    m_pePredMode[ui] = MODE_NONE;
+#if HHI_INTERVIEW_SKIP
+    m_pbRenderable[ui]=  0 ;
+#endif
+    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()->getEntropySliceCurStartCUAddr())
+    {
+      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);
+#if HHI_MPI
+      m_piTextureModeDepth[ui] = pcCU->getTextureModeDepth(uiPartOffset+ui);
+#endif
+      m_puhWidth  [ui] = pcCU->getWidth(uiPartOffset+ui);
+      m_puhHeight  [ui] = pcCU->getHeight(uiPartOffset+ui);
+      m_puhTrIdx  [ui] = pcCU->getTransformIdx(uiPartOffset+ui);
+      m_nsqtPartIdx[ui] = pcCU->getNSQTPartIdx(uiPartOffset+ui);
+      m_pePartSize[ui] = pcCU->getPartitionSize(uiPartOffset+ui);
+      m_pePredMode[ui] = pcCU->getPredictionMode(uiPartOffset+ui);
+      m_pbIPCMFlag[ui]=pcCU->m_pbIPCMFlag[uiPartOffset+ui];
+      m_phQP[ui] = pcCU->m_phQP[uiPartOffset+ui];
+      m_puiAlfCtrlFlag[ui]=pcCU->m_puiAlfCtrlFlag[uiPartOffset+ui];
+      m_pbMergeFlag[ui]=pcCU->m_pbMergeFlag[uiPartOffset+ui];
+#if LGE_ILLUCOMP_B0045
+      m_pbICFlag[ui]=pcCU->m_pbICFlag[uiPartOffset+ui];
+#endif
+      m_puhMergeIndex[ui]=pcCU->m_puhMergeIndex[uiPartOffset+ui];
+#if MERL_VSP_C0152
+      m_piVSPIndex[ui]=pcCU->m_piVSPIndex[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 HHI_DMM_WEDGE_INTRA
+      m_puiWedgeFullTabIdx      [ui]=pcCU->getWedgeFullTabIdx       (uiPartOffset+ui);
+      m_piWedgeFullDeltaDC1     [ui]=pcCU->getWedgeFullDeltaDC1     (uiPartOffset+ui);
+      m_piWedgeFullDeltaDC2     [ui]=pcCU->getWedgeFullDeltaDC2     (uiPartOffset+ui);
+
+      m_puiWedgePredDirTabIdx   [ui]=pcCU->getWedgePredDirTabIdx    (uiPartOffset+ui);
+      m_piWedgePredDirDeltaDC1  [ui]=pcCU->getWedgePredDirDeltaDC1  (uiPartOffset+ui);
+      m_piWedgePredDirDeltaDC2  [ui]=pcCU->getWedgePredDirDeltaDC2  (uiPartOffset+ui);
+      m_piWedgePredDirDeltaEnd  [ui]=pcCU->getWedgePredDirDeltaEnd  (uiPartOffset+ui);
+#endif
+#if HHI_DMM_PRED_TEX
+      m_puiWedgePredTexTabIdx   [ui]=pcCU->getWedgePredTexTabIdx    (uiPartOffset+ui);
+#if LGE_DMM3_SIMP_C0044
+      m_puiWedgePredTexIntraTabIdx [ui]=pcCU->getWedgePredTexIntraTabIdx (uiPartOffset+ui);
+#endif
+      m_piWedgePredTexDeltaDC1  [ui]=pcCU->getWedgePredTexDeltaDC1  (uiPartOffset+ui);
+      m_piWedgePredTexDeltaDC2  [ui]=pcCU->getWedgePredTexDeltaDC2  (uiPartOffset+ui);
+
+      m_piContourPredTexDeltaDC1[ui]=pcCU->getContourPredTexDeltaDC1(uiPartOffset+ui);
+      m_piContourPredTexDeltaDC2[ui]=pcCU->getContourPredTexDeltaDC2(uiPartOffset+ui);
+#endif    
+#if H3D_IVRP
+      m_pbResPredAvailable[ui] = pcCU->m_pbResPredAvailable[ uiPartOffset + ui ];
+      m_pbResPredFlag     [ui] = pcCU->m_pbResPredFlag     [ uiPartOffset + ui ];
+#endif
+#if RWTH_SDC_DLT_B0036
+      m_pbSDCFlag         [ui] = pcCU->m_pbSDCFlag         [ uiPartOffset + ui ];
+      m_apSegmentDCOffset[0][ui] = pcCU->m_apSegmentDCOffset[0][ uiPartOffset + ui ];
+      m_apSegmentDCOffset[1][ui] = pcCU->m_apSegmentDCOffset[1][ 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 );
+#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()->getEntropySliceCurStartCUAddr())
+  {
+    // 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_uiSliceStartCU,pcCU->m_uiSliceStartCU+uiPartOffset,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_uiEntropySliceStartCU,pcCU->m_uiEntropySliceStartCU+uiPartOffset,sizeof(UInt)*m_uiNumPartition);
+}
+
+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;
+  memset( m_puhDepth    + uiAbsPartIdx,     uiDepth,  uiSizeInUchar );
+  memset( m_puhWidth    + uiAbsPartIdx,     uhWidth,  uiSizeInUchar );
+  memset( m_puhHeight   + uiAbsPartIdx,     uhHeight, uiSizeInUchar );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Copy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComDataCU::copySubCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiPart = uiAbsPartIdx;
+  
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = pcCU->getSlice();
+  m_uiCUAddr           = pcCU->getAddr();
+  m_uiAbsIdxInLCU      = uiAbsPartIdx;
+  
+  m_uiCUPelX           = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  m_uiCUPelY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  
+  UInt uiWidth         = g_uiMaxCUWidth  >> uiDepth;
+  UInt uiHeight        = g_uiMaxCUHeight >> uiDepth;
+  
+  m_phQP=pcCU->getQP()                    + uiPart;
+  m_pePartSize = pcCU->getPartitionSize() + uiPart;
+#if HHI_INTERVIEW_SKIP
+  m_pbRenderable         = pcCU->getRenderable()        + uiPart;
+
+#endif
+  m_pePredMode=pcCU->getPredictionMode()  + uiPart;
+  
+  m_pbMergeFlag         = pcCU->getMergeFlag()        + uiPart;
+#if LGE_ILLUCOMP_B0045
+  m_pbICFlag            = pcCU->getICFlag()           + uiPart;
+#endif
+  m_puhMergeIndex       = pcCU->getMergeIndex()       + uiPart;
+#if MERL_VSP_C0152
+  m_piVSPIndex          = pcCU->getVSPIndex()         + uiPart;
+#endif
+#if H3D_IVRP
+  m_pbResPredAvailable  = pcCU->getResPredAvail()     + uiPart;
+  m_pbResPredFlag       = pcCU->getResPredFlag ()     + uiPart;
+#endif
+  m_puhLumaIntraDir     = pcCU->getLumaIntraDir()     + uiPart;
+  m_puhChromaIntraDir   = pcCU->getChromaIntraDir()   + uiPart;
+  m_puhInterDir         = pcCU->getInterDir()         + uiPart;
+  m_puhTrIdx            = pcCU->getTransformIdx()     + uiPart;
+  m_nsqtPartIdx         = pcCU->getNSQTPartIdx()      + 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;
+  
+  m_puhDepth=pcCU->getDepth()                     + uiPart;
+  m_puhWidth=pcCU->getWidth()                     + uiPart;
+  m_puhHeight=pcCU->getHeight()                   + uiPart;
+#if HHI_MPI
+  m_piTextureModeDepth=pcCU->getTextureModeDepth()+ uiPart;
+#endif
+  
+  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);
+  
+  UInt uiTmp = uiWidth*uiHeight;
+  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;
+#if ADAPTIVE_QP_SELECTION
+  m_pcArlCoeffY= pcCU->getArlCoeffY() + uiCoffOffset;  
+#endif
+  m_pcIPCMSampleY = pcCU->getPCMSampleY() + uiCoffOffset;
+
+  uiTmp >>= 2;
+  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_uiSliceStartCU,pcCU->m_uiSliceStartCU+uiPart,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_uiEntropySliceStartCU,pcCU->m_uiEntropySliceStartCU+uiPart,sizeof(UInt)*m_uiNumPartition);
+
+#if HHI_DMM_WEDGE_INTRA
+  m_puiWedgeFullTabIdx       = pcCU->getWedgeFullTabIdx()        + uiPart;   
+  m_piWedgeFullDeltaDC1      = pcCU->getWedgeFullDeltaDC1()      + uiPart;   
+  m_piWedgeFullDeltaDC2      = pcCU->getWedgeFullDeltaDC2()      + uiPart;   
+
+  m_puiWedgePredDirTabIdx    = pcCU->getWedgePredDirTabIdx()     + uiPart;   
+  m_piWedgePredDirDeltaDC1   = pcCU->getWedgePredDirDeltaDC1()   + uiPart;   
+  m_piWedgePredDirDeltaDC2   = pcCU->getWedgePredDirDeltaDC2()   + uiPart;   
+  m_piWedgePredDirDeltaEnd   = pcCU->getWedgePredDirDeltaEnd()   + uiPart;
+#endif
+#if HHI_DMM_PRED_TEX
+  m_puiWedgePredTexTabIdx    = pcCU->getWedgePredTexTabIdx()     + uiPart;   
+#if LGE_DMM3_SIMP_C0044
+  m_puiWedgePredTexIntraTabIdx = pcCU->getWedgePredTexIntraTabIdx() + uiPart;   
+#endif
+  m_piWedgePredTexDeltaDC1   = pcCU->getWedgePredTexDeltaDC1()   + uiPart;   
+  m_piWedgePredTexDeltaDC2   = pcCU->getWedgePredTexDeltaDC2()   + uiPart;   
+
+  m_piContourPredTexDeltaDC1 = pcCU->getContourPredTexDeltaDC1() + uiPart;   
+  m_piContourPredTexDeltaDC2 = pcCU->getContourPredTexDeltaDC2() + uiPart;   
+#endif
+#if LGE_EDGE_INTRA_A0070
+  if( pcCU->getSlice()->getSPS()->isDepth() )
+  {
+    m_pucEdgeCode         = pcCU->getEdgeCode( uiPart );
+    m_pucEdgeNumber       = pcCU->getEdgeNumber() + uiPart;
+    m_pucEdgeStartPos     = pcCU->getEdgeStartPos() + uiPart;
+    m_pbEdgeLeftFirst     = pcCU->getEdgeLeftFirst() + uiPart;
+    m_pbEdgePartition     = pcCU->getEdgePartition( uiPart );
+#if LGE_EDGE_INTRA_DELTA_DC
+    m_piEdgeDeltaDC0      = pcCU->getEdgeDeltaDC0() + uiPart;
+    m_piEdgeDeltaDC1      = pcCU->getEdgeDeltaDC1() + uiPart;
+#endif
+  }
+#endif
+#if RWTH_SDC_DLT_B0036
+  m_pbSDCFlag               = pcCU->getSDCFlag()            + uiPart;
+  m_apSegmentDCOffset[0]    = pcCU->getSDCSegmentDCOffset(0) + uiPart;
+  m_apSegmentDCOffset[1]    = pcCU->getSDCSegmentDCOffset(1) + uiPart;
+#endif
+}
+
+// Copy inter prediction info from the biggest CU
+Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList )
+{
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = pcCU->getSlice();
+  m_uiCUAddr           = pcCU->getAddr();
+  m_uiAbsIdxInLCU      = 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_pePartSize         = pcCU->getPartitionSize ()        + uiAbsPartIdx;
+#if HHI_INTERVIEW_SKIP
+  m_pbRenderable         = pcCU->getRenderable()        + uiAbsPartIdx;
+
+#endif
+  m_pePredMode         = pcCU->getPredictionMode()        + 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;
+#if LGE_ILLUCOMP_B0045
+  m_pbICFlag           = pcCU->getICFlag()                + uiAbsPartIdx;
+#endif
+  m_puhMergeIndex      = pcCU->getMergeIndex()            + uiAbsPartIdx;
+#if MERL_VSP_C0152
+  m_piVSPIndex         = pcCU->getVSPIndex()              + uiAbsPartIdx;
+#endif
+#if H3D_IVRP
+  m_pbResPredAvailable = pcCU->getResPredAvail()          + uiAbsPartIdx;
+  m_pbResPredFlag      = pcCU->getResPredFlag ()          + uiAbsPartIdx;
+#endif
+  m_apiMVPIdx[eRefPicList] = pcCU->getMVPIdx(eRefPicList) + uiAbsPartIdx;
+  m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;
+  
+  m_acCUMvField[ eRefPicList ].linkToWithOffset( pcCU->getCUMvField(eRefPicList), uiAbsPartIdx );
+#if HHI_MPI
+  m_piTextureModeDepth = pcCU->getTextureModeDepth() + uiAbsPartIdx;
+#endif
+
+  memcpy(m_uiSliceStartCU,pcCU->m_uiSliceStartCU+uiAbsPartIdx,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_uiEntropySliceStartCU,pcCU->m_uiEntropySliceStartCU+uiAbsPartIdx,sizeof(UInt)*m_uiNumPartition);
+}
+
+// Copy small CU to bigger CU.
+// One of quarter parts overwritten by predicted sub part.
+Void TComDataCU::copyPartFrom( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth )
+{
+  assert( uiPartUnitIdx<4 );
+  
+  m_dTotalCost         += pcCU->getTotalCost();
+  m_uiTotalDistortion  += pcCU->getTotalDistortion();
+  m_uiTotalBits        += pcCU->getTotalBits();
+  
+  UInt uiOffset         = pcCU->getTotalNumPart()*uiPartUnitIdx;
+  
+  UInt uiNumPartition = pcCU->getTotalNumPart();
+  Int iSizeInUchar  = sizeof( UChar ) * uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * uiNumPartition;
+#if MERL_VSP_C0152
+  Int iSizeInChar   = sizeof( Char )  * uiNumPartition;
+#endif
+  
+  Int sizeInChar  = sizeof( Char ) * uiNumPartition;
+  memcpy( m_phQP       + uiOffset, pcCU->getQP(),             sizeInChar                        );
+  memcpy( m_pePartSize + uiOffset, pcCU->getPartitionSize(),  sizeof( *m_pePartSize ) * uiNumPartition );
+  memcpy( m_pePredMode + uiOffset, pcCU->getPredictionMode(), sizeof( *m_pePredMode ) * uiNumPartition );
+  #if HHI_INTERVIEW_SKIP
+  memcpy( m_pbRenderable + uiOffset, pcCU->getRenderable(),         iSizeInBool  );
+#endif
+  memcpy( m_puiAlfCtrlFlag      + uiOffset, pcCU->getAlfCtrlFlag(),       iSizeInBool  );
+  memcpy( m_pbMergeFlag         + uiOffset, pcCU->getMergeFlag(),         iSizeInBool  );
+#if LGE_ILLUCOMP_B0045
+  memcpy( m_pbICFlag            + uiOffset, pcCU->getICFlag(),            iSizeInBool );
+#endif
+  memcpy( m_puhMergeIndex       + uiOffset, pcCU->getMergeIndex(),        iSizeInUchar );
+#if MERL_VSP_C0152
+  memcpy( m_piVSPIndex          + uiOffset, pcCU->getVSPIndex(),          iSizeInChar );
+#endif
+#if H3D_IVRP
+  memcpy( m_pbResPredAvailable  + uiOffset, pcCU->getResPredAvail(),      iSizeInBool  );
+  memcpy( m_pbResPredFlag       + uiOffset, pcCU->getResPredFlag(),       iSizeInBool  );
+#endif
+  memcpy( m_puhLumaIntraDir     + uiOffset, pcCU->getLumaIntraDir(),      iSizeInUchar );
+  memcpy( m_puhChromaIntraDir   + uiOffset, pcCU->getChromaIntraDir(),    iSizeInUchar );
+  memcpy( m_puhInterDir         + uiOffset, pcCU->getInterDir(),          iSizeInUchar );
+  memcpy( m_puhTrIdx            + uiOffset, pcCU->getTransformIdx(),      iSizeInUchar );
+  memcpy( m_nsqtPartIdx         + uiOffset, pcCU->getNSQTPartIdx(),       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 );
+  
+  memcpy( m_puhDepth  + uiOffset, pcCU->getDepth(),  iSizeInUchar );
+  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 );
+#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_uiSliceStartCU        + uiOffset, pcCU->m_uiSliceStartCU,        sizeof( UInt ) * uiNumPartition  );
+  memcpy( m_uiEntropySliceStartCU + uiOffset, pcCU->m_uiEntropySliceStartCU, sizeof( UInt ) * uiNumPartition  );
+
+#if HHI_DMM_WEDGE_INTRA
+  memcpy( m_puiWedgeFullTabIdx       + uiOffset, pcCU->getWedgeFullTabIdx(),        sizeof( UInt ) * uiNumPartition );
+  memcpy( m_piWedgeFullDeltaDC1      + uiOffset, pcCU->getWedgeFullDeltaDC1(),      sizeof( Int  ) * uiNumPartition );
+  memcpy( m_piWedgeFullDeltaDC2      + uiOffset, pcCU->getWedgeFullDeltaDC2(),      sizeof( Int  ) * uiNumPartition );
+
+  memcpy( m_puiWedgePredDirTabIdx    + uiOffset, pcCU->getWedgePredDirTabIdx(),     sizeof( UInt ) * uiNumPartition );
+  memcpy( m_piWedgePredDirDeltaDC1   + uiOffset, pcCU->getWedgePredDirDeltaDC1(),   sizeof( Int  ) * uiNumPartition );
+  memcpy( m_piWedgePredDirDeltaDC2   + uiOffset, pcCU->getWedgePredDirDeltaDC2(),   sizeof( Int  ) * uiNumPartition );
+  memcpy( m_piWedgePredDirDeltaEnd   + uiOffset, pcCU->getWedgePredDirDeltaEnd(),   sizeof( Int  ) * uiNumPartition );
+#endif
+#if HHI_DMM_PRED_TEX
+  memcpy( m_puiWedgePredTexTabIdx    + uiOffset, pcCU->getWedgePredTexTabIdx(),     sizeof( UInt ) * uiNumPartition );
+#if LGE_DMM3_SIMP_C0044
+  memcpy( m_puiWedgePredTexIntraTabIdx + uiOffset, pcCU->getWedgePredTexIntraTabIdx(), sizeof( UInt ) * uiNumPartition );
+#endif
+  memcpy( m_piWedgePredTexDeltaDC1   + uiOffset, pcCU->getWedgePredTexDeltaDC1(),   sizeof( Int  ) * uiNumPartition );
+  memcpy( m_piWedgePredTexDeltaDC2   + uiOffset, pcCU->getWedgePredTexDeltaDC2(),   sizeof( Int  ) * uiNumPartition );
+
+  memcpy( m_piContourPredTexDeltaDC1 + uiOffset, pcCU->getContourPredTexDeltaDC1(), sizeof( Int  ) * uiNumPartition );
+  memcpy( m_piContourPredTexDeltaDC2 + uiOffset, pcCU->getContourPredTexDeltaDC2(), sizeof( Int  ) * uiNumPartition );
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+  if( getSlice()->getSPS()->isDepth() )
+  {
+    memcpy( getEdgeCode( uiOffset ), pcCU->getEdgeCode(0), iSizeInUchar * LGE_EDGE_INTRA_MAX_EDGE_NUM_PER_4x4 );
+    memcpy( getEdgeNumber() + uiOffset, pcCU->getEdgeNumber(), iSizeInUchar );
+    memcpy( getEdgeStartPos() + uiOffset, pcCU->getEdgeStartPos(), iSizeInUchar );
+    memcpy( getEdgeLeftFirst() + uiOffset, pcCU->getEdgeLeftFirst(), iSizeInBool );
+    memcpy( getEdgePartition( uiOffset ), pcCU->getEdgePartition(0), iSizeInBool * 16 );
+#if LGE_EDGE_INTRA_DELTA_DC
+    memcpy( getEdgeDeltaDC0() + uiOffset, pcCU->getEdgeDeltaDC0(), sizeof( Int  ) * uiNumPartition );
+    memcpy( getEdgeDeltaDC1() + uiOffset, pcCU->getEdgeDeltaDC1(), sizeof( Int  ) * uiNumPartition );
+#endif
+  }
+#endif
+
+#if HHI_MPI
+  memcpy( m_piTextureModeDepth + uiOffset, pcCU->getTextureModeDepth(), sizeof( Int ) * uiNumPartition );
+#endif
+#if RWTH_SDC_DLT_B0036
+  memcpy( m_pbSDCFlag     + uiOffset, pcCU->getSDCFlag(),      iSizeInBool  );
+  memcpy( m_apSegmentDCOffset[0]     + uiOffset, pcCU->getSDCSegmentDCOffset(0), sizeof( Pel ) * uiNumPartition);
+  memcpy( m_apSegmentDCOffset[1]     + uiOffset, pcCU->getSDCSegmentDCOffset(1), sizeof( Pel ) * uiNumPartition);
+#endif
+}
+
+// Copy current predicted part to a CU in picture.
+// It is used to predict for next part
+Void TComDataCU::copyToPic( UChar uhDepth )
+{
+  TComDataCU*& rpcCU = m_pcPic->getCU( m_uiCUAddr );
+  
+  rpcCU->getTotalCost()       = m_dTotalCost;
+  rpcCU->getTotalDistortion() = m_uiTotalDistortion;
+  rpcCU->getTotalBits()       = m_uiTotalBits;
+  
+  Int iSizeInUchar  = sizeof( UChar ) * m_uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * m_uiNumPartition;
+#if MERL_VSP_C0152
+  Int iSizeInChar   = sizeof( Char  ) * m_uiNumPartition;
+#endif
+  
+  Int sizeInChar  = sizeof( Char ) * m_uiNumPartition;
+  memcpy( rpcCU->getQP() + m_uiAbsIdxInLCU, m_phQP, sizeInChar  );
+
+  memcpy( rpcCU->getPartitionSize()  + m_uiAbsIdxInLCU, m_pePartSize, sizeof( *m_pePartSize ) * m_uiNumPartition );
+#if HHI_INTERVIEW_SKIP
+  memcpy( rpcCU->getRenderable()         + m_uiAbsIdxInLCU, m_pbRenderable,         iSizeInBool  );
+#endif
+  memcpy( rpcCU->getPredictionMode() + m_uiAbsIdxInLCU, m_pePredMode, sizeof( *m_pePredMode ) * m_uiNumPartition );
+  
+  memcpy( rpcCU->getAlfCtrlFlag()    + m_uiAbsIdxInLCU, m_puiAlfCtrlFlag,    iSizeInBool  );
+  
+  memcpy( rpcCU->getMergeFlag()         + m_uiAbsIdxInLCU, m_pbMergeFlag,         iSizeInBool  );
+#if LGE_ILLUCOMP_B0045
+  memcpy( rpcCU->getICFlag()            + m_uiAbsIdxInLCU, m_pbICFlag,            iSizeInBool );
+#endif
+  memcpy( rpcCU->getMergeIndex()        + m_uiAbsIdxInLCU, m_puhMergeIndex,       iSizeInUchar );
+#if MERL_VSP_C0152
+  memcpy( rpcCU->getVSPIndex()          + m_uiAbsIdxInLCU, m_piVSPIndex,         iSizeInChar );
+#endif
+#if H3D_IVRP
+  memcpy( rpcCU->getResPredAvail()      + m_uiAbsIdxInLCU, m_pbResPredAvailable,  iSizeInBool  );
+  memcpy( rpcCU->getResPredFlag()       + m_uiAbsIdxInLCU, m_pbResPredFlag,       iSizeInBool  );
+#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->getNSQTPartIdx()       + m_uiAbsIdxInLCU, m_nsqtPartIdx,         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 );
+  
+  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  );
+#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_uiSliceStartCU        + m_uiAbsIdxInLCU, m_uiSliceStartCU,        sizeof( UInt ) * m_uiNumPartition  );
+  memcpy( rpcCU->m_uiEntropySliceStartCU + m_uiAbsIdxInLCU, m_uiEntropySliceStartCU, sizeof( UInt ) * m_uiNumPartition  );
+
+#if HHI_DMM_WEDGE_INTRA
+  memcpy( rpcCU->getWedgeFullTabIdx()        + m_uiAbsIdxInLCU, m_puiWedgeFullTabIdx,       sizeof( UInt ) * m_uiNumPartition );
+  memcpy( rpcCU->getWedgeFullDeltaDC1()      + m_uiAbsIdxInLCU, m_piWedgeFullDeltaDC1,      sizeof( Int  ) * m_uiNumPartition );
+  memcpy( rpcCU->getWedgeFullDeltaDC2()      + m_uiAbsIdxInLCU, m_piWedgeFullDeltaDC2,      sizeof( Int  ) * m_uiNumPartition );
+
+  memcpy( rpcCU->getWedgePredDirTabIdx()     + m_uiAbsIdxInLCU, m_puiWedgePredDirTabIdx,    sizeof( UInt ) * m_uiNumPartition );
+  memcpy( rpcCU->getWedgePredDirDeltaDC1()   + m_uiAbsIdxInLCU, m_piWedgePredDirDeltaDC1,   sizeof( Int  ) * m_uiNumPartition );
+  memcpy( rpcCU->getWedgePredDirDeltaDC2()   + m_uiAbsIdxInLCU, m_piWedgePredDirDeltaDC2,   sizeof( Int  ) * m_uiNumPartition );
+  memcpy( rpcCU->getWedgePredDirDeltaEnd()   + m_uiAbsIdxInLCU, m_piWedgePredDirDeltaEnd,   sizeof( Int  ) * m_uiNumPartition );
+#endif
+#if HHI_DMM_PRED_TEX
+  memcpy( rpcCU->getWedgePredTexTabIdx()     + m_uiAbsIdxInLCU, m_puiWedgePredTexTabIdx,    sizeof( UInt ) * m_uiNumPartition );
+#if LGE_DMM3_SIMP_C0044
+  memcpy( rpcCU->getWedgePredTexIntraTabIdx() + m_uiAbsIdxInLCU, m_puiWedgePredTexIntraTabIdx,    sizeof( UInt ) * m_uiNumPartition );
+#endif
+  memcpy( rpcCU->getWedgePredTexDeltaDC1()   + m_uiAbsIdxInLCU, m_piWedgePredTexDeltaDC1,   sizeof( Int  ) * m_uiNumPartition );
+  memcpy( rpcCU->getWedgePredTexDeltaDC2()   + m_uiAbsIdxInLCU, m_piWedgePredTexDeltaDC2,   sizeof( Int  ) * m_uiNumPartition );
+
+  memcpy( rpcCU->getContourPredTexDeltaDC1() + m_uiAbsIdxInLCU, m_piContourPredTexDeltaDC1, sizeof( Int  ) * m_uiNumPartition );
+  memcpy( rpcCU->getContourPredTexDeltaDC2() + m_uiAbsIdxInLCU, m_piContourPredTexDeltaDC2, sizeof( Int  ) * m_uiNumPartition );
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+  if( rpcCU->getSlice()->getSPS()->isDepth() )
+  {
+    memcpy( rpcCU->getEdgeCode( m_uiAbsIdxInLCU ),        m_pucEdgeCode,    iSizeInUchar * LGE_EDGE_INTRA_MAX_EDGE_NUM_PER_4x4 );
+    memcpy( rpcCU->getEdgeNumber()    + m_uiAbsIdxInLCU,  m_pucEdgeNumber,  iSizeInUchar );
+    memcpy( rpcCU->getEdgeStartPos()  + m_uiAbsIdxInLCU,  m_pucEdgeStartPos,iSizeInUchar );
+    memcpy( rpcCU->getEdgeLeftFirst() + m_uiAbsIdxInLCU,  m_pbEdgeLeftFirst,iSizeInBool );
+    memcpy( rpcCU->getEdgePartition( m_uiAbsIdxInLCU ),   m_pbEdgePartition,iSizeInBool * 16 );
+#if LGE_EDGE_INTRA_DELTA_DC
+    memcpy( rpcCU->getEdgeDeltaDC0() + m_uiAbsIdxInLCU,   m_piEdgeDeltaDC0, sizeof( Int  ) * m_uiNumPartition );
+    memcpy( rpcCU->getEdgeDeltaDC1() + m_uiAbsIdxInLCU,   m_piEdgeDeltaDC1, sizeof( Int  ) * m_uiNumPartition );
+#endif
+  }
+#endif
+
+#if HHI_MPI
+  memcpy( rpcCU->getTextureModeDepth() + m_uiAbsIdxInLCU, m_piTextureModeDepth, sizeof( Int ) * m_uiNumPartition );
+#endif
+#if RWTH_SDC_DLT_B0036
+  memcpy( rpcCU->getSDCFlag() + m_uiAbsIdxInLCU, m_pbSDCFlag,      iSizeInBool  );
+  memcpy( rpcCU->getSDCSegmentDCOffset(0) + m_uiAbsIdxInLCU, m_apSegmentDCOffset[0], sizeof( Pel ) * m_uiNumPartition);
+  memcpy( rpcCU->getSDCSegmentDCOffset(1) + m_uiAbsIdxInLCU, m_apSegmentDCOffset[1], sizeof( Pel ) * m_uiNumPartition);
+#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;
+#if MERL_VSP_C0152
+  Int iSizeInChar   = sizeof( Char   ) * uiQNumPart;
+#endif
+  
+  Int sizeInChar  = sizeof( Char ) * uiQNumPart;
+  memcpy( rpcCU->getQP() + uiPartOffset, m_phQP, sizeInChar );
+  memcpy( rpcCU->getPartitionSize()  + uiPartOffset, m_pePartSize, sizeof( *m_pePartSize ) * uiQNumPart );
+#if HHI_INTERVIEW_SKIP
+  memcpy( rpcCU->getRenderable()         + uiPartOffset, m_pbRenderable,         iSizeInBool  );
+#endif
+  memcpy( rpcCU->getPredictionMode() + uiPartOffset, m_pePredMode, sizeof( *m_pePredMode ) * uiQNumPart );
+  
+  memcpy( rpcCU->getAlfCtrlFlag()       + uiPartOffset, m_puiAlfCtrlFlag,      iSizeInBool  );
+  memcpy( rpcCU->getMergeFlag()         + uiPartOffset, m_pbMergeFlag,         iSizeInBool  );
+#if LGE_ILLUCOMP_B0045
+  memcpy( rpcCU->getICFlag()            + uiPartOffset, m_pbICFlag,            iSizeInBool );
+#endif
+  memcpy( rpcCU->getMergeIndex()        + uiPartOffset, m_puhMergeIndex,       iSizeInUchar );
+#if MERL_VSP_C0152
+  memcpy( rpcCU->getVSPIndex()          + uiPartOffset, m_piVSPIndex,         iSizeInChar );
+#endif
+#if H3D_IVRP
+  memcpy( rpcCU->getResPredAvail()      + uiPartOffset, m_pbResPredAvailable,  iSizeInBool  );
+  memcpy( rpcCU->getResPredFlag()       + uiPartOffset, m_pbResPredFlag,       iSizeInBool  );
+#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->getNSQTPartIdx()       + uiPartOffset, m_nsqtPartIdx,         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 );
+  
+  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_uiSliceStartCU        + uiPartOffset, m_uiSliceStartCU,        sizeof( UInt ) * uiQNumPart  );
+  memcpy( rpcCU->m_uiEntropySliceStartCU + uiPartOffset, m_uiEntropySliceStartCU, sizeof( UInt ) * uiQNumPart  );
+
+#if HHI_DMM_WEDGE_INTRA
+  memcpy( rpcCU->getWedgeFullTabIdx()        + uiPartOffset, m_puiWedgeFullTabIdx,       sizeof( UInt ) * uiQNumPart );
+  memcpy( rpcCU->getWedgeFullDeltaDC1()      + uiPartOffset, m_piWedgeFullDeltaDC1,      sizeof( Int  ) * uiQNumPart );
+  memcpy( rpcCU->getWedgeFullDeltaDC2()      + uiPartOffset, m_piWedgeFullDeltaDC2,      sizeof( Int  ) * uiQNumPart );
+
+  memcpy( rpcCU->getWedgePredDirTabIdx()     + uiPartOffset, m_puiWedgePredDirTabIdx,    sizeof( UInt ) * uiQNumPart );
+  memcpy( rpcCU->getWedgePredDirDeltaDC1()   + uiPartOffset, m_piWedgePredDirDeltaDC1,   sizeof( Int  ) * uiQNumPart );
+  memcpy( rpcCU->getWedgePredDirDeltaDC2()   + uiPartOffset, m_piWedgePredDirDeltaDC2,   sizeof( Int  ) * uiQNumPart );
+  memcpy( rpcCU->getWedgePredDirDeltaEnd()   + uiPartOffset, m_piWedgePredDirDeltaEnd,   sizeof( Int  ) * uiQNumPart );
+#endif
+#if HHI_DMM_PRED_TEX
+  memcpy( rpcCU->getWedgePredTexTabIdx()     + uiPartOffset, m_puiWedgePredTexTabIdx,    sizeof( UInt ) * uiQNumPart );
+#if LGE_DMM3_SIMP_C0044
+  memcpy( rpcCU->getWedgePredTexIntraTabIdx() + uiPartOffset, m_puiWedgePredTexIntraTabIdx, sizeof( UInt ) * uiQNumPart );
+#endif
+  memcpy( rpcCU->getWedgePredTexDeltaDC1()   + uiPartOffset, m_piWedgePredTexDeltaDC1,   sizeof( Int  ) * uiQNumPart );
+  memcpy( rpcCU->getWedgePredTexDeltaDC2()   + uiPartOffset, m_piWedgePredTexDeltaDC2,   sizeof( Int  ) * uiQNumPart );
+
+  memcpy( rpcCU->getContourPredTexDeltaDC1() + uiPartOffset, m_piContourPredTexDeltaDC1, sizeof( Int  ) * uiQNumPart );
+  memcpy( rpcCU->getContourPredTexDeltaDC2() + uiPartOffset, m_piContourPredTexDeltaDC2, sizeof( Int  ) * uiQNumPart );
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+  if( rpcCU->getSlice()->getSPS()->isDepth() )
+  {
+    memcpy( rpcCU->getEdgeCode( uiPartOffset ),       m_pucEdgeCode,    iSizeInUchar * LGE_EDGE_INTRA_MAX_EDGE_NUM_PER_4x4 );
+    memcpy( rpcCU->getEdgeNumber()    + uiPartOffset, m_pucEdgeNumber,  iSizeInUchar );
+    memcpy( rpcCU->getEdgeStartPos()  + uiPartOffset, m_pucEdgeStartPos,iSizeInUchar );
+    memcpy( rpcCU->getEdgeLeftFirst() + uiPartOffset, m_pbEdgeLeftFirst,iSizeInBool );
+    memcpy( rpcCU->getEdgePartition( uiPartOffset ),  m_pbEdgePartition,iSizeInBool * 16 );
+#if LGE_EDGE_INTRA_DELTA_DC
+    memcpy( rpcCU->getEdgeDeltaDC0() + uiPartOffset,  m_piEdgeDeltaDC0, sizeof( Int  ) * uiQNumPart  );
+    memcpy( rpcCU->getEdgeDeltaDC1() + uiPartOffset,  m_piEdgeDeltaDC1, sizeof( Int  ) * uiQNumPart  );
+#endif
+  }
+#endif
+
+#if HHI_MPI
+  memcpy( rpcCU->getTextureModeDepth() + uiPartOffset, m_piTextureModeDepth, sizeof( Int ) * uiQNumPart  );
+#endif
+#if RWTH_SDC_DLT_B0036
+  memcpy( rpcCU->getSDCFlag() + uiPartOffset, m_pbSDCFlag,      iSizeInBool  );
+  memcpy( rpcCU->getSDCSegmentDCOffset(0) + uiPartOffset, m_apSegmentDCOffset[0], sizeof( Pel ) * uiQNumPart);
+  memcpy( rpcCU->getSDCSegmentDCOffset(1) + uiPartOffset, m_apSegmentDCOffset[1], sizeof( Pel ) * uiQNumPart);
+#endif
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Other public functions
+// --------------------------------------------------------------------------------------------------------------------
+
+TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction
+                                 , Bool bEnforceTileRestriction
+                                 )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( RasterAddress::isEqualCol( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+    {
+      TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+      if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+        ||(bEnforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx))))
+      {
+        return NULL;
+      }
+      return m_pcPic->getCU( getAddr() );
+    }
+    else
+    {
+      uiLPartUnitIdx -= m_uiAbsIdxInLCU;
+      if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+        ||(bEnforceEntropySliceRestriction && (this->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+      {
+        return NULL;
+      }
+      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)))
+      ||
+       (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceTileRestriction && ( m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))  )  )
+      )
+  {
+    return NULL;
+  }
+  return m_pcCULeft;
+}
+
+
+TComDataCU* TComDataCU::getPUAbove( UInt& uiAPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction, Bool MotionDataCompresssion
+                                  , Bool planarAtLCUBoundary 
+                                  , 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 ) )
+    {
+      TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+      if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+        ||(bEnforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx))))
+      {
+        return NULL;
+      }
+      return m_pcPic->getCU( getAddr() );
+    }
+    else
+    {
+      uiAPartUnitIdx -= m_uiAbsIdxInLCU;
+      if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+        ||(bEnforceEntropySliceRestriction && (this->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+      {
+        return NULL;
+      }
+      return this;
+    }
+  }
+
+  if(planarAtLCUBoundary)
+  {
+    return NULL;
+  }
+  
+  uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+  if(MotionDataCompresssion)
+  {
+    uiAPartUnitIdx = g_motionRefer[uiAPartUnitIdx];
+  }
+
+  if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceTileRestriction &&(m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))))
+      )
+  {
+    return NULL;
+  }
+  return m_pcCUAbove;
+}
+
+TComDataCU* TComDataCU::getPUAboveLeft( UInt& uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction, Bool MotionDataCompresssion )
+{
+  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 ) )
+      {
+        TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+        if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+          ||(bEnforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx)))) 
+        {
+          return NULL;
+        }
+        return m_pcPic->getCU( getAddr() );
+      }
+      else
+      {
+        uiALPartUnitIdx -= m_uiAbsIdxInLCU;
+        if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+          ||(bEnforceEntropySliceRestriction && (this->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+        {
+          return NULL;
+        }
+        return this;
+      }
+    }
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + getPic()->getNumPartInCU() - uiNumPartInCUWidth - 1 ];
+    if(MotionDataCompresssion)
+    {
+      uiALPartUnitIdx = g_motionRefer[uiALPartUnitIdx];
+    }
+  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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiALPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - 1 ];
+  if(MotionDataCompresssion)
+  {
+    uiALPartUnitIdx = g_motionRefer[uiALPartUnitIdx];
+  }
+  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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (m_pcCUAboveLeft==NULL || m_pcCUAboveLeft->getSlice()==NULL || 
+       m_pcCUAboveLeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveLeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveLeft;
+}
+
+TComDataCU* TComDataCU::getPUAboveRight( UInt& uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction, Bool MotionDataCompresssion )
+{
+  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 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 ) )
+        {
+          TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+          if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+            ||(bEnforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx))))
+          {
+            return NULL;
+          }
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+          if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+            ||(bEnforceEntropySliceRestriction && (this->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+          {
+            return NULL;
+          }
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + 1 ];
+    if(MotionDataCompresssion)
+    {
+      uiARPartUnitIdx = g_motionRefer[uiARPartUnitIdx];
+    }
+
+  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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(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;
+    return NULL;
+  }
+  
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+  if(MotionDataCompresssion)
+  {
+    uiARPartUnitIdx = g_motionRefer[uiARPartUnitIdx];
+  }
+  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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (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() )->getEntropySliceStartCU(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, Bool bEnforceEntropySliceRestriction )
+{
+  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 ) )
+        {
+          TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+          if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+            ||(bEnforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx))))
+          {
+            return NULL;
+          }
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+          if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+            ||(bEnforceEntropySliceRestriction && (this->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+          {
+            return NULL;
+          }
+          return this;
+        }
+      }
+      uiBLPartUnitIdx = 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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(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::getPUBelowLeftAdi(UInt& uiBLPartUnitIdx, UInt uiPuHeight,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+{
+  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 ) )
+        {
+          TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+          if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx)))
+            ||(bEnforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx))))
+          {
+            return NULL;
+          }
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+          if ((bEnforceSliceRestriction        && (this->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiCurrPartUnitIdx) || m_pcSlice==NULL))
+            ||(bEnforceEntropySliceRestriction && (this->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+          {
+            return NULL;
+          }
+          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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(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 uiPuWidth, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+{
+  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() )
+  {
+    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 ) )
+        {
+          TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+          if ((bEnforceSliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
+           ||( bEnforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx))))
+
+          {
+            return NULL;
+          }
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+          if ((bEnforceSliceRestriction && (this->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL))
+            ||(bEnforceEntropySliceRestriction && (this->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrPartUnitIdx) || m_pcSlice==NULL)))
+          {
+            return NULL;
+          }
+          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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(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;
+    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()))
+       ))||
+       (bEnforceEntropySliceRestriction && (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() )->getEntropySliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveRight;
+}
+
+/** Get left QpMinCu
+*\param   uiLPartUnitIdx
+*\param   uiCurrAbsIdxInLCU
+*\param   bEnforceSliceRestriction
+*\param   bEnforceEntropySliceRestriction
+*\returns TComDataCU*   point of TComDataCU of left QpMinCu
+*/
+TComDataCU* TComDataCU::getQpMinCuLeft( UInt& uiLPartUnitIdx, UInt uiCurrAbsIdxInLCU, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction)
+{
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+  UInt uiAbsRorderQpMinCUIdx   = g_auiZscanToRaster[(uiCurrAbsIdxInLCU>>(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1)))<<(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1))];
+  UInt uiNumPartInQpMinCUWidth = getSlice()->getPPS()->getMinCuDQPSize()>>2;
+
+  UInt uiAbsZorderQpMinCUIdx   = (uiCurrAbsIdxInLCU>>(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1)))<<(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1));
+  if( (uiCurrAbsIdxInLCU != uiAbsZorderQpMinCUIdx) && 
+    ((bEnforceSliceRestriction && (m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrAbsIdxInLCU) != m_pcPic->getCU( getAddr() )->getSliceStartCU (uiAbsZorderQpMinCUIdx))) ||
+    (bEnforceEntropySliceRestriction &&(m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiCurrAbsIdxInLCU) != m_pcPic->getCU( getAddr() )->getEntropySliceStartCU (uiAbsZorderQpMinCUIdx)) )) )
+  {
+    return NULL;
+  }
+
+  if ( !RasterAddress::isZeroCol( uiAbsRorderQpMinCUIdx, uiNumPartInCUWidth ) )
+  {
+    uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsRorderQpMinCUIdx - uiNumPartInQpMinCUWidth ];
+    TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+    if ((bEnforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (uiAbsZorderQpMinCUIdx)))
+      ||(bEnforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiAbsZorderQpMinCUIdx))))
+    {
+      return NULL;
+    }
+    return m_pcPic->getCU( getAddr() );
+  }
+
+  uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsRorderQpMinCUIdx + uiNumPartInCUWidth - uiNumPartInQpMinCUWidth ];
+
+  if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiAbsZorderQpMinCUIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(uiAbsZorderQpMinCUIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+
+  if ( m_pcCULeft && m_pcCULeft->getAddr() != getAddr() )
+  {
+    return NULL;
+  }
+
+  return m_pcCULeft;
+}
+
+/** Get Above QpMinCu
+*\param   aPartUnitIdx
+*\param   currAbsIdxInLCU
+*\param   enforceSliceRestriction
+*\param   enforceEntropySliceRestriction
+*\returns TComDataCU*   point of TComDataCU of above QpMinCu
+*/
+TComDataCU* TComDataCU::getQpMinCuAbove( UInt& aPartUnitIdx, UInt currAbsIdxInLCU, Bool enforceSliceRestriction, Bool enforceEntropySliceRestriction )
+{
+  UInt numPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+  UInt absRorderQpMinCUIdx   = g_auiZscanToRaster[(currAbsIdxInLCU>>(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1)))<<(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1))];
+ 
+  UInt absZorderQpMinCUIdx   = (currAbsIdxInLCU>>(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1)))<<(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1));
+  if( (currAbsIdxInLCU != absZorderQpMinCUIdx) && 
+     ((enforceSliceRestriction        && (m_pcPic->getCU( getAddr() )->getSliceStartCU(currAbsIdxInLCU) != m_pcPic->getCU( getAddr() )->getSliceStartCU (absZorderQpMinCUIdx)))
+    ||(enforceEntropySliceRestriction && (m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(currAbsIdxInLCU) != m_pcPic->getCU( getAddr() )->getEntropySliceStartCU (absZorderQpMinCUIdx)) )) )
+  {
+    return NULL;
+  }
+
+  if ( !RasterAddress::isZeroRow( absRorderQpMinCUIdx, numPartInCUWidth ) )
+  {
+    aPartUnitIdx = g_auiRasterToZscan[ absRorderQpMinCUIdx - numPartInCUWidth ];
+    TComDataCU* pcTempReconCU = m_pcPic->getCU( getAddr() );
+    if ((enforceSliceRestriction        && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+aPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU       (absZorderQpMinCUIdx)))
+      ||(enforceEntropySliceRestriction && (pcTempReconCU==NULL || pcTempReconCU->getSlice() == NULL || pcTempReconCU->getSCUAddr()+aPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(absZorderQpMinCUIdx))))
+    {
+      return NULL;
+    }
+    return m_pcPic->getCU( getAddr() );
+  }
+  
+  aPartUnitIdx = g_auiRasterToZscan[ absRorderQpMinCUIdx + m_pcPic->getNumPartInCU() - numPartInCUWidth ];
+
+  if ( (enforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+aPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(absZorderQpMinCUIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))||
+       (enforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+aPartUnitIdx < m_pcPic->getCU( getAddr() )->getEntropySliceStartCU(absZorderQpMinCUIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+
+  if ( m_pcCUAbove && m_pcCUAbove->getAddr() != getAddr() )
+  {
+    return NULL;
+  }
+
+  return m_pcCUAbove;
+}
+
+/** Get reference QP from left QpMinCu or latest coded QP
+*\param   uiCurrAbsIdxInLCU
+*\returns Char   reference QP value
+*/
+Char TComDataCU::getRefQP( UInt uiCurrAbsIdxInLCU )
+{
+  UInt        lPartIdx, aPartIdx;
+  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);
+}
+
+Int TComDataCU::getLastValidPartIdx( Int iAbsPartIdx )
+{
+  Int iLastValidPartIdx = iAbsPartIdx-1;
+  while ( iLastValidPartIdx >= 0
+       && getPredictionMode( iLastValidPartIdx ) == MODE_NONE )
+  {
+    UInt uiDepth = getDepth( iLastValidPartIdx );
+    iLastValidPartIdx -= m_uiNumPartition>>(uiDepth<<1);
+  }
+  return iLastValidPartIdx;
+}
+
+Char TComDataCU::getLastCodedQP( UInt uiAbsPartIdx )
+{
+  UInt uiQUPartIdxMask = ~((1<<(8-(getSlice()->getPPS()->getMaxCuDQPDepth()<<1)))-1);
+  Int iLastValidPartIdx = getLastValidPartIdx( uiAbsPartIdx&uiQUPartIdxMask );
+  if ( uiAbsPartIdx < m_uiNumPartition
+    && (getSCUAddr()+iLastValidPartIdx < getSliceStartCU(m_uiAbsIdxInLCU+uiAbsPartIdx) || getSCUAddr()+iLastValidPartIdx < getEntropySliceStartCU(m_uiAbsIdxInLCU+uiAbsPartIdx) ))
+  {
+    return getSlice()->getSliceQp();
+  }
+  else
+  if ( iLastValidPartIdx >= 0 )
+  {
+    return getQP( iLastValidPartIdx );
+  }
+  else
+  {
+    if ( getZorderIdxInCU() > 0 )
+    {
+      return getPic()->getCU( getAddr() )->getLastCodedQP( getZorderIdxInCU() );
+    }
+    else if ( getAddr() > 0 )
+    {
+      return getPic()->getCU( getAddr()-1 )->getLastCodedQP( getPic()->getNumPartInCU() );
+    }
+    else
+    {
+      return getSlice()->getSliceQp();
+    }
+  }
+}
+#if LOSSLESS_CODING
+/** 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 
+ */
+Bool TComDataCU::isLosslessCoded(UInt absPartIdx)
+{
+  return ( getSlice()->getSPS()->getUseLossless() && ((getQP(absPartIdx) + getSlice()->getSPS()->getQpBDOffsetY()) == 0) );
+}
+#endif
+
+/** Get allowed chroma intra modes
+*\param   uiAbsPartIdx
+*\param   uiModeList  pointer to chroma intra modes array
+*\returns 
+*- fill uiModeList with chroma intra modes
+*/
+Void TComDataCU::getAllowedChromaDir( UInt uiAbsPartIdx, UInt* uiModeList )
+{
+  uiModeList[0] = PLANAR_IDX;
+  uiModeList[1] = VER_IDX;
+  uiModeList[2] = HOR_IDX;
+  uiModeList[3] = DC_IDX;
+  uiModeList[4] = LM_CHROMA_IDX;
+  uiModeList[5] = DM_CHROMA_IDX;
+
+  UInt uiLumaMode = getLumaIntraDir( uiAbsPartIdx );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  mapDMMtoIntraMode( uiLumaMode );
+#endif
+
+  for( Int i = 0; i < NUM_CHROMA_MODE - 2; i++ )
+  {
+    if( uiLumaMode == uiModeList[i] )
+    {
+      uiModeList[i] = 34; // VER+8 mode
+      break;
+    }
+  }
+}
+
+/** Get most probable intra modes
+*\param   uiAbsPartIdx
+*\param   uiIntraDirPred  pointer to the array for MPM storage
+*\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;
+  Int         iLeftIntraDir, iAboveIntraDir;
+  Int         uiPredNum = 0;
+  
+  // Get intra direction of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  
+  iLeftIntraDir  = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  mapDMMtoIntraMode( iLeftIntraDir );
+#endif
+#if LGE_EDGE_INTRA_A0070
+  mapEdgeIntratoDC( iLeftIntraDir );
+#endif
+  
+  // Get intra direction of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, true, false, true );
+  
+  iAboveIntraDir = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  mapDMMtoIntraMode( iAboveIntraDir );
+#endif
+#if LGE_EDGE_INTRA_A0070
+  mapEdgeIntratoDC( iAboveIntraDir );
+#endif
+  
+  uiPredNum = 3;
+  if(iLeftIntraDir == iAboveIntraDir)
+  {
+    if( piMode )
+    {
+      *piMode = 1;
+    }
+    
+    if (iLeftIntraDir > 1) // angular modes
+    {
+      uiIntraDirPred[0] = iLeftIntraDir;
+      uiIntraDirPred[1] = ((iLeftIntraDir + 29) % 32) + 2;
+      uiIntraDirPred[2] = ((iLeftIntraDir - 1 ) % 32) + 2;
+    }
+    else //non-angular
+    {
+      uiIntraDirPred[0] = PLANAR_IDX;
+      uiIntraDirPred[1] = DC_IDX;
+      uiIntraDirPred[2] = VER_IDX; 
+    }
+  }
+  else
+  {
+    if( piMode )
+    {
+      *piMode = 2;
+    }
+    uiIntraDirPred[0] = iLeftIntraDir;
+    uiIntraDirPred[1] = iAboveIntraDir;
+    
+    if (iLeftIntraDir && iAboveIntraDir ) //both modes are non-planar
+    {
+      uiIntraDirPred[2] = PLANAR_IDX;
+    }
+    else
+    {
+      uiIntraDirPred[2] =  (iLeftIntraDir+iAboveIntraDir)<2? VER_IDX : DC_IDX;
+    }
+  }
+  
+  return uiPredNum;
+}
+
+#if LGE_EDGE_INTRA_A0070
+UInt TComDataCU::getCtxEdgeIntra( UInt uiAbsPartIdx )
+{
+  UInt        uiCtx = 0;
+  return uiCtx;
+}
+#endif
+
+UInt TComDataCU::getCtxSplitFlag( UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx;
+  // Get left split flag
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx  = ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
+  
+  // Get above split flag
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx += ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
+  
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxQtCbf( UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  if( eType )
+  {
+    return uiTrDepth;
+  }
+  else
+  {
+    const UInt uiDepth = getDepth( uiAbsPartIdx );
+    const UInt uiLog2TrafoSize = g_aucConvertToBit[ getSlice()->getSPS()->getMaxCUWidth() ] + 2 - uiDepth - uiTrDepth;
+    const UInt uiCtx = uiTrDepth == 0 || uiLog2TrafoSize == getSlice()->getSPS()->getQuadtreeTULog2MaxSize() ? 1 : 0;
+    return uiCtx;
+  }
+}
+
+UInt TComDataCU::getQuadtreeTULog2MinSizeInCU( UInt absPartIdx )
+{
+  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 log2MinTUSizeInCU = 0;
+  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
+    log2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MinSize();
+  }
+  else
+  {
+    // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is still >= QuadtreeTULog2MinSize
+    log2MinTUSizeInCU = log2CbSize - ( quadtreeTUMaxDepth - 1 + interSplitFlag + intraSplitFlag); // stop when trafoDepth == hierarchy_depth = splitFlag
+    if ( log2MinTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize())
+    {
+      // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is still > QuadtreeTULog2MaxSize
+      log2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize();
+    }  
+  }
+  return log2MinTUSizeInCU;
+}
+
+
+#if H3D_IVRP
+UInt
+TComDataCU::getCtxResPredFlag( UInt uiAbsPartIdx )
+{
+#if 1 // simple context
+  UInt        uiCtx = 0;
+#else
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  // Get BCBP of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx    = ( pcTempCU ) ? pcTempCU->getResPredFlag( uiTempPartIdx ) : 0;
+  
+  // Get BCBP of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx   += ( pcTempCU ) ? pcTempCU->getResPredFlag( uiTempPartIdx ) : 0;
+#endif  
+  return uiCtx;
+}
+#endif
+
+
+UInt TComDataCU::getCtxSkipFlag( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  // Get BCBP of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx    = ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
+  
+  // Get BCBP of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx   += ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
+  
+  return uiCtx;
+}
+
+#if LGE_ILLUCOMP_B0045
+UInt TComDataCU::getCtxICFlag( UInt uiAbsPartIdx )
+{
+  UInt        uiCtx = 0;
+
+  return uiCtx;
+}
+#endif
+
+UInt TComDataCU::getCtxInterDir( UInt uiAbsPartIdx )
+{
+  return getDepth( uiAbsPartIdx );
+}
+
+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 );
+}
+
+/** 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 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::setDepthSubParts( UInt uiDepth, UInt uiAbsPartIdx )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  memset( m_puhDepth + uiAbsPartIdx, uiDepth, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Bool TComDataCU::isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  return (((m_uiAbsIdxInLCU + uiAbsPartIdx)% uiPartNumb) == 0);
+}
+
+Void TComDataCU::setAlfCtrlFlagSubParts( Bool uiFlag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> ( 2 * uiDepth );
+  memset( m_puiAlfCtrlFlag + uiAbsPartIdx, uiFlag, sizeof( *m_puiAlfCtrlFlag ) * uiCurrPartNumb );
+}
+
+Void TComDataCU::createTmpAlfCtrlFlag()
+{
+  m_puiTmpAlfCtrlFlag = new Bool[ m_uiNumPartition ];
+}
+
+Void TComDataCU::destroyTmpAlfCtrlFlag()
+{
+  if(m_puiTmpAlfCtrlFlag)
+  {
+    delete[] m_puiTmpAlfCtrlFlag;
+    m_puiTmpAlfCtrlFlag = NULL;
+  }
+}
+
+Void TComDataCU::copyAlfCtrlFlagToTmp()
+{
+  memcpy( m_puiTmpAlfCtrlFlag, m_puiAlfCtrlFlag, sizeof( *m_puiAlfCtrlFlag )*m_uiNumPartition );
+}
+
+Void TComDataCU::copyAlfCtrlFlagFromTmp()
+{
+  memcpy( m_puiAlfCtrlFlag, m_puiTmpAlfCtrlFlag, sizeof( *m_puiAlfCtrlFlag )*m_uiNumPartition );
+}
+
+Void TComDataCU::setPartSizeSubParts( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pePartSize) == 1 );
+  memset( m_pePartSize + uiAbsPartIdx, eMode, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+#if HHI_INTERVIEW_SKIP
+Void TComDataCU::setRenderableSubParts ( Bool bRenderable, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for (UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_pbRenderable[uiAbsPartIdx + ui] = bRenderable;
+  }
+}
+#endif
+
+Void TComDataCU::setPredModeSubParts( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pePartSize) == 1 );
+  memset( m_pePredMode + uiAbsPartIdx, eMode, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+
+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() )->getEntropySliceStartCU(uiSCUIdx+getZorderIdxInCU()) == pcSlice->getEntropySliceCurStartCUAddr() )
+    {
+      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 );
+}
+
+template<typename T>
+Void TComDataCU::setSubPart( T uiParameter, T* puhBaseLCU, 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;
+  switch ( m_pePartSize[ uiCUAddr ] )
+  {
+    case SIZE_2Nx2N:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, 4 * uiCurrPartNumQ );
+      break;
+    case SIZE_2NxN:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, 2 * uiCurrPartNumQ );
+      break;
+    case SIZE_Nx2N:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, uiCurrPartNumQ );
+      memset( puhBaseLCU + uiCUAddr + 2 * uiCurrPartNumQ, uiParameter, uiCurrPartNumQ );
+      break;
+    case SIZE_NxN:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, uiCurrPartNumQ ); 
+      break;
+    case SIZE_2NxnU:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, ((uiCurrPartNumQ >> 1) + (uiCurrPartNumQ << 1)) );                      
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_2NxnD:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, ((uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1)) );                      
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nLx2N:
+      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) ); 
+      }
+      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)) ); 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    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) );                           
+      }
+      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) );                          
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    default:
+      assert( 0 );
+  }
+}
+
+Void TComDataCU::setMergeFlagSubParts ( Bool bMergeFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart( bMergeFlag, m_pbMergeFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+#if RWTH_SDC_DLT_B0036
+Void TComDataCU::setSDCFlagSubParts ( Bool bSDCFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart( bSDCFlag, m_pbSDCFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+UInt TComDataCU::getCtxSDCFlag( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  // left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, false );
+  uiCtx    = ( pcTempCU ) ? pcTempCU->getSDCFlag( uiTempPartIdx ) : 0;
+  
+  // above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, false );
+  uiCtx   += ( pcTempCU ) ? pcTempCU->getSDCFlag( uiTempPartIdx ) : 0;
+  
+  return uiCtx;
+}
+
+Bool TComDataCU::getSDCAvailable( UInt uiAbsPartIdx )
+{
+  if( !getSlice()->getSPS()->isDepth() || getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N )
+    return false;
+  
+  UInt uiLumaPredMode = getLumaIntraDir( uiAbsPartIdx );
+  
+  if(!isIntra(uiAbsPartIdx))
+    return false;
+  
+  for(UInt ui=0; ui<RWTH_SDC_NUM_PRED_MODES; ui++)
+  {
+    if( g_auiSDCPredModes[ui] == uiLumaPredMode )
+      return true;
+  }
+  // else
+  return false;
+}
+#endif
+
+Void TComDataCU::setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiMergeIndex, m_puhMergeIndex, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+#if MERL_VSP_C0152
+Void TComDataCU::setVSPIndexSubParts ( Char iVSPIdx, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Char>( iVSPIdx, m_piVSPIndex, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+#endif
+
+#if H3D_IVRP
+Void TComDataCU::setResPredAvailSubParts( Bool bResPredAvailable, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart( bResPredAvailable, m_pbResPredAvailable, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setResPredFlagSubParts( Bool bResPredFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart( bResPredFlag, m_pbResPredFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+#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 )
+{
+  setSubPart<UChar>( uiDir, m_puhInterDir, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+#if LGE_ILLUCOMP_B0045
+Void TComDataCU::setICFlagSubParts( Bool bICFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  memset( m_pbICFlag + uiAbsPartIdx, bICFlag, (m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ))*sizeof(Bool) );
+}
+
+#if LGE_ILLUCOMP_DEPTH_C0046
+//This modification is not needed after integrating JCT3V-C0137
+Bool TComDataCU::isICFlagRequired(UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiPartAddr;
+  UInt iNumbPart;
+
+  if(!getSlice()->getIsDepth())
+  {
+    Int iWidth, iHeight;
+
+    iNumbPart = ( getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N ? 1 : (getPartitionSize(uiAbsPartIdx) == SIZE_NxN ? 4 : 2) );
+
+    for(UInt i = 0; i < iNumbPart; i++)
+    {
+      getPartIndexAndSize(i, uiPartAddr, iWidth, iHeight, uiAbsPartIdx, true);
+      uiPartAddr += uiAbsPartIdx;
+
+      for(UInt uiRefIdx = 0; uiRefIdx < 2; uiRefIdx++)
+      {
+        RefPicList eRefList = uiRefIdx ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+        Int iBestRefIdx = getCUMvField(eRefList)->getRefIdx(uiPartAddr);
+
+        if((getInterDir(uiPartAddr) & (uiRefIdx+1)) && iBestRefIdx >= 0 && getSlice()->getViewId() != getSlice()->getRefViewId(eRefList, iBestRefIdx))
+        {
+          return true;
+        }
+      }
+    }
+  }
+  else
+  {
+    iNumbPart = getPic()->getNumPartInCU() >> (uiDepth << 1);
+
+    for(UInt i = 0; i < iNumbPart; i++)
+    {
+      uiPartAddr = uiAbsPartIdx + i;
+
+      for(UInt uiRefIdx = 0; uiRefIdx < 2; uiRefIdx++)
+      {
+        RefPicList eRefList = uiRefIdx ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+        Int iBestRefIdx = getCUMvField(eRefList)->getRefIdx(uiPartAddr);
+
+        if((getInterDir(uiPartAddr) & (uiRefIdx+1)) && iBestRefIdx >= 0 && getSlice()->getViewId() != getSlice()->getRefViewId(eRefList, iBestRefIdx))
+        {
+          return true;
+        }
+      }
+    }
+  }
+
+  return false;
+}
+#else
+Bool TComDataCU::isICFlagRequired(UInt uiAbsPartIdx)
+{
+  UInt uiPartAddr;
+  UInt iNumbPart;
+  Int iWidth, iHeight;
+
+  UInt uiPartMode = getPartitionSize(uiAbsPartIdx);
+
+  iNumbPart = (uiPartMode == SIZE_2Nx2N ? 1 : (uiPartMode == SIZE_NxN ? 4 : 2) );
+
+  for(UInt i = 0; i < iNumbPart; i++)
+  {
+    getPartIndexAndSize(i, uiPartAddr, iWidth, iHeight, uiAbsPartIdx, true);
+    uiPartAddr += uiAbsPartIdx;
+
+    for(UInt uiRefIdx = 0; uiRefIdx < 2; uiRefIdx++)
+    {
+      RefPicList eRefList = uiRefIdx ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+      Int iBestRefIdx = getCUMvField(eRefList)->getRefIdx(uiPartAddr);
+
+      if((getInterDir(uiPartAddr) & (uiRefIdx+1)) && iBestRefIdx >= 0 && getSlice()->getViewId() != getSlice()->getRefViewId(eRefList, iBestRefIdx))
+      {
+        return true;
+    }
+  }
+  }
+  return false;
+}
+#endif
+#endif
+
+Void TComDataCU::setMVPIdxSubParts( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Char>( iMVPIdx, m_apiMVPIdx[eRefPicList], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setMVPNumSubParts( Int iMVPNum, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Char>( iMVPNum, m_apiMVPNum[eRefPicList], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+
+Void TComDataCU::setTrIdxSubParts( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhTrIdx + uiAbsPartIdx, uiTrIdx, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Void TComDataCU::setNSQTIdxSubParts( UInt absPartIdx, UInt depth )
+{
+  UInt currPartNumb = m_pcPic->getNumPartInCU() >> (depth << 1);
+  
+  memset( m_nsqtPartIdx + absPartIdx, absPartIdx, sizeof(UChar)*currPartNumb );
+}
+
+Void  TComDataCU::setNSQTIdxSubParts( UInt log2TrafoSize, UInt absPartIdx, UInt absTUPartIdx, UInt trMode )
+{
+  UInt trWidth, trHeight;
+  UInt nsTUWidthInBaseUnits, nsTUHeightInBaseUnits;
+  UInt lcuWidthInBaseUnits = getPic()->getNumPartInWidth();
+  UInt minTuSize = ( 1 << getSlice()->getSPS()->getQuadtreeTULog2MinSize() );
+
+  trWidth = trHeight = ( 1 << log2TrafoSize );
+
+  if ( useNonSquareTrans( trMode, absPartIdx ) && ( trWidth > minTuSize ) )
+  {
+    trWidth  = ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_nLx2N || m_pePartSize[absPartIdx] == SIZE_nRx2N )? trWidth >> 1  : trWidth << 1;
+    trHeight = ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_nLx2N || m_pePartSize[absPartIdx] == SIZE_nRx2N )? trHeight << 1 : trHeight >> 1;
+  }
+
+  nsTUWidthInBaseUnits  = trWidth / getPic()->getMinCUWidth();
+  nsTUHeightInBaseUnits = trHeight / getPic()->getMinCUHeight();
+  
+  if ( nsTUWidthInBaseUnits > nsTUHeightInBaseUnits )
+  {
+    UInt currPartNumb = nsTUHeightInBaseUnits*nsTUHeightInBaseUnits;
+    memset( m_nsqtPartIdx + absTUPartIdx                                                                , absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+  nsTUHeightInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+2*nsTUHeightInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+3*nsTUHeightInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+  }
+  else if ( nsTUWidthInBaseUnits < nsTUHeightInBaseUnits )
+  {
+    UInt currPartNumb = nsTUWidthInBaseUnits*nsTUWidthInBaseUnits;
+    memset( m_nsqtPartIdx + absTUPartIdx                                                                                   , absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+  nsTUWidthInBaseUnits*lcuWidthInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+2*nsTUWidthInBaseUnits*lcuWidthInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+    memset( m_nsqtPartIdx + g_auiRasterToZscan[g_auiZscanToRaster[absTUPartIdx]+3*nsTUWidthInBaseUnits*lcuWidthInBaseUnits], absPartIdx, sizeof(UChar)*(currPartNumb) );
+  }
+  else
+  {
+    UInt currPartNumb = nsTUWidthInBaseUnits*nsTUHeightInBaseUnits;
+    memset( m_nsqtPartIdx + absTUPartIdx, absPartIdx, sizeof(UChar)*(currPartNumb) );
+  }
+}
+
+Void TComDataCU::setSizeSubParts( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhWidth  + uiAbsPartIdx, uiWidth,  sizeof(UChar)*uiCurrPartNumb );
+  memset( m_puhHeight + uiAbsPartIdx, uiHeight, sizeof(UChar)*uiCurrPartNumb );
+}
+
+UChar TComDataCU::getNumPartInter()
+{
+  UChar iNumPart = 0;
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:    iNumPart = 1; break;
+    case SIZE_2NxN:     iNumPart = 2; break;
+    case SIZE_Nx2N:     iNumPart = 2; break;
+    case SIZE_NxN:      iNumPart = 4; break;
+    case SIZE_2NxnU:    iNumPart = 2; break;
+    case SIZE_2NxnD:    iNumPart = 2; break;
+    case SIZE_nLx2N:    iNumPart = 2; break;
+    case SIZE_nRx2N:    iNumPart = 2; break;
+    default:            assert (0);   break;
+  }
+  
+  return  iNumPart;
+}
+
+#if H3D_IVRP
+Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx, Bool bLCU)
+{
+  UInt uiNumPartition  = bLCU ? (getWidth(uiAbsPartIdx)*getHeight(uiAbsPartIdx) >> 4) : m_uiNumPartition;
+  UInt uiTmpAbsPartIdx = bLCU ? uiAbsPartIdx : 0;
+
+  switch ( m_pePartSize[uiTmpAbsPartIdx] )
+  {
+  case SIZE_2NxN:
+    riWidth = getWidth(uiTmpAbsPartIdx);      riHeight = getHeight(uiTmpAbsPartIdx) >> 1; ruiPartAddr = ( uiPartIdx == 0 )? 0 : uiNumPartition >> 1;
+    break;
+  case SIZE_Nx2N:
+    riWidth = getWidth(uiTmpAbsPartIdx) >> 1; riHeight = getHeight(uiTmpAbsPartIdx);      ruiPartAddr = ( uiPartIdx == 0 )? 0 : uiNumPartition >> 2;
+    break;
+  case SIZE_NxN:
+    riWidth = getWidth(uiTmpAbsPartIdx) >> 1; riHeight = getHeight(uiTmpAbsPartIdx) >> 1; ruiPartAddr = ( uiNumPartition >> 2 ) * uiPartIdx;
+    break;
+  case SIZE_2NxnU:
+    riWidth     = getWidth(uiTmpAbsPartIdx);
+    riHeight    = ( uiPartIdx == 0 ) ?  getHeight(uiTmpAbsPartIdx) >> 2 : ( getHeight(uiTmpAbsPartIdx) >> 2 ) + ( getHeight(uiTmpAbsPartIdx) >> 1 );
+    ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : uiNumPartition >> 3;
+    break;
+  case SIZE_2NxnD:
+    riWidth     = getWidth(uiTmpAbsPartIdx);
+    riHeight    = ( uiPartIdx == 0 ) ?  ( getHeight(uiTmpAbsPartIdx) >> 2 ) + ( getHeight(uiTmpAbsPartIdx) >> 1 ) : getHeight(uiTmpAbsPartIdx) >> 2;
+    ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (uiNumPartition >> 1) + (uiNumPartition >> 3);
+    break;
+  case SIZE_nLx2N:
+    riWidth     = ( uiPartIdx == 0 ) ? getWidth(uiTmpAbsPartIdx) >> 2 : ( getWidth(uiTmpAbsPartIdx) >> 2 ) + ( getWidth(uiTmpAbsPartIdx) >> 1 );
+    riHeight    = getHeight(uiTmpAbsPartIdx);
+    ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : uiNumPartition >> 4;
+    break;
+  case SIZE_nRx2N:
+    riWidth     = ( uiPartIdx == 0 ) ? ( getWidth(uiTmpAbsPartIdx) >> 2 ) + ( getWidth(uiTmpAbsPartIdx) >> 1 ) : getWidth(uiTmpAbsPartIdx) >> 2;
+    riHeight    = getHeight(uiTmpAbsPartIdx);
+    ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (uiNumPartition >> 2) + (uiNumPartition >> 4);
+    break;
+  default:
+    assert ( m_pePartSize[uiTmpAbsPartIdx ] == SIZE_2Nx2N ); 
+    riWidth = getWidth(uiTmpAbsPartIdx);      riHeight = getHeight(uiTmpAbsPartIdx);      ruiPartAddr = 0;
+    break;
+  }
+}
+#else
+Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight )
+{
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2NxN:
+      riWidth = getWidth(0);      riHeight = getHeight(0) >> 1; ruiPartAddr = ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      riWidth = getWidth(0) >> 1; riHeight = getHeight(0);      ruiPartAddr = ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 2;
+      break;
+    case SIZE_NxN:
+      riWidth = getWidth(0) >> 1; riHeight = getHeight(0) >> 1; ruiPartAddr = ( m_uiNumPartition >> 2 ) * uiPartIdx;
+      break;
+    case SIZE_2NxnU:
+      riWidth     = getWidth(0);
+      riHeight    = ( uiPartIdx == 0 ) ?  getHeight(0) >> 2 : ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 );
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : m_uiNumPartition >> 3;
+      break;
+    case SIZE_2NxnD:
+      riWidth     = getWidth(0);
+      riHeight    = ( uiPartIdx == 0 ) ?  ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 ) : getHeight(0) >> 2;
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 3);
+      break;
+    case SIZE_nLx2N:
+      riWidth     = ( uiPartIdx == 0 ) ? getWidth(0) >> 2 : ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 );
+      riHeight    = getHeight(0);
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : m_uiNumPartition >> 4;
+      break;
+    case SIZE_nRx2N:
+      riWidth     = ( uiPartIdx == 0 ) ? ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 ) : getWidth(0) >> 2;
+      riHeight    = getHeight(0);
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (m_uiNumPartition >> 2) + (m_uiNumPartition >> 4);
+      break;
+    default:
+      assert ( m_pePartSize[0] == SIZE_2Nx2N );
+      riWidth = getWidth(0);      riHeight = getHeight(0);      ruiPartAddr = 0;
+      break;
+  }
+}
+#endif
+
+Void TComDataCU::getMvField ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField )
+{
+  if ( pcCU == NULL )  // OUT OF BOUNDARY
+  {
+    TComMv  cZeroMv;
+    rcMvField.setMvField( cZeroMv, NOT_VALID );
+    return;
+  }
+  
+  TComCUMvField*  pcCUMvField = pcCU->getCUMvField( eRefPicList );
+  rcMvField.setMvField( pcCUMvField->getMv( uiAbsPartIdx ), pcCUMvField->getRefIdx( uiAbsPartIdx ) );
+}
+
+Void TComDataCU::deriveLeftRightTopIdxGeneral ( PartSize eCUMode, UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+{
+  ruiPartIdxLT = m_uiAbsIdxInLCU + uiAbsPartIdx;
+  UInt uiPUWidth = 0;
+  
+  switch ( m_pePartSize[uiAbsPartIdx] )
+  {
+    case SIZE_2Nx2N: uiPUWidth = m_puhWidth[uiAbsPartIdx];  break;
+    case SIZE_2NxN:  uiPUWidth = m_puhWidth[uiAbsPartIdx];   break;
+    case SIZE_Nx2N:  uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 1;  break;
+    case SIZE_NxN:   uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 1; break;
+    case SIZE_2NxnU:   uiPUWidth = m_puhWidth[uiAbsPartIdx]; break;
+    case SIZE_2NxnD:   uiPUWidth = m_puhWidth[uiAbsPartIdx]; break;
+    case SIZE_nLx2N:   
+      if ( uiPartIdx == 0 )
+      {
+        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2; 
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2); 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nRx2N:   
+      if ( uiPartIdx == 0 )
+      {
+        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2); 
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2; 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  ruiPartIdxRT = g_auiRasterToZscan [g_auiZscanToRaster[ ruiPartIdxLT ] + uiPUWidth / m_pcPic->getMinCUWidth() - 1 ];
+}
+
+Void TComDataCU::deriveLeftBottomIdxGeneral( PartSize eCUMode, UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB )
+{
+  UInt uiPUHeight = 0;
+  switch ( m_pePartSize[uiAbsPartIdx] )
+  {
+    case SIZE_2Nx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];    break;
+    case SIZE_2NxN:  uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 1;    break;
+    case SIZE_Nx2N:  uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    case SIZE_NxN:   uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 1;    break;
+    case SIZE_2NxnU: 
+      if ( uiPartIdx == 0 )
+      {
+        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;    
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);    
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_2NxnD: 
+      if ( uiPartIdx == 0 )
+      {
+        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);    
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;    
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nLx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    case SIZE_nRx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU + uiAbsPartIdx ] + ((uiPUHeight / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInWidth()];
+}
+
+Void TComDataCU::deriveLeftRightTopIdx ( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+{
+  ruiPartIdxLT = m_uiAbsIdxInLCU;
+  ruiPartIdxRT = g_auiRasterToZscan [g_auiZscanToRaster[ ruiPartIdxLT ] + m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1 ];
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:                                                                                                                                break;
+    case SIZE_2NxN:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1; ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 2; ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : m_uiNumPartition >> 2;
+      break;
+    case SIZE_NxN:
+      ruiPartIdxLT += ( m_uiNumPartition >> 2 ) * uiPartIdx;         ruiPartIdxRT +=  ( m_uiNumPartition >> 2 ) * ( uiPartIdx - 1 );
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 3;
+      ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 3;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 1 ) + ( m_uiNumPartition >> 3 );
+      ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 1 ) + ( m_uiNumPartition >> 3 );
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 4;
+      ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : ( m_uiNumPartition >> 2 ) + ( m_uiNumPartition >> 4 );
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 2 ) + ( m_uiNumPartition >> 4 );
+      ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : m_uiNumPartition >> 4;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+}
+
+Void TComDataCU::deriveLeftBottomIdx( PartSize      eCUMode,   UInt  uiPartIdx,      UInt&      ruiPartIdxLB )
+{
+  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInWidth()];
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:
+      ruiPartIdxLB += m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxN:
+      ruiPartIdxLB += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 )? m_uiNumPartition >> 1 : (m_uiNumPartition >> 2)*3;
+      break;
+    case SIZE_NxN:
+      ruiPartIdxLB += ( m_uiNumPartition >> 2 ) * uiPartIdx;
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? -((Int)m_uiNumPartition >> 3) : m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? m_uiNumPartition >> 1 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 4);
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? m_uiNumPartition >> 1 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 2) + (m_uiNumPartition >> 4);
+      break;
+    default:
+      assert (0);
+      break;
+  }
+}
+
+/** Derives the partition index of neighbouring bottom right block
+ * \param [in]  eCUMode
+ * \param [in]  uiPartIdx 
+ * \param [out] ruiPartIdxRB 
+ */
+Void TComDataCU::deriveRightBottomIdx( PartSize      eCUMode,   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];
+
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:  
+      ruiPartIdxRB += m_uiNumPartition >> 1;    
+      break;
+    case SIZE_2NxN:  
+      ruiPartIdxRB += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;   
+      break;
+    case SIZE_Nx2N:  
+      ruiPartIdxRB += ( uiPartIdx == 0 )? m_uiNumPartition >> 2 : (m_uiNumPartition >> 1);   
+      break;
+    case SIZE_NxN:   
+      ruiPartIdxRB += ( m_uiNumPartition >> 2 ) * ( uiPartIdx - 1 );   
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? -((Int)m_uiNumPartition >> 3) : m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 3) + (m_uiNumPartition >> 4): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3) + (m_uiNumPartition >> 4) : m_uiNumPartition >> 1;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+}
+
+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 ) )
+  {
+    return false;
+  }
+
+  for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+  {
+    if ( getInterDir( uiAbsPartIdx ) & ( 1 << uiRefListIdx ) )
+    {
+      if ( getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiAbsPartIdx )     != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiCandAbsPartIdx ) || 
+        getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiAbsPartIdx ) != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiCandAbsPartIdx ) )
+      {
+        return false;
+      }
+    }
+  }
+
+  return true;
+}
+
+/** Constructs a list of merging candidates
+ * \param uiAbsPartIdx
+ * \param uiPUIdx 
+ * \param uiDepth
+ * \param pcMvFieldNeighbours
+ * \param puhInterDirNeighbours
+ * \param numValidMergeCand
+ */
+#if MERL_VSP_C0152
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int* iVSPIndexTrue, Int mrgCandIdx )
+#else
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx )
+#endif
+{
+#if H3D_IVMP
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+#if FCO_FIX
+  const Int extraMergeCand = ( ( ( getSlice()->getIsDepth() && m_pcSlice->getTexturePic() ) || getSlice()->getSPS()->getMultiviewMvPredMode() )? 1 : 0 );
+#else
+  const Int extraMergeCand = ( ( getSlice()->getIsDepth() || getSlice()->getSPS()->getMultiviewMvPredMode() )? 1 : 0 );
+#endif
+#else
+  const Int extraMergeCand = ( getSlice()->getSPS()->getMultiviewMvPredMode() ? 1 : 0 );
+#endif
+#endif
+
+  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiAbsPartIdx;
+  UInt uiIdx = 1;
+#if H3D_IVMP
+  Bool abCandIsInter[ MRG_MAX_NUM_CANDS_MEM ];
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS_MEM; ++ui )
+#else
+  Bool abCandIsInter[ MRG_MAX_NUM_CANDS ];
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+#endif
+  {
+    abCandIsInter[ui] = false;
+  }
+  // compute the location of the current PU
+  Int xP, yP, nPSW, nPSH;
+  this->getPartPosition(uiPUIdx, xP, yP, nPSW, nPSH);
+
+#if MERL_VSP_C0152
+  Bool bVspMvZeroDone[3] = {false, false, false};
+#endif
+  
+  Int iCount = 0;
+
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  PartSize cCurPS = getPartitionSize( uiAbsPartIdx );
+  deriveLeftRightTopIdxGeneral( cCurPS, uiAbsPartIdx, uiPUIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral( cCurPS, uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
+
+#if H3D_IVMP
+  Bool bNoPdmMerge   = ( m_pcSlice->getSPS()->getViewId() == 0 || ( m_pcSlice->getSPS()->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) != PDM_USE_FOR_MERGE );
+
+  //===== add merge with predicted depth maps =====
+  TComMv  acPdmMv       [4];
+  Int     aiPdmRefIdx   [4] = {-1, -1, -1, -1};
+  Bool    bLeftAvai         = false;
+  Int     iPosLeftAbove[2]  = {-1, -1};
+
+#if H3D_NBDV
+  acPdmMv[0].m_bDvMcp = acPdmMv[1].m_bDvMcp = acPdmMv[2].m_bDvMcp = acPdmMv[3].m_bDvMcp = false; 
+#endif //H3D_NBDV
+
+#if H3D_IVRP
+  Bool bDVAvail = true;
+#endif
+
+#if H3D_NBDV
+  DisInfo cDisInfo;
+  cDisInfo.iN = 0;
+  if(!bNoPdmMerge)
+  {
+#if FCO_DVP_REFINE_C0132_C0170
+    if( !getPic()->getDepthCoded() )
+#endif
+    getDisMvpCandNBDV(uiPUIdx, uiAbsPartIdx, &cDisInfo , true
+#if MERL_VSP_C0152
+            , true
+#endif      
+);
+  }
+#if FCO_DVP_REFINE_C0132_C0170
+  if(getPic()->getDepthCoded() )
+  {
+    TComPic*      pcCodedDepthMap = getPic()->getRecDepthMap();
+    TComMv        cColMv;
+
+    cColMv.setZero();
+    estimateDVFromDM(uiPUIdx, pcCodedDepthMap, uiAbsPartIdx, &cColMv, false);
+
+    cDisInfo.iN = 1;
+    cDisInfo.m_acMvCand[0].setHor( cColMv.getHor() );
+    cDisInfo.m_acMvCand[0].setVer( cColMv.getVer() );
+    cDisInfo.m_aVIdxCan[0] = 0;
+
+  }
+#endif
+  if(cDisInfo.iN==0)
+  {
+    cDisInfo.iN = 1;
+    cDisInfo.m_acMvCand[0].setHor(0);
+    cDisInfo.m_acMvCand[0].setVer(0);
+    cDisInfo.m_aVIdxCan[0] = 0;
+#if H3D_IVRP
+    bDVAvail = false;
+#endif
+  }
+
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+#if FCO_FIX
+  if( m_pcSlice->getIsDepth() && m_pcSlice->getTexturePic() )
+#else
+  if( m_pcSlice->getIsDepth())
+#endif
+  {
+    UInt uiPartIdxCenter;
+    xDeriveCenterIdx( cCurPS, uiPUIdx, uiPartIdxCenter );    
+    TComDataCU *pcTextureCU = m_pcSlice->getTexturePic()->getCU( getAddr() );
+    if ( pcTextureCU && !pcTextureCU->isIntra( uiPartIdxCenter ) )
+    {
+      abCandIsInter[iCount] = true;      
+      puhInterDirNeighbours[iCount] = pcTextureCU->getInterDir( uiPartIdxCenter );
+      if( ( puhInterDirNeighbours[iCount] & 1 ) == 1 )
+      {
+        pcTextureCU->getMvField( pcTextureCU, uiPartIdxCenter, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+        TComMv cMvPred = pcMvFieldNeighbours[iCount<<1].getMv();
+        const TComMv cAdd( 1 << ( 2 - 1 ), 1 << ( 2 - 1 ) );
+        cMvPred+=cAdd;
+        cMvPred>>=2;
+        clipMv(cMvPred);
+        pcMvFieldNeighbours[iCount<<1].setMvField(cMvPred,pcMvFieldNeighbours[iCount<<1].getRefIdx());
+      }
+      if ( getSlice()->isInterB() )
+      {
+        if( ( puhInterDirNeighbours[iCount] & 2 ) == 2 )
+        {
+          pcTextureCU->getMvField( pcTextureCU, uiPartIdxCenter, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+          TComMv cMvPred = pcMvFieldNeighbours[(iCount<<1)+1].getMv();
+          const TComMv cAdd( 1 << ( 2 - 1 ), 1 << ( 2 - 1 ) );
+          cMvPred+=cAdd;
+          cMvPred>>=2;
+          clipMv(cMvPred);
+          pcMvFieldNeighbours[(iCount<<1)+1].setMvField(cMvPred,pcMvFieldNeighbours[(iCount<<1)+1].getRefIdx());
+        }
+      }
+#if MERL_VSP_C0152
+      xInheritVspMode( pcTextureCU, uiPartIdxCenter, bVspMvZeroDone, iCount, iVSPIndexTrue, pcMvFieldNeighbours, &cDisInfo ) ;
+#endif
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+#endif
+
+  Int iPdmDir[2] = {0, 0};
+  getUnifiedMvPredCan(uiPUIdx, REF_PIC_LIST_0, 0, aiPdmRefIdx, acPdmMv, &cDisInfo, iPdmDir, true);
+  Int iPdmInterDir;
+#else // H3D_NBDV
+  Int iPdmDir[2] = {0, 0};
+  Int     iPdmInterDir      = getPdmMergeCandidate( uiPUIdx, aiPdmRefIdx, acPdmMv );
+  iPdmDir[0] = iPdmInterDir; 
+  iPdmDir[1] = iPdmInterDir; 
+#endif // H3D_NBDV
+#if H3D_IVRP
+  if (m_pcSlice->getSPS()->getMultiviewResPredMode()==1 && iPdmDir[0] && !bNoPdmMerge && cCurPS == SIZE_2Nx2N && bDVAvail)
+  {
+    setResPredAvailSubParts(true, 0, 0, uiDepth);
+  }
+#endif
+
+  if( iPdmDir[0] && !bNoPdmMerge )
+  {
+    abCandIsInter        [ iCount ] = true;
+    puhInterDirNeighbours[ iCount ] = iPdmDir[0];
+    iPdmInterDir                    = iPdmDir[0];
+
+    if( ( iPdmInterDir & 1 ) == 1 )
+    {
+      pcMvFieldNeighbours[ iCount<<1    ].setMvField( acPdmMv[ 0 ], aiPdmRefIdx[ 0 ] );
+    }
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+    else
+    {
+      pcMvFieldNeighbours[ iCount<<1    ].setMvField( TComMv(0,0), NOT_VALID );
+    }
+#endif
+    if( ( iPdmInterDir & 2 ) == 2 )
+    {
+      pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( acPdmMv[ 1 ], aiPdmRefIdx[ 1 ] );
+    }
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+    else
+    {
+      pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( TComMv(0,0), NOT_VALID );
+    }
+#endif
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }  
+  
+#endif //  H3D_IVMP 
+
+#if MERL_VSP_COMPENSATION_C0152
+  //===== vsp 0 ===== 
+  if( iCount < 4 + extraMergeCand )
+    if ( !xAddVspMergeCand(0, 1, bVspMvZeroDone, uiDepth, abCandIsInter, iCount, puhInterDirNeighbours, pcMvFieldNeighbours, iVSPIndexTrue, mrgCandIdx, &cDisInfo) )
+      return;
+#endif
+
+  //left
+  UInt uiLeftPartIdx = 0;
+  TComDataCU* pcCULeft = 0;
+  pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB, true, false );
+  if (pcCULeft) 
+  {
+    if (!pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP))
+    {
+      pcCULeft = NULL;
+    }
+  }
+  PartSize partSize = getPartitionSize( uiAbsPartIdx );
+  if (!(uiPUIdx == 1 && (partSize == SIZE_Nx2N || partSize == SIZE_nLx2N || partSize == SIZE_nRx2N)))
+  {
+    if ( pcCULeft && !pcCULeft->isIntra( uiLeftPartIdx )
+#if MERL_VSP_C0152
+      CHECK_ADD_YET(pcCULeft, uiLeftPartIdx, 1)
+#endif
+      )
+    {
+      abCandIsInter[iCount] = true;
+      // get Inter Dir
+      puhInterDirNeighbours[iCount] = pcCULeft->getInterDir( uiLeftPartIdx );
+      // get Mv from Left
+      pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+      if ( getSlice()->isInterB() )
+      {
+        pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      }
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+      else
+      {
+        pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( TComMv(0,0), NOT_VALID );
+      }
+#endif
+
+#if H3D_IVMP
+      Bool bRemoveSpa = false; //pruning to inter-view candidates
+      Int  iCnloop    = iCount - 1;
+      for(; iCnloop >= 0; iCnloop --)
+      {
+        if(puhInterDirNeighbours[iCount] == puhInterDirNeighbours[iCnloop] && pcMvFieldNeighbours[iCnloop<<1]==pcMvFieldNeighbours[(iCount<<1)] && pcMvFieldNeighbours[(iCnloop<<1)+1]==pcMvFieldNeighbours[(iCount<<1)+1])
+        {
+          bRemoveSpa                      = true;
+          abCandIsInter        [ iCount ] = false;
+
+          //reset to the default value for IC, MC
+          puhInterDirNeighbours[iCount]   = 0;
+          TComMv  cZeroMv;
+          pcMvFieldNeighbours[iCount<<1].setMvField( cZeroMv, NOT_VALID );
+          pcMvFieldNeighbours[(iCount<<1)+1].setMvField( cZeroMv, NOT_VALID );
+          break;
+        }
+      }
+      if(!bRemoveSpa)
+      {
+        bLeftAvai = true;
+        iPosLeftAbove[0] = iCount;
+#endif  // H3D_IVMP 
+#if H3D_NBDV
+        pcMvFieldNeighbours[iCount<<1    ].getMv().m_bDvMcp = false;
+        pcMvFieldNeighbours[(iCount<<1)+1].getMv().m_bDvMcp = false;
+#endif
+#if MERL_VSP_C0152
+        xInheritVspMode( pcCULeft, uiLeftPartIdx, bVspMvZeroDone, iCount, iVSPIndexTrue, pcMvFieldNeighbours, &cDisInfo ) ;
+#endif
+        if ( mrgCandIdx == iCount )
+        {
+          return;
+        }
+        iCount ++;
+#if H3D_IVMP
+      }
+#endif 
+    }
+  }
+
+  // above
+  UInt uiAbovePartIdx = 0;
+  TComDataCU* pcCUAbove = 0;
+  pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT, true, false, true );
+    if (pcCUAbove) 
+    {
+      if (!pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP))
+      {
+        pcCUAbove = NULL;
+      }
+    }
+  if ( pcCUAbove && !pcCUAbove->isIntra( uiAbovePartIdx ) 
+#if MERL_VSP_C0152
+    CHECK_ADD_YET(pcCUAbove, uiAbovePartIdx, 1)
+#endif
+    && !(uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD))
+    && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAbove->getInterDir( uiAbovePartIdx );
+    // get Mv from Left
+    pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+    else
+    {
+      pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( TComMv(0,0), NOT_VALID );
+    }
+#endif
+#if H3D_IVMP
+    Bool bRemoveSpa = false; //pruning to inter-view candidates
+    Int  iCnloop    = bLeftAvai? (iCount-2): (iCount-1);
+    for(; iCnloop >= 0; iCnloop --)
+    {
+      if(puhInterDirNeighbours[iCount] == puhInterDirNeighbours[iCnloop] && pcMvFieldNeighbours[iCnloop<<1]==pcMvFieldNeighbours[(iCount<<1)] && pcMvFieldNeighbours[(iCnloop<<1)+1]==pcMvFieldNeighbours[(iCount<<1)+1])
+      {
+        bRemoveSpa                      = true;
+        abCandIsInter        [ iCount ] = false;
+
+        //reset to the default value for IC, MC
+        puhInterDirNeighbours[iCount]   = 0;
+        TComMv  cZeroMv;
+        pcMvFieldNeighbours[iCount<<1].setMvField( cZeroMv, NOT_VALID );
+        pcMvFieldNeighbours[(iCount<<1)+1].setMvField( cZeroMv, NOT_VALID );
+        break;
+      }
+    }
+    if(!bRemoveSpa)
+    {
+      iPosLeftAbove[1] = iCount;
+#endif //  H3D_IVMP 
+#if H3D_NBDV
+    pcMvFieldNeighbours[iCount<<1    ].getMv().m_bDvMcp = false;
+    pcMvFieldNeighbours[(iCount<<1)+1].getMv().m_bDvMcp = false;
+#endif
+#if MERL_VSP_C0152
+     xInheritVspMode( pcCUAbove, uiAbovePartIdx, bVspMvZeroDone, iCount, iVSPIndexTrue, pcMvFieldNeighbours, &cDisInfo ) ;
+#endif
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+#if H3D_IVMP
+    }
+#endif
+  }
+
+  // above right
+  UInt uiAboveRightPartIdx = 0;
+  TComDataCU* pcCUAboveRight = 0;
+  pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT, true, false, true );
+  if (pcCUAboveRight) 
+  {
+    if (!pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP))
+    {
+      pcCUAboveRight = NULL;
+    }
+  }
+  if ( pcCUAboveRight && !pcCUAboveRight->isIntra( uiAboveRightPartIdx ) 
+#if MERL_VSP_C0152
+    CHECK_ADD_YET(pcCUAboveRight, uiAboveRightPartIdx, 1)
+#endif
+    && ( !pcCUAbove || pcCUAbove->isIntra( uiAbovePartIdx ) || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAboveRight->getInterDir( uiAboveRightPartIdx );
+    // get Mv from Left
+    pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+    else
+    {
+      pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( TComMv(0,0), NOT_VALID );
+    }
+#endif
+#if H3D_NBDV
+    pcMvFieldNeighbours[iCount<<1    ].getMv().m_bDvMcp = false;
+    pcMvFieldNeighbours[(iCount<<1)+1].getMv().m_bDvMcp = false;
+#endif
+#if MERL_VSP_C0152
+    xInheritVspMode( pcCUAboveRight, uiAboveRightPartIdx, bVspMvZeroDone, iCount, iVSPIndexTrue, pcMvFieldNeighbours, &cDisInfo ) ;
+#endif
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+
+#if H3D_IVMP
+
+  if(extraMergeCand)
+  {
+    if(!bNoPdmMerge && iPdmDir[1] )
+    {
+      assert(iCount < MRG_MAX_NUM_CANDS_MEM);
+      Bool bRemoveSpa = false; //pruning to A1, B1
+      abCandIsInter        [ iCount ] = true;
+      puhInterDirNeighbours[ iCount ] = iPdmDir[1];
+      if( ( iPdmDir[1] & 1 ) == 1 )
+      {
+        pcMvFieldNeighbours[ iCount<<1    ].setMvField( acPdmMv[ 2 ], aiPdmRefIdx[ 2 ] );
+      }
+      if( ( iPdmDir[1] & 2 ) == 2 )
+      {
+        pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( acPdmMv[ 3 ], aiPdmRefIdx[ 3 ] );
+      }
+      for(Int i = 0; i < 2; i ++)
+      {
+        Int iCnloop = iPosLeftAbove[i];
+        if(iCnloop == -1) 
+          continue;
+        if(puhInterDirNeighbours[iCount] == puhInterDirNeighbours[iCnloop] && pcMvFieldNeighbours[iCnloop<<1]==pcMvFieldNeighbours[(iCount<<1)] && pcMvFieldNeighbours[(iCnloop<<1)+1]==pcMvFieldNeighbours[(iCount<<1)+1])
+        {
+          bRemoveSpa                      = true;
+          abCandIsInter        [ iCount ] = false;
+          //reset to the default value for IC, MC
+          puhInterDirNeighbours[iCount]   = 0;
+          TComMv  cZeroMv;
+          pcMvFieldNeighbours[iCount<<1].setMvField( cZeroMv, NOT_VALID );
+          pcMvFieldNeighbours[(iCount<<1)+1].setMvField( cZeroMv, NOT_VALID );
+          break;
+        }
+      }
+      if(!bRemoveSpa)
+      {
+#if H3D_NBDV
+        pcMvFieldNeighbours[iCount<<1    ].getMv().m_bDvMcp = false;
+        pcMvFieldNeighbours[(iCount<<1)+1].getMv().m_bDvMcp = false;
+#endif
+        if ( mrgCandIdx == iCount )
+          return;
+        iCount ++;
+      }
+    }    
+  }
+#endif // H3D_IVMP 
+
+
+  //left bottom
+  UInt uiLeftBottomPartIdx = 0;
+  TComDataCU* pcCULeftBottom = 0;
+  pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB, true, false );
+  if (pcCULeftBottom)
+  {
+    if (!pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP))
+    {
+      pcCULeftBottom = NULL;
+    }
+  }
+  if ( pcCULeftBottom && !pcCULeftBottom->isIntra( uiLeftBottomPartIdx ) 
+#if MERL_VSP_C0152
+    CHECK_ADD_YET(pcCULeftBottom, uiLeftBottomPartIdx, 1)
+#endif
+    && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeftBottom->getInterDir( uiLeftBottomPartIdx );
+    // get Mv from Left
+    pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+    else
+    {
+      pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( TComMv(0,0), NOT_VALID );
+    }
+#endif
+#if H3D_NBDV
+    pcMvFieldNeighbours[iCount<<1    ].getMv().m_bDvMcp = false;
+    pcMvFieldNeighbours[(iCount<<1)+1].getMv().m_bDvMcp = false;
+#endif
+#if MERL_VSP_C0152
+     xInheritVspMode( pcCULeftBottom, uiLeftBottomPartIdx, bVspMvZeroDone, iCount, iVSPIndexTrue, pcMvFieldNeighbours, &cDisInfo ) ;
+#endif
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+ 
+  
+  // above left
+#if H3D_IVMP
+  if( iCount < 4 + extraMergeCand )
+#else
+  if( iCount < 4 )
+#endif
+  {
+    UInt uiAboveLeftPartIdx = 0;
+    TComDataCU* pcCUAboveLeft = 0;
+    pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr, true, false, true );
+    if (pcCUAboveLeft) 
+    {
+      if (!pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP))
+      {
+        pcCUAboveLeft = NULL;
+      }
+    }
+    if( pcCUAboveLeft && !pcCUAboveLeft->isIntra( uiAboveLeftPartIdx )
+#if MERL_VSP_C0152
+     CHECK_ADD_YET(pcCUAboveLeft, uiAboveLeftPartIdx, 1)
+#endif
+     && ( !pcCULeft || pcCULeft->isIntra( uiLeftPartIdx ) || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+     && ( !pcCUAbove || pcCUAbove->isIntra( uiAbovePartIdx ) || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+     )
+    {
+      abCandIsInter[iCount] = true;
+      // get Inter Dir
+      puhInterDirNeighbours[iCount] = pcCUAboveLeft->getInterDir( uiAboveLeftPartIdx );
+      // get Mv from Left
+      pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+      if ( getSlice()->isInterB() )
+      {
+        pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      }
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+      else
+      {
+        pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( TComMv(0,0), NOT_VALID );
+      }
+#endif
+#if H3D_NBDV
+      pcMvFieldNeighbours[iCount<<1    ].getMv().m_bDvMcp = false;
+      pcMvFieldNeighbours[(iCount<<1)+1].getMv().m_bDvMcp = false;
+#endif
+#if MERL_VSP_C0152
+     xInheritVspMode( pcCUAboveLeft, uiAboveLeftPartIdx, bVspMvZeroDone, iCount, iVSPIndexTrue, pcMvFieldNeighbours, &cDisInfo ) ;
+#endif
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+
+#if MERL_VSP_COMPENSATION_C0152
+  //===== vsp 5 =====
+  if( iCount < 4 + extraMergeCand )
+    if ( !xAddVspMergeCand(5, 1, bVspMvZeroDone, uiDepth, abCandIsInter, iCount, puhInterDirNeighbours, pcMvFieldNeighbours, iVSPIndexTrue, mrgCandIdx, &cDisInfo) )
+      return;
+#endif
+
+  if ( getSlice()->getPPS()->getEnableTMVPFlag() 
+#if H3D_IVMP
+       && iCount < (MRG_MAX_NUM_CANDS_SIGNALED + extraMergeCand)
+#endif
+  )
+  {
+    // col [2]
+#if !QC_TMVP_IDX_MOD_B0046
+    Int iRefIdxSkip[2] = {-1, -1};
+    for (Int i=0; i<2; i++)
+    {
+      RefPicList  eRefPicList = ( i==1 ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+      Int iRefIdxTmp;
+      if ( uiPUIdx != 0 )
+      {
+        iRefIdxTmp = 0;
+      }
+      else
+      {    
+        iRefIdxTmp = (pcCULeft != NULL) ? pcCULeft->getCUMvField(eRefPicList)->getRefIdx(uiLeftPartIdx) : -1;
+      }
+      iRefIdxSkip[i] = (iRefIdxTmp != -1) ? iRefIdxTmp : 0;
+    }
+#endif
+    //>> MTK colocated-RightBottom
+    UInt uiPartIdxRB;
+    Int uiLCUIdx = getAddr();
+    PartSize eCUMode = getPartitionSize( 0 );
+
+#if MERL_VSP_C0152 // Potential bug, not related to BW_VSP
+    if (eCUMode==SIZE_NxN)
+    {
+      printf("Size NxN ???");
+      assert(0);
+    }
+#endif
+
+    deriveRightBottomIdx( eCUMode, uiPUIdx, uiPartIdxRB );  
+
+    UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+    UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+    TComMv cColMv;
+#if QC_TMVP_IDX_MOD_B0046
+    Int iRefIdx = 0;
+#else
+    Int iRefIdx;
+#endif
+    if      ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
+    {
+      uiLCUIdx = -1;
+    }
+    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+    {
+      uiLCUIdx = -1;
+    }
+    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() ];
+        uiLCUIdx = -1 ; 
+      }
+      else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+        uiLCUIdx = getAddr() + 1;
+      }
+      else //is the right bottom corner of LCU                       
+      {
+        uiAbsPartAddr = 0;
+        uiLCUIdx = -1 ; 
+      }
+    }
+#if !QC_TMVP_IDX_MOD_B0046
+    iRefIdx = iRefIdxSkip[0];
+#else
+    iRefIdx = 0;
+#endif
+    Bool bExistMV = false;
+    UInt uiPartIdxCenter;
+    UInt uiCurLCUIdx = getAddr();
+    xDeriveCenterIdx( eCUMode, uiPUIdx, uiPartIdxCenter );
+    bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_0, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx 
+#if QC_TMVP_MRG_REFIDX_C0047
+    , 1
+#endif
+    );
+    if( bExistMV == false )
+    {
+      bExistMV = xGetColMVP( REF_PIC_LIST_0, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx 
+#if QC_TMVP_MRG_REFIDX_C0047
+    , 1
+#endif
+    );
+    }
+    if( bExistMV )
+    {
+      UInt uiArrayAddr = iCount;
+      abCandIsInter[uiArrayAddr] = true;
+      pcMvFieldNeighbours[uiArrayAddr << 1].setMvField( cColMv, iRefIdx );
+
+      if ( getSlice()->isInterB() )
+      {       
+#if !QC_TMVP_IDX_MOD_B0046
+        iRefIdx = iRefIdxSkip[1];
+#else
+        iRefIdx = 0;
+#endif
+        bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_1, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx
+#if QC_TMVP_MRG_REFIDX_C0047
+        , 1
+#endif
+        );
+        if( bExistMV == false )
+        {
+          bExistMV = xGetColMVP( REF_PIC_LIST_1, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx 
+#if QC_TMVP_MRG_REFIDX_C0047
+        , 1
+#endif  
+        );
+        }
+        if( bExistMV )
+        {
+          pcMvFieldNeighbours[ ( uiArrayAddr << 1 ) + 1 ].setMvField( cColMv, iRefIdx );
+          puhInterDirNeighbours[uiArrayAddr] = 3;
+        }
+        else
+        {
+          puhInterDirNeighbours[uiArrayAddr] = 1;
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+          pcMvFieldNeighbours[ ( uiArrayAddr << 1 ) + 1 ].setMvField( TComMv(0,0), NOT_VALID );
+#endif
+        }
+      }
+      else
+      {
+        puhInterDirNeighbours[uiArrayAddr] = 1;
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+        pcMvFieldNeighbours[ ( uiArrayAddr << 1 ) + 1 ].setMvField( TComMv(0,0), NOT_VALID );
+#endif
+      }
+#if H3D_NBDV
+      pcMvFieldNeighbours[uiArrayAddr<<1    ].getMv().m_bDvMcp = false;
+      pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getMv().m_bDvMcp = false;
+#endif
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount++;
+    }
+    uiIdx++;
+
+  }
+
+  UInt uiArrayAddr = iCount;
+  UInt uiCutoff = uiArrayAddr;
+    
+  if ( getSlice()->isInterB() )
+  {
+#if H3D_IVMP
+    Int iCombinedCount = 0;
+    Int iMaxCombCount  = ( extraMergeCand ?  6 :  5 );
+    Int iMaxIdx        = ( extraMergeCand ? 20 : 12 );
+    UInt uiPriorityList0[20] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3,    0, 4, 1, 4, 2, 4, 3, 4 };
+    UInt uiPriorityList1[20] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2,    4, 0, 4, 1, 4, 2, 4, 3 };
+
+    for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!=MRG_MAX_NUM_CANDS_MEM && iCombinedCount<iMaxCombCount && idx < iMaxIdx; idx++)
+#else
+    Int iCombinedCount = 0;
+    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};
+
+    for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!=MRG_MAX_NUM_CANDS && iCombinedCount<5 && idx < 12; idx++)
+#endif
+    {
+      Int i = uiPriorityList0[idx]; Int j = uiPriorityList1[idx];
+#if MERL_VSP_C0152
+      Bool bValid = true;
+      if (pcMvFieldNeighbours[i<<1].getRefIdx() < 0 || pcMvFieldNeighbours[(j<<1)+1].getRefIdx() < 0) // NOT_VALID
+        bValid = false;
+#endif
+      if (abCandIsInter[i] && abCandIsInter[j]&& (puhInterDirNeighbours[i]&0x1)&&(puhInterDirNeighbours[j]&0x2)
+#if MERL_VSP_C0152
+       && bValid
+#endif
+         )
+      {
+        abCandIsInter[uiArrayAddr] = true;
+        puhInterDirNeighbours[uiArrayAddr] = 3;
+
+        // get Mv from cand[i] and cand[j]
+        pcMvFieldNeighbours[uiArrayAddr << 1].setMvField(pcMvFieldNeighbours[i<<1].getMv(), pcMvFieldNeighbours[i<<1].getRefIdx());
+        pcMvFieldNeighbours[( uiArrayAddr << 1 ) + 1].setMvField(pcMvFieldNeighbours[(j<<1)+1].getMv(), pcMvFieldNeighbours[(j<<1)+1].getRefIdx());
+
+        Int iRefPOCL0    = m_pcSlice->getRefPOC   ( REF_PIC_LIST_0, pcMvFieldNeighbours[(uiArrayAddr<<1)].getRefIdx() );
+        Int iRefViewIdL0 = m_pcSlice->getRefViewId( REF_PIC_LIST_0, pcMvFieldNeighbours[(uiArrayAddr<<1)].getRefIdx() );
+        Int iRefPOCL1    = m_pcSlice->getRefPOC   ( REF_PIC_LIST_1, pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getRefIdx() );
+        Int iRefViewIdL1 = m_pcSlice->getRefViewId( REF_PIC_LIST_1, pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getRefIdx() );
+        if(iRefPOCL0 == iRefPOCL1 && iRefViewIdL0 == iRefViewIdL1 && pcMvFieldNeighbours[(uiArrayAddr<<1)].getMv() == pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getMv())
+        {
+          abCandIsInter[uiArrayAddr] = false;
+        }
+        else
+        {
+          uiArrayAddr++;
+          iCombinedCount++;
+        }
+      }
+    }
+  }
+
+  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);
+#if H3D_IVMP
+  for (int r=0; r<iNumRefIdx && uiArrayAddr!=MRG_MAX_NUM_CANDS_MEM; r++)
+#else
+  for (int r=0; r<iNumRefIdx && uiArrayAddr!=MRG_MAX_NUM_CANDS; r++)
+#endif
+  {
+    abCandIsInter[uiArrayAddr] = true;
+    puhInterDirNeighbours[uiArrayAddr] = 1;
+    pcMvFieldNeighbours[uiArrayAddr << 1].setMvField( TComMv(0, 0), r);
+
+    if ( getSlice()->isInterB() )
+    {
+      puhInterDirNeighbours[uiArrayAddr] = 3;
+      pcMvFieldNeighbours[(uiArrayAddr << 1) + 1].setMvField(TComMv(0, 0), r);
+    }
+#if FIX_CU_BASED_MRG_CAND_LIST_B0136
+    else
+    {
+      pcMvFieldNeighbours[ ( uiArrayAddr << 1 ) + 1 ].setMvField( TComMv(0,0), NOT_VALID );
+    }
+#endif
+    uiArrayAddr++;
+  }
+#if H3D_IVMP
+  if (uiArrayAddr > MRG_MAX_NUM_CANDS_SIGNALED + extraMergeCand )
+  {
+    uiArrayAddr = MRG_MAX_NUM_CANDS_SIGNALED + extraMergeCand;
+  }
+#else
+  if (uiArrayAddr > MRG_MAX_NUM_CANDS_SIGNALED)
+  {
+    uiArrayAddr = MRG_MAX_NUM_CANDS_SIGNALED;
+  }
+#endif
+  numValidMergeCand = uiArrayAddr;
+}
+
+/** Check the duplicated candidate in the list
+ * \param pcMvFieldNeighbours
+ * \param puhInterDirNeighbours 
+ * \param pbCandIsInter
+ * \param ruiArrayAddr
+ * \returns Void
+ */
+Void TComDataCU::xCheckDuplicateCand(TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, bool* pbCandIsInter, UInt& ruiArrayAddr)
+{
+  if (getSlice()->isInterB())
+  {
+    UInt uiMvFieldNeighIdxCurr = ruiArrayAddr << 1;
+    Int iRefIdxL0 = pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getRefIdx();
+    Int iRefIdxL1 = pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr + 1 ].getRefIdx();
+    TComMv MvL0 = pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getMv();
+    TComMv MvL1 = pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr + 1 ].getMv();
+
+    for (int k=0; k<ruiArrayAddr; k++)
+    {
+      UInt uiMvFieldNeighIdxComp = k << 1;
+      if (iRefIdxL0 == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getRefIdx() && 
+          iRefIdxL1 == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp + 1 ].getRefIdx() &&
+          MvL0 == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getMv() && 
+          MvL1 == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp + 1 ].getMv() &&
+          puhInterDirNeighbours[ ruiArrayAddr ] == puhInterDirNeighbours[ k ] )
+      {
+        pbCandIsInter[ruiArrayAddr] = false;
+        break;
+      }
+    }
+  }
+  else
+  {
+    UInt uiMvFieldNeighIdxCurr = ruiArrayAddr << 1;
+    Int iRefIdxL0 = pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getRefIdx();
+    TComMv MvL0 = pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getMv();
+
+    for (int k=0; k<ruiArrayAddr; k++)
+    {
+      UInt uiMvFieldNeighIdxComp = k << 1;
+      if (iRefIdxL0 == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getRefIdx() && 
+          MvL0 == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getMv() && 
+          puhInterDirNeighbours[ ruiArrayAddr ] == puhInterDirNeighbours[ k ] )
+      {
+        pbCandIsInter[ruiArrayAddr] = false;
+        break;
+      }
+    }
+  }
+
+  if (pbCandIsInter[ruiArrayAddr])
+  {
+    ++ruiArrayAddr;
+  }
+}
+
+Void TComDataCU::xCheckCornerCand( TComDataCU* pcCorner, UInt uiCornerPUIdx, UInt uiIter, Bool& rbValidCand )
+{
+  if( uiIter == 0 )
+  {
+    if( pcCorner && !pcCorner->isIntra( uiCornerPUIdx ) 
+#if MERL_VSP_C0152
+     && !pcCorner->getVSPIndex( uiCornerPUIdx )
+#endif
+    )
+    {
+      rbValidCand = true;
+      if( getSlice()->isInterB() )
+      {
+        if ( pcCorner->getInterDir( uiCornerPUIdx ) == 1 )
+        {
+          if( pcCorner->getCUMvField(REF_PIC_LIST_0)->getRefIdx( uiCornerPUIdx ) != 0 )
+          {
+            rbValidCand = false;
+          }
+        }
+        else if ( pcCorner->getInterDir( uiCornerPUIdx ) == 2 )
+        {
+          if( pcCorner->getCUMvField(REF_PIC_LIST_1)->getRefIdx( uiCornerPUIdx ) != 0 )
+          {
+            rbValidCand = false;
+          }
+        }
+        else
+        {
+          if( pcCorner->getCUMvField(REF_PIC_LIST_0)->getRefIdx( uiCornerPUIdx ) != 0 || pcCorner->getCUMvField(REF_PIC_LIST_1)->getRefIdx( uiCornerPUIdx ) != 0 )
+          {
+            rbValidCand = false;
+          }
+        }
+      }
+      else if( pcCorner->getCUMvField(REF_PIC_LIST_0)->getRefIdx( uiCornerPUIdx ) != 0 )
+      {
+        rbValidCand = false;
+      }
+    }
+  }
+  else
+  {
+    if( pcCorner && !pcCorner->isIntra( uiCornerPUIdx ) 
+#if MERL_VSP_C0152
+     && !pcCorner->getVSPIndex( uiCornerPUIdx )
+#endif
+    )
+    {
+      rbValidCand = true;
+      if( getSlice()->isInterB() )
+      {
+        if ( pcCorner->getInterDir( uiCornerPUIdx ) == 1 )
+        {
+          if( pcCorner->getCUMvField(REF_PIC_LIST_0)->getRefIdx( uiCornerPUIdx ) < 0 )
+          {
+            rbValidCand = false;
+          }
+        }
+        else if ( pcCorner->getInterDir( uiCornerPUIdx ) == 2 )
+        {
+          if( pcCorner->getCUMvField(REF_PIC_LIST_1)->getRefIdx( uiCornerPUIdx ) < 0 )
+          {
+            rbValidCand = false;
+          }
+        }
+        else
+        {
+          if( pcCorner->getCUMvField(REF_PIC_LIST_0)->getRefIdx( uiCornerPUIdx ) < 0 || pcCorner->getCUMvField(REF_PIC_LIST_1)->getRefIdx( uiCornerPUIdx ) < 0 )
+          {
+            rbValidCand = false;
+          }
+        }
+      }
+      else if( pcCorner->getCUMvField(REF_PIC_LIST_0)->getRefIdx( uiCornerPUIdx ) < 0 )
+      {
+        rbValidCand = false;
+      }
+    }
+  }
+}
+/** 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 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)
+{
+
+  UInt plevel = this->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() + 2;
+  if ((xN>>plevel)!= (xP>>plevel))
+  {
+    return true;
+  }
+  if ((yN>>plevel)!= (yP>>plevel))
+  {
+    return true;
+  }
+  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
+ */
+Void TComDataCU::getPartPosition( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH)
+{
+  UInt col = m_uiCUPelX;
+  UInt row = m_uiCUPelY;
+
+  switch ( m_pePartSize[0] )
+  {
+  case SIZE_2NxN:
+    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);      
+    xP   = (partIdx ==0)? col: col + nPSW;
+    yP   = row;
+    break;
+  case SIZE_NxN:
+    nPSW = getWidth(0) >> 1; 
+    nPSH = getHeight(0) >> 1; 
+    xP   = col + (partIdx&0x1)*nPSW;
+    yP   = row + (partIdx>>1)*nPSH;
+    break;
+  case SIZE_2NxnU:
+    nPSW = getWidth(0);
+    nPSH = ( partIdx == 0 ) ?  getHeight(0) >> 2 : ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 );
+    xP   = col;
+    yP   = (partIdx ==0)? row: row + getHeight(0) - nPSH;
+
+    break;
+  case SIZE_2NxnD:
+    nPSW = getWidth(0);
+    nPSH = ( partIdx == 0 ) ?  ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 ) : getHeight(0) >> 2;
+    xP   = col;
+    yP   = (partIdx ==0)? row: row + getHeight(0) - nPSH;
+    break;
+  case SIZE_nLx2N:
+    nPSW = ( partIdx == 0 ) ? getWidth(0) >> 2 : ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 );
+    nPSH = getHeight(0);
+    xP   = (partIdx ==0)? col: col + getWidth(0) - nPSW;
+    yP   = row;
+    break;
+  case SIZE_nRx2N:
+    nPSW = ( partIdx == 0 ) ? ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 ) : getWidth(0) >> 2;
+    nPSH = getHeight(0);
+    xP   = (partIdx ==0)? col: col + getWidth(0) - nPSW;
+    yP   = row;
+    break;
+  default:
+    assert ( m_pePartSize[0] == SIZE_2Nx2N );
+    nPSW = getWidth(0);      
+    nPSH = getHeight(0);      
+    xP   = col ;
+    yP   = row ;
+
+    break;
+  }
+}
+
+AMVP_MODE TComDataCU::getAMVPMode(UInt uiIdx)
+{
+  return m_pcSlice->getSPS()->getAMVPMode(m_puhDepth[uiIdx]);
+}
+#if H3D_NBDV
+/** construct a list of disparity motion vectors from the neighbouring PUs **/
+Void TComDataCU::getDisMvpCand ( UInt uiPartIdx, UInt uiPartAddr,DisInfo* pDInfo )
+{
+  PartSize eCUMode = getPartitionSize( uiPartAddr );
+  TComDataCU* pcTmpCU = NULL;
+  pDInfo->iN = 0;
+
+  RefPicList eRefPicList = REF_PIC_LIST_0 ;
+  //-- Get Spatial MV
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+  deriveLeftRightTopIdxGeneral( eCUMode, uiPartAddr, uiPartIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral( eCUMode, uiPartAddr, uiPartIdx, uiPartIdxLB );
+
+  UInt uiIdx = 0;
+    pcTmpCU = getPULeft(uiIdx, uiPartIdxLB, true, false);
+  if(pcTmpCU != NULL && !pcTmpCU->isIntra( uiIdx ) )
+#if MERL_VSP_C0152
+  if(! pcTmpCU->getVSPIndex(uiIdx))
+#endif
+  {
+    for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+    {
+      eRefPicList = RefPicList(iList);
+      Int refId = pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ;
+      if( refId >= 0)
+      {
+        Int refViewIdx  = pcTmpCU->getSlice()->getRefViewId( eRefPicList, refId);
+        if (refViewIdx!= m_pcSlice->getViewId())
+        {
+           TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+           clipMv(cMvPred);
+           pDInfo->m_acMvCand[ pDInfo->iN] = cMvPred; 
+           pDInfo->m_aVIdxCan[ pDInfo->iN++] = refViewIdx;
+           return;
+        }
+      }
+    }
+  }
+      pcTmpCU = getPUAbove(uiIdx, uiPartIdxRT, true, false, true);
+
+  if(pcTmpCU != NULL && !pcTmpCU->isIntra( uiIdx ))
+#if MERL_VSP_C0152
+  if(! pcTmpCU->getVSPIndex(uiIdx))
+#endif
+  {
+    for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+    {
+      eRefPicList = RefPicList(iList);
+      Int refId = pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ;
+      if( refId >= 0)
+      {
+        Int refViewIdx  = pcTmpCU->getSlice()->getRefViewId( eRefPicList, refId);
+        if (refViewIdx!= m_pcSlice->getViewId())
+        {
+           TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+           clipMv(cMvPred);
+           pDInfo->m_acMvCand[ pDInfo->iN] = cMvPred; 
+           pDInfo->m_aVIdxCan[ pDInfo->iN++] = refViewIdx;
+           return;
+        }
+      }
+    }
+  }
+
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartIdxRT, true, false, true);
+  if(pcTmpCU != NULL && !pcTmpCU->isIntra( uiIdx ) )
+#if MERL_VSP_C0152
+  if(! pcTmpCU->getVSPIndex(uiIdx))
+#endif
+  {
+    for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+    {
+      eRefPicList = RefPicList(iList);
+      Int refId = pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ;
+      if( refId >= 0)
+      {
+        Int refViewIdx  = pcTmpCU->getSlice()->getRefViewId( eRefPicList, refId);
+        if (refViewIdx!= m_pcSlice->getViewId())
+        {
+           TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+           clipMv(cMvPred);
+           pDInfo->m_acMvCand[ pDInfo->iN] = cMvPred; 
+           pDInfo->m_aVIdxCan[ pDInfo->iN++] = refViewIdx;
+           return;
+        }
+      }
+    }
+  }
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartIdxLB, true, false);
+  if(pcTmpCU != NULL && !pcTmpCU->isIntra( uiIdx ))
+#if MERL_VSP_C0152
+  if(! pcTmpCU->getVSPIndex(uiIdx))
+#endif
+  {
+    for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+    {
+      eRefPicList = RefPicList(iList);
+      Int refId = pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ;
+      if( refId >= 0)
+      {
+        Int refViewIdx  = pcTmpCU->getSlice()->getRefViewId( eRefPicList, refId);
+        if (refViewIdx!= m_pcSlice->getViewId())
+        {
+           TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+           clipMv(cMvPred);
+           pDInfo->m_acMvCand[ pDInfo->iN] = cMvPred; 
+           pDInfo->m_aVIdxCan[ pDInfo->iN++] = refViewIdx;
+           return;
+        }
+      }
+    }
+  }
+
+  // Above predictor search
+      pcTmpCU = getPUAboveLeft(uiIdx, (m_uiAbsIdxInLCU + uiPartAddr), true, false, true);
+    assert(uiPartIdxLT == (m_uiAbsIdxInLCU + uiPartAddr));
+  if(pcTmpCU != NULL && !pcTmpCU->isIntra( uiIdx ))
+#if MERL_VSP_C0152
+  if(! pcTmpCU->getVSPIndex(uiIdx))
+#endif
+  {
+    for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+    {
+      eRefPicList = RefPicList(iList);
+      Int refId = pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ;
+      if( refId >= 0)
+      {
+        Int refViewIdx  = pcTmpCU->getSlice()->getRefViewId( eRefPicList, refId);
+        if (refViewIdx!= m_pcSlice->getViewId())
+        {
+           TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+           clipMv(cMvPred);
+           pDInfo->m_acMvCand[ pDInfo->iN] = cMvPred; 
+           pDInfo->m_aVIdxCan[ pDInfo->iN++] = refViewIdx;
+           return;
+        }
+      }
+    }
+  }
+  //Get temporal MV
+  TComMv cColMv;
+  Int iTargetViewIdx = 0;
+  Int iTStartViewIdx = 0;
+  UInt uiPartIdxRB, uiBRIdx;
+  Int uiViewIdxCurr= getSlice()->getViewId();
+
+  UInt uiAbsPartAddr;
+  int uiLCUIdx = getAddr();
+  Int uiLCUnew = uiLCUIdx;
+  eCUMode = getPartitionSize( 0 );
+  deriveRightBottomIdx( eCUMode, uiPartIdx, uiPartIdxRB );  
+  uiBRIdx = uiPartIdxLT;
+  UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+  if ( (( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) < m_pcSlice->getSPS()->getPicWidthInLumaSamples() ) &&(( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getSPS()->getPicHeightInLumaSamples() ))  // image boundary check
+  {
+    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
+    {
+      uiBRIdx = g_auiRasterToZscan[ uiAbsPartIdxTmp + uiNumPartInCUWidth + 1 ];
+    }
+    else if ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+    {
+      uiBRIdx = g_auiRasterToZscan[ (uiAbsPartIdxTmp + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
+      uiLCUnew = uiLCUIdx + m_pcPic->getFrameWidthInCU();
+    }
+    else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+    {
+      uiBRIdx = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+      uiLCUnew = uiLCUIdx + 1;
+    }
+    else //is the right bottom corner of LCU                       
+    {
+      uiBRIdx = 0;
+      uiLCUnew = uiLCUIdx + m_pcPic->getFrameWidthInCU() + 1;
+    }
+  }
+
+  Int MaxRef = getSlice()->getNumRefIdx(RefPicList(0));
+  UInt uiNumPartInCUHeight = m_pcPic->getNumPartInHeight();
+  UInt uiPUVert = (UInt)((Int)g_auiZscanToRaster[uiPartIdxLB]/(Int)(uiNumPartInCUWidth)-(Int)g_auiZscanToRaster[uiPartIdxLT]/(Int)(uiNumPartInCUWidth));
+  UInt uiPUHorStart  = g_auiZscanToRaster[uiPartIdxLT];
+  UInt uiPUHorEnd    = g_auiZscanToRaster[uiPartIdxRT];
+  for( Int i= 0; i< getSlice()->getNumRefIdx(RefPicList(0)); i ++)
+  {
+    getSlice()->getRefPic( RefPicList(0), i)->setCandPicCheckedFlag(0);
+  }
+  for( Int i= 0; i< getSlice()->getNumRefIdx(RefPicList(1)); i ++)
+  {
+    getSlice()->getRefPic( RefPicList(1), i)->setCandPicCheckedFlag(0);
+  }
+  {
+    //check the col-located picture
+    eRefPicList = RefPicList(getSlice()->isInterB() ? getSlice()->getColDir() : 0);
+#if COLLOCATED_REF_IDX
+    Int lpRef = getSlice()->getColRefIdx();
+#else
+    Int lpRef = 0;
+#endif
+    if( m_pcSlice->getViewId() == getSlice()->getRefPic( eRefPicList, lpRef)->getViewId() ) 
+    {
+      if (uiViewIdxCurr > 1)  
+      {
+        if( (uiLCUnew >= 0 && xGetColDisMV( eRefPicList, lpRef, uiLCUnew, uiBRIdx, cColMv, iTargetViewIdx, iTStartViewIdx)) )
+        {
+          clipMv(cColMv);
+          pDInfo->m_acMvCand[pDInfo->iN] = cColMv;
+          pDInfo->m_aVIdxCan[pDInfo->iN++] = iTargetViewIdx;
+          return ;
+        }
+      }
+      for(UInt uiLoopVert = 0; uiLoopVert <= uiPUVert; uiLoopVert+=4)
+        for( uiIdx = uiPUHorStart; uiIdx <= uiPUHorEnd; uiIdx +=4 )
+        {
+          uiAbsPartAddr = g_auiRasterToZscan[uiIdx+uiNumPartInCUWidth*uiLoopVert];
+          if ( uiLCUIdx >= 0 && xGetColDisMV( eRefPicList, lpRef, uiLCUIdx, uiAbsPartAddr, cColMv, iTargetViewIdx, iTStartViewIdx ) ) 
+          {
+            clipMv(cColMv);
+            pDInfo->m_acMvCand[pDInfo->iN] = cColMv;
+            pDInfo->m_aVIdxCan[pDInfo->iN++] = iTargetViewIdx;
+            return ;
+          }
+        }
+        for(UInt uiIdx_y = 0; uiIdx_y <uiNumPartInCUHeight; uiIdx_y +=4 )
+          for(UInt uiIdx_X = 0; uiIdx_X <uiNumPartInCUWidth; uiIdx_X +=4 )
+          {
+            uiIdx = uiIdx_X + uiIdx_y * uiNumPartInCUWidth;
+            uiAbsPartAddr = g_auiRasterToZscan[uiIdx];
+            if ( uiLCUIdx >= 0 && xGetColDisMV( eRefPicList,  lpRef, uiLCUIdx, uiAbsPartAddr, cColMv, iTargetViewIdx, iTStartViewIdx ) ) 
+            {
+              clipMv(cColMv);
+              pDInfo->m_acMvCand[pDInfo->iN] = cColMv;
+              pDInfo->m_aVIdxCan[pDInfo->iN++] = iTargetViewIdx;
+              return ;
+            }
+          }
+          if (uiViewIdxCurr == 1)  
+          {
+            if( (uiLCUnew >= 0 && xGetColDisMV( eRefPicList, lpRef, uiLCUnew, uiBRIdx, cColMv, iTargetViewIdx, iTStartViewIdx)) ) 
+            {
+              clipMv(cColMv);
+              pDInfo->m_acMvCand[pDInfo->iN] = cColMv;
+              pDInfo->m_aVIdxCan[pDInfo->iN++] = iTargetViewIdx;
+              return ;
+            }
+          }
+    }
+    getSlice()->getRefPic( eRefPicList, lpRef)->setCandPicCheckedFlag(1);
+  }
+  {
+    //check the remaining reference pictures in list0 and list1
+    if(getSlice()->isInterB())
+    {
+      if(getSlice()->getNumRefIdx(RefPicList(0))< getSlice()->getNumRefIdx(RefPicList(1)))
+        MaxRef = getSlice()->getNumRefIdx(RefPicList(1));
+    }
+    for(Int lpRef = 0; lpRef < MaxRef; lpRef++)
+    {
+      for(Int lpNr = 0; lpNr < (getSlice()->isInterB() ? 2: 1); lpNr ++)
+      {
+        eRefPicList = RefPicList(0);
+        if(getSlice()->isInterB())
+          eRefPicList = RefPicList(lpNr==0 ? (getSlice()->getColDir()): (1-getSlice()->getColDir()));
+        if(getSlice()->getRefPic( eRefPicList, lpRef)->getCandPicCheckedFlag())
+          continue;
+        
+        if(lpRef >= getSlice()->getNumRefIdx(eRefPicList)||(m_pcSlice->getViewId() != getSlice()->getRefPic( eRefPicList, lpRef)->getViewId()))
+          continue;
+        if (uiViewIdxCurr > 1 ) 
+        {
+          if( (uiLCUnew >= 0 && xGetColDisMV( eRefPicList, lpRef, uiLCUnew, uiBRIdx, cColMv, iTargetViewIdx, iTStartViewIdx)) )
+          {
+          clipMv(cColMv);
+          pDInfo->m_acMvCand[pDInfo->iN] = cColMv;
+          pDInfo->m_aVIdxCan[pDInfo->iN++] = iTargetViewIdx;
+          return ;
+          }
+        }
+        for(UInt uiLoopVert = 0; uiLoopVert <= uiPUVert; uiLoopVert += 4)
+          for( uiIdx = uiPUHorStart; uiIdx <= uiPUHorEnd; uiIdx += 4 )
+          {
+            uiAbsPartAddr = g_auiRasterToZscan[uiIdx+uiNumPartInCUWidth*uiLoopVert];
+            if ( uiLCUIdx >= 0 && xGetColDisMV( eRefPicList, lpRef, uiLCUIdx, uiAbsPartAddr, cColMv, iTargetViewIdx, iTStartViewIdx ) ) 
+            {
+              clipMv(cColMv);
+              pDInfo->m_acMvCand[pDInfo->iN] = cColMv;
+              pDInfo->m_aVIdxCan[pDInfo->iN++] = iTargetViewIdx;
+              return ;
+            }
+          }
+        for(UInt uiIdx_y = 0; uiIdx_y <uiNumPartInCUHeight; uiIdx_y += 4 )
+          for(UInt uiIdx_X = 0; uiIdx_X <uiNumPartInCUWidth; uiIdx_X += 4 )
+          {
+            uiIdx = uiIdx_X + uiIdx_y * uiNumPartInCUWidth;
+            uiAbsPartAddr = g_auiRasterToZscan[uiIdx];
+            if ( uiLCUIdx >= 0 && xGetColDisMV( eRefPicList,  lpRef, uiLCUIdx, uiAbsPartAddr, cColMv, iTargetViewIdx, iTStartViewIdx ) ) 
+            {
+              clipMv(cColMv);
+              pDInfo->m_acMvCand[pDInfo->iN] = cColMv;
+              pDInfo->m_aVIdxCan[pDInfo->iN++] = iTargetViewIdx;
+              return ;
+            }
+          }
+        if (uiViewIdxCurr == 1 ) 
+        {
+          if( (uiLCUnew >= 0 && xGetColDisMV( eRefPicList, lpRef, uiLCUnew, uiBRIdx, cColMv, iTargetViewIdx, iTStartViewIdx)) )
+          {
+            clipMv(cColMv);
+            pDInfo->m_acMvCand[pDInfo->iN] = cColMv;
+            pDInfo->m_aVIdxCan[pDInfo->iN++] = iTargetViewIdx;
+            return ;
+          }
+        }
+        getSlice()->getRefPic( eRefPicList, lpRef)->setCandPicCheckedFlag(1);
+      }//reference lists
+    }//reference indices
+  }//remaining pictures
+}
+
+#if MERL_VSP_C0152
+Pel TComDataCU::getMcpFromDM(TComPicYuv* pcBaseViewDepthPicYuv, TComMv* mv, Int iBlkX, Int iBlkY, Int iBlkWidth, Int iBlkHeight, Int* aiShiftLUT, Int iShiftPrec, Bool bSimpleDvpRefine)
+{
+  Int depStride =  pcBaseViewDepthPicYuv->getStride();
+
+  Int iPictureWidth  = pcBaseViewDepthPicYuv->getWidth();
+  Int iPictureHeight = pcBaseViewDepthPicYuv->getHeight();
+
+  Int depthPosX = Clip3(0,   iPictureWidth - iBlkWidth,  iBlkX + (mv->getHor()>>2));
+  Int depthPosY = Clip3(0,   iPictureHeight- iBlkHeight,  iBlkY + (mv->getVer()>>2));
+
+  Pel *pDepthPel   = pcBaseViewDepthPicYuv->getLumaAddr() + depthPosX + depthPosY * depStride;
+  Pel  maxDepthVal = 0;
+
+  if ( bSimpleDvpRefine )
+  {
+    Int depthStartPosX = Clip3(0,   iPictureWidth - iBlkWidth,  iBlkX + (mv->getHor()>>2));
+    Int depthStartPosY = Clip3(0,   iPictureHeight- iBlkHeight,  iBlkY + (mv->getVer()>>2));
+    Int depthEndPosX   = Clip3(0,   iPictureWidth - 1,  iBlkX + iBlkWidth - 1 + (mv->getHor()>>2));
+    Int depthEndPosY   = Clip3(0,   iPictureHeight - 1,  iBlkY + iBlkHeight - 1 + (mv->getVer()>>2));
+    Int iCenterX = (depthStartPosX + depthEndPosX) >> 1;
+    Int iCenterY = (depthStartPosY + depthEndPosY) >> 1;
+
+    Pel *depthTL  = pcBaseViewDepthPicYuv->getLumaAddr();
+    Int aiDepth[5];
+    aiDepth[0] = depthTL[ (depthStartPosY) * depStride + depthStartPosX ];      // Left Top
+    aiDepth[1] = depthTL[ (depthEndPosY)   * depStride + depthStartPosX ];      // Left Bottom
+    aiDepth[2] = depthTL[ (depthStartPosY) * depStride + depthEndPosX   ];      // Right Top
+    aiDepth[3] = depthTL[ (depthEndPosY)   * depStride + depthEndPosX   ];      // Right Bottom
+    aiDepth[4] = depthTL[ (iCenterY)       * depStride + iCenterX       ];      // Center
+    for (Int i = 0; i < 5; i++)
+    {
+      if (maxDepthVal < aiDepth[i])
+        maxDepthVal = aiDepth[i];
+    }
+  }
+  else
+  {
+    for (Int j = 0; j < iBlkHeight; j++)
+    {
+      for (Int i = 0; i < iBlkWidth; i++)
+      {
+        if (maxDepthVal < pDepthPel[i])
+          maxDepthVal = pDepthPel[i];
+  }
+      pDepthPel += depStride;
+    }
+  }
+
+  Int iDisp = aiShiftLUT[ maxDepthVal ] << iShiftPrec;
+
+  return iDisp;
+}
+Void TComDataCU::estimateDVFromDM(UInt uiPartIdx, TComPic* picDepth, UInt uiPartAddr, TComMv* cMvPred, Bool bSimpleDvpRefine)
+{
+  if (picDepth)
+  {
+    UInt uiAbsPartAddrCurrCU = m_uiAbsIdxInLCU + uiPartAddr;
+    Int iWidth, iHeight;
+    getPartIndexAndSize( uiPartIdx, uiPartAddr, iWidth, iHeight ); // The modified value of uiPartAddr won't be used any more
+    
+    TComPicYuv* pcBaseViewDepthPicYuv = picDepth->getPicYuvRec();
+    Int iBlkX = ( getAddr() % picDepth->getFrameWidthInCU() ) * g_uiMaxCUWidth  + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartAddrCurrCU ] ];
+    Int iBlkY = ( getAddr() / picDepth->getFrameWidthInCU() ) * g_uiMaxCUHeight + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartAddrCurrCU ] ];
+    Int* aiShiftLUT;
+    Int  iShiftPrec;
+
+    getSlice()->getBWVSPLUTParam(aiShiftLUT, iShiftPrec);
+
+    Pel iDisp = getMcpFromDM( pcBaseViewDepthPicYuv, cMvPred, iBlkX, iBlkY, iWidth, iHeight, aiShiftLUT, iShiftPrec, bSimpleDvpRefine );
+    cMvPred->setHor( iDisp );
+    clipMv(*cMvPred);
+  }
+}
+#endif
+
+#if H3D_NBDV
+
+Bool TComDataCU::xCheckSpatialNBDV( TComDataCU* pcTmpCU, UInt uiIdx, UInt uiPartIdx, UInt uiPartAddr, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, McpDisInfo* paMvpDvInfo, UInt uiMvpDvPos, Bool bDepthRefine )
+{
+  if( pcTmpCU != NULL && !pcTmpCU->isIntra( uiIdx ) )
+  {
+    Bool bTmpIsSkipped = pcTmpCU->isSkipped( uiIdx );
+    for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+    {
+      RefPicList eRefPicList = RefPicList(iList);
+      Int      refId = pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ;
+      TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+
+      if( refId >= 0)
+      {
+        Int refViewIdx  = pcTmpCU->getSlice()->getRefViewId( eRefPicList, refId );
+        if (refViewIdx != m_pcSlice->getViewId()) // DCP
+        {          
+          clipMv(cMvPred);
+
+          TComPic* picDepth = getSlice()->getRefPicBaseDepth();
+
+          if (picDepth && bDepthRefine)
+            estimateDVFromDM(uiPartIdx, picDepth, uiPartAddr, &cMvPred, true);
+
+          pNbDvInfo->m_acMvCand[ pNbDvInfo->iN   ] = cMvPred;
+          pNbDvInfo->m_aVIdxCan[ pNbDvInfo->iN++ ] = refViewIdx;
+
+          return true;
+        }
+        else if ( bSearchForMvpDv && cMvPred.m_bDvMcp && bTmpIsSkipped )
+        {
+          assert( uiMvpDvPos < MCP_DIS_CANS );
+          paMvpDvInfo->m_acMvCand[iList][ uiMvpDvPos ] = TComMv( cMvPred.m_iDvMcpDispX, cMvPred.m_iDvMcpDispY );
+          paMvpDvInfo->m_aVIdxCan[iList][ uiMvpDvPos ] = 0; // works only for CTC
+          paMvpDvInfo->m_bAvailab[iList][ uiMvpDvPos ] = true;
+          paMvpDvInfo->m_bFound                        = true; 
+        }
+      }
+#if MERL_VSP_C0152
+      else if (pcTmpCU->getVSPIndex(uiIdx) != 0) // is VSP
+      { 
+        TComPic* picDepth = pcTmpCU->getSlice()->getRefPicBaseDepth();
+        if (picDepth && bDepthRefine)
+          estimateDVFromDM(uiPartIdx, picDepth, uiPartAddr, &cMvPred);
+
+        cMvPred.setVer(0);
+
+        pNbDvInfo->m_acMvCand[ pNbDvInfo->iN]   = cMvPred;
+        pNbDvInfo->m_aVIdxCan[ pNbDvInfo->iN++] = 0; // refViewIdx;
+        return true;
+      }
+#endif
+    }
+  }
+  return false; 
+}
+
+
+Void TComDataCU::xDeriveRightBottomNbIdx( PartSize eCUMode, UInt uiPartIdx, Int &riLCUIdxRBNb, Int &riPartIdxRBNb )
+{
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();  
+  Int uiLCUIdx = getAddr();
+
+  UInt uiPartIdxRB;
+  deriveRightBottomIdx( eCUMode, uiPartIdx, uiPartIdxRB );  
+  UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+
+  if (( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() )>= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+  {
+    riLCUIdxRBNb  = -1;
+    riPartIdxRBNb = -1;
+  }
+  else if(( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() )>= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+  {
+    riLCUIdxRBNb  = -1;
+    riPartIdxRBNb = -1;
+  }
+  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
+    {
+      riPartIdxRBNb = g_auiRasterToZscan[ uiAbsPartIdxTmp + uiNumPartInCUWidth + 1 ];
+      riLCUIdxRBNb  = uiLCUIdx; 
+    }
+    else if ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+    {
+      riPartIdxRBNb = -1;
+      riLCUIdxRBNb  = -1;
+    }
+    else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+    {
+      riPartIdxRBNb = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+      riLCUIdxRBNb = uiLCUIdx + 1;
+    }
+    else //is the right bottom corner of LCU                       
+    {
+      riPartIdxRBNb = -1;
+      riLCUIdxRBNb  = -1;
+    }
+  }
+}
+
+
+Void TComDataCU::getDisMvpCandNBDV( UInt uiPartIdx, UInt uiPartAddr, DisInfo* pDInfo , Bool bParMerge
+#if MERL_VSP_C0152
+                                , Bool bDepthRefine
+#endif
+                                )
+{
+  //// ******* Init variables ******* /////
+  // Init disparity struct for results
+  pDInfo->iN = 0;    
+
+  // Init struct for disparities from MCP neighboring blocks
+  McpDisInfo cMvpDvInfo;
+  cMvpDvInfo.m_bFound = false; 
+  for (UInt iCurDvMcpCand = 0; iCurDvMcpCand < MCP_DIS_CANS; iCurDvMcpCand++)
+  {
+    for (UInt iList = 0; iList < 2; iList++)
+    {
+      cMvpDvInfo.m_acMvCand[iList][iCurDvMcpCand].setZero();
+      cMvpDvInfo.m_aVIdxCan[iList][iCurDvMcpCand] = 0; 
+      cMvpDvInfo.m_bAvailab[iList][iCurDvMcpCand] = false; 
+    }
+  }
+
+  // Get Positions  
+  PartSize eCUMode    = getPartitionSize( uiPartAddr );    
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;  
+
+  deriveLeftRightTopIdxGeneral( eCUMode, uiPartAddr, uiPartIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral  ( eCUMode, uiPartAddr, uiPartIdx, uiPartIdxLB );
+
+  // Get parameters for parallel merge
+  Int xP, yP, nPSW, nPSH;
+  if( bParMerge)
+    this->getPartPosition(uiPartIdx, xP, yP, nPSW, nPSH);
+
+  //// ******* Get disparity from temporal neighboring blocks ******* /////
+  if ( getSlice()->getPPS()->getEnableTMVPFlag() )
+  {
+    TComMv cColMv;
+    Int iTargetViewIdx = 0;
+    Int iTStartViewIdx = 0;    
+
+    ///*** Derive center position ***
+    UInt uiPartIdxCenter;
+    Int  uiLCUIdx   = getAddr();
+
+    xDeriveCenterIdx( eCUMode, uiPartIdx, uiPartIdxCenter );
+
+    ///*** Derive bottom right neighbour position ***
+    eCUMode          = getPartitionSize( 0 ); // Necessary?    
+    Int iLCUIdxRBNb  = -1;    
+    Int iPartIdxRBNb = -1;
+
+    xDeriveRightBottomNbIdx( eCUMode, uiPartIdx, iLCUIdxRBNb, iPartIdxRBNb );
+
+    ///*** Search temporal candidate pictures for disparity vector ***
+    const Int iNumCandPics = 2;
+    for(Int curCandPic = 0; curCandPic < iNumCandPics; curCandPic++)
+    {
+      // Get candidate picture
+      RefPicList eCurRefPicList   = REF_PIC_LIST_0 ;
+      Int        curCandPicRefIdx = 0;
+
+      if( curCandPic == 0 ) // check the co-located picture
+      { 
+        eCurRefPicList   = RefPicList(getSlice()->isInterB() ? getSlice()->getColDir() : 0);
+        curCandPicRefIdx = getSlice()->getColRefIdx();
+      }
+      else                  // check RAP
+      {
+        if( !(getPic()->getRapbCheck()) )
+          break;
+
+        eCurRefPicList   = getPic()->getRapRefList();
+        curCandPicRefIdx = getPic()->getRapRefIdx();
+      }
+
+      // Check BR and Center       
+      if( m_pcSlice->getViewId() == getSlice()->getRefPic( eCurRefPicList, curCandPicRefIdx)->getViewId() ) 
+      {
+        for(Int curPosition = 0; curPosition < 2; curPosition++) 
+        {
+          Bool bCheck = false; 
+          if ( curPosition == 0 && iLCUIdxRBNb >= 0 )
+            bCheck = xGetColDisMV( eCurRefPicList, curCandPicRefIdx, iLCUIdxRBNb, iPartIdxRBNb,  cColMv, iTargetViewIdx, iTStartViewIdx);
+
+          if (curPosition == 1 )
+            bCheck = xGetColDisMV( eCurRefPicList, curCandPicRefIdx, uiLCUIdx,   uiPartIdxCenter,  cColMv, iTargetViewIdx, iTStartViewIdx );
+
+          if( bCheck )
+          {
+            clipMv(cColMv);
+            TComPic* picDepth = getSlice()->getRefPicBaseDepth();
+            if (picDepth && bDepthRefine)
+              estimateDVFromDM(uiPartIdx, picDepth, uiPartAddr, &cColMv, true);
+
+            pDInfo->m_acMvCand[ pDInfo->iN] = cColMv;
+            pDInfo->m_aVIdxCan[ pDInfo->iN++] = iTargetViewIdx;
+            return ;
+          }
+        } // Loop positions
+      }
+    } // Loop candidate views
+  } // if TMVP Flag
+
+  UInt uiIdx = 0;
+  Bool        bCheckMcpDv = false;   
+  TComDataCU* pcTmpCU     = NULL;
+
+
+  //// ******* Get disparity from left block ******* /////
+  pcTmpCU = getPULeft(uiIdx, uiPartIdxLB, true, false);
+  if ( uiPartIdx == 1 && (eCUMode == SIZE_Nx2N || eCUMode == SIZE_nLx2N || eCUMode == SIZE_nRx2N) )
+  {
+    pcTmpCU = NULL;
+  }
+
+  if (pcTmpCU && bParMerge) 
+  {
+    if (!pcTmpCU->isDiffMER(xP -1, yP+nPSH-1, xP, yP))
+    {
+      pcTmpCU = NULL;
+    }
+  }
+
+  bCheckMcpDv = true; 
+  if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, uiPartIdx, uiPartAddr, pDInfo, bCheckMcpDv, &cMvpDvInfo, DVFROM_LEFT, bDepthRefine ) )
+    return;
+
+
+  //// ******* Get disparity from above block ******* /////
+  pcTmpCU = getPUAbove(uiIdx, uiPartIdxRT, true, false, true);
+  if ( uiPartIdx == 1 && (eCUMode == SIZE_2NxN || eCUMode == SIZE_2NxnU || eCUMode == SIZE_2NxnD) )
+  {
+    pcTmpCU = NULL;
+  }
+
+  if (pcTmpCU && bParMerge) 
+  {
+    if (!pcTmpCU->isDiffMER(xP+nPSW-1, yP-1, xP, yP))
+    {
+      pcTmpCU = NULL;
+    }
+  }
+
+  if(pcTmpCU != NULL )
+  {
+    bCheckMcpDv = ( ( getAddr() - pcTmpCU->getAddr() ) == 0);
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, uiPartIdx, uiPartAddr, pDInfo, bCheckMcpDv, &cMvpDvInfo, DVFROM_ABOVE, bDepthRefine ) )
+      return;
+  }
+
+  //// ******* Get disparity from above right block ******* /////
+  pcTmpCU = getPUAboveRight(uiIdx, uiPartIdxRT, true, false, true);
+
+  if (pcTmpCU && bParMerge) 
+  {
+    if (!pcTmpCU->isDiffMER(xP+nPSW, yP-1, xP, yP))
+    {
+      pcTmpCU = NULL;
+    }
+  }
+
+  if(pcTmpCU != NULL )
+  {
+    bCheckMcpDv = ( ( getAddr() - pcTmpCU->getAddr() ) == 0);
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, uiPartIdx, uiPartAddr, pDInfo, bCheckMcpDv, &cMvpDvInfo, DVFROM_ABOVERIGHT, bDepthRefine ) )
+      return;
+  }
+
+
+  //// ******* Get disparity from below left block ******* /////
+  pcTmpCU = getPUBelowLeft(uiIdx, uiPartIdxLB, true, false);
+
+  if (pcTmpCU && bParMerge)
+  {
+    if (!pcTmpCU->isDiffMER(xP-1, yP+nPSH, xP, yP))
+    {
+      pcTmpCU = NULL;
+    }
+  }
+
+  if( pcTmpCU != NULL )
+  {
+    bCheckMcpDv = true; 
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, uiPartIdx, uiPartAddr, pDInfo, bCheckMcpDv, &cMvpDvInfo, DVFROM_LEFTBELOW, bDepthRefine ) )
+      return;
+  }
+
+
+  //// ******* Get disparity from above left block ******* /////
+  pcTmpCU = getPUAboveLeft(uiIdx, (m_uiAbsIdxInLCU + uiPartAddr), true, false, true);
+  assert(uiPartIdxLT == (m_uiAbsIdxInLCU + uiPartAddr));
+
+  if (pcTmpCU && bParMerge) 
+  {
+    if (!pcTmpCU->isDiffMER(xP-1, yP-1, xP, yP))
+    {
+      pcTmpCU = NULL;
+    }
+  }
+
+  if( pcTmpCU != NULL )
+  {
+    bCheckMcpDv = (( getAddr() - pcTmpCU->getAddr() ) <= 1); 
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, uiPartIdx, uiPartAddr, pDInfo, bCheckMcpDv, &cMvpDvInfo, DVFROM_ABOVELEFT, bDepthRefine ) )
+      return;
+  }
+
+  //// ******* Search MCP blocks ******* /////
+  if( cMvpDvInfo.m_bFound ) 
+  {
+    for( Int curPos = 0 ; curPos < MCP_DIS_CANS ; curPos++ ) 
+    {
+      for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+      {
+        if( cMvpDvInfo.m_bAvailab[iList][curPos] )
+        {
+          TComMv cDispVec = cMvpDvInfo.m_acMvCand[iList][ curPos ];
+          clipMv( cDispVec );
+
+          TComPic* picDepth = getSlice()->getRefPicBaseDepth();
+          if (picDepth && bDepthRefine)
+            estimateDVFromDM(uiPartIdx, picDepth, uiPartAddr, &cDispVec, true);
+
+          pDInfo->m_acMvCand[ pDInfo->iN]   = cDispVec;
+          pDInfo->m_aVIdxCan[ pDInfo->iN++] = 0;
+          return;
+        }
+      }
+    }
+  }
+  return;
+}
+#endif
+
+#endif
+
+/** Constructs a list of candidates for AMVP
+ * \param uiPartIdx
+ * \param uiPartAddr 
+ * \param eRefPicList
+ * \param iRefIdx
+ * \param pInfo
+ */
+#if H3D_IVMP
+Void TComDataCU::fillMvpCand ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo, Int iMVPIdx)
+{
+  if (!m_pcSlice->getSPS()->getViewId() || !m_pcSlice->getSPS()->getMultiviewMvPredMode())
+  {
+    // HEVC
+    fillMvpCandBase(uiPartIdx, uiPartAddr, eRefPicList, iRefIdx, pInfo);
+  }
+  else
+  {
+    if (iMVPIdx!=0)
+    {
+      // HEVC part
+      fillMvpCandBase(uiPartIdx, uiPartAddr, eRefPicList, iRefIdx, pInfo);
+      if (iRefIdx < 0)
+      {
+        return;
+      }
+      for (Int j = AMVP_MAX_NUM_CANDS - 1; j >= 0; j--)
+      {
+        pInfo->m_acMvCand[j+1] = pInfo->m_acMvCand[j];
+      }
+      pInfo->iN++;
+    }
+    if (iMVPIdx<=0)
+    {
+#if H3D_NBDV
+      // Extension part
+      DisInfo cDisInfo;
+      cDisInfo.iN = 0;
+#if FCO_DVP_REFINE_C0132_C0170
+      if( !getPic()->getDepthCoded() )
+#endif
+      getDisMvpCandNBDV(uiPartIdx, uiPartAddr, &cDisInfo, false
+#if MERL_VSP_C0152
+            , true
+#endif
+              ); 
+
+#if FCO_DVP_REFINE_C0132_C0170
+      if(getPic()->getDepthCoded() )
+      {
+        TComPic*      pcCodedDepthMap = getPic()->getRecDepthMap();
+        TComMv        cColMv;
+
+        cColMv.setZero();
+        estimateDVFromDM(uiPartIdx, pcCodedDepthMap, uiPartAddr, &cColMv, false);
+
+        cDisInfo.iN = 1;
+        cDisInfo.m_acMvCand[0].setHor( cColMv.getHor() );
+        cDisInfo.m_acMvCand[0].setVer( cColMv.getVer() );
+        cDisInfo.m_aVIdxCan[0] = 0;
+      }
+#endif
+      if(cDisInfo.iN==0)
+      {
+        cDisInfo.iN = 1;
+        cDisInfo.m_acMvCand[0].setHor(0);
+        cDisInfo.m_acMvCand[0].setVer(0);
+        cDisInfo.m_aVIdxCan[0] = 0;
+      }
+      Int paiPdmRefIdx[4] = {-1, -1, -1, -1};
+      Int iPdmDir[4]      = {-1, -1, -1, -1};
+      TComMv cPdmMvPred[4];
+      cPdmMvPred[0].m_bDvMcp = cPdmMvPred[1].m_bDvMcp = false; 
+      if(getUnifiedMvPredCan(uiPartIdx, eRefPicList, iRefIdx, paiPdmRefIdx, cPdmMvPred, &cDisInfo, iPdmDir, false))
+#else // H3D_NBDV
+      if( getPdmMvPred( uiPartIdx, eRefPicList, iRefIdx, cPdmMvPred ) )
+#endif
+
+      {
+        clipMv( cPdmMvPred[0] );
+        pInfo->m_acMvCand[0] = cPdmMvPred[0];
+      }
+      else
+      {
+        pInfo->m_acMvCand[0].set(0,0);
+      }
+    }
+  }
+}
+
+
+Void TComDataCU::fillMvpCandBase( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo )
+#else //  H3D_IVMP  
+Void TComDataCU::fillMvpCand ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo )
+#endif //  H3D_IVMP 
+{
+  PartSize eCUMode = getPartitionSize( 0 );
+  
+  TComMv cMvPred;
+  Bool bAddedSmvp = false;
+
+  pInfo->iN = 0;  
+  if (iRefIdx < 0)
+  {
+    return;
+  }
+
+  //-- Get Spatial MV
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  Bool bAdded = false;
+  
+  deriveLeftRightTopIdx( eCUMode, uiPartIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdx( eCUMode, uiPartIdx, uiPartIdxLB );
+  
+  TComDataCU* tmpCU = NULL;
+  UInt idx;
+  tmpCU = getPUBelowLeft(idx, uiPartIdxLB, true, false);
+  bAddedSmvp = (tmpCU != NULL) && (tmpCU->getPredictionMode(idx) != MODE_INTRA);
+
+  if (!bAddedSmvp)
+  {
+    tmpCU = getPULeft(idx, uiPartIdxLB, true, false);
+    bAddedSmvp = (tmpCU != NULL) && (tmpCU->getPredictionMode(idx) != MODE_INTRA);
+  }
+
+  // Left predictor search
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+  if (!bAdded) 
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+  }
+  
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+    if (!bAdded) 
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+    }
+  }
+
+  // Above predictor search
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+
+  if (!bAdded) 
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+  }
+
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+  }
+  bAdded = bAddedSmvp;
+  if (pInfo->iN==2) bAdded = true;
+
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+    if (!bAdded) 
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+    }
+
+    if(!bAdded)
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+    }
+  }
+  
+  if (getAMVPMode(uiPartAddr) == AM_NONE)  //Should be optimized later for special cases
+  {
+    assert(pInfo->iN > 0);
+    pInfo->iN = 1;
+    return;
+  }
+
+
+  if ( pInfo->iN == 2 )
+  {
+    if ( pInfo->m_acMvCand[ 0 ] == pInfo->m_acMvCand[ 1 ] )
+    {
+      pInfo->iN = 1;
+#if QC_MRG_CANS_B0048
+      pInfo->m_acMvCand[ 1 ].set(0, 0);
+#endif
+    }
+  }
+
+  if ( getSlice()->getPPS()->getEnableTMVPFlag() )
+  {
+    // Get Temporal Motion Predictor
+    int iRefIdx_Col = iRefIdx;
+    TComMv cColMv;
+    UInt uiPartIdxRB;
+    UInt uiAbsPartIdx;  
+    UInt uiAbsPartAddr;
+    int uiLCUIdx = getAddr();
+
+    deriveRightBottomIdx( eCUMode, uiPartIdx, uiPartIdxRB );
+    uiAbsPartAddr = m_uiAbsIdxInLCU + uiPartAddr;
+
+    //----  co-located RightBottom Temporal Predictor (H) ---//
+    uiAbsPartIdx = g_auiZscanToRaster[uiPartIdxRB];
+    if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
+    {
+      uiLCUIdx = -1;
+    }
+    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+    {
+      uiLCUIdx = -1;
+    }
+    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() ];
+        uiLCUIdx      = -1 ; 
+      }
+      else if ( uiAbsPartIdx / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + 1 ];
+        uiLCUIdx = getAddr() + 1;
+      }
+      else //is the right bottom corner of LCU                       
+      {
+        uiAbsPartAddr = 0;
+        uiLCUIdx      = -1 ; 
+      }
+    }
+    if ( uiLCUIdx >= 0 && xGetColMVP( eRefPicList, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx_Col ) )
+    {
+#if H3D_NBDV
+      cColMv.m_bDvMcp = false;
+#endif
+      pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+    }
+    else 
+    {
+      UInt uiPartIdxCenter;
+      UInt uiCurLCUIdx = getAddr();
+      xDeriveCenterIdx( eCUMode, uiPartIdx, uiPartIdxCenter );
+      if (xGetColMVP( eRefPicList, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx_Col ))
+      {
+#if H3D_NBDV
+        cColMv.m_bDvMcp = false;
+#endif
+        pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+      }
+    }
+    //----  co-located RightBottom Temporal Predictor  ---//
+  }
+
+
+  if (pInfo->iN > AMVP_MAX_NUM_CANDS)
+  {
+    pInfo->iN = AMVP_MAX_NUM_CANDS;
+  }
+  else if (pInfo->iN < AMVP_MAX_NUM_CANDS)
+  {
+      pInfo->m_acMvCand[pInfo->iN].set(0,0);
+      pInfo->iN++;
+  }
+  return ;
+}
+
+Void TComDataCU::clipMv    (TComMv&  rcMv)
+{
+  Int  iMvShift = 2;
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( getSlice()->getIsDepth() )
+    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;
+  
+  rcMv.setHor( min (iHorMax, max (iHorMin, rcMv.getHor())) );
+  rcMv.setVer( min (iVerMax, max (iVerMin, rcMv.getVer())) );
+}
+
+
+Void TComDataCU::convertTransIdx( UInt uiAbsPartIdx, UInt uiTrIdx, UInt& ruiLumaTrMode, UInt& ruiChromaTrMode )
+{
+  ruiLumaTrMode   = uiTrIdx;
+  ruiChromaTrMode = uiTrIdx;
+  return;
+}
+
+UInt TComDataCU::getIntraSizeIdx(UInt uiAbsPartIdx)
+{
+  UInt uiShift = ( (m_puhTrIdx[uiAbsPartIdx]==0) && (m_pePartSize[uiAbsPartIdx]==SIZE_NxN) ) ? m_puhTrIdx[uiAbsPartIdx]+1 : m_puhTrIdx[uiAbsPartIdx];
+  uiShift = ( m_pePartSize[uiAbsPartIdx]==SIZE_NxN ? 1 : 0 );
+  
+  UChar uiWidth = m_puhWidth[uiAbsPartIdx]>>uiShift;
+  UInt  uiCnt = 0;
+  while( uiWidth )
+  {
+    uiCnt++;
+    uiWidth>>=1;
+  }
+  uiCnt-=2;
+  return uiCnt > 6 ? 6 : uiCnt;
+}
+
+Void TComDataCU::clearCbf( UInt uiIdx, TextType eType, UInt uiNumParts )
+{
+  ::memset( &m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx], 0, sizeof(UChar)*uiNumParts);
+}
+
+/** Set a I_PCM flag for all sub-partitions of a partition.
+ * \param bIpcmFlag I_PCM flag
+ * \param uiAbsPartIdx patition index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TComDataCU::setIPCMFlagSubParts  (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (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
+ */
+Bool TComDataCU::isSkipped( UInt uiPartIdx )
+{
+  if ( m_pcSlice->isIntra () )
+  {
+    return false;
+  }
+  return ( m_pePredMode[ uiPartIdx ] == MODE_SKIP && getMergeFlag( uiPartIdx ) && !getQtRootCbf( uiPartIdx ) );
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Bool TComDataCU::xAddMVPCand( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir )
+{
+  TComDataCU* pcTmpCU = NULL;
+  UInt uiIdx;
+  switch( eDir )
+  {
+    case MD_LEFT:
+    {
+      pcTmpCU = getPULeft(uiIdx, uiPartUnitIdx, true, false);
+      break;
+    }
+    case MD_ABOVE:
+    {
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+    case MD_ABOVE_RIGHT:
+    {
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+    case MD_BELOW_LEFT:
+    {
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx, true, false);
+      break;
+    }
+    case MD_ABOVE_LEFT:
+    {
+      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+    default:
+    {
+      break;
+    }
+  }
+ 
+#if MERL_VSP_C0152
+  if(pcTmpCU != NULL && pcTmpCU->getVSPIndex(uiIdx))
+  {
+    return false;
+  }
+#endif
+
+  if ( pcTmpCU != NULL && m_pcSlice->isEqualRef(eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx), iRefIdx) )
+  {
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+#if H3D_NBDV
+    cMvPred.m_bDvMcp = false;
+#endif 
+    pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
+    return true;
+  }
+
+  if ( pcTmpCU == NULL ) 
+  {
+    return false;
+  }
+  
+  RefPicList eRefPicList2nd = REF_PIC_LIST_0;
+  if(       eRefPicList == REF_PIC_LIST_0 )
+  {
+    eRefPicList2nd = REF_PIC_LIST_1;
+  }
+  else if ( eRefPicList == REF_PIC_LIST_1)
+  {
+    eRefPicList2nd = REF_PIC_LIST_0;
+  }
+
+
+  Int iCurrRefPOC = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
+  Int iNeibRefPOC;
+
+
+  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0 )
+  {
+#if QC_IV_AS_LT_B0046
+    Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getIsLongTerm();
+    Bool bIsNeibRefLongTerm = m_pcSlice->getRefPic( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx))->getIsLongTerm();
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
+    if ( (bIsCurrRefLongTerm == bIsNeibRefLongTerm) && (iNeibRefPOC == iCurrRefPOC) )
+#else
+    if( pcTmpCU->getSlice()->getRefViewId( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) ) != m_pcSlice->getRefViewId( eRefPicList, iRefIdx ) )
+    {
+      return false;
+    }
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
+    if( iNeibRefPOC == iCurrRefPOC ) // Same Reference Frame But Diff List//
+#endif
+    {
+      TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
+#if H3D_NBDV
+      cMvPred.m_bDvMcp = false;
+#endif
+      pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
+      return true;
+    }
+  }
+  return false;
+}
+
+
+/** 
+ * \param pInfo
+ * \param eRefPicList 
+ * \param iRefIdx
+ * \param uiPartUnitIdx
+ * \param eDir
+ * \returns Bool
+ */
+Bool TComDataCU::xAddMVPCandOrder( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir )
+{
+  TComDataCU* pcTmpCU = NULL;
+  UInt uiIdx;
+
+  switch( eDir )
+  {
+  case MD_LEFT:
+    {
+      pcTmpCU = getPULeft(uiIdx, uiPartUnitIdx, true, false);
+      break;
+    }
+  case MD_ABOVE:
+    {
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+  case MD_ABOVE_RIGHT:
+    {
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+  case MD_BELOW_LEFT:
+    {
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx, true, false);
+      break;
+    }
+  case MD_ABOVE_LEFT:
+    {
+      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx, true, false, true);
+      break;
+    }
+  default:
+    {
+      break;
+    }
+  }
+
+  if ( pcTmpCU == NULL ) 
+  {
+    return false;
+  }
+
+#if MERL_VSP_C0152
+  if(pcTmpCU->getVSPIndex(uiIdx))
+  {
+    return false;
+  }
+#endif
+  RefPicList eRefPicList2nd = REF_PIC_LIST_0;
+  if(       eRefPicList == REF_PIC_LIST_0 )
+  {
+    eRefPicList2nd = REF_PIC_LIST_1;
+  }
+  else if ( eRefPicList == REF_PIC_LIST_1)
+  {
+    eRefPicList2nd = REF_PIC_LIST_0;
+  }
+
+  Int iCurrPOC = m_pcSlice->getPOC();
+  Int iCurrRefPOC = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
+  Int iNeibPOC = iCurrPOC;
+  Int iNeibRefPOC;
+#if INTER_VIEW_VECTOR_SCALING_C0116
+  Int iCurrViewId = m_pcSlice->getViewOrderIdx(); // will be changed to view_id
+  Int iCurrRefViewId = m_pcSlice->getRefPic(eRefPicList, iRefIdx)->getViewOrderIdx(); // will be changed to view_id
+  Int iNeibViewId = iCurrViewId;
+  Int iNeibRefViewId;
+#endif
+#if QC_IV_AS_LT_B0046
+  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getIsLongTerm();
+  Bool bIsNeibRefLongTerm = false;
+#endif
+  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0 )
+  {
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
+#if INTER_VIEW_VECTOR_SCALING_C0116
+    iNeibRefViewId = pcTmpCU->getSlice()->getRefPic(eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx))->getViewOrderIdx(); // will be changed to view_id
+#endif
+#if QC_IV_AS_LT_B0046
+    bIsNeibRefLongTerm = m_pcSlice->getRefPic( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx))->getIsLongTerm() ;
+#if INTER_VIEW_VECTOR_SCALING_C0116
+    if ( (bIsCurrRefLongTerm == bIsNeibRefLongTerm) && ((iNeibRefPOC == iCurrRefPOC) && (iNeibRefViewId == iCurrRefViewId)))
+#else
+    if ( (bIsCurrRefLongTerm == bIsNeibRefLongTerm) && (iNeibRefPOC == iCurrRefPOC) )
+#endif
+#else
+    if( pcTmpCU->getSlice()->getRefViewId( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) ) != m_pcSlice->getRefViewId( eRefPicList, iRefIdx ) )
+      return false;
+    if( iNeibRefPOC == iCurrRefPOC ) // Same Reference Frame But Diff List//
+#endif
+    {
+      TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
+#if H3D_NBDV
+      cMvPred.m_bDvMcp = false;
+#endif
+      clipMv(cMvPred);
+      pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
+      return true;
+    }
+  }
+
+  //---------------  V1 (END) ------------------//
+  if( pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) >= 0)
+  {
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) );
+#if INTER_VIEW_VECTOR_SCALING_C0116
+    iNeibRefViewId = pcTmpCU->getSlice()->getRefPic(eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx))->getViewOrderIdx(); // will be changed to view_id
+#endif
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+    TComMv rcMv;
+#if QC_IV_AS_LT_B0046
+    bIsNeibRefLongTerm = m_pcSlice->getRefPic( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx))->getIsLongTerm(); 
+    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm )
+    {
+#else
+    if( pcTmpCU->getSlice()->getRefViewId( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ) != m_pcSlice->getRefViewId( eRefPicList, iRefIdx ) )
+    {
+      return false;
+    }
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0116
+    Int iScale = 4096;
+    if((iCurrRefPOC != iNeibRefPOC)  )    // inter & inter
+        iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+    else if(m_pcSlice->getIVScalingFlag())    // inter-view & inter-view
+        iScale = xGetDistScaleFactor( iCurrViewId, iCurrRefViewId, iNeibViewId, iNeibRefViewId );
+#else
+    Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+#endif
+    if ( iScale == 4096 )
+    {
+      rcMv = cMvPred;
+    }
+    else
+    {
+      rcMv = cMvPred.scaleMv( iScale );
+    }
+#if H3D_NBDV
+    rcMv.m_bDvMcp = false;
+#endif
+    pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
+    return true;
+#if QC_IV_AS_LT_B0046
+    }
+#endif
+  }
+  //---------------------- V2(END) --------------------//
+  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0)
+  {
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
+#if INTER_VIEW_VECTOR_SCALING_C0116
+    iNeibRefViewId = pcTmpCU->getSlice()->getRefPic(eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx))->getViewOrderIdx(); // will be changed to view_id
+#endif
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
+    TComMv rcMv;
+#if QC_IV_AS_LT_B0046
+    bIsNeibRefLongTerm = m_pcSlice->getRefPic( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx))->getIsLongTerm(); ;
+    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm )
+    {
+#else
+    if( pcTmpCU->getSlice()->getRefViewId( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) ) != m_pcSlice->getRefViewId( eRefPicList, iRefIdx ) )
+    {
+      return false;
+    }
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0116
+    Int iScale = 4096;
+    if((iCurrRefPOC != iNeibRefPOC))    // inter & inter
+        iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+    else if(m_pcSlice->getIVScalingFlag())    // inter-view & inter-view
+        iScale = xGetDistScaleFactor( iCurrViewId, iCurrRefViewId, iNeibViewId, iNeibRefViewId );
+#else
+    Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+#endif
+    if ( iScale == 4096 )
+    {
+      rcMv = cMvPred;
+    }
+    else
+    {
+      rcMv = cMvPred.scaleMv( iScale );
+    }
+#if H3D_NBDV
+    rcMv.m_bDvMcp = false;
+#endif
+    pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
+    return true;
+#if QC_IV_AS_LT_B0046
+  }
+#endif
+  }
+  //---------------------- V3(END) --------------------//
+  return false;
+}
+
+#if H3D_NBDV
+Bool TComDataCU::xGetColDisMV( RefPicList eRefPicList, Int refidx, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv , Int & iTargetViewIdx, Int & iStartViewIdx )
+{
+  UInt uiAbsPartAddr = uiPartUnitIdx;
+
+  RefPicList  eColRefPicList = REF_PIC_LIST_0;
+  Int iColViewIdx, iColRefViewIdx;
+  TComPic *pColPic = getSlice()->getRefPic( eRefPicList, refidx);
+  TComDataCU *pColCU = pColPic->getCU( uiCUAddr );
+  iColViewIdx = pColCU->getSlice()->getViewId();
+#if MERL_VSP_C0152
+  if( pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiAbsPartAddr) < 0)
+  {
+    return false;
+  }
+#endif
+
+  if (pColCU->getPic()==0||pColCU->getPartitionSize(uiPartUnitIdx)==SIZE_NONE||pColCU->isIntra(uiAbsPartAddr))
+  {
+    return false;
+  }
+  for (Int ilist = 0; ilist < (pColCU->getSlice()->isInterB()? 2:1); ilist++) 
+  {
+    if(pColCU->getSlice()->isInterB())
+    {
+        eColRefPicList = RefPicList(ilist);
+    }
+
+    Int iColRefIdx = pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiAbsPartAddr);
+
+    if (iColRefIdx < 0)
+    {
+      continue;
+    }
+
+    iColRefViewIdx = pColCU->getSlice()->getRefPic(eColRefPicList, iColRefIdx)->getViewId();
+
+    if ( iColViewIdx    == iColRefViewIdx ) // temporal vector
+    {
+      continue;
+    }
+    else 
+    {
+      rcMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+      rcMv.m_bDvMcp = false;
+      iTargetViewIdx  = iColRefViewIdx ;
+      iStartViewIdx   = iColViewIdx   ;
+      return true;    
+    }
+  }
+
+  return false;
+}
+#endif 
+/** 
+ * \param eRefPicList
+ * \param uiCUAddr 
+ * \param uiPartUnitIdx
+ * \param riRefIdx
+ * \returns Bool
+ */
+Bool TComDataCU::xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx 
+#if QC_TMVP_MRG_REFIDX_C0047
+  ,
+  Bool bMRG
+#endif
+)
+{
+  UInt uiAbsPartAddr = uiPartUnitIdx;
+
+  RefPicList  eColRefPicList;
+  Int iColPOC, iColRefPOC, iCurrPOC, iCurrRefPOC, iScale;
+  TComMv cColMv;
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Int iColViewId, iColRefViewId, iCurrViewId, iCurrRefViewId;
+#endif
+
+  // use coldir.
+#if COLLOCATED_REF_IDX
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? getSlice()->getColDir() : 0), getSlice()->getColRefIdx());
+#else
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? getSlice()->getColDir() : 0), 0);
+#endif
+  TComDataCU *pColCU = pColPic->getCU( uiCUAddr );
+  if(pColCU->getPic()==0||pColCU->getPartitionSize(uiPartUnitIdx)==SIZE_NONE)
+  {
+    return false;
+  }
+  iCurrPOC = m_pcSlice->getPOC();    
+  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+  iColPOC = pColCU->getSlice()->getPOC();  
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  iCurrViewId = m_pcSlice->getViewOrderIdx(); // will be changed to view_id    
+  iCurrRefViewId = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getViewOrderIdx(); // will be changed to view_id
+  iColViewId = pColCU->getSlice()->getViewOrderIdx(); // will be changed to view_id
+#endif
+
+  if (pColCU->isIntra(uiAbsPartAddr))
+  {
+    return false;
+  }
+
+#if !INTER_VIEW_VECTOR_SCALING_C0115&!QC_IV_AS_LT_B0046
+  if( m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getViewId() != m_pcSlice->getViewId() )
+    return false;
+#endif
+
+  if ( !pColPic->getUsedForTMVP() )
+  {
+    return false;
+  }
+
+  eColRefPicList = getSlice()->getCheckLDC() ? eRefPicList : RefPicList(1-getSlice()->getColDir());
+
+  Int iColRefIdx = pColCU->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+
+  if (iColRefIdx < 0 )
+  {
+    eColRefPicList = RefPicList(1 - eColRefPicList);
+    iColRefIdx = pColCU->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+
+    if (iColRefIdx < 0 )
+    {
+      return false;
+    }
+  }
+
+  // Scale the vector.
+  iColRefPOC = pColCU->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  iColRefViewId = pColCU->getSlice()->getRefPic( eColRefPicList, pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiAbsPartAddr))->getViewOrderIdx(); // will be changed to view_id 
+#endif
+#if !QC_IV_AS_LT_B0046
+  if( pColCU->getSlice()->getRefViewId( eColRefPicList, iColRefIdx ) != pColCU->getSlice()->getViewId() )
+  {
+    return false;
+  }
+#else
+  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
+  Bool bIsColRefLongTerm = pColCU->getSlice()->getWasLongTerm(eColRefPicList, iColRefIdx); 
+  if(bIsCurrRefLongTerm != bIsColRefLongTerm) 
+  {
+#if QC_TMVP_MRG_REFIDX_C0047
+    cColMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+    iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+    if(bMRG )
+    {
+      Int iUpdRefIdx  = m_pcSlice->getNewRefIdx(eRefPicList);
+      if(iUpdRefIdx > 0 )
+      {
+        riRefIdx = iUpdRefIdx;
+        bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
+        iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+#if INTER_VIEW_VECTOR_SCALING_C0115
+        iCurrRefViewId = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getViewOrderIdx(); // will be changed to view_id
+#endif
+      }
+      else
+        return false;
+    }else
+    {
+#endif
+    assert( ((iColPOC == iColRefPOC)&&(iCurrPOC != iCurrRefPOC))||((iColPOC != iColRefPOC)&&(iCurrPOC == iCurrRefPOC)));
+    return false;
+#if QC_TMVP_MRG_REFIDX_C0047
+    }
+#endif
+  }
+#endif
+  cColMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+
+  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+#if QC_IV_AS_LT_B0046
+  {
+    assert( ((iColPOC != iColRefPOC)&&(iCurrPOC != iCurrRefPOC))||((iColPOC == iColRefPOC)&&(iCurrPOC == iCurrRefPOC)));
+    if(!bIsCurrRefLongTerm)  //short-term
+    {
+      iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
+      if ( iScale == 4096 )
+      {
+        rcMv = cColMv;
+      }
+      else
+      {
+        rcMv = cColMv.scaleMv( iScale );
+      }
+    }else
+#if INTER_VIEW_VECTOR_SCALING_C0115
+    {
+        if((iCurrPOC == iCurrRefPOC) && m_pcSlice->getIVScalingFlag())    // inter-view & inter-view
+            iScale = xGetDistScaleFactor( iCurrViewId, iCurrRefViewId, iColViewId, iColRefViewId );
+        else
+            iScale = 4096;            // inter & inter
+      if ( iScale == 4096 )
+      {
+        rcMv = cColMv;
+      }
+      else
+      {
+        rcMv = cColMv.scaleMv( iScale );
+      }
+  }
+#else
+    rcMv = cColMv; //inter-view
+#endif
+  }
+#endif
+
+  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)
+{
+  Int iDiffPocD = iColPOC - iColRefPOC;
+  Int iDiffPocB = iCurrPOC - iCurrRefPOC;
+  
+  if( iDiffPocD == iDiffPocB )
+  {
+    return 4096;
+  }
+  else
+  {
+    Int iTDB      = Clip3( -128, 127, iDiffPocB );
+    Int iTDD      = Clip3( -128, 127, iDiffPocD );
+    Int iX        = (0x4000 + abs(iTDD/2)) / iTDD;
+    Int iScale    = Clip3( -4096, 4095, (iTDB * iX + 32) >> 6 );
+    return iScale;
+  }
+}
+
+/** 
+ * \param eCUMode
+ * \param uiPartIdx 
+ * \param ruiPartIdxCenter
+ * \returns Void
+ */
+Void TComDataCU::xDeriveCenterIdx( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxCenter )
+{
+  UInt uiPartAddr;
+  Int  iPartWidth;
+  Int  iPartHeight;
+  getPartIndexAndSize( uiPartIdx, uiPartAddr, iPartWidth, iPartHeight);
+  
+  ruiPartIdxCenter = m_uiAbsIdxInLCU+uiPartAddr; // partition origin.
+  ruiPartIdxCenter = g_auiRasterToZscan[ g_auiZscanToRaster[ ruiPartIdxCenter ]
+                                        + ( iPartHeight/m_pcPic->getMinCUHeight()  )/2*m_pcPic->getNumPartInWidth()
+                                        + ( iPartWidth/m_pcPic->getMinCUWidth()  )/2];
+}
+
+/** 
+ * \param uiPartIdx
+ * \param eRefPicList 
+ * \param iRefIdx
+ * \param pcMv
+ * \returns Bool
+ */
+Bool TComDataCU::xGetCenterCol( UInt uiPartIdx, RefPicList eRefPicList, int iRefIdx, TComMv *pcMv )
+{
+  PartSize eCUMode = getPartitionSize( 0 );
+  
+  Int iCurrPOC = m_pcSlice->getPOC();
+  
+  // use coldir.
+#if COLLOCATED_REF_IDX
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? getSlice()->getColDir() : 0), getSlice()->getColRefIdx());
+#else
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? getSlice()->getColDir() : 0), 0);
+#endif
+  TComDataCU *pColCU = pColPic->getCU( m_uiCUAddr );
+  
+  Int iColPOC = pColCU->getSlice()->getPOC();
+  UInt uiPartIdxCenter;
+  xDeriveCenterIdx( eCUMode, uiPartIdx, uiPartIdxCenter );
+  
+  if (pColCU->isIntra(uiPartIdxCenter))
+  {
+    return false;
+  }
+
+  if( m_pcSlice->getRefPic( eRefPicList, iRefIdx )->getViewId() != m_pcSlice->getViewId() )
+  {
+    return false;
+  }
+
+  // Prefer a vector crossing us.  Prefer shortest.
+  RefPicList eColRefPicList = REF_PIC_LIST_0;
+  bool bFirstCrosses = false;
+  Int  iFirstColDist = -1;
+  for (Int l = 0; l < 2; l++)
+  {
+    bool bSaveIt = false;
+    int iColRefIdx = pColCU->getCUMvField(RefPicList(l))->getRefIdx(uiPartIdxCenter);
+    if (iColRefIdx < 0)
+    {
+      continue;
+    }
+    int iColRefPOC = pColCU->getSlice()->getRefPOC(RefPicList(l), iColRefIdx);
+    if( pColCU->getSlice()->getRefViewId( RefPicList(l), iColRefIdx ) != pColCU->getSlice()->getViewId() )
+    {
+      continue;
+    }
+    int iColDist = abs(iColRefPOC - iColPOC);
+    bool bCrosses = iColPOC < iCurrPOC ? iColRefPOC > iCurrPOC : iColRefPOC < iCurrPOC;
+    if (iFirstColDist < 0)
+    {
+      bSaveIt = true;
+    }
+    else if (bCrosses && !bFirstCrosses)
+    {
+      bSaveIt = true;
+    }
+    else if (bCrosses == bFirstCrosses && l == eRefPicList)
+    {
+      bSaveIt = true;
+    }
+    
+    if (bSaveIt)
+    {
+      bFirstCrosses = bCrosses;
+      iFirstColDist = iColDist;
+      eColRefPicList = RefPicList(l);
+    }
+  }
+
+#if MERL_VSP_C0152 // Preventive
+  if (pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiPartIdxCenter) < 0) // NOT_VALID
+    return false;
+#endif
+  
+  // Scale the vector.
+  Int iColRefPOC = pColCU->getSlice()->getRefPOC(eColRefPicList, pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiPartIdxCenter));
+  TComMv cColMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiPartIdxCenter);
+  
+  Int iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, iRefIdx)->getPOC();
+  Int iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
+  if ( iScale == 4096 )
+  {
+    pcMv[0] = cColMv;
+  }
+  else
+  {
+    pcMv[0] = cColMv.scaleMv( iScale );
+  }
+  
+  return true;
+}
+
+Void TComDataCU::compressMV()
+{
+  Int scaleFactor = 4 * AMVP_DECIMATION_FACTOR / m_unitSize;
+  if (scaleFactor > 0)
+  {
+#if HHI_MPI
+    m_acCUMvField[0].compress(m_pePredMode, m_puhInterDir, scaleFactor);
+    m_acCUMvField[1].compress(m_pePredMode, m_puhInterDir, scaleFactor);
+#else
+    m_acCUMvField[0].compress(m_pePredMode, scaleFactor);
+    m_acCUMvField[1].compress(m_pePredMode, scaleFactor);    
+#endif
+  }
+}
+
+UInt TComDataCU::getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra)
+{
+  
+  UInt uiCTXIdx;
+  UInt uiScanIdx;
+  UInt uiDirMode;
+
+  if ( !bIsIntra ) 
+  {
+    uiScanIdx = SCAN_ZIGZAG;
+    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);
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    mapDMMtoIntraMode( uiDirMode );
+#endif
+
+    uiScanIdx = SCAN_ZIGZAG;
+    if (uiCTXIdx >3 && uiCTXIdx < 6) //if multiple scans supported for PU size
+    {
+      uiScanIdx = abs((Int) uiDirMode - VER_IDX) < 5 ? 1 : (abs((Int)uiDirMode - HOR_IDX) < 5 ? 2 : 0);
+    }
+  }
+  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 HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    mapDMMtoIntraMode( uiDirMode );
+#endif
+    }
+    uiScanIdx = SCAN_ZIGZAG;
+    if (uiCTXIdx >4 && uiCTXIdx < 7) //if multiple scans supported for PU size
+    {
+      uiScanIdx = abs((Int) uiDirMode - VER_IDX) < 5 ? 1 : (abs((Int)uiDirMode - HOR_IDX) < 5 ? 2 : 0);
+    }
+  }
+
+  return uiScanIdx;
+}
+
+Bool TComDataCU::useNonSquareTrans(UInt uiTrMode, Int absPartIdx)
+{
+  UInt minTuSize = ( 1 << ( getSlice()->getSPS()->getQuadtreeTULog2MinSize() + 1 ) );
+  const UInt uiLog2TrSize = g_aucConvertToBit[ getSlice()->getSPS()->getMaxCUWidth() >> ( m_puhDepth[ absPartIdx ] + uiTrMode ) ] + 2;
+  if ( uiTrMode && uiLog2TrSize < getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && ( getWidth( absPartIdx ) > minTuSize ) &&
+      ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_2NxN || ( m_pePartSize[absPartIdx] >= SIZE_2NxnU && m_pePartSize[absPartIdx] <= SIZE_nRx2N ) ) )
+  {
+    return getSlice()->getSPS()->getUseNSQT();
+  }
+  else
+  {
+    return false;
+  }
+}
+
+Void TComDataCU::getNSQTSize(Int trMode, Int absPartIdx, Int &trWidth, Int &trHeight)
+{
+  UInt minTuSize = ( 1 << getSlice()->getSPS()->getQuadtreeTULog2MinSize() );
+  if ( useNonSquareTrans( trMode, absPartIdx ) && ( trWidth > minTuSize ) )
+  {
+    trWidth  = ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_nLx2N || m_pePartSize[absPartIdx] == SIZE_nRx2N )? trWidth >> 1 : trWidth << 1;
+    trHeight = ( m_pePartSize[absPartIdx] == SIZE_Nx2N || m_pePartSize[absPartIdx] == SIZE_nLx2N || m_pePartSize[absPartIdx] == SIZE_nRx2N )? trHeight << 1 : trHeight >> 1;
+  }
+}
+Bool TComDataCU::useNonSquarePU(UInt absPartIdx)
+{
+  if ( ( m_pePartSize[absPartIdx] == SIZE_Nx2N ) || ( m_pePartSize[absPartIdx] == SIZE_2NxN ) || ( m_pePartSize[absPartIdx] >= SIZE_2NxnU && m_pePartSize[absPartIdx] <= SIZE_nRx2N ) )
+  {
+    return true;
+  }
+  else
+  {
+    return false;
+  }
+}
+
+UInt TComDataCU::getInterTUSplitDirection( Int trWidth, Int trHeight, Int trLastWidth, Int trLastHeight )
+{
+  UInt interTUSplitDirection = 2;
+  if ( ( trWidth == trLastWidth ) && ( trHeight < trLastHeight ) )
+  {
+    interTUSplitDirection = 0;
+  }
+  else if ( ( trWidth < trLastWidth ) && ( trHeight == trLastHeight ) )
+  {
+    interTUSplitDirection = 1;
+  }    
+
+  return interTUSplitDirection;
+}
+
+UInt TComDataCU::getNSAbsPartIdx ( UInt log2TrafoSize, UInt absPartIdx, UInt absTUPartIdx, UInt innerQuadIdx, UInt trMode )
+{
+  Int trWidth, trHeight, trLastWidth, trLastHeight;
+  UInt lcuWidthInBaseUnits = getPic()->getNumPartInWidth();
+  UInt nsTUWidthInBaseUnits, nsTUHeightInBaseUnits;
+  UInt interTUSplitDirection;
+  
+  if( isIntra(absPartIdx) )
+  {
+    return absPartIdx;
+  }
+
+  trWidth = trHeight = ( 1 << log2TrafoSize );
+  trLastWidth = trWidth << 1, trLastHeight = trHeight << 1;  
+
+  getNSQTSize( trMode,     absPartIdx, trWidth,     trHeight );
+  getNSQTSize( trMode - 1, absPartIdx, trLastWidth, trLastHeight );
+  interTUSplitDirection = getInterTUSplitDirection ( trWidth, trHeight, trLastWidth, trLastHeight );
+
+  nsTUWidthInBaseUnits  = trWidth / getPic()->getMinCUWidth();
+  nsTUHeightInBaseUnits = trHeight / getPic()->getMinCUHeight();    
+
+  if ( interTUSplitDirection != 2 )  
+  {
+    UInt uiNSTUBaseUnits = nsTUWidthInBaseUnits < nsTUHeightInBaseUnits ? nsTUWidthInBaseUnits : nsTUHeightInBaseUnits;
+    absTUPartIdx = g_auiRasterToZscan[ g_auiZscanToRaster[absTUPartIdx] + innerQuadIdx * uiNSTUBaseUnits * lcuWidthInBaseUnits * ( 1 - interTUSplitDirection ) + innerQuadIdx * uiNSTUBaseUnits * interTUSplitDirection ];
+  }
+  else  
+  {
+    absTUPartIdx = g_auiRasterToZscan[ g_auiZscanToRaster[absTUPartIdx] + (innerQuadIdx & 0x01) * nsTUWidthInBaseUnits + ( ( innerQuadIdx >> 1 ) & 0x01 ) * nsTUHeightInBaseUnits * lcuWidthInBaseUnits ]; 
+  }
+
+  return absTUPartIdx;  
+}
+
+UInt TComDataCU::getNSAddrChroma( UInt uiLog2TrSizeC, UInt uiTrModeC, UInt uiQuadrant, UInt absTUPartIdx )
+{  
+  if( uiLog2TrSizeC != getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    return absTUPartIdx;
+  }
+
+  UInt lcuWidthInBaseUnits = getPic()->getNumPartInWidth();
+  Int trWidth  = ( 1 << ( uiLog2TrSizeC + 1 ) );
+  Int trHeight = ( 1 << ( uiLog2TrSizeC + 1 ) );
+  Int trLastWidth = trWidth << 1, trLastHeight = trHeight << 1;
+
+  getNSQTSize ( uiTrModeC - 1, absTUPartIdx, trLastWidth, trLastHeight );
+  getNSQTSize ( uiTrModeC,     absTUPartIdx, trWidth,     trHeight );
+
+  UInt interTUSplitDirection = getInterTUSplitDirection ( trWidth, trHeight, trLastWidth, trLastHeight );
+  UInt nsTUWidthInBaseUnits  = trWidth / getPic()->getMinCUWidth();
+  UInt nsTUHeightInBaseUnits = trHeight / getPic()->getMinCUHeight();
+  UInt firstTURasterIdx = 0, absTUPartIdxC = 0; 
+
+  if(interTUSplitDirection != 2)
+  {
+    UInt uiNSTUBaseUnits = nsTUWidthInBaseUnits < nsTUHeightInBaseUnits ? 1 : lcuWidthInBaseUnits;
+    firstTURasterIdx   = g_auiZscanToRaster[absTUPartIdx] - uiQuadrant * uiNSTUBaseUnits;
+    absTUPartIdxC      = g_auiRasterToZscan[firstTURasterIdx] + uiQuadrant * nsTUWidthInBaseUnits * nsTUHeightInBaseUnits;
+  }
+  else
+  {
+    UInt uiNSTUBaseUnits = nsTUWidthInBaseUnits < nsTUHeightInBaseUnits ? 2 * lcuWidthInBaseUnits : 2;
+    firstTURasterIdx   = g_auiZscanToRaster[absTUPartIdx] - ( ( uiQuadrant >> 1 ) & 0x01 ) * nsTUHeightInBaseUnits * lcuWidthInBaseUnits - ( uiQuadrant & 0x01 ) * nsTUWidthInBaseUnits;
+    absTUPartIdxC      = g_auiRasterToZscan[firstTURasterIdx + uiQuadrant * uiNSTUBaseUnits];
+  }
+
+  return absTUPartIdxC;
+}
+
+
+UInt TComDataCU::getSCUAddr()
+{ 
+  return getPic()->getPicSym()->getInverseCUOrderMap(m_uiCUAddr)*(1<<(m_pcSlice->getSPS()->getMaxCUDepth()<<1))+m_uiAbsIdxInLCU; 
+}
+
+/** Set neighboring blocks availabilities for non-deblocked filtering 
+ * \param numLCUInPicWidth number of LCUs in picture width
+ * \param numLCUInPicHeight number of LCUs in picture height
+ * \param numSUInLCUWidth number of SUs in LCU width
+ * \param numSUInLCUHeight number of SUs in LCU height
+ * \param picWidth picture width
+ * \param picHeight picture height
+ * \param bIndependentSliceBoundaryEnabled true for independent slice boundary enabled
+ * \param bTopTileBoundary true means that top boundary coincides tile boundary
+ * \param bDownTileBoundary true means that bottom boundary coincides tile boundary
+ * \param bLeftTileBoundary true means that left boundary coincides tile boundary
+ * \param bRightTileBoundary true means that right boundary coincides tile boundary
+ * \param bIndependentTileBoundaryEnabled true for independent tile boundary enabled
+ */
+Void TComDataCU::setNDBFilterBlockBorderAvailability(UInt numLCUInPicWidth, UInt numLCUInPicHeight, UInt numSUInLCUWidth, UInt numSUInLCUHeight, UInt picWidth, UInt picHeight
+                                                    ,Bool bIndependentSliceBoundaryEnabled
+                                                    ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
+                                                    ,Bool bIndependentTileBoundaryEnabled)
+{
+  UInt numSUInLCU = numSUInLCUWidth*numSUInLCUHeight;
+  Int* pSliceIDMapLCU = m_piSliceSUMap;
+
+  UInt uiLPelX, uiTPelY;
+  UInt width, height;
+  Bool bPicRBoundary, bPicBBoundary, bPicTBoundary, bPicLBoundary;
+  Bool bLCURBoundary= false, bLCUBBoundary= false, bLCUTBoundary= false, bLCULBoundary= false;
+  Bool* pbAvailBorder;
+  Bool* pbAvail;
+  UInt rTLSU, rBRSU, widthSU, heightSU;
+  UInt zRefSU;
+  Int* pRefID;
+  Int* pRefMapLCU;
+  UInt rTRefSU= 0, rBRefSU= 0, rLRefSU= 0, rRRefSU= 0;
+  Int* pRRefMapLCU= NULL;
+  Int* pLRefMapLCU= NULL;
+  Int* pTRefMapLCU= NULL;
+  Int* pBRefMapLCU= NULL;
+  Int  sliceID;
+  UInt numSGU = (UInt)m_vNDFBlock.size();
+
+  for(Int i=0; i< numSGU; i++)
+  {
+    NDBFBlockInfo& rSGU = m_vNDFBlock[i];
+
+    sliceID = rSGU.sliceID;
+    uiLPelX = rSGU.posX;
+    uiTPelY = rSGU.posY;
+    width   = rSGU.width;
+    height  = rSGU.height;
+
+    rTLSU     = g_auiZscanToRaster[ rSGU.startSU ];
+    rBRSU     = g_auiZscanToRaster[ rSGU.endSU   ];
+    widthSU   = rSGU.widthSU;
+    heightSU  = rSGU.heightSU;
+
+    pbAvailBorder = rSGU.isBorderAvailable;
+
+    bPicTBoundary= (uiTPelY == 0                       )?(true):(false);
+    bPicLBoundary= (uiLPelX == 0                       )?(true):(false);
+    bPicRBoundary= (!(uiLPelX+ width < picWidth )  )?(true):(false);
+    bPicBBoundary= (!(uiTPelY + height < picHeight))?(true):(false);
+
+    bLCULBoundary = (rTLSU % numSUInLCUWidth == 0)?(true):(false);
+    bLCURBoundary = ( (rTLSU+ widthSU) % numSUInLCUWidth == 0)?(true):(false);
+    bLCUTBoundary = ( (UInt)(rTLSU / numSUInLCUWidth)== 0)?(true):(false);
+    bLCUBBoundary = ( (UInt)(rBRSU / numSUInLCUWidth) == (numSUInLCUHeight-1) )?(true):(false);
+
+    //       SGU_L
+    pbAvail = &(pbAvailBorder[SGU_L]);
+    if(bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (!bIndependentSliceBoundaryEnabled)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCULBoundary = (rTLSU % uiNumSUInLCUWidth == 0)?(true):(false);
+      if(bLCULBoundary)
+      {
+        rLRefSU     = rTLSU + numSUInLCUWidth -1;
+        zRefSU      = g_auiRasterToZscan[rLRefSU];
+        pRefMapLCU = pLRefMapLCU= (pSliceIDMapLCU - numSUInLCU);
+      }
+      else
+      {
+        zRefSU   = g_auiRasterToZscan[rTLSU - 1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+    }
+
+    //       SGU_R
+    pbAvail = &(pbAvailBorder[SGU_R]);
+    if(bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (!bIndependentSliceBoundaryEnabled)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //       bLCURBoundary = ( (rTLSU+ uiWidthSU) % uiNumSUInLCUWidth == 0)?(true):(false);
+      if(bLCURBoundary)
+      {
+        rRRefSU      = rTLSU + widthSU - numSUInLCUWidth;
+        zRefSU       = g_auiRasterToZscan[rRRefSU];
+        pRefMapLCU  = pRRefMapLCU= (pSliceIDMapLCU + numSUInLCU);
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU + widthSU];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+    }
+
+    //       SGU_T
+    pbAvail = &(pbAvailBorder[SGU_T]);
+    if(bPicTBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (!bIndependentSliceBoundaryEnabled)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCUTBoundary = ( (UInt)(rTLSU / uiNumSUInLCUWidth)== 0)?(true):(false);
+      if(bLCUTBoundary)
+      {
+        rTRefSU      = numSUInLCU - (numSUInLCUWidth - rTLSU);
+        zRefSU       = g_auiRasterToZscan[rTRefSU];
+        pRefMapLCU  = pTRefMapLCU= (pSliceIDMapLCU - (numLCUInPicWidth*numSUInLCU));
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU - numSUInLCUWidth];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+    }
+
+    //       SGU_B
+    pbAvail = &(pbAvailBorder[SGU_B]);
+    if(bPicBBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (!bIndependentSliceBoundaryEnabled)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCUBBoundary = ( (UInt)(rBRSU / uiNumSUInLCUWidth) == (uiNumSUInLCUHeight-1) )?(true):(false);
+      if(bLCUBBoundary)
+      {
+        rBRefSU      = rTLSU % numSUInLCUWidth;
+        zRefSU       = g_auiRasterToZscan[rBRefSU];
+        pRefMapLCU  = pBRefMapLCU= (pSliceIDMapLCU + (numLCUInPicWidth*numSUInLCU));
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU + (heightSU*numSUInLCUWidth)];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+    }
+
+    //       SGU_TL
+    pbAvail = &(pbAvailBorder[SGU_TL]);
+    if(bPicTBoundary || bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (!bIndependentSliceBoundaryEnabled)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUTBoundary && bLCULBoundary)
+      {
+        zRefSU       = numSUInLCU -1;
+        pRefMapLCU  = pSliceIDMapLCU - ( (numLCUInPicWidth+1)*numSUInLCU);
+      }
+      else if(bLCUTBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rTRefSU- 1];
+        pRefMapLCU  = pTRefMapLCU;
+      }
+      else if(bLCULBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rLRefSU- numSUInLCUWidth ];
+        pRefMapLCU  = pLRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU - numSUInLCUWidth -1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+    }
+
+    //       SGU_TR
+    pbAvail = &(pbAvailBorder[SGU_TR]);
+    if(bPicTBoundary || bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (!bIndependentSliceBoundaryEnabled)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUTBoundary && bLCURBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[numSUInLCU - numSUInLCUWidth];
+        pRefMapLCU  = pSliceIDMapLCU - ( (numLCUInPicWidth-1)*numSUInLCU);        
+      }
+      else if(bLCUTBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rTRefSU+ widthSU];
+        pRefMapLCU  = pTRefMapLCU;
+      }
+      else if(bLCURBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rRRefSU- numSUInLCUWidth ];
+        pRefMapLCU  = pRRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU - numSUInLCUWidth +widthSU];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+    }
+
+    //       SGU_BL
+    pbAvail = &(pbAvailBorder[SGU_BL]);
+    if(bPicBBoundary || bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (!bIndependentSliceBoundaryEnabled)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUBBoundary && bLCULBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[numSUInLCUWidth - 1];
+        pRefMapLCU  = pSliceIDMapLCU + ( (numLCUInPicWidth-1)*numSUInLCU);        
+      }
+      else if(bLCUBBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rBRefSU - 1];
+        pRefMapLCU  = pBRefMapLCU;
+      }
+      else if(bLCULBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rLRefSU+ heightSU*numSUInLCUWidth ];
+        pRefMapLCU  = pLRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU + heightSU*numSUInLCUWidth -1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+    }
+
+    //       SGU_BR
+    pbAvail = &(pbAvailBorder[SGU_BR]);
+    if(bPicBBoundary || bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (!bIndependentSliceBoundaryEnabled)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUBBoundary && bLCURBoundary)
+      {
+        zRefSU = 0;
+        pRefMapLCU = pSliceIDMapLCU+ ( (numLCUInPicWidth+1)*numSUInLCU);
+      }
+      else if(bLCUBBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[ rBRefSU + widthSU];
+        pRefMapLCU = pBRefMapLCU;
+      }
+      else if(bLCURBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[ rRRefSU + (heightSU*numSUInLCUWidth)];
+        pRefMapLCU = pRRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU      = g_auiRasterToZscan[ rTLSU + (heightSU*numSUInLCUWidth)+ widthSU];
+        pRefMapLCU = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):(false);
+    }
+
+    if(bIndependentTileBoundaryEnabled)
+    {
+      //left LCU boundary
+      if(!bPicLBoundary && bLCULBoundary)
+      {
+        if(bLeftTileBoundary)
+        {
+          pbAvailBorder[SGU_L] = pbAvailBorder[SGU_TL] = pbAvailBorder[SGU_BL] = false;
+        }
+      }
+      //right LCU boundary
+      if(!bPicRBoundary && bLCURBoundary)
+      {
+        if(bRightTileBoundary)
+        {
+          pbAvailBorder[SGU_R] = pbAvailBorder[SGU_TR] = pbAvailBorder[SGU_BR] = false;
+        }
+      }
+      //top LCU boundary
+      if(!bPicTBoundary && bLCUTBoundary)
+      {
+        if(bTopTileBoundary)
+        {
+          pbAvailBorder[SGU_T] = pbAvailBorder[SGU_TL] = pbAvailBorder[SGU_TR] = false;
+        }
+      }
+      //down LCU boundary
+      if(!bPicBBoundary && bLCUBBoundary)
+      {
+        if(bDownTileBoundary)
+        {
+          pbAvailBorder[SGU_B] = pbAvailBorder[SGU_BL] = pbAvailBorder[SGU_BR] = false;
+        }
+      }
+    }
+    rSGU.allBordersAvailable = true;
+    for(Int b=0; b< NUM_SGU_BORDER; b++)
+    {
+      if(pbAvailBorder[b] == false)
+      {
+        rSGU.allBordersAvailable = false;
+        break;
+      }
+    }
+
+  }
+}
+
+Void TComDataCU::getPosInPic( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY )
+{
+  riPosX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIndex]] + getCUPelX();
+  riPosY = g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIndex]] + getCUPelY();  
+}
+
+// -------------------------------------------------------------------------------------------------------------------
+// public functions for depth model modes
+// -------------------------------------------------------------------------------------------------------------------
+#if HHI_DMM_WEDGE_INTRA
+Void TComDataCU::setWedgeFullTabIdxSubParts( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_puiWedgeFullTabIdx[uiAbsPartIdx+ui] = uiTIdx;
+  }
+}
+
+Void TComDataCU::setWedgeFullDeltaDC1SubParts( Int iDC1, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piWedgeFullDeltaDC1[uiAbsPartIdx+ui] = iDC1;
+  }
+}
+
+Void TComDataCU::setWedgeFullDeltaDC2SubParts( Int iDC2, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piWedgeFullDeltaDC2[uiAbsPartIdx+ui] = iDC2;
+  }
+}
+
+Void TComDataCU::setWedgePredDirTabIdxSubParts( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_puiWedgePredDirTabIdx[uiAbsPartIdx+ui] = uiTIdx;
+  }
+}
+
+Void TComDataCU::setWedgePredDirDeltaDC1SubParts( Int iDC1, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piWedgePredDirDeltaDC1[uiAbsPartIdx+ui] = iDC1;
+  }
+}
+
+Void TComDataCU::setWedgePredDirDeltaDC2SubParts( Int iDC2, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piWedgePredDirDeltaDC2[uiAbsPartIdx+ui] = iDC2;
+  }
+}
+
+Void TComDataCU::setWedgePredDirDeltaEndSubParts( Int iDelta, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piWedgePredDirDeltaEnd[uiAbsPartIdx+ui] = iDelta;
+  }
+}
+#endif
+#if HHI_DMM_PRED_TEX
+Void TComDataCU::setWedgePredTexTabIdxSubParts( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_puiWedgePredTexTabIdx[uiAbsPartIdx+ui] = uiTIdx;
+  }
+}
+
+#if LGE_DMM3_SIMP_C0044
+Void TComDataCU::setWedgePredTexIntraTabIdxSubParts( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_puiWedgePredTexIntraTabIdx[uiAbsPartIdx+ui] = uiTIdx;
+  }
+}
+#endif
+
+Void TComDataCU::setWedgePredTexDeltaDC1SubParts( Int iDC1, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piWedgePredTexDeltaDC1[uiAbsPartIdx+ui] = iDC1;
+  }
+}
+
+Void TComDataCU::setWedgePredTexDeltaDC2SubParts( Int iDC2, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piWedgePredTexDeltaDC2[uiAbsPartIdx+ui] = iDC2;
+  }
+}
+
+Void TComDataCU::setContourPredTexDeltaDC1SubParts( Int iDC1, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piContourPredTexDeltaDC1[uiAbsPartIdx+ui] = iDC1;
+  }
+}
+
+Void TComDataCU::setContourPredTexDeltaDC2SubParts( Int iDC2, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for ( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piContourPredTexDeltaDC2[uiAbsPartIdx+ui] = iDC2;
+  }
+}
+#endif
+
+#if HHI_MPI
+Void TComDataCU::setTextureModeDepthSubParts( Int iTextureModeDepth, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  for (UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_piTextureModeDepth[uiAbsPartIdx + ui] = iTextureModeDepth;
+  }
+}
+
+Void TComDataCU::copyTextureMotionDataFrom( TComDataCU* pcCU, UInt uiDepth, UInt uiAbsPartIdxSrc, UInt uiAbsPartIdxDst )
+{
+  assert( getSlice()->getIsDepth() && ! pcCU->getSlice()->getIsDepth() );
+  UInt uiNumPartition = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  memcpy( m_pePredMode + uiAbsPartIdxDst,  pcCU->getPredictionMode() + uiAbsPartIdxSrc, sizeof( m_pePredMode[0] ) * uiNumPartition );
+  memcpy( m_puhInterDir + uiAbsPartIdxDst, pcCU->getInterDir() + uiAbsPartIdxSrc,       sizeof( m_puhInterDir[0] ) * uiNumPartition );
+
+#if MERL_VSP_C0152 && MTK_UNCONSTRAINED_MVI_B0083
+  memcpy( m_piVSPIndex + uiAbsPartIdxDst,  pcCU->getVSPIndex() + uiAbsPartIdxSrc, sizeof( m_piVSPIndex[0] ) * uiNumPartition );
+#endif
+
+#if !MTK_UNCONSTRAINED_MVI_B0083
+  memcpy( m_apiMVPIdx[0] + uiAbsPartIdxDst, pcCU->getMVPIdx(REF_PIC_LIST_0) + uiAbsPartIdxSrc, sizeof(*m_apiMVPIdx[0]) * uiNumPartition );
+  memcpy( m_apiMVPIdx[1] + uiAbsPartIdxDst, pcCU->getMVPIdx(REF_PIC_LIST_1) + uiAbsPartIdxSrc, sizeof(*m_apiMVPIdx[0]) * uiNumPartition );
+  memcpy( m_apiMVPNum[0] + uiAbsPartIdxDst, pcCU->getMVPNum(REF_PIC_LIST_0) + uiAbsPartIdxSrc, sizeof(*m_apiMVPNum[0]) * uiNumPartition );
+  memcpy( m_apiMVPNum[1] + uiAbsPartIdxDst, pcCU->getMVPNum(REF_PIC_LIST_1) + uiAbsPartIdxSrc, sizeof(*m_apiMVPNum[0]) * uiNumPartition );
+#endif
+
+  pcCU->getCUMvField( REF_PIC_LIST_0 )->copyTo( &m_acCUMvField[0], -Int(uiAbsPartIdxSrc) + uiAbsPartIdxDst, uiAbsPartIdxSrc, uiNumPartition );
+  pcCU->getCUMvField( REF_PIC_LIST_1 )->copyTo( &m_acCUMvField[1], -Int(uiAbsPartIdxSrc) + uiAbsPartIdxDst, uiAbsPartIdxSrc, uiNumPartition );
+
+#if MTK_UNCONSTRAINED_MVI_B0083
+  if( pcCU->getSlice()->getSliceType() == P_SLICE)
+  {
+    m_acCUMvField[0].setUndefinedMv( uiAbsPartIdxDst, uiNumPartition, m_pePredMode, m_puhInterDir,  0, 1);
+    m_acCUMvField[1].setUndefinedMv( uiAbsPartIdxDst, uiNumPartition, m_pePredMode, m_puhInterDir, -1, 1);
+  }
+  else
+  {
+    m_acCUMvField[0].setUndefinedMv( uiAbsPartIdxDst, uiNumPartition, m_pePredMode, m_puhInterDir,  0, 3);
+    m_acCUMvField[1].setUndefinedMv( uiAbsPartIdxDst, uiNumPartition, m_pePredMode, m_puhInterDir,  0, 3);
+  }
+#endif
+
+
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  m_acCUMvField[0].decreaseMvAccuracy( uiAbsPartIdxDst, uiNumPartition, 2 );
+  m_acCUMvField[1].decreaseMvAccuracy( uiAbsPartIdxDst, uiNumPartition, 2 );
+#endif
+}
+#endif
+
+// -------------------------------------------------------------------------------------------------------------------
+// public functions for Multi-view tools
+// -------------------------------------------------------------------------------------------------------------------
+#if H3D_IVMP
+#if !H3D_NBDV
+Int
+TComDataCU::getPdmMergeCandidate( UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv )
+{
+  TComDepthMapGenerator* pcDepthMapGenerator = m_pcSlice->getSPS()->getDepthMapGenerator();
+  ROFRS( pcDepthMapGenerator, 0 );
+  return pcDepthMapGenerator->getPdmMergeCandidate( this, uiPartIdx, paiPdmRefIdx, pacPdmMv );
+}
+
+
+Bool
+TComDataCU::getPdmMvPred( UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv, Bool bMerge )
+{
+  TComDepthMapGenerator* pcDepthMapGenerator = m_pcSlice->getSPS()->getDepthMapGenerator();
+  ROFRS( pcDepthMapGenerator, false );
+  return pcDepthMapGenerator->getPdmMvPred( this, uiPartIdx, eRefPicList, iRefIdx, rcMv, bMerge );
+}
+#else //H3D_NBDV
+Bool
+TComDataCU::getUnifiedMvPredCan(UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* iPdm, Bool bMerge )
+{
+  TComDepthMapGenerator* pcDepthMapGenerator = m_pcSlice->getSPS()->getDepthMapGenerator();
+  ROFRS( pcDepthMapGenerator, false );
+  if (pDInfo->iN > 0 && pcDepthMapGenerator->getPdmCandidate(this, uiPartIdx, eRefPicList, iRefIdx, paiPdmRefIdx, pacPdmMv, pDInfo, iPdm, bMerge))
+    return true;
+  return false;
+}
+#endif //H3D_NBDV
+
+Bool      
+TComDataCU::getIViewOrgDepthMvPred( UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv )
+{
+  TComDepthMapGenerator* pcDepthMapGenerator = m_pcSlice->getSPS()->getDepthMapGenerator();
+  ROFRS( pcDepthMapGenerator, false );
+  return pcDepthMapGenerator->getIViewOrgDepthMvPred( this, uiPartIdx, eRefPicList, iRefIdx, rcMv );
+}
+#endif
+
+#if H3D_IVRP
+Bool
+TComDataCU::getResidualSamples( UInt uiPartIdx, Bool bRecon, TComYuv* pcYuv )
+{
+  TComResidualGenerator*  pcResidualGenerator = m_pcSlice->getSPS()->getResidualGenerator();
+  ROFRS( pcResidualGenerator, false );
+#if H3D_NBDV
+  DisInfo cDisInfo;
+  cDisInfo.iN = 0;
+  PartSize m_peSaved =  getPartitionSize( 0 );
+  m_pePartSize[0] =  SIZE_2Nx2N;
+#if FCO_DVP_REFINE_C0132_C0170
+  if(getPic()->getDepthCoded() )
+  {
+    TComPic*      pcCodedDepthMap = getPic()->getRecDepthMap();
+    TComMv        cColMv;
+
+    cColMv.setZero();
+    estimateDVFromDM(0, pcCodedDepthMap, 0, &cColMv, false);
+
+    cDisInfo.iN = 1;
+    cDisInfo.m_acMvCand[0].setHor( cColMv.getHor() );
+    cDisInfo.m_acMvCand[0].setVer( cColMv.getVer() );
+    cDisInfo.m_aVIdxCan[0] = 0;
+
+  }
+  else
+#endif
+
+  getDisMvpCandNBDV( 0, 0,  &cDisInfo, false );  
+
+  if( cDisInfo.iN == 0)
+  {
+    m_pePartSize[0] = m_peSaved;
+    return false;
+  }
+  else
+  {
+    Bool bAvailable = pcResidualGenerator->getResidualSamples( this, uiPartIdx, pcYuv, cDisInfo.m_acMvCand[0], bRecon );       
+    m_pePartSize[0] = m_peSaved;
+    return bAvailable;
+  }
+#else
+  return pcResidualGenerator->getResidualSamples( this, uiPartIdx, pcYuv, bRecon ); 
+#endif
+}
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+Void TComDataCU::reconPartition( UInt uiAbsPartIdx, UInt uiDepth, Bool bLeft, UChar ucStartPos, UChar ucNumEdge, UChar* pucEdgeCode, Bool* pbRegion )
+{
+  Int iWidth;
+  Int iHeight;
+  if( uiDepth == 0 )
+  {
+    iWidth = 64;
+    iHeight = 64;
+  }
+  else if( uiDepth == 1 )
+  {
+    iWidth = 32;
+    iHeight = 32;
+  }
+  else if( uiDepth == 2 )
+  {
+    iWidth = 16;
+    iHeight = 16;
+  }
+  else if( uiDepth == 3 )
+  {
+    iWidth = 8;
+    iHeight = 8;
+  }
+  else // uiDepth == 4
+  {
+    iWidth = 4;
+    iHeight = 4;
+  }
+
+  Int iPtr = 0;
+  Int iX, iY;
+  Int iDir = -1;
+  Int iDiffX = 0, iDiffY = 0;
+
+  // 1. Edge Code -> Vert & Horz Edges
+  Bool*  pbEdge = (Bool*) xMalloc( Bool, 4 * iWidth * iHeight );
+
+  for( UInt ui = 0; ui < 4 * iWidth * iHeight; ui++ )
+    pbEdge  [ ui ] = false;
+
+  // Direction : left(0), right(1), top(2), bottom(3), left-top(4), right-top(5), left-bottom(6), right-bottom(7)
+  // Code      : 0deg(0), 45deg(1), -45deg(2), 90deg(3), -90deg(4), 135deg(5), -135deg(6)
+  const UChar tableDir[8][7] = { { 0, 6, 4, 3, 2, 7, 5 },
+  { 1, 5, 7, 2, 3, 4, 6 },
+  { 2, 4, 5, 0, 1, 6, 7 },
+  { 3, 7, 6, 1, 0, 5, 4 },
+  { 4, 0, 2, 6, 5, 3, 1 },
+  { 5, 2, 1, 4, 7, 0, 3 },
+  { 6, 3, 0, 7, 4, 1, 2 },
+  { 7, 1, 3, 5, 6, 2, 0 }};
+
+  UChar ucCode = pucEdgeCode[iPtr++];
+
+  if( !bLeft )
+  {
+    iX = ucStartPos;
+    iY = 0;
+
+    switch(ucCode)
+    {
+    case 0: // bottom
+      iDir = 3;
+      if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+      break;
+    case 2: // left-bottom
+      iDir = 6;
+      if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+      break;
+    case 1: // right-bottom
+      iDir = 7;
+      if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      break;
+    case 4: // left
+      iDir = 0;
+      assert(false);
+      break;
+    case 3: // right
+      iDir = 1;
+      if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      break;
+    }
+  }
+  else
+  {
+    iX = 0;
+    iY = ucStartPos;
+
+    switch(ucCode)
+    {
+    case 0: // right
+      iDir = 1;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      break;
+    case 1: // right-top
+      iDir = 5;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+      break;
+    case 2: // right-bottom
+      iDir = 7;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      break;
+    case 3: // top
+      iDir = 2;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+      break;
+    case 4: // bottom
+      iDir = 3;
+      assert(false);
+      break;
+    }
+  }
+
+  switch( iDir )
+  {
+  case 0: // left
+    iDiffX = -1;
+    iDiffY = 0;
+    break;
+  case 1: // right
+    iDiffX = +1;
+    iDiffY = 0;
+    break;
+  case 2: // top
+    iDiffX = 0;
+    iDiffY = -1;
+    break;
+  case 3: // bottom
+    iDiffX = 0;
+    iDiffY = +1;
+    break;
+  case 4: // left-top
+    iDiffX = -1;
+    iDiffY = -1;
+    break;
+  case 5: // right-top
+    iDiffX = +1;
+    iDiffY = -1;
+    break;
+  case 6: // left-bottom
+    iDiffX = -1;
+    iDiffY = +1;
+    break;
+  case 7: // right-bottom
+    iDiffX = +1;
+    iDiffY = +1;
+    break;
+  }
+
+  iX += iDiffX;
+  iY += iDiffY;
+
+  while( iPtr < ucNumEdge )
+  {
+    ucCode = pucEdgeCode[iPtr++];
+
+    Int iNewDir = tableDir[iDir][ucCode];
+
+    switch( iNewDir )
+    {
+    case 0: // left
+      iDiffX = -1;
+      iDiffY = 0;
+      break;
+    case 1: // right
+      iDiffX = +1;
+      iDiffY = 0;
+      break;
+    case 2: // top
+      iDiffX = 0;
+      iDiffY = -1;
+      break;
+    case 3: // bottom
+      iDiffX = 0;
+      iDiffY = +1;
+      break;
+    case 4: // left-top
+      iDiffX = -1;
+      iDiffY = -1;
+      break;
+    case 5: // right-top
+      iDiffX = +1;
+      iDiffY = -1;
+      break;
+    case 6: // left-bottom
+      iDiffX = -1;
+      iDiffY = +1;
+      break;
+    case 7: // right-bottom
+      iDiffX = +1;
+      iDiffY = +1;
+      break;
+    }
+
+    switch( iDir )
+    {
+    case 0: // left
+      switch( ucCode )
+      {
+      case 0:
+      case 2:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        break;
+      case 1:
+      case 3:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 4:
+      case 6:
+        // no
+        break;
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      }
+      break;
+    case 1: // right
+      switch( ucCode )
+      {
+      case 0:
+      case 2:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 1:
+      case 3:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 4:
+      case 6:
+        // no
+        break;
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      }
+      break;
+    case 2: // top
+      switch( ucCode )
+      {
+      case 0:
+      case 2:
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 1:
+      case 3:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 4:
+      case 6:
+        // no
+        break;
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      }
+      break;
+    case 3: // bottom
+      switch( ucCode )
+      {
+      case 0:
+      case 2:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 1:
+      case 3:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 4:
+      case 6:
+        // no
+        break;
+      case 5:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      }
+      break;
+    case 4: // left-top
+      switch( ucCode )
+      {
+      case 0:
+      case 1:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 2:
+      case 4:
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 3:
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 6:
+        // no
+        break;
+      }
+      break;
+    case 5: // right-top
+      switch( ucCode )
+      {
+      case 0:
+      case 1:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 2:
+      case 4:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 3:
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 6:
+        // no
+        break;
+      }
+      break;
+    case 6: // left-bottom
+      switch( ucCode )
+      {
+      case 0:
+      case 1:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 2:
+      case 4:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        break;
+      case 3:
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 6:
+        // no
+        break;
+      }
+      break;
+    case 7: // right-bottom
+      switch( ucCode )
+      {
+      case 0:
+      case 1:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 2:
+      case 4:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 3:
+      case 5:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 6:
+        // no
+        break;
+      }
+      break;
+    }
+
+    assert( iX >= 0 && iX <= iWidth );
+    assert( iY >= 0 && iY <= iHeight );
+
+    iX += iDiffX;
+    iY += iDiffY;
+    iDir = iNewDir;
+  }
+
+  // finalize edge chain
+  if( iX == iWidth-1 )
+  {
+    if( iY == 0 )
+    {
+      if( iDir == 1 )
+      {
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 5 )
+      {
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+    else if( iY == iHeight-1 )
+    {
+      if( iDir == 3 )
+      {
+        pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+      }
+      else if( iDir == 7 )
+      {
+        pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+    else
+    {
+      if( iDir == 1 )
+      {
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 3 )
+      {
+        pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 5 )
+      {
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 7 )
+      {
+        pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+  }
+  else if( iX == 0 )
+  {
+    if( iY == 0 )
+    {
+      if( iDir == 2 )
+      {
+        pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+      }
+      else if( iDir == 4 )
+      {
+        pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+    else if( iY == iHeight-1 )
+    {
+      if( iDir == 0 )
+      {
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 6 )
+      {
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+    else
+    {
+      if( iDir == 0 )
+      {
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 2 )
+      {
+        pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 4 )
+      {
+        pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 6 )
+      {
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+  }
+  else if( iY == 0 )
+  {
+    if( iDir == 1 )
+    {
+      pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 2 )
+    {
+      pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 4 )
+    {
+      pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 5 )
+    {
+      pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else
+    {
+      assert(false);
+    }
+  }
+  else if( iY == iHeight-1 )
+  {
+    if( iDir == 0 )
+    {
+      pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 3 )
+    {
+      pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 6 )
+    {
+      pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 7 )
+    {
+      pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else
+    {
+      assert(false);
+    }
+  }
+  else
+  {
+    printf("xPredIntraEdge: wrong termination\n");
+    assert(false);
+  }
+
+  // Reconstruct Region from Chain Code
+  Bool* pbVisit  = (Bool*) xMalloc( Bool, iWidth * iHeight );
+  Int*  piStack  = (Int* ) xMalloc( Int,  iWidth * iHeight );
+
+  for( UInt ui = 0; ui < iWidth * iHeight; ui++ )
+  {
+    pbRegion[ ui ] = true; // fill it as region 1 (we'll discover region 0 next)
+    pbVisit [ ui ] = false;
+  }
+
+  iPtr = 0;
+  piStack[iPtr++] = (0 << 8) | (0);
+  pbRegion[ 0 ] = false;
+
+  while(iPtr > 0)
+  {
+    Int iTmp = piStack[--iPtr];
+    Int iX1, iY1;
+    iX1 = iTmp & 0xff;
+    iY1 = (iTmp >> 8) & 0xff;
+
+    pbVisit[ iX1 + iY1 * iWidth ] = true;
+
+    assert( iX1 >= 0 && iX1 < iWidth );
+    assert( iY1 >= 0 && iY1 < iHeight );
+
+    if( iX1 > 0 && !pbEdge[ 2 * iX1 - 1 + 4 * iY1 * iWidth ] && !pbVisit[ iX1 - 1 + iY1 * iWidth ] )
+    {
+      piStack[iPtr++] = (iY1 << 8) | (iX1 - 1);
+      pbRegion[ iX1 - 1 + iY1 * iWidth ] = false;
+    }
+    if( iX1 < iWidth - 1 && !pbEdge[ 2 * iX1 + 1 + 4 * iY1 * iWidth ] && !pbVisit[ iX1 + 1 + iY1 * iWidth ] )
+    {
+      piStack[iPtr++] = (iY1 << 8) | (iX1 + 1);
+      pbRegion[ iX1 + 1 + iY1 * iWidth ] = false;
+    }
+    if( iY1 > 0 && !pbEdge[ 2 * iX1 + 2 * (2 * iY1 - 1) * iWidth ] && !pbVisit[ iX1 + (iY1 - 1) * iWidth ] )
+    {
+      piStack[iPtr++] = ((iY1 - 1) << 8) | iX1;
+      pbRegion[ iX1 + (iY1 - 1) * iWidth ] = false;
+    }
+    if( iY1 < iHeight - 1 && !pbEdge[ 2 * iX1 + 2 * (2 * iY1 + 1) * iWidth ] && !pbVisit[ iX1 + (iY1 + 1) * iWidth ] )
+    {
+      piStack[iPtr++] = ((iY1 + 1) << 8) | iX1;
+      pbRegion[ iX1 + (iY1 + 1) * iWidth ] = false;
+    }
+  }
+
+  xFree( pbEdge );
+  xFree( pbVisit );
+  xFree( piStack );
+}
+
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDataCU.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDataCU.h	(revision 341)
@@ -0,0 +1,908 @@
+/* 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-2012, 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     TComDataCU.h
+    \brief    CU data structure (header)
+    \todo     not all entities are documented
+*/
+
+#ifndef _TCOMDATACU_
+#define _TCOMDATACU_
+
+#include <assert.h>
+
+// Include files
+#include "CommonDef.h"
+#include "TComMotionInfo.h"
+#include "TComSlice.h"
+#include "TComRdCost.h"
+#include "TComPattern.h"
+
+#if H3D_IVRP
+#include "TComYuv.h"
+#endif
+
+#include <algorithm>
+#include <vector>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Non-deblocking in-loop filter processing block data structure
+// ====================================================================================================================
+
+/// Non-deblocking filter processing block border tag
+enum NDBFBlockBorderTag
+{
+  SGU_L = 0,
+  SGU_R,
+  SGU_T,
+  SGU_B,
+  SGU_TL,
+  SGU_TR,
+  SGU_BL,
+  SGU_BR,
+  NUM_SGU_BORDER
+};
+
+/// Non-deblocking filter processing block information
+struct NDBFBlockInfo
+{
+  Int   tileID;   //!< tile ID
+  Int   sliceID;  //!< slice ID
+  UInt  startSU;  //!< starting SU z-scan address in LCU
+  UInt  endSU;    //!< ending SU z-scan address in LCU
+  UInt  widthSU;  //!< number of SUs in width
+  UInt  heightSU; //!< number of SUs in height
+  UInt  posX;     //!< top-left X coordinate in picture
+  UInt  posY;     //!< top-left Y coordinate in picture
+  UInt  width;    //!< number of pixels in width
+  UInt  height;   //!< number of pixels in height
+  Bool  isBorderAvailable[NUM_SGU_BORDER];  //!< the border availabilities
+  Bool  allBordersAvailable;
+
+  NDBFBlockInfo():tileID(0), sliceID(0), startSU(0), endSU(0) {} //!< constructor
+  const NDBFBlockInfo& operator= (const NDBFBlockInfo& src);  //!< "=" operator
+};
+
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU data structure class
+class TComDataCU
+{
+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_uiCUPelX;           ///< CU position in a pixel (X)
+  UInt          m_uiCUPelY;           ///< CU position in a pixel (Y)
+  UInt          m_uiNumPartition;     ///< total number of minimum partitions in a CU
+  UChar*        m_puhWidth;           ///< array of widths
+  UChar*        m_puhHeight;          ///< array of heights
+  UChar*        m_puhDepth;           ///< array of depths
+  Int           m_unitSize;           ///< size of a "minimum partition"
+#if HHI_MPI
+  Int*          m_piTextureModeDepth; ///< at which depth are prediction data inherited from texture picture ( -1 : none )
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // CU data
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Char*         m_pePartSize;         ///< array of partition sizes
+#if HHI_INTERVIEW_SKIP
+  Bool*         m_pbRenderable;        ///< array of merge flags
+#endif
+  Char*         m_pePredMode;         ///< array of prediction modes
+  Char*         m_phQP;               ///< array of QP values
+  UChar*        m_puhTrIdx;           ///< array of transform indices
+  UChar*        m_nsqtPartIdx;        ///< array of absPartIdx mapping table, map zigzag to NSQT
+  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)
+#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)
+
+  Int*          m_piSliceSUMap;       ///< pointer of slice ID map
+  std::vector<NDBFBlockInfo> m_vNDFBlock;
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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
+  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
+#if LGE_ILLUCOMP_B0045
+  Bool*         m_pbICFlag;           ///< array of IC flags
+#endif
+  UChar*        m_puhMergeIndex;      ///< array of merge candidate indices
+#if MERL_VSP_C0152
+  Char*         m_piVSPIndex;         ///< array of VSP flags to indicate the current block uses synthetic predictor or not
+                                      ///< value 0: non-VSP, value 1: VSP
+#endif
+#if AMP_MRG
+  Bool          m_bIsMergeAMP;
+#endif
+  UChar*        m_puhLumaIntraDir;    ///< array of intra directions (luma)
+  UChar*        m_puhChromaIntraDir;  ///< array of intra directions (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
+  Bool*         m_puiAlfCtrlFlag;     ///< array of ALF flags
+  Bool*         m_puiTmpAlfCtrlFlag;  ///< temporal array of ALF flags
+  
+  Bool*         m_pbIPCMFlag;         ///< array of intra_pcm flags
+
+  Int           m_numSucIPCM;         ///< the number of succesive IPCM blocks associated with the current log2CUSize
+  Bool          m_lastCUSucIPCMFlag;  ///< True indicates that the last CU is IPCM and shares the same root as the current CU.  
+#if H3D_IVRP
+  Bool*         m_pbResPredAvailable; ///< array of residual prediction available flags
+  Bool*         m_pbResPredFlag;      ///< array of residual prediction flags
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+  UChar*        m_pucEdgeCode;          ///< array of edge code
+  UChar*        m_pucEdgeNumber;        ///< total number of edge
+  UChar*        m_pucEdgeStartPos;      ///< starting point position
+  Bool*         m_pbEdgeLeftFirst;      ///< true if edge should be checked in left boundary first
+  Bool*         m_pbEdgePartition;      ///< true if it belongs to region 1, otherwise, region 0
+#if LGE_EDGE_INTRA_DELTA_DC
+  Int*          m_piEdgeDeltaDC0;
+  Int*          m_piEdgeDeltaDC1;
+#endif
+#endif
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // misc. variables
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool          m_bDecSubCu;          ///< indicates decoder-mode
+  Double        m_dTotalCost;         ///< sum of partition RD costs
+  Dist          m_uiTotalDistortion;  ///< sum of partition distortion
+  UInt          m_uiTotalBits;        ///< sum of partition bits
+  UInt          m_uiTotalBins;       ///< sum of partition bins
+  UInt*         m_uiSliceStartCU;    ///< Start CU address of current slice
+  UInt*         m_uiEntropySliceStartCU; ///< Start CU address of current slice
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // depth model mode data
+  // -------------------------------------------------------------------------------------------------------------------
+#if HHI_DMM_WEDGE_INTRA
+  UInt*         m_puiWedgeFullTabIdx;
+  Int*          m_piWedgeFullDeltaDC1;
+  Int*          m_piWedgeFullDeltaDC2;
+
+  UInt*         m_puiWedgePredDirTabIdx;
+  Int*          m_piWedgePredDirDeltaDC1;
+  Int*          m_piWedgePredDirDeltaDC2;
+  Int*          m_piWedgePredDirDeltaEnd;
+#endif
+#if HHI_DMM_PRED_TEX
+  UInt*         m_puiWedgePredTexTabIdx;
+#if LGE_DMM3_SIMP_C0044
+  UInt*         m_puiWedgePredTexIntraTabIdx;
+#endif
+  Int*          m_piWedgePredTexDeltaDC1;
+  Int*          m_piWedgePredTexDeltaDC2;
+
+  Int*          m_piContourPredTexDeltaDC1;
+  Int*          m_piContourPredTexDeltaDC2;
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  Bool*         m_pbSDCFlag;
+  Pel*          m_apSegmentDCOffset[2];
+#endif
+
+protected:
+  
+  /// add possible motion vector predictor candidates
+  Bool          xAddMVPCand           ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
+  Bool          xAddMVPCandOrder      ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
+#if MERL_VSP_C0152
+  inline Bool   xAddVspMergeCand      ( UChar ucVspMergePos, Int vspIdx, Bool* bVspMvZeroDone, UInt uiDepth, Bool* abCandIsInter, Int& iCount,
+                                        UChar* puhInterDirNeighbours, TComMvField* pcMvFieldNeighbours, Int* iVSPIndexTrue, Int mrgCandIdx, DisInfo* pDisInfo );
+  inline Void   xInheritVspMode       ( TComDataCU* pcCURef, UInt uiIdx, Bool* bVspMvZeroDone, Int iCount, Int* iVSPIndexTrue, TComMvField* pcMvFieldNeighbours, DisInfo* pDInfo ) ;
+#endif
+  Void          deriveRightBottomIdx        ( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxRB );
+  Bool          xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx 
+#if QC_TMVP_MRG_REFIDX_C0047
+  ,
+  Bool bMRG = 0
+#endif
+  );
+#if H3D_NBDV
+  Void          xDeriveRightBottomNbIdx( PartSize eCUMode, UInt uiPartIdx, Int &uiLCUIdxRBNb, Int &uiPartIdxRBNb );
+  Bool          xCheckSpatialNBDV( TComDataCU* pcTmpCU, UInt uiIdx, UInt uiPartIdx, UInt uiPartAddr, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, McpDisInfo* paMvpDvInfo, UInt uiMvpDvPos, Bool bDepthRefine );
+  Bool          xGetColDisMV( RefPicList eRefPicList, Int refidx, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int & iTargetViewIdx, Int & iStartViewIdx );
+#endif 
+  
+
+  Void xCheckCornerCand( TComDataCU* pcCorner, UInt uiCornerIdx, UInt uiIter, Bool& rbValidCand );
+  /// compute required bits to encode MVD (used in AMVP)
+  UInt          xGetMvdBits           ( TComMv cMvd );
+  UInt          xGetComponentBits     ( Int iVal );
+  
+  /// compute scaling factor from POC difference
+  Int           xGetDistScaleFactor   ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
+  
+  Void xDeriveCenterIdx( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxCenter );
+  Bool xGetCenterCol( UInt uiPartIdx, RefPicList eRefPicList, int iRefIdx, TComMv *pcMv );
+  
+  Void xCheckDuplicateCand(TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, bool* pbCandIsInter, UInt& ruiArrayAddr);
+
+
+public:
+  TComDataCU();
+  virtual ~TComDataCU();
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // create / destroy / initialize / copy
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          create                ( UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+#if ADAPTIVE_QP_SELECTION
+    , Bool bGlobalRMARLBuffer = false
+#endif  
+    );
+  Void          destroy               ();
+  
+  Void          initCU                ( TComPic* pcPic, UInt uiCUAddr );
+  Void          initEstData           ( UInt uiDepth, Int qp );
+  Void          initSubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp );
+  Void          setOutsideCUPart      ( UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
+  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList );
+  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;         }
+  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;       }
+  
+  UChar*        getDepth              ()                        { return m_puhDepth;        }
+  UChar         getDepth              ( UInt uiIdx )            { return m_puhDepth[uiIdx]; }
+  Void          setDepth              ( UInt uiIdx, UChar  uh ) { m_puhDepth[uiIdx] = uh;   }
+  
+  Void          setDepthSubParts      ( UInt uiDepth, UInt uiAbsPartIdx );
+  Void          getPosInPic           ( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY );
+#if HHI_MPI
+  Int*          getTextureModeDepth   ()                        { return m_piTextureModeDepth; }
+  Int           getTextureModeDepth   ( UInt uiIdx )            { return m_piTextureModeDepth[uiIdx]; }
+  Void          setTextureModeDepth   ( UInt uiIdx, Int iTextureModeDepth ){ m_piTextureModeDepth[uiIdx] = iTextureModeDepth; }
+  Void          setTextureModeDepthSubParts( Int iTextureModeDepth, UInt uiAbsPartIdx, UInt uiDepth );
+  Void          copyTextureMotionDataFrom( TComDataCU* pcCU, UInt uiDepth, UInt uiAbsPartIdxSrc, UInt uiAbsPartIdxDst = 0 );
+#endif
+
+   // -------------------------------------------------------------------------------------------------------------------
+  // member functions for CU data
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Char*         getPartitionSize      ()                        { return m_pePartSize;        }
+  PartSize      getPartitionSize      ( UInt uiIdx )            { return static_cast<PartSize>( m_pePartSize[uiIdx] ); }
+  Void          setPartitionSize      ( UInt uiIdx, PartSize uh){ m_pePartSize[uiIdx] = uh;   }
+  Void          setPartSizeSubParts   ( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth );
+  
+#if HHI_INTERVIEW_SKIP
+  Bool*         getRenderable          ()                        { return m_pbRenderable;               }
+    Bool          getRenderable          ( UInt uiIdx )            { return m_pbRenderable[uiIdx];        }
+    Void          setRenderable          ( UInt uiIdx, Bool b )    { m_pbRenderable[uiIdx] = b;           }
+    Void          setRenderableSubParts  ( Bool bRenderable, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  
+  Char*         getPredictionMode     ()                        { return m_pePredMode;        }
+  PredMode      getPredictionMode     ( UInt uiIdx )            { return static_cast<PredMode>( m_pePredMode[uiIdx] ); }
+  Void          setPredictionMode     ( UInt uiIdx, PredMode uh){ m_pePredMode[uiIdx] = uh;   }
+  Void          setPredModeSubParts   ( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  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];       }
+  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 );
+
+#if LOSSLESS_CODING
+  Bool          isLosslessCoded(UInt absPartIdx);
+#endif
+  UChar*        getNSQTPartIdx        ()                        { return m_nsqtPartIdx;        }
+  UChar         getNSQTPartIdx        ( UInt idx )              { return m_nsqtPartIdx[idx];   }
+  Void          setNSQTIdxSubParts    ( UInt absPartIdx, UInt depth );
+  Void          setNSQTIdxSubParts    ( UInt log2TrafoSize, UInt absPartIdx, UInt absTUPartIdx, UInt trMode );
+  
+  UChar*        getTransformIdx       ()                        { return m_puhTrIdx;          }
+  UChar         getTransformIdx       ( UInt uiIdx )            { return m_puhTrIdx[uiIdx];   }
+  Void          setTrIdxSubParts      ( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  UInt          getQuadtreeTULog2MinSizeInCU( UInt absPartIdx );
+  
+  TComCUMvField* getCUMvField         ( RefPicList e )          { return  &m_acCUMvField[e];  }
+  
+  TCoeff*&      getCoeffY             ()                        { return m_pcTrCoeffY;        }
+  TCoeff*&      getCoeffCb            ()                        { return m_pcTrCoeffCb;       }
+  TCoeff*&      getCoeffCr            ()                        { return m_pcTrCoeffCr;       }
+#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    );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for coding tool information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool*         getMergeFlag          ()                        { return m_pbMergeFlag;               }
+  Bool          getMergeFlag          ( UInt uiIdx )            { return m_pbMergeFlag[uiIdx];        }
+  Void          setMergeFlag          ( UInt uiIdx, Bool b )    { m_pbMergeFlag[uiIdx] = b;           }
+  Void          setMergeFlagSubParts  ( Bool bMergeFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+
+  UChar*        getMergeIndex         ()                        { return m_puhMergeIndex;                         }
+  UChar         getMergeIndex         ( UInt uiIdx )            { return m_puhMergeIndex[uiIdx];                  }
+  Void          setMergeIndex         ( UInt uiIdx, UInt uiMergeIndex ) { m_puhMergeIndex[uiIdx] = uiMergeIndex;  }
+  Void          setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+
+#if MERL_VSP_C0152
+  Char*         getVSPIndex        ()                        { return m_piVSPIndex;        }
+  Char          getVSPIndex        ( UInt uiIdx )            { return m_piVSPIndex[uiIdx]; }
+  Void          setVSPIndex        ( UInt uiIdx, Int n )     { m_piVSPIndex[uiIdx] = n;    }
+  Void          setVSPIndexSubParts( Char bVSPIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+#endif
+
+  template <typename T>
+  Void          setSubPart            ( T bParameter, T* pbBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
+
+#if LGE_ILLUCOMP_B0045
+  Bool*         getICFlag             ()                        { return m_pbICFlag;               }
+  Bool          getICFlag             ( UInt uiIdx )            { return m_pbICFlag[uiIdx];        }
+  Void          setICFlag             ( UInt uiIdx, Bool  uh )  { m_pbICFlag[uiIdx] = uh;          }
+  Void          setICFlagSubParts     ( Bool bICFlag,  UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+#if LGE_ILLUCOMP_DEPTH_C0046
+  Bool          isICFlagRequired      (UInt uiAbsPartIdx, UInt uiDepth); //This modification is not needed after integrating JCT3V-C0137
+#else
+  Bool          isICFlagRequired      (UInt uiAbsPartIdx);
+#endif
+#endif
+
+#if AMP_MRG
+  Void          setMergeAMP( Bool b )      { m_bIsMergeAMP = b; }
+  Bool          getMergeAMP( )             { return m_bIsMergeAMP; }
+#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*        getInterDir           ()                        { return m_puhInterDir;               }
+  UChar         getInterDir           ( UInt uiIdx )            { return m_puhInterDir[uiIdx];        }
+  Void          setInterDir           ( UInt uiIdx, UChar  uh ) { m_puhInterDir[uiIdx] = uh;          }
+  Void          setInterDirSubParts   ( UInt uiDir,  UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  
+  Bool*         getAlfCtrlFlag        ()                        { return m_puiAlfCtrlFlag;            }
+  Bool          getAlfCtrlFlag        ( UInt uiIdx )            { return m_puiAlfCtrlFlag[uiIdx];     }
+  Void          setAlfCtrlFlag        ( UInt uiIdx, Bool uiFlag){ m_puiAlfCtrlFlag[uiIdx] = uiFlag;   }
+  Void          setAlfCtrlFlagSubParts( Bool uiFlag, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void          createTmpAlfCtrlFlag  ();
+  Void          destroyTmpAlfCtrlFlag ();
+  Void          copyAlfCtrlFlagToTmp  ();
+  Void          copyAlfCtrlFlagFromTmp();
+  
+  Bool*         getIPCMFlag           ()                        { return m_pbIPCMFlag;               }
+  Bool          getIPCMFlag           (UInt uiIdx )             { return m_pbIPCMFlag[uiIdx];        }
+  Void          setIPCMFlag           (UInt uiIdx, Bool b )     { m_pbIPCMFlag[uiIdx] = b;           }
+  Void          setIPCMFlagSubParts   (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth);
+
+  Int           getNumSucIPCM         ()                        { return m_numSucIPCM;             }
+  Void          setNumSucIPCM         ( Int num )               { m_numSucIPCM = num;              }
+  Bool          getLastCUSucIPCMFlag  ()                        { return m_lastCUSucIPCMFlag;        }
+  Void          setLastCUSucIPCMFlag  ( Bool flg )              { m_lastCUSucIPCMFlag = flg;         }
+
+  /// get slice ID for SU
+  Int           getSUSliceID          (UInt uiIdx)              {return m_piSliceSUMap[uiIdx];      } 
+
+  /// get the pointer of slice ID map
+  Int*          getSliceSUMap         ()                        {return m_piSliceSUMap;             }
+
+  /// set the pointer of slice ID map
+  Void          setSliceSUMap         (Int *pi)                 {m_piSliceSUMap = pi;               }
+
+  std::vector<NDBFBlockInfo>* getNDBFilterBlocks()      {return &m_vNDFBlock;}
+  Void setNDBFilterBlockBorderAvailability(UInt numLCUInPicWidth, UInt numLCUInPicHeight, UInt numSUInLCUWidth, UInt numSUInLCUHeight, UInt picWidth, UInt picHeight
+                                          ,Bool bIndependentSliceBoundaryEnabled
+                                          ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
+                                          ,Bool bIndependentTileBoundaryEnabled );
+
+#if H3D_IVMP
+#if !H3D_NBDV
+  Int           getPdmMergeCandidate      ( UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv );
+  Bool          getPdmMvPred              ( UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv, Bool bMerge = false );
+#else //!H3D_NBDV
+  Bool          getUnifiedMvPredCan       ( UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* iPdm, Bool bMerge );
+  Void          getDisMvpCand        ( UInt uiPartIdx, UInt uiPartAddr, DisInfo* pDInfo );
+  Void          getDisMvpCandNBDV( UInt uiPartIdx, UInt uiPartAddr, DisInfo* pDInfo , Bool bParMerg = false
+#if MERL_VSP_C0152
+                              , Bool bDepthRefine = false
+#endif //MERL_VSP_C0152
+    );
+#endif // !H3D_NBDV
+
+
+
+#if MERL_VSP_C0152
+  Pel           getMcpFromDM(TComPicYuv* pcBaseViewDepthPicYuv, TComMv* mv, Int iBlkX, Int iBlkY, Int iWidth, Int iHeight, Int* aiShiftLUT, Int iShiftPrec, Bool bSimpleDvpRefine = false);
+  Void          estimateDVFromDM(UInt uiPartIdx, TComPic* picDepth, UInt uiPartAddr, TComMv* cMvPred, Bool bSimpleDvpRefine = false);
+#endif
+  Bool          getIViewOrgDepthMvPred( UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv );
+#endif //  H3D_IVMP 
+#if H3D_IVRP
+  Bool*         getResPredAvail         ()                        { return m_pbResPredAvailable;        }
+  Bool          getResPredAvail         ( UInt uiIdx )            { return m_pbResPredAvailable[uiIdx]; }
+  Void          setResPredAvail         ( UInt uiIdx, Bool b )    { m_pbResPredAvailable[uiIdx] = b;    }
+  Void          setResPredAvailSubParts ( Bool b, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+
+  Bool*         getResPredFlag          ()                        { return m_pbResPredFlag;        }
+  Bool          getResPredFlag          ( UInt uiIdx )            { return m_pbResPredFlag[uiIdx]; }
+  Void          setResPredFlag          ( UInt uiIdx, Bool b )    { m_pbResPredFlag[uiIdx] = b;    }
+  Void          setResPredFlagSubParts  ( Bool b, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+
+  Void          setResPredIndicator     ( Bool bAv, Bool bRP )    { m_pbResPredAvailable[0] = bAv; m_pbResPredFlag[0] = bRP; }
+#endif
+#if H3D_IVRP
+  Bool          getResidualSamples( UInt uiPartIdx, Bool bRecon, TComYuv* pcYuv = 0 );
+#endif
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for accessing partition information
+  // -------------------------------------------------------------------------------------------------------------------
+#if H3D_IVRP
+  Void          getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx = 0, Bool bLCU = false);
+#endif
+  UChar         getNumPartInter       ();
+  Bool          isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth);
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for motion vector
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          getMvField            ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField );
+  
+  AMVP_MODE     getAMVPMode           ( UInt uiIdx );
+#if H3D_IVMP
+  Void          fillMvpCandBase       ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo );
+  Void          fillMvpCand           ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo , Int iMVPIdx=-1);
+#endif
+  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];     }
+  Char*         getMVPIdx             ( RefPicList eRefPicList )                          { return m_apiMVPIdx[eRefPicList];            }
+
+  Void          setMVPNum             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPNum ) { m_apiMVPNum[eRefPicList][uiIdx] = iMVPNum;  }
+  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     );
+  Void          getMvPredLeft         ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldA.getMv(); }
+  Void          getMvPredAbove        ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldB.getMv(); }
+  Void          getMvPredAboveRight   ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldC.getMv(); }
+  
+  Void          compressMV            ();
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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*   getCUColocated              ( RefPicList eRefPicList ) { return m_apcCUColocated[eRefPicList]; }
+
+
+  TComDataCU*   getPULeft                   ( UInt&  uiLPartUnitIdx , UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true
+                                            , Bool bEnforceTileRestriction=true 
+                                            );
+
+  TComDataCU*   getPUAbove                  ( UInt&  uiAPartUnitIdx , UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true, Bool MotionDataCompresssion = false
+                                            , Bool planarAtLCUBoundary = false 
+                                            , Bool bEnforceTileRestriction=true 
+                                            );
+
+  TComDataCU*   getPUAboveLeft              ( UInt&  uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true, Bool MotionDataCompresssion = false );
+  TComDataCU*   getPUAboveRight             ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true, Bool MotionDataCompresssion = false );
+  TComDataCU*   getPUBelowLeft              ( UInt& uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+
+  TComDataCU*   getQpMinCuLeft              ( UInt&  uiLPartUnitIdx , UInt uiCurrAbsIdxInLCU, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+  TComDataCU*   getQpMinCuAbove             ( UInt&  aPartUnitIdx , UInt currAbsIdxInLCU, Bool enforceSliceRestriction=true, Bool enforceEntropySliceRestriction=true );
+  Char          getRefQP                    ( UInt   uiCurrAbsIdxInLCU                       );
+
+  TComDataCU*   getPUAboveRightAdi          ( UInt&  uiARPartUnitIdx, UInt uiPuWidth, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+  TComDataCU*   getPUBelowLeftAdi           ( UInt& uiBLPartUnitIdx, UInt uiPuHeight, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+  
+  Void          deriveLeftRightTopIdx       ( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
+  Void          deriveLeftBottomIdx         ( PartSize eCUMode, 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 );
+#if MERL_VSP_C0152
+  Void          getInterMergeCandidates     ( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int* uiVSPIndexTrue, Int mrgCandIdx = -1 );
+#else
+  Void          getInterMergeCandidates     ( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 );
+#endif
+  Void          deriveLeftRightTopIdxGeneral( PartSize eCUMode, UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
+  Void          deriveLeftBottomIdxGeneral  ( PartSize eCUMode, 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)
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for symbol prediction (most probable / mode conversion)
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          getIntraSizeIdx                 ( UInt uiAbsPartIdx                                       );
+  Void          convertTransIdx                 ( UInt uiAbsPartIdx, UInt uiTrIdx, UInt& ruiLumaTrMode, UInt& ruiChromaTrMode );
+  
+  Void          getAllowedChromaDir             ( UInt uiAbsPartIdx, UInt* uiModeList );
+  Int           getIntraDirLumaPredictor        ( UInt uiAbsPartIdx, Int* uiIntraDirPred, Int* piMode = NULL );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for SBAC context
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          getCtxSplitFlag                 ( UInt   uiAbsPartIdx, UInt uiDepth                   );
+  UInt          getCtxQtCbf                     ( UInt   uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+
+  UInt          getCtxSkipFlag                  ( UInt   uiAbsPartIdx                                 );
+#if LGE_ILLUCOMP_B0045
+  UInt          getCtxICFlag                    ( UInt   uiAbsPartIdx                                 );
+#endif
+  UInt          getCtxInterDir                  ( UInt   uiAbsPartIdx                                 );
+
+#if H3D_IVRP
+  UInt          getCtxResPredFlag               ( UInt   uiAbsPartIdx                                 );
+#endif
+  
+  UInt          getSliceStartCU         ( UInt pos )                  { return m_uiSliceStartCU[pos-m_uiAbsIdxInLCU];                                                                                          }
+  UInt          getEntropySliceStartCU  ( UInt pos )                  { return m_uiEntropySliceStartCU[pos-m_uiAbsIdxInLCU];                                                                                   }
+  UInt&         getTotalBins            ()                            { return m_uiTotalBins;                                                                                                  }
+
+#if LGE_EDGE_INTRA_A0070
+  UInt          getCtxEdgeIntra ( UInt uiAbsPartIdx );
+#endif
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for RD cost storage
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Double&       getTotalCost()                  { return m_dTotalCost;        }
+  Dist&         getTotalDistortion()            { return m_uiTotalDistortion; }
+  UInt&         getTotalBits()                  { return m_uiTotalBits;       }
+  UInt&         getTotalNumPart()               { return m_uiNumPartition;    }
+
+  UInt          getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra);
+
+  Bool          useNonSquareTrans( UInt uiTrMode, Int absPartIdx );
+  Void          getNSQTSize(Int trMode, Int absPartIdx, Int &trWidth, Int &trHeight);
+  Bool          useNonSquarePU   ( UInt absPartIdx);
+  UInt          getInterTUSplitDirection ( Int width, Int height, Int trLastWidth, Int trLastHeight );
+  UInt          getNSAbsPartIdx  ( UInt log2TrafoSize, UInt absPartIdx, UInt absTUPartIdx, UInt innerQuadIdx, UInt trMode );
+  UInt          getNSAddrChroma   ( UInt uiLog2TrSizeC, UInt uiTrModeC, UInt uiQuadrant, UInt absTUPartIdx );
+  
+// -------------------------------------------------------------------------------------------------------------------
+  // member functions for depth model modes
+  // -------------------------------------------------------------------------------------------------------------------
+#if HHI_DMM_WEDGE_INTRA
+  UInt* getWedgeFullTabIdx                ()                      { return m_puiWedgeFullTabIdx;              }
+  UInt  getWedgeFullTabIdx                ( UInt uiIdx )          { return m_puiWedgeFullTabIdx[uiIdx];       }
+  Void  setWedgeFullTabIdx                ( UInt uiIdx, UInt uh ) { m_puiWedgeFullTabIdx[uiIdx] = uh;         }
+  Void  setWedgeFullTabIdxSubParts        ( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth );
+  Int*  getWedgeFullDeltaDC1              ()                      { return m_piWedgeFullDeltaDC1;             }
+  Int   getWedgeFullDeltaDC1              ( UInt uiIdx )          { return m_piWedgeFullDeltaDC1[uiIdx];      }
+  Void  setWedgeFullDeltaDC1              ( UInt uiIdx, Int i )   { m_piWedgeFullDeltaDC1[uiIdx] = i;         }
+  Void  setWedgeFullDeltaDC1SubParts      ( Int iDC1, UInt uiAbsPartIdx, UInt uiDepth );
+  Int*  getWedgeFullDeltaDC2              ()                      { return m_piWedgeFullDeltaDC2;             }
+  Int   getWedgeFullDeltaDC2              ( UInt uiIdx )          { return m_piWedgeFullDeltaDC2[uiIdx];      }
+  Void  setWedgeFullDeltaDC2              ( UInt uiIdx, Int i )   { m_piWedgeFullDeltaDC2[uiIdx] = i;         }
+  Void  setWedgeFullDeltaDC2SubParts      ( Int iDC2, UInt uiAbsPartIdx, UInt uiDepth );
+
+  UInt* getWedgePredDirTabIdx             ()                      { return m_puiWedgePredDirTabIdx;           }
+  UInt  getWedgePredDirTabIdx             ( UInt uiIdx )          { return m_puiWedgePredDirTabIdx[uiIdx];    }
+  Void  setWedgePredDirTabIdx             ( UInt uiIdx, UInt uh ) { m_puiWedgePredDirTabIdx[uiIdx] = uh;      }
+  Void  setWedgePredDirTabIdxSubParts     ( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth );
+  Int*  getWedgePredDirDeltaDC1           ()                      { return m_piWedgePredDirDeltaDC1;          }
+  Int   getWedgePredDirDeltaDC1           ( UInt uiIdx )          { return m_piWedgePredDirDeltaDC1[uiIdx];   }
+  Void  setWedgePredDirDeltaDC1           ( UInt uiIdx, Int i )   { m_piWedgePredDirDeltaDC1[uiIdx] = i;      }
+  Void  setWedgePredDirDeltaDC1SubParts   ( Int iDC1, UInt uiAbsPartIdx, UInt uiDepth );
+  Int*  getWedgePredDirDeltaDC2           ()                      { return m_piWedgePredDirDeltaDC2;          }
+  Int   getWedgePredDirDeltaDC2           ( UInt uiIdx )          { return m_piWedgePredDirDeltaDC2[uiIdx];   }
+  Void  setWedgePredDirDeltaDC2           ( UInt uiIdx, Int i )   { m_piWedgePredDirDeltaDC2[uiIdx] = i;      }
+  Void  setWedgePredDirDeltaDC2SubParts   ( Int iDC2, UInt uiAbsPartIdx, UInt uiDepth );
+  Int*  getWedgePredDirDeltaEnd           ()                      { return m_piWedgePredDirDeltaEnd;          }
+  Int   getWedgePredDirDeltaEnd           ( UInt uiIdx )          { return m_piWedgePredDirDeltaEnd[uiIdx];   }
+  Void  setWedgePredDirDeltaEnd           ( UInt uiIdx, Int iD )  { m_piWedgePredDirDeltaEnd[uiIdx] = iD;     }
+  Void  setWedgePredDirDeltaEndSubParts   ( Int iDelta, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if HHI_DMM_PRED_TEX
+  UInt* getWedgePredTexTabIdx             ()                      { return m_puiWedgePredTexTabIdx;           }
+  UInt  getWedgePredTexTabIdx             ( UInt uiIdx )          { return m_puiWedgePredTexTabIdx[uiIdx];    }
+  Void  setWedgePredTexTabIdx             ( UInt uiIdx, UInt uh ) { m_puiWedgePredTexTabIdx[uiIdx] = uh;      }
+  Void  setWedgePredTexTabIdxSubParts     ( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth );
+#if LGE_DMM3_SIMP_C0044
+  UInt* getWedgePredTexIntraTabIdx             ()                      { return m_puiWedgePredTexIntraTabIdx;           }
+  UInt  getWedgePredTexIntraTabIdx             ( UInt uiIdx )          { return m_puiWedgePredTexIntraTabIdx[uiIdx];    }
+  Void  setWedgePredTexIntraTabIdx             ( UInt uiIdx, UInt uh ) { m_puiWedgePredTexIntraTabIdx[uiIdx] = uh;      }
+  Void  setWedgePredTexIntraTabIdxSubParts     ( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth );
+#endif 
+  Int*  getWedgePredTexDeltaDC1           ()                      { return m_piWedgePredTexDeltaDC1;          }
+  Int   getWedgePredTexDeltaDC1           ( UInt uiIdx )          { return m_piWedgePredTexDeltaDC1[uiIdx];   }
+  Void  setWedgePredTexDeltaDC1           ( UInt uiIdx, Int i )   { m_piWedgePredTexDeltaDC1[uiIdx] = i;      }
+  Void  setWedgePredTexDeltaDC1SubParts   ( Int iDC1, UInt uiAbsPartIdx, UInt uiDepth );
+  Int*  getWedgePredTexDeltaDC2           ()                      { return m_piWedgePredTexDeltaDC2;          }
+  Int   getWedgePredTexDeltaDC2           ( UInt uiIdx )          { return m_piWedgePredTexDeltaDC2[uiIdx];   }
+  Void  setWedgePredTexDeltaDC2           ( UInt uiIdx, Int i )   { m_piWedgePredTexDeltaDC2[uiIdx] = i;      }
+  Void  setWedgePredTexDeltaDC2SubParts   ( Int iDC2, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Int*  getContourPredTexDeltaDC1         ()                      { return m_piContourPredTexDeltaDC1;        }
+  Int   getContourPredTexDeltaDC1         ( UInt uiIdx )          { return m_piContourPredTexDeltaDC1[uiIdx]; }
+  Void  setContourPredTexDeltaDC1         ( UInt uiIdx, Int i )   { m_piContourPredTexDeltaDC1[uiIdx] = i;    }
+  Void  setContourPredTexDeltaDC1SubParts ( Int iDC1, UInt uiAbsPartIdx, UInt uiDepth );
+  Int*  getContourPredTexDeltaDC2         ()                      { return m_piContourPredTexDeltaDC2;        }
+  Int   getContourPredTexDeltaDC2         ( UInt uiIdx )          { return m_piContourPredTexDeltaDC2[uiIdx]; }
+  Void  setContourPredTexDeltaDC2         ( UInt uiIdx, Int i )   { m_piContourPredTexDeltaDC2[uiIdx] = i;    }
+  Void  setContourPredTexDeltaDC2SubParts ( Int iDC2, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+  UChar*        getEdgeCode( UInt uiIdx )                 { return &m_pucEdgeCode[uiIdx * LGE_EDGE_INTRA_MAX_EDGE_NUM_PER_4x4]; }
+  UChar*        getEdgeNumber( )                          { return m_pucEdgeNumber;           }
+  UChar         getEdgeNumber( UInt uiIdx )               { return m_pucEdgeNumber[uiIdx];    }
+  Void          setEdgeNumber( UInt uiIdx, UChar val )    { m_pucEdgeNumber[uiIdx] = val;     }
+  UChar*        getEdgeStartPos( )                        { return m_pucEdgeStartPos;         }
+  UChar         getEdgeStartPos( UInt uiIdx )             { return m_pucEdgeStartPos[uiIdx];  }
+  Void          setEdgeStartPos( UInt uiIdx, UChar val )  { m_pucEdgeStartPos[uiIdx] = val;   }
+  Bool*         getEdgeLeftFirst( )                       { return m_pbEdgeLeftFirst;         }
+  Bool          getEdgeLeftFirst( UInt uiIdx )            { return m_pbEdgeLeftFirst[uiIdx];  }
+  Void          setEdgeLeftFirst( UInt uiIdx, Bool val )  { m_pbEdgeLeftFirst[uiIdx] = val;   }
+  Bool*         getEdgePartition( UInt uiIdx )              { return &m_pbEdgePartition[uiIdx * 16]; }
+  Void          reconPartition( UInt uiAbsPartIdx, UInt uiDepth, Bool bLeft, UChar ucStartPos, UChar ucNumEdge, UChar* pucEdgeCode, Bool* pbRegion );
+
+#if LGE_EDGE_INTRA_DELTA_DC
+  Int*          getEdgeDeltaDC0( )                          { return m_piEdgeDeltaDC0; }
+  Int*          getEdgeDeltaDC1( )                          { return m_piEdgeDeltaDC1; }
+  Int           getEdgeDeltaDC0( UInt uiIdx )               { return m_piEdgeDeltaDC0[uiIdx]; }
+  Int           getEdgeDeltaDC1( UInt uiIdx )               { return m_piEdgeDeltaDC1[uiIdx]; }
+  Void          setEdgeDeltaDC0( UInt uiIdx, Int val )      { m_piEdgeDeltaDC0[uiIdx] = val;  }
+  Void          setEdgeDeltaDC1( UInt uiIdx, Int val )      { m_piEdgeDeltaDC1[uiIdx] = val;  }
+#endif
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  Bool*         getSDCFlag          ()                        { return m_pbSDCFlag;               }
+  Bool          getSDCFlag          ( UInt uiIdx )            { return m_pbSDCFlag[uiIdx];        }
+  Void          setSDCFlagSubParts  ( Bool bSDCFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  
+  UInt          getCtxSDCFlag              ( UInt uiAbsPartIdx );
+  
+  Bool          getSDCAvailable             ( UInt uiAbsPartIdx );
+  
+  Pel*          getSDCSegmentDCOffset( UInt uiSeg ) { return m_apSegmentDCOffset[uiSeg]; }
+  Pel           getSDCSegmentDCOffset( UInt uiSeg, UInt uiPartIdx ) { return m_apSegmentDCOffset[uiSeg][uiPartIdx]; }
+  Void          setSDCSegmentDCOffset( Pel pOffset, UInt uiSeg, UInt uiPartIdx) { m_apSegmentDCOffset[uiSeg][uiPartIdx] = pOffset; }
+ 
+
+#endif
+};
+
+namespace RasterAddress
+{
+  /** Check whether 2 addresses point to the same column
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualCol( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    // addrA % numUnitsPerRow == addrB % numUnitsPerRow
+    return (( addrA ^ addrB ) &  ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether 2 addresses point to the same row
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualRow( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    // addrA / numUnitsPerRow == addrB / numUnitsPerRow
+    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
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualRowOrCol( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    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
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isZeroCol( Int addr, Int numUnitsPerRow )
+  {
+    // addr % numUnitsPerRow == 0
+    return ( addr & ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether one address points to the first row
+   * \param addr           Address in raster scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isZeroRow( Int addr, Int numUnitsPerRow )
+  {
+    // addr / numUnitsPerRow == 0
+    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
+   * \param val            Given column index value
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool lessThanCol( Int addr, Int val, Int numUnitsPerRow )
+  {
+    // addr % numUnitsPerRow < val
+    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
+   * \param val            Given row index value
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool lessThanRow( Int addr, Int val, Int numUnitsPerRow )
+  {
+    // addr / numUnitsPerRow < val
+    return addr < val * numUnitsPerRow;
+  }
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDepthMapGenerator.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDepthMapGenerator.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDepthMapGenerator.cpp	(revision 341)
@@ -0,0 +1,1660 @@
+/* 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-2011, 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 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     TComDepthMapGenerator.cpp
+    \brief    depth map generator class
+*/
+
+
+
+#include "CommonDef.h"
+#include "TComDepthMapGenerator.h"
+
+
+#if DEPTH_MAP_GENERATION
+
+TComDepthMapGenerator::TComDepthMapGenerator()
+{
+  m_bCreated            = false;
+  m_bInit               = false;
+  m_bDecoder            = false;
+  m_pcPrediction        = 0;
+  m_pcSPSAccess         = 0;
+  m_pcAUPicAccess       = 0;
+  m_uiMaxDepth          = 0;
+  m_uiOrgDepthBitDepth  = 0;
+  m_uiSubSampExpX       = 0;
+  m_uiSubSampExpY       = 0;
+  m_ppcYuv              = 0;
+  m_ppcCU               = 0;
+}
+
+TComDepthMapGenerator::~TComDepthMapGenerator()
+{
+  destroy ();
+  uninit  ();
+}
+
+Void
+TComDepthMapGenerator::create( Bool bDecoder, UInt uiPicWidth, UInt uiPicHeight, UInt uiMaxCUDepth, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiOrgBitDepth, UInt uiSubSampExpX, UInt uiSubSampExpY )
+{
+  destroy();
+  m_bDecoder            = bDecoder;
+  m_uiMaxDepth          = uiMaxCUDepth;
+  m_uiOrgDepthBitDepth  = uiOrgBitDepth;
+  m_uiSubSampExpX       = uiSubSampExpX;
+  m_uiSubSampExpY       = uiSubSampExpY;
+#if !H3D_NBDV
+  m_ppcYuv              = new TComYuv*    [ m_uiMaxDepth ];
+  m_ppcCU               = new TComDataCU* [ m_uiMaxDepth ];
+  for( UInt uiDepth = 0; uiDepth < m_uiMaxDepth; uiDepth++ )
+  {
+    UInt  uiNumPart = 1 << ( ( m_uiMaxDepth - uiDepth ) << 1 );
+    UInt  uiWidth   = uiMaxCUWidth  >> uiDepth;
+    UInt  uiHeight  = uiMaxCUHeight >> uiDepth;
+
+    m_ppcYuv[ uiDepth ] = new TComYuv;    m_ppcYuv[ uiDepth ]->create( uiWidth >> m_uiSubSampExpX, uiHeight >> m_uiSubSampExpY );
+    m_ppcCU [ uiDepth ] = new TComDataCU; m_ppcCU [ uiDepth ]->create( uiNumPart, uiWidth, uiHeight, true, uiMaxCUWidth >> (uiMaxCUDepth - 1) );
+  }
+  m_cTmpPic.create( uiPicWidth >> m_uiSubSampExpX, uiPicHeight >> m_uiSubSampExpY, uiMaxCUWidth >> m_uiSubSampExpX, uiMaxCUHeight >> m_uiSubSampExpY, uiMaxCUDepth );
+  xSetChroma( &m_cTmpPic, ( 1 << uiOrgBitDepth ) >> 1 );
+#endif //!H3D_NBDV
+  m_bCreated    = true;
+}
+
+Void
+TComDepthMapGenerator::destroy()
+{
+  if( m_bCreated )
+  {
+    m_bCreated    = false;
+#if !H3D_NBDV
+    for( UInt uiDepth = 0; uiDepth < m_uiMaxDepth; uiDepth++ )
+    {
+      if( m_ppcYuv[ uiDepth ] )
+      {
+        m_ppcYuv[ uiDepth ]->destroy(); delete m_ppcYuv[ uiDepth ]; m_ppcYuv[ uiDepth ] = 0;
+      }
+      if( m_ppcCU [ uiDepth ] )
+      {
+        m_ppcCU [ uiDepth ]->destroy(); delete m_ppcCU [ uiDepth ]; m_ppcCU [ uiDepth ] = 0;
+      }
+    }
+    delete [] m_ppcYuv; m_ppcYuv = 0;
+    delete [] m_ppcCU;  m_ppcCU  = 0;
+    m_cTmpPic.destroy();
+#endif //!H3D_NBDV
+    m_uiMaxDepth          = 0;
+    m_uiOrgDepthBitDepth  = 0;
+    m_uiSubSampExpX       = 0;
+    m_uiSubSampExpY       = 0;
+    m_bDecoder            = false;
+  }
+}
+
+#if VIDYO_VPS_INTEGRATION
+Void
+TComDepthMapGenerator::init( TComPrediction* pcPrediction, TComVPSAccess* pcVPSAccess, TComSPSAccess* pcSPSAccess, TComAUPicAccess* pcAUPicAccess )
+#else
+Void
+TComDepthMapGenerator::init( TComPrediction* pcPrediction, TComSPSAccess* pcSPSAccess, TComAUPicAccess* pcAUPicAccess )
+#endif
+{
+  AOF( pcPrediction  );
+  AOF( pcSPSAccess   );
+  AOF( pcAUPicAccess );
+  uninit();
+  m_pcPrediction  = pcPrediction;
+#if VIDYO_VPS_INTEGRATION
+  m_pcVPSAccess   = pcVPSAccess;
+#endif
+  m_pcSPSAccess   = pcSPSAccess;
+  m_pcAUPicAccess = pcAUPicAccess;
+  m_bInit         = true;
+}
+
+Void
+TComDepthMapGenerator::uninit()
+{
+  if( m_bInit )
+  {
+    m_bInit         = false;
+    m_pcPrediction  = 0;
+    m_pcSPSAccess   = 0;
+    m_pcAUPicAccess = 0;
+  }
+}
+
+Void  
+TComDepthMapGenerator::initViewComponent( TComPic* pcPic )
+{
+  AOF  ( m_bCreated && m_bInit );
+  AOF  ( pcPic );
+  AOT  ( pcPic->getSPS()->getViewId() && !pcPic->getSPS()->isDepth() && pcPic->getPOC() && pcPic->getSPS()->getPredDepthMapGeneration() != m_pcSPSAccess->getPdm() );
+  m_bPDMAvailable = false;
+  m_uiCurrViewId  = pcPic->getSPS()->getViewId();
+#if PDM_REMOVE_DEPENDENCE
+  pcPic->setStoredPDMforV2(0);
+#endif
+  // update SPS list and AU pic list and set depth map generator in SPS
+#if VIDYO_VPS_INTEGRATION
+  m_pcVPSAccess  ->addVPS( pcPic->getVPS() );
+#endif
+  m_pcSPSAccess  ->addSPS( pcPic->getSPS() );
+  m_pcAUPicAccess->addPic( pcPic );
+  pcPic->getSPS()->setDepthMapGenerator( this );
+
+  // check whether we have depth data or don't use pred depth prediction
+  ROFVS( pcPic->getSPS()->getViewId() );
+  ROTVS( pcPic->getSPS()->isDepth  () );
+  ROFVS( m_pcSPSAccess->getPdm     () );
+
+  // set basic SPS parameters
+  const Int iDisparityDir = 1; // 1 or -1, depending on the usage of disparity vectors
+  TComSPS*  pcSPS         = pcPic->getSPS                 ();
+  Int       iVOI          = pcSPS->getViewOrderIdx        ();
+  UInt      uiPdmPrec     = pcSPS->getPdmPrecision        ();
+  UInt      uiCamPrec     = pcSPS->getCamParPrecision     ();
+  Bool      bInSlice      = pcSPS->hasCamParInSliceHeader ();
+  Int       iScaleVOI01   = ( 1 << ( uiPdmPrec + PDM_INTER_CALC_SHIFT + PDM_VIRT_DEPTH_PRECISION - 2 ) );
+
+  // check availability of base views and set base id list
+  std::vector<Int>  aiAbsDeltaVOI;
+  for( UInt uiBaseId = 0; uiBaseId < m_uiCurrViewId; uiBaseId++ )
+  {
+    TComSPS*  pcBaseSPS     = m_pcSPSAccess  ->getSPS( uiBaseId );
+    TComPic*  pcBasePic     = m_pcAUPicAccess->getPic( uiBaseId );
+    AOF( pcBaseSPS != 0 && pcBasePic != 0 );
+    Int       iDeltaVOI     = iVOI - pcBaseSPS->getViewOrderIdx();
+    Int       iAbsDeltaVOI  = ( iDeltaVOI < 0 ? -iDeltaVOI : iDeltaVOI ); 
+    AOT( iAbsDeltaVOI == 0 );
+    aiAbsDeltaVOI.push_back( iAbsDeltaVOI );
+  }
+  m_auiBaseIdList.clear();
+  while( (UInt)m_auiBaseIdList.size() < m_uiCurrViewId )
+  {
+    Int       iMinAbsDelta  = MAX_INT;
+    UInt      uiNextBaseId  = MAX_VIEW_NUM;
+    for( UInt uiBaseId = 0; uiBaseId < m_uiCurrViewId; uiBaseId++ )
+    {
+      if( aiAbsDeltaVOI[ uiBaseId ] > 0 && aiAbsDeltaVOI[ uiBaseId ] <= iMinAbsDelta )
+      {
+        iMinAbsDelta  = aiAbsDeltaVOI[ uiBaseId ];
+        uiNextBaseId  = uiBaseId;
+      }
+    }
+    m_auiBaseIdList.push_back( uiNextBaseId );
+    aiAbsDeltaVOI[ uiNextBaseId ] = 0;
+  }
+
+  // check availability of prediction depth map
+  if( m_uiCurrViewId )
+  {
+#if PDM_REMOVE_DEPENDENCE
+    UInt      uiBaseVId   = m_auiBaseIdList[0];
+#else
+    Bool      bCheckVId1  = ( m_uiCurrViewId > 1 && m_auiBaseIdList[0] == 0 );
+    UInt      uiBaseVId   = ( bCheckVId1 ? 1 : m_auiBaseIdList[0] );
+#endif
+    TComPic*  pcBasePic   = m_pcAUPicAccess->getPic( uiBaseVId );
+    SliceType eSliceType  = pcBasePic->getCurrSlice()->getSliceType();
+    Bool      bNoRAPdm    = ( pcPic->getSPS()->getPredDepthMapGeneration() == 1 );
+    m_bPDMAvailable       = ( eSliceType != I_SLICE || !bNoRAPdm );
+  }
+
+  // update disparity depth conversion parameters
+  for( UInt uiBaseId = 0; uiBaseId < m_uiCurrViewId; uiBaseId++ )
+  {
+    TComSPS*  pcBaseSPS   = m_pcSPSAccess->getSPS( uiBaseId );
+    Int       iBaseVOI    = pcBaseSPS->getViewOrderIdx();
+
+    // disparity -> virtual depth
+    Int       iVNominator = ( 1 << PDM_LOG4_SCALE_DENOMINATOR ) + pcSPS->getPdmScaleNomDelta()[ uiBaseId ];
+    Int       iVDiv       = iVOI - iBaseVOI;
+    Int       iVAdd       = ( iVDiv > 0 ? iVDiv / 2 : -iVDiv / 2 );
+    Int       iVScalePred = ( iScaleVOI01 + iVAdd ) / iVDiv;
+    Int       iVShift     = PDM_INTER_CALC_SHIFT;
+    Int       iVScale     = Int( ( (Int64)iVNominator * (Int64)iVScalePred + (Int64)( ( 1 << PDM_LOG4_SCALE_DENOMINATOR ) >> 1 ) ) >> PDM_LOG4_SCALE_DENOMINATOR );
+    Int       iVOffset    = pcSPS->getPdmOffset()[ uiBaseId ] << PDM_OFFSET_SHIFT;
+    m_aaiConvParsDisparity2VirtDepth[ uiBaseId ][ 0 ] = iDisparityDir * iVScale;
+    m_aaiConvParsDisparity2VirtDepth[ uiBaseId ][ 1 ] = iDisparityDir * iVOffset + ( ( 1 << iVShift ) >> 1 );
+    m_aaiConvParsDisparity2VirtDepth[ uiBaseId ][ 2 ] = iVShift;
+
+    // virtual depth -> disparity
+    Int       iVInvAdd    = ( iVScale > 0 ? iVScale / 2 : -iVScale / 2 );
+    Int       iVInvScale  = Int( ( ( Int64(  1        ) << ( iVShift << 1 ) ) + iVInvAdd ) / Int64( iVScale ) );
+    Int       iVInvOffset = Int( ( ( Int64( -iVOffset ) <<   iVShift        ) + iVInvAdd ) / Int64( iVScale ) );
+    m_aaiConvParsVirtDepth2Disparity[ uiBaseId ][ 0 ] = iDisparityDir * iVInvScale;
+    m_aaiConvParsVirtDepth2Disparity[ uiBaseId ][ 1 ] = iDisparityDir * iVInvOffset + ( ( 1 << iVShift ) >> 1 );
+    m_aaiConvParsVirtDepth2Disparity[ uiBaseId ][ 2 ] = iVShift;
+
+    // coded depth -> virtual depth
+    Int       iCScale     = ( bInSlice ? pcPic->getCurrSlice()->getCodedScale () : pcSPS->getCodedScale () )[ uiBaseId ];
+    Int       iCOffset    = ( bInSlice ? pcPic->getCurrSlice()->getCodedOffset() : pcSPS->getCodedOffset() )[ uiBaseId ] << m_uiOrgDepthBitDepth;
+    Int       iCShift     = m_uiOrgDepthBitDepth + uiCamPrec + 1 - 2;
+    Int       iCVShift    = PDM_INTER_CALC_SHIFT;
+    Int       iTmpShift   = iVShift + iCShift - iCVShift; AOF( iTmpShift >= 0 )
+    Int       iCVScale    = Int( ( Int64( iVScale ) * Int64( iCScale  ) + Int64( ( 1 << iTmpShift ) >> 1 ) ) >> iTmpShift );
+    Int       iCVOffset   = Int( ( Int64( iVScale ) * Int64( iCOffset ) + Int64( ( 1 << iTmpShift ) >> 1 ) ) >> iTmpShift );
+    iTmpShift             = iVShift - iCVShift;           AOF( iTmpShift >= 0 )
+    iCVOffset            +=      ( iVOffset                             +      ( ( 1 << iTmpShift ) >> 1 ) ) >> iTmpShift;
+    m_aaiConvParsOrigDepth2VirtDepth[ uiBaseId ][ 0 ] = iCVScale;
+    m_aaiConvParsOrigDepth2VirtDepth[ uiBaseId ][ 1 ] = iCVOffset + ( ( 1 << iCVShift ) >> 1 );
+    m_aaiConvParsOrigDepth2VirtDepth[ uiBaseId ][ 2 ] = iCVShift;
+
+    // virtual depth -> coded depth
+    Int       iCVAdd      = ( iCVScale > 0 ? iCVScale / 2 : -iCVScale / 2 );
+    Int       iCVInvScale = Int( ( ( Int64(  1         ) << ( iCVShift << 1 ) ) + iCVAdd ) / Int64( iCVScale ) );
+    Int       iCVInvOffset= Int( ( ( Int64( -iCVOffset ) <<   iCVShift        ) + iCVAdd ) / Int64( iCVScale ) );
+    m_aaiConvParsVirtDepth2OrigDepth[ uiBaseId ][ 0 ] = iCVInvScale;
+    m_aaiConvParsVirtDepth2OrigDepth[ uiBaseId ][ 1 ] = iCVInvOffset + ( ( 1 << iCVShift ) >> 1 );
+    m_aaiConvParsVirtDepth2OrigDepth[ uiBaseId ][ 2 ] = iCVShift;
+  }
+
+  if( m_uiCurrViewId > 0 )
+  {
+    UInt      uiBaseId    = 0;
+    UInt      uiBaseVOI   = 0; // per definition
+    Int       iVNominator = ( 1 << PDM_LOG4_SCALE_DENOMINATOR ) + pcSPS->getPdmScaleNomDelta()[ uiBaseId ];
+    Int       iVDiv       = iVOI - uiBaseVOI;
+    Int       iVAdd       = ( iVDiv > 0 ? iVDiv / 2 : -iVDiv / 2 );
+    Int       iVScalePred = ( iScaleVOI01 + iVAdd ) / iVDiv;
+    Int       iVShift     = PDM_INTER_CALC_SHIFT;
+    Int       iVScale     = Int( ( (Int64)iVNominator * (Int64)iVScalePred + (Int64)( ( 1 << PDM_LOG4_SCALE_DENOMINATOR ) >> 1 ) ) >> PDM_LOG4_SCALE_DENOMINATOR );
+    Int       iVOffset    = pcSPS->getPdmOffset()[ uiBaseId ] << PDM_OFFSET_SHIFT;
+
+    // coded depth -> virtual depth (current view)
+    Int       iCScale     = ( bInSlice ? pcPic->getCurrSlice()->getInvCodedScale () : pcSPS->getInvCodedScale () )[ uiBaseId ];
+    Int       iCOffset    = ( bInSlice ? pcPic->getCurrSlice()->getInvCodedOffset() : pcSPS->getInvCodedOffset() )[ uiBaseId ] << m_uiOrgDepthBitDepth;
+    Int       iCShift     = m_uiOrgDepthBitDepth + uiCamPrec + 1 - 2;
+    Int       iCVShift    = PDM_INTER_CALC_SHIFT;
+    Int       iTmpShift   = iVShift + iCShift - iCVShift; AOF( iTmpShift >= 0 )
+    Int       iCVScale    = Int( ( Int64( -iVScale ) * Int64( iCScale  ) + Int64( ( 1 << iTmpShift ) >> 1 ) ) >> iTmpShift );
+    Int       iCVOffset   = Int( ( Int64( -iVScale ) * Int64( iCOffset ) + Int64( ( 1 << iTmpShift ) >> 1 ) ) >> iTmpShift );
+    iTmpShift             = iVShift - iCVShift;           AOF( iTmpShift >= 0 )
+    iCVOffset            +=      ( iVOffset                             +      ( ( 1 << iTmpShift ) >> 1 ) ) >> iTmpShift;
+    m_aaiConvParsOrigDepth2VirtDepth[ m_uiCurrViewId ][ 0 ] = iCVScale;
+    m_aaiConvParsOrigDepth2VirtDepth[ m_uiCurrViewId ][ 1 ] = iCVOffset + ( ( 1 << iCVShift ) >> 1 );
+    m_aaiConvParsOrigDepth2VirtDepth[ m_uiCurrViewId ][ 2 ] = iCVShift;
+
+    // virtual depth -> coded depth
+    Int       iCVAdd      = ( iCVScale > 0 ? iCVScale / 2 : -iCVScale / 2 );
+    Int       iCVInvScale = Int( ( ( Int64(  1         ) << ( iCVShift << 1 ) ) + iCVAdd ) / Int64( iCVScale ) );
+    Int       iCVInvOffset= Int( ( ( Int64( -iCVOffset ) <<   iCVShift        ) + iCVAdd ) / Int64( iCVScale ) );
+    m_aaiConvParsVirtDepth2OrigDepth[ m_uiCurrViewId ][ 0 ] = iCVInvScale;
+    m_aaiConvParsVirtDepth2OrigDepth[ m_uiCurrViewId ][ 1 ] = iCVInvOffset + ( ( 1 << iCVShift ) >> 1 );
+    m_aaiConvParsVirtDepth2OrigDepth[ m_uiCurrViewId ][ 2 ] = iCVShift;
+  }
+  else if( pcPic->getPOC() == 0 )
+  { // set dummy values
+    m_aaiConvParsOrigDepth2VirtDepth[ m_uiCurrViewId ][ 0 ] = 0;
+    m_aaiConvParsOrigDepth2VirtDepth[ m_uiCurrViewId ][ 1 ] = 0;
+    m_aaiConvParsOrigDepth2VirtDepth[ m_uiCurrViewId ][ 2 ] = 0;
+    m_aaiConvParsVirtDepth2OrigDepth[ m_uiCurrViewId ][ 0 ] = 0;
+    m_aaiConvParsVirtDepth2OrigDepth[ m_uiCurrViewId ][ 1 ] = 0;
+    m_aaiConvParsVirtDepth2OrigDepth[ m_uiCurrViewId ][ 2 ] = 0;
+  }
+
+
+#if 0 // print out for debugging
+  if( m_uiCurrViewId )
+  {
+    printf( "\n\ninit slice of view %d (VOI=%2d):\n===============================\n", m_uiCurrViewId, iVOI );
+    {
+      printf( "\n  disparity -> virtual depth:\n" );
+      for( UInt uiBaseId = 0; uiBaseId < m_uiCurrViewId; uiBaseId++ )
+      {
+        Int*    pP = m_aaiConvParsDisparity2VirtDepth[ uiBaseId ];
+        Double  dF = 1.0 / Double( 1 << pP[ 2 ] );
+        Double  dA = dF  * Double( pP[ 0 ] );
+        Double  dB = dF  * Double( pP[ 1 ] - ( ( 1 << pP[ 2 ] ) >> 1 ) );
+        printf( "    BId=%d:    a = %10.4lf    b = %10.4lf\n", uiBaseId, dA, dB );
+      }
+      printf( "\n  virtual depth -> disparity:\n" );
+      for( UInt uiBaseId = 0; uiBaseId < m_uiCurrViewId; uiBaseId++ )
+      {
+        Int*    pP = m_aaiConvParsVirtDepth2Disparity[ uiBaseId ];
+        Double  dF = 1.0 / Double( 1 << pP[ 2 ] );
+        Double  dA = dF  * Double( pP[ 0 ] );
+        Double  dB = dF  * Double( pP[ 1 ] - ( ( 1 << pP[ 2 ] ) >> 1 ) );
+        printf( "    BId=%d:    a = %10.4lf    b = %10.4lf\n", uiBaseId, dA, dB );
+      }
+      printf( "\n  original depth -> virtual depth:\n" );
+      for( UInt uiBaseId = 0; uiBaseId <= m_uiCurrViewId; uiBaseId++ )
+      {
+        Int*    pP = m_aaiConvParsOrigDepth2VirtDepth[ uiBaseId ];
+        Double  dF = 1.0 / Double( 1 << pP[ 2 ] );
+        Double  dA = dF  * Double( pP[ 0 ] );
+        Double  dB = dF  * Double( pP[ 1 ] - ( ( 1 << pP[ 2 ] ) >> 1 ) );
+        printf( "    VId=%d:    a = %10.4lf    b = %10.4lf\n", uiBaseId, dA, dB );
+      }
+      printf( "\n  virtual depth -> original depth:\n" );
+      for( UInt uiBaseId = 0; uiBaseId <= m_uiCurrViewId; uiBaseId++ )
+      {
+        Int*    pP = m_aaiConvParsVirtDepth2OrigDepth[ uiBaseId ];
+        Double  dF = 1.0 / Double( 1 << pP[ 2 ] );
+        Double  dA = dF  * Double( pP[ 0 ] );
+        Double  dB = dF  * Double( pP[ 1 ] - ( ( 1 << pP[ 2 ] ) >> 1 ) );
+        printf( "    VId=%d:    a = %10.4lf    b = %10.4lf\n", uiBaseId, dA, dB );
+      }
+      printf( "\n" );
+    }
+  }
+#endif
+}
+
+#if !H3D_NBDV
+Bool
+TComDepthMapGenerator::predictDepthMap( TComPic* pcPic )
+{
+  AOF  ( m_bCreated && m_bInit );
+  AOF  ( pcPic );
+  ROTRS( pcPic->getSPS()->isDepth(),  true );
+  ROFRS( m_pcSPSAccess->getPdm(),     true );
+  AOF  ( pcPic->getPredDepthMap() );
+  AOF  ( pcPic->getSPS()->getViewId() == m_uiCurrViewId );
+
+#if PDM_OUTPUT_PRED_DEPTH_MAP
+  Char acFilenameBase[1024];
+  ::sprintf( acFilenameBase, "PDM_%s_Prd", ( m_bDecoder ? "Dec" : "Enc" ) );
+#endif
+
+  Bool bUndefined = true;
+  if( m_uiCurrViewId )
+  {
+    AOF( m_auiBaseIdList.size() );
+    UInt        uiBaseId    = m_auiBaseIdList[ 0 ];
+    TComPic*    pcBasePic   = m_pcAUPicAccess->getPic( uiBaseId );
+    AOF( pcBasePic );
+
+    if( m_uiCurrViewId == 1 )
+    {
+      if( pcBasePic->getPOC() == 0 )
+      {
+        pcBasePic->removePrdDepthMapBuffer();
+        pcBasePic->addPrdDepthMapBuffer( PDM_SUB_SAMP_EXP_X(m_pcSPSAccess->getPdm()), PDM_SUB_SAMP_EXP_Y(m_pcSPSAccess->getPdm()) );
+        xClearDepthMap( pcBasePic );
+#if PDM_REMOVE_DEPENDENCE
+        xClearDepthMap( pcBasePic, PDM_UNDEFINED_DEPTH, 1 );
+#endif
+      }
+#if PDM_OUTPUT_PRED_DEPTH_MAP
+      dumpDepthMap( pcBasePic, acFilenameBase );
+#endif
+    }
+
+    Bool  bLoadDepth  = ( m_pcSPSAccess->getPdm() == 2 );
+    if( m_pcSPSAccess->getPdm() > 2 )
+    {
+      bLoadDepth = ( pcBasePic->getCurrSlice()->getSliceType() == I_SLICE );
+    }
+
+    if( bLoadDepth)
+    { // load coded depth of base view
+      TComPic*  pcBaseDepth = m_pcAUPicAccess->getPic( uiBaseId, true );
+      AOF( pcBaseDepth );
+      AOF( pcBaseDepth->getPicYuvRec() );
+      AOF( pcBaseDepth->getPicYuvRec()->getWidth () == pcBasePic->getPredDepthMap()->getWidth () );
+      AOF( pcBaseDepth->getPicYuvRec()->getHeight() == pcBasePic->getPredDepthMap()->getHeight() );
+      Int       iWidth      = pcBasePic  ->getPredDepthMap()->getWidth    ();
+      Int       iHeight     = pcBasePic  ->getPredDepthMap()->getHeight   ();
+      Int       iDesStride  = pcBasePic  ->getPredDepthMap()->getStride   ();
+      Int       iSrcStride  = pcBaseDepth->getPicYuvRec   ()->getStride   ();
+      Pel*      pDesSamples = pcBasePic  ->getPredDepthMap()->getLumaAddr ( 0 );
+      Pel*      pSrcSamples = pcBaseDepth->getPicYuvRec   ()->getLumaAddr ( 0 );
+      for( Int iY = 0; iY < iHeight; iY++, pSrcSamples += iSrcStride, pDesSamples += iDesStride )
+      {
+        for( Int iX = 0; iX < iWidth; iX++ )
+        {
+          pDesSamples[ iX ] = xGetVirtDepthFromOrigDepth( uiBaseId, pSrcSamples[ iX ] );
+        }
+      }
+    }
+
+    // convert depth of base view to current view
+    bUndefined = xConvertDepthMapRef2Curr( pcPic, pcBasePic );
+
+#if PDM_OUTPUT_PRED_DEPTH_MAP
+    dumpDepthMap( pcPic, acFilenameBase );
+#endif
+  }
+  else
+  {
+    xClearDepthMap( pcPic );
+#if PDM_REMOVE_DEPENDENCE
+    xClearDepthMap( pcPic, PDM_UNDEFINED_DEPTH, 1 );
+#endif
+  }
+  return bUndefined;
+}
+
+
+Void
+TComDepthMapGenerator::updateDepthMap( TComPic* pcPic )
+{
+  AOF  ( m_bCreated && m_bInit );
+  AOF  ( pcPic );
+  ROTVS( pcPic->getSPS()->isDepth() );
+  ROFVS( m_pcSPSAccess->getPdm() == 1 || m_pcSPSAccess->getPdm() == 3 );
+  AOF  ( pcPic->getPredDepthMap() );
+  AOF  ( pcPic->getSPS()->getViewId() == m_uiCurrViewId );
+
+#if PDM_OUTPUT_PRED_DEPTH_MAP
+  Char acFilenameBase[1024];
+  ::sprintf( acFilenameBase, "PDM_%s_Upd", ( m_bDecoder ? "Dec" : "Enc" ) );
+#endif
+
+  // predict depth map using current coding symbols
+#if PDM_REMOVE_DEPENDENCE
+  pcPic->setStoredPDMforV2(0);
+  xPredictDepthMap( pcPic );
+  if(m_uiCurrViewId==0)
+  {
+    pcPic->setStoredPDMforV2(1);
+    xPredictDepthMap( pcPic );
+    pcPic->setStoredPDMforV2(0);
+  }
+#else
+  xPredictDepthMap( pcPic );
+#if PDM_OUTPUT_PRED_DEPTH_MAP
+  if( m_uiCurrViewId )
+  {
+    dumpDepthMap( pcPic, acFilenameBase );
+  }
+#endif
+#endif
+
+  // generate base depth map
+  if( m_uiCurrViewId == 1 )
+  {
+    TComPic* pcBasePic = m_pcAUPicAccess->getPic( 0 );
+    AOF( pcBasePic );
+    xConvertDepthMapCurr2Ref( pcBasePic, pcPic );
+#if PDM_OUTPUT_PRED_DEPTH_MAP
+    dumpDepthMap( pcBasePic, acFilenameBase );
+#endif
+  }
+#if PDM_REMOVE_DEPENDENCE
+  if( m_uiCurrViewId == 2 )
+  {
+    TComPic* pcBasePic = m_pcAUPicAccess->getPic( 0 );
+    AOF( pcBasePic );
+    xConvertDepthMapCurr2Ref( pcBasePic, pcPic );
+#if PDM_OUTPUT_PRED_DEPTH_MAP
+    dumpDepthMap( pcBasePic, acFilenameBase );
+#endif
+  }
+#endif
+}
+
+
+Void
+TComDepthMapGenerator::dumpDepthMap( TComPic* pcPic, char* pFilenameBase )
+{
+  AOF( m_bCreated && m_bInit );
+  AOF( pcPic );
+  AOF( pFilenameBase );
+  AOF( m_uiOrgDepthBitDepth == 8 + g_uiBitIncrement );
+  AOF( pcPic->getSPS()->getViewId() <= m_uiCurrViewId );
+
+  // convert to output format 
+  Int         iMax        = ( 1 << m_uiOrgDepthBitDepth ) - 1;
+  UInt        uiViewId    = pcPic->getSPS()->getViewId();
+  TComPicYuv* pcPicYuv    = pcPic->getPredDepthMap();
+  Int         iWidth      = pcPicYuv->getWidth    ();
+  Int         iHeight     = pcPicYuv->getHeight   ();
+  Int         iSrcStride  = pcPicYuv->getStride   ();
+  Int         iDstStride  = m_cTmpPic.getStride   ();
+#if PDM_REMOVE_DEPENDENCE
+  if(pcPic->getStoredPDMforV2())
+     pcPicYuv    = pcPic->getPredDepthMapTemp();
+#endif
+  Pel*        pSrcSamples = pcPicYuv->getLumaAddr ( 0 );
+  Pel*        pDstSamples = m_cTmpPic.getLumaAddr ( 0 );
+  Int         iMidOrgDpth = ( 1 << m_uiOrgDepthBitDepth ) >> 1;
+  AOF( m_cTmpPic.getWidth () == iWidth  );
+  AOF( m_cTmpPic.getHeight() == iHeight );
+  for( Int iY = 0; iY < iHeight; iY++, pSrcSamples += iSrcStride, pDstSamples += iDstStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      Int iOrgDepth     = ( pSrcSamples[ iX ] != PDM_UNDEFINED_DEPTH ? xGetOrigDepthFromVirtDepth( uiViewId, pSrcSamples[ iX ] ) : iMidOrgDpth );
+      pDstSamples[ iX ] = Max( 0, Min( iMax, iOrgDepth ) );
+    }
+  }
+
+  // output
+  Char  acFilename[1024];
+  ::sprintf     ( acFilename, "%s_V%d.yuv", pFilenameBase, uiViewId );
+  m_cTmpPic.dump( acFilename, ( pcPic->getPOC() != 0 )  );
+}
+
+#endif //!H3D_NBDV
+
+#if H3D_IVMP
+Void  
+TComDepthMapGenerator::covertOrgDepthMap( TComPic* pcPic )
+{
+  AOF  ( m_bCreated && m_bInit   );
+  AOF  ( pcPic );
+  ROFVS( pcPic->getOrgDepthMap() );
+  AOF  ( pcPic->getViewId() );
+
+  UInt  uiBaseId = pcPic->getViewId();
+  Int   iWidth   = pcPic->getOrgDepthMap()->getWidth    ();
+  Int   iHeight  = pcPic->getOrgDepthMap()->getHeight   ();
+  Int   iStride  = pcPic->getOrgDepthMap()->getStride   ();
+  Pel*  pSamples = pcPic->getOrgDepthMap()->getLumaAddr ( 0 );
+  for( Int iY = 0; iY < iHeight; iY++, pSamples += iStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pSamples[ iX ] = xGetVirtDepthFromOrigDepth( uiBaseId, pSamples[ iX ] );
+    }
+  }
+}
+#endif
+
+Int
+TComDepthMapGenerator::getDisparity( TComPic* pcPic, Int iPosX, Int iPosY, UInt uiRefViewId )
+{
+  AOF( pcPic );
+  AOF( pcPic->getPredDepthMap() );
+  AOF( iPosX >= 0 && iPosX < pcPic->getPredDepthMap()->getWidth () );
+  AOF( iPosY >= 0 && iPosY < pcPic->getPredDepthMap()->getHeight() );
+  Pel*   piPdmMap    = pcPic->getPredDepthMap()->getLumaAddr( 0 );
+  Int    iStride     = pcPic->getPredDepthMap()->getStride  ();
+  Int    iPrdDepth   = piPdmMap[ iPosX + iPosY * iStride ];
+  Int    iDisparity  = xGetDisparityFromVirtDepth( uiRefViewId, iPrdDepth );
+  return iDisparity;
+}
+
+
+
+#if H3D_IVMP
+Bool
+TComDepthMapGenerator::getPdmCandidate(TComDataCU* pcCU, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* iPdm, Bool bMerge )
+{
+  AOF  ( m_bCreated && m_bInit );
+  TComSlice*    pcSlice     = pcCU->getSlice ();
+  TComSPS*      pcSPS       = pcSlice->getSPS();
+  AOF  ( pcSPS->getViewId() == m_uiCurrViewId );
+
+  TComPic*      pcRefPic    = pcSlice->getRefPic( eRefPicList, iRefIdx );
+  UInt          uiRefViewId = pcRefPic->getSPS()->getViewId();
+  Bool          bInterview  = ( uiRefViewId < m_uiCurrViewId );
+  Bool          bPdmIView   = ( ( pcSPS->getMultiviewMvPredMode() & PDM_USE_FOR_IVIEW ) == PDM_USE_FOR_IVIEW );
+  Bool          bPdmInter   = ( ( pcSPS->getMultiviewMvPredMode() & PDM_USE_FOR_INTER ) == PDM_USE_FOR_INTER );
+  Bool          bPdmMerge   = ( ( pcSPS->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) == PDM_USE_FOR_MERGE );
+  if(!bMerge)
+  {
+    ROTRS( ( bInterview && !bMerge ) && !bPdmIView, false );
+    ROTRS( (!bInterview && !bMerge ) && !bPdmInter, false );
+    ROTRS(                  bMerge   && !bPdmMerge, false );
+  }
+  else
+    ROTRS( !bPdmMerge, 0 );
+
+
+  Bool abPdmAvailable[4] = {false, false, false, false};
+
+  Int iValid = 0;
+  Int iViewId = 0;
+  for( UInt uiBId = 0; uiBId < m_uiCurrViewId && iValid==0; uiBId++ )
+  {
+
+    UInt        uiBaseId    = uiBId;
+    TComPic*    pcBasePic   = m_pcAUPicAccess->getPic( uiBaseId );
+    for( Int iRefListId = 0; iRefListId < 2 && iValid==0; iRefListId++ )
+    {
+      RefPicList  eRefPicListTest = RefPicList( iRefListId );
+      Int         iNumRefPics = pcSlice->getNumRefIdx( eRefPicListTest ) ;
+      for( Int iRefIndex = 0; iRefIndex < iNumRefPics; iRefIndex++ )
+      { 
+        if(pcBasePic->getPOC() == pcSlice->getRefPic( eRefPicListTest, iRefIndex )->getPOC() 
+          && pcBasePic->getViewId() == pcSlice->getRefPic( eRefPicListTest, iRefIndex )->getViewId())
+        {
+          iValid=1;
+          iViewId = uiBaseId;
+          break;
+        }
+      }
+    }
+  }
+  if (iValid == 0)
+    return false;
+
+  //--- get base CU/PU and check prediction mode ---
+  TComPic*    pcBasePic   = m_pcAUPicAccess->getPic( iViewId );
+  TComPicYuv* pcBaseRec   = pcBasePic->getPicYuvRec   ();
+  if(bMerge || !bInterview)
+  {
+#if H3D_NBDV
+    Int  iCurrPosX, iCurrPosY;
+    UInt          uiPartAddr;
+    Int           iWidth;
+    Int           iHeight;
+
+    pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iWidth, iHeight );
+    pcBaseRec->getTopLeftSamplePos( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr, iCurrPosX, iCurrPosY );
+    iCurrPosX  += ( ( iWidth  - 1 ) >> 1 );
+    iCurrPosY  += ( ( iHeight - 1 ) >> 1 );
+
+    Int         iBasePosX   = Clip3( 0, pcBaseRec->getWidth () - 1, iCurrPosX + ( (pDInfo->m_acMvCand[0].getHor() + 2 ) >> 2 ) );
+    Int         iBasePosY   = Clip3( 0, pcBaseRec->getHeight() - 1, iCurrPosY + ( (pDInfo->m_acMvCand[0].getVer() + 2 ) >> 2 )); 
+    Int         iBaseCUAddr;
+    Int         iBaseAbsPartIdx;
+    pcBaseRec->getCUAddrAndPartIdx( iBasePosX , iBasePosY , iBaseCUAddr, iBaseAbsPartIdx );
+#else //H3D_NBDV
+    Int  iPrdDepth, iCurrPosX, iCurrPosY;
+    Bool bAvailable  = xGetPredDepth( pcCU, uiPartIdx, iPrdDepth, &iCurrPosX, &iCurrPosY );
+    AOF( bAvailable );
+    TComPicYuv* pcBasePdm   = pcBasePic->getPredDepthMap();
+    Int         iDisparity  = xGetDisparityFromVirtDepth( iViewId, iPrdDepth );
+    Int         iShiftX     = m_uiSubSampExpX + 2;
+    Int         iAddX       = ( 1 << iShiftX ) >> 1;
+    Int         iBasePosX   = Clip3( 0, pcBasePdm->getWidth () - 1, iCurrPosX + ( ( iDisparity + iAddX ) >> iShiftX ) );
+    Int         iBasePosY   = Clip3( 0, pcBasePdm->getHeight() - 1, iCurrPosY                               );
+    Int         iBaseCUAddr;
+    Int         iBaseAbsPartIdx;
+    pcBaseRec->getCUAddrAndPartIdx( iBasePosX<< m_uiSubSampExpX , iBasePosY<< m_uiSubSampExpY , iBaseCUAddr, iBaseAbsPartIdx );
+#endif // H3D_NBDV
+    TComDataCU* pcBaseCU    = pcBasePic->getCU( iBaseCUAddr );
+    if( pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) == MODE_INTER || pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) == MODE_SKIP )
+    {
+      for( UInt uiCurrRefListId = 0; uiCurrRefListId < 2; uiCurrRefListId++ )
+      {
+        RefPicList  eCurrRefPicList = RefPicList( uiCurrRefListId );
+        if(!bMerge && eCurrRefPicList != eRefPicList)
+          continue;
+        Bool bLoop_stop = false;
+        for(Int iLoop = 0; iLoop < 2 && !bLoop_stop; ++iLoop)
+        {
+          RefPicList eBaseRefPicList = (iLoop ==1)? RefPicList( 1 -  uiCurrRefListId ) : RefPicList( uiCurrRefListId );
+          TComMvField cBaseMvField;
+          pcBaseCU->getMvField( pcBaseCU, iBaseAbsPartIdx, eBaseRefPicList, cBaseMvField );
+          Int         iBaseRefIdx     = cBaseMvField.getRefIdx();
+          if (iBaseRefIdx >= 0)
+          {
+            Int iBaseRefPOC = pcBaseCU->getSlice()->getRefPOC(eBaseRefPicList, iBaseRefIdx);
+            if (iBaseRefPOC != pcSlice->getPOC())    
+            {
+              for (Int iPdmRefIdx = (bMerge?0: iRefIdx); iPdmRefIdx < (bMerge? pcSlice->getNumRefIdx( eCurrRefPicList ): (iRefIdx+1)); iPdmRefIdx++)
+              {
+                if (iBaseRefPOC == pcSlice->getRefPOC(eCurrRefPicList, iPdmRefIdx))
+                {
+                  abPdmAvailable[ uiCurrRefListId ] = true;
+                  TComMv cMv(cBaseMvField.getHor(), cBaseMvField.getVer());
+#if H3D_NBDV
+                  if( bMerge )
+                  {
+                    cMv.m_bDvMcp = true;
+                    cMv.m_iDvMcpDispX = pDInfo->m_acMvCand[0].getHor();
+                  }
+#endif
+                  pcCU->clipMv( cMv );
+                  if(bMerge)
+                  {
+                    paiPdmRefIdx  [ uiCurrRefListId ] = iPdmRefIdx;
+                    pacPdmMv      [ uiCurrRefListId ] = cMv;
+                    bLoop_stop = true;
+                    break;
+                  }else
+                  {
+                    pacPdmMv  [0] = cMv;
+                    return true;
+                  }
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+    if( bMerge )
+      iPdm[0] = ( abPdmAvailable[0] ? 1 : 0 ) + ( abPdmAvailable[1] ? 2 : 0 );
+  }
+  if(bMerge || bInterview)
+  {
+    for( Int iRefListId = 0; iRefListId < 2 ; iRefListId++ )
+    {
+      RefPicList  eRefPicListDMV       = RefPicList( iRefListId );
+      Int         iNumRefPics       = pcSlice->getNumRefIdx( eRefPicListDMV );
+      for( Int iPdmRefIdx = (bMerge ? 0: iRefIdx); iPdmRefIdx < (bMerge ? iNumRefPics: (iRefIdx+1) ); iPdmRefIdx++ )
+      {
+        if( pcSlice->getRefPOC( eRefPicListDMV, iPdmRefIdx ) == pcSlice->getPOC())
+        {
+          abPdmAvailable[ iRefListId+2 ] = true;
+          paiPdmRefIdx  [ iRefListId+2 ] = iPdmRefIdx;
+#if H3D_NBDV
+          TComMv cMv = pDInfo->m_acMvCand[0]; 
+          cMv.setVer(0);
+#else
+          TComMv cMv(iDisparity, 0);
+#endif
+          pcCU->clipMv( cMv );
+          pacPdmMv      [ iRefListId + 2] = cMv;
+          if(bMerge)
+            break;
+          else
+          {
+            pacPdmMv [0] = cMv;
+            return true;
+          }
+        }
+      }
+    }
+    iPdm[1] = ( abPdmAvailable[2] ? 1 : 0 ) + ( abPdmAvailable[3] ? 2 : 0 );
+  }
+  return false;
+}
+
+
+Bool  // first version 
+TComDepthMapGenerator::getIViewOrgDepthMvPred( TComDataCU* pcCU, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv )
+{
+  AOF  ( m_bCreated && m_bInit );
+  AOF  ( iRefIdx >= 0 );
+  AOF  ( pcCU );
+
+  TComSlice*    pcSlice     = pcCU->getSlice ();
+  TComPic*      pcPic       = pcCU->getPic   ();
+  TComSPS*      pcSPS       = pcSlice->getSPS();
+  AOF  ( pcSPS->getViewId() == m_uiCurrViewId );
+  ROFRS( pcPic->getOrgDepthMap(),      false );
+  
+  TComPic*      pcRefPic    = pcSlice->getRefPic( eRefPicList, iRefIdx );
+  UInt          uiRefViewId = pcRefPic->getSPS()->getViewId();
+  Int           iRefPoc     = pcRefPic->getPOC();
+  ROFRS( uiRefViewId < m_uiCurrViewId, false );
+  AOF  ( iRefPoc    == pcSlice->getPOC() );
+
+  //===== get predicted depth for middle position of current PU (first version) =====  
+  UInt          uiPartAddr;
+  Int           iWidth;
+  Int           iHeight;
+  pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iWidth, iHeight );
+  TComPicYuv*   pcOrgDepthMap  = pcPic->getOrgDepthMap();
+  Pel*          piOrgDepthMap  = pcOrgDepthMap->getLumaAddr ( 0 );
+  Int           iCurrStride    = pcOrgDepthMap->getStride   ();
+  Int           iCurrPosX;
+  Int           iCurrPosY;
+  pcOrgDepthMap->getTopLeftSamplePos( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr, iCurrPosX, iCurrPosY );
+  iCurrPosX                    += ( iWidth  - 1 ) >> 1;
+  iCurrPosY                    += ( iHeight - 1 ) >> 1;
+  Int           iPrdDepth       = piOrgDepthMap[ iCurrPosX + iCurrPosY * iCurrStride ];
+  
+  //===== get disparity vector =====
+  Int           iDisparity      = xGetDisparityFromVirtDepth( uiRefViewId, iPrdDepth );
+  rcMv.set    ( iDisparity, 0 );
+  return        true;
+}
+#endif //  H3D_IVMP 
+
+
+
+
+
+#if !H3D_NBDV
+/*=======================================================*
+ *=====                                             =====*
+ *=====     p i c t u r e   o p e r a t i o n s     =====*
+ *=====                                             =====*
+ *=======================================================*/
+
+Bool
+TComDepthMapGenerator::xConvertDepthMapCurr2Ref( TComPic* pcRef, TComPic* pcCur )
+{
+  AOF( pcCur->getSPS()->getViewId() == m_uiCurrViewId );
+  AOF( pcCur->getSPS()->getViewId()  > pcRef->getSPS()->getViewId() );
+  AOF( pcCur->getPredDepthMap() );
+  AOF( pcRef->getPredDepthMap() );
+  AOF( pcRef->getPredDepthMap()->getWidth () == pcCur->getPredDepthMap()->getWidth () );
+  AOF( pcRef->getPredDepthMap()->getHeight() == pcCur->getPredDepthMap()->getHeight() );
+#if PDM_REMOVE_DEPENDENCE
+  if( pcCur->getViewId() == 1)
+    xClearDepthMap( pcRef );
+  else if (pcCur->getViewId() == 2)
+    xClearDepthMap( pcRef, PDM_UNDEFINED_DEPTH, 1 );
+#else
+  xClearDepthMap( pcRef );
+#endif
+  TComPicYuv* pcCurDepthMap =  pcCur->getPredDepthMap    ();
+  TComPicYuv* pcRefDepthMap =  pcRef->getPredDepthMap    ();
+  Int         iWidth        =  pcCurDepthMap->getWidth   ();
+  Int         iHeight       =  pcCurDepthMap->getHeight  ();
+  Int         iCurStride    =  pcCurDepthMap->getStride  ();
+  Int         iRefStride    =  pcRefDepthMap->getStride  ();
+  Pel*        pCurSamples   =  pcCurDepthMap->getLumaAddr( 0 );
+  Pel*        pRefSamples   =  pcRefDepthMap->getLumaAddr( 0 );
+  Int         iRefViewIdx   =  pcRef->getViewId();
+#if PDM_REMOVE_DEPENDENCE
+  if( pcCur->getViewId() == 2)
+  {
+    pcRefDepthMap =  pcRef->getPredDepthMapTemp();
+    pRefSamples   =  pcRefDepthMap->getLumaAddr( 0 );
+  }
+#endif 
+  Int         iShiftX       = m_uiSubSampExpX + 2;
+  Int         iAddX         = ( 1 << iShiftX ) >> 1;
+  for( Int iY = 0; iY < iHeight; iY++, pCurSamples += iCurStride, pRefSamples += iRefStride )
+  {
+    for( Int iXCur = 0; iXCur < iWidth; iXCur++ )
+    {
+      Int iDepth = pCurSamples[ iXCur ];
+      Int iDisp  = xGetDisparityFromVirtDepth( iRefViewIdx, iDepth );
+      Int iXRef  = iXCur + ( ( iDisp + iAddX ) >> iShiftX );
+      if( iXRef >= 0 && iXRef < iWidth && iDepth > pRefSamples[ iXRef ] )
+      {
+        pRefSamples[ iXRef ] = iDepth;
+      }
+    }
+  }
+  Bool    bUndefined = xFillDepthMapHoles( pcRef );
+  pcRefDepthMap->setBorderExtension( false );
+  pcRefDepthMap->extendPicBorder   ();
+  return  bUndefined;
+}
+
+
+Bool
+TComDepthMapGenerator::xConvertDepthMapRef2Curr( TComPic* pcCur, TComPic* pcRef )
+{
+  AOF( pcCur->getSPS()->getViewId() == m_uiCurrViewId );
+  AOF( pcCur->getSPS()->getViewId()  > pcRef->getSPS()->getViewId() );
+  AOF( pcCur->getPredDepthMap() );
+#if PDM_REMOVE_DEPENDENCE
+  if(pcCur->getViewId() == 1)
+  {
+    AOF( pcRef->getPredDepthMap() );
+  }else
+  {
+    AOF( pcRef->getPredDepthMapTemp() );
+  }
+#else
+  AOF( pcRef->getPredDepthMap() );
+#endif
+  AOF( pcRef->getPredDepthMap()->getWidth () == pcCur->getPredDepthMap()->getWidth () );
+  AOF( pcRef->getPredDepthMap()->getHeight() == pcCur->getPredDepthMap()->getHeight() );
+
+  xClearDepthMap( pcCur );
+  TComPicYuv* pcRefDepthMap =  pcRef->getPredDepthMap    ();
+#if PDM_REMOVE_DEPENDENCE
+  if(pcCur->getViewId() == 2)
+    pcRefDepthMap =  pcRef->getPredDepthMapTemp        ();
+#endif
+  TComPicYuv* pcCurDepthMap =  pcCur->getPredDepthMap    ();
+  Int         iWidth        =  pcRefDepthMap->getWidth   ();
+  Int         iHeight       =  pcRefDepthMap->getHeight  ();
+  Int         iRefStride    =  pcRefDepthMap->getStride  ();
+  Int         iCurStride    =  pcCurDepthMap->getStride  ();
+  Pel*        pRefSamples   =  pcRefDepthMap->getLumaAddr( 0 );
+  Pel*        pCurSamples   =  pcCurDepthMap->getLumaAddr( 0 );
+  Int         iRefViewIdx   =  pcRef->getViewId();
+  Int         iShiftX       = m_uiSubSampExpX + 2;
+  Int         iAddX         = ( 1 << iShiftX ) >> 1;
+  for( Int iY = 0; iY < iHeight; iY++, pRefSamples += iRefStride, pCurSamples += iCurStride )
+  {
+    for( Int iXRef = 0; iXRef < iWidth; iXRef++ )
+    {
+      Int iDepth = pRefSamples[ iXRef ];
+      Int iDisp  = xGetDisparityFromVirtDepth( iRefViewIdx, iDepth );
+      Int iXCur  = iXRef - ( ( iDisp + iAddX ) >> iShiftX );
+      if( iXCur >= 0 && iXCur < iWidth && iDepth > pCurSamples[ iXCur ] )
+      {
+        pCurSamples[ iXCur ] = iDepth;
+      }
+    }
+  }
+  Bool    bUndefined = xFillDepthMapHoles( pcCur );
+  pcCurDepthMap->setBorderExtension( false );
+  pcCurDepthMap->extendPicBorder   ();
+  return  bUndefined;
+}
+
+
+Bool
+TComDepthMapGenerator::xPredictDepthMap( TComPic* pcPic )
+{
+  for( UInt uiCUAddr = 0; uiCUAddr < pcPic->getPicSym()->getNumberOfCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+    xPredictCUDepthMap( pcCU, 0, 0 );
+  }
+  Bool    bUndefined = xFillDepthMapHoles( pcPic );
+#if PDM_REMOVE_DEPENDENCE
+  if(pcPic->getStoredPDMforV2() == 1){
+  pcPic->getPredDepthMapTemp()->setBorderExtension( false );
+  pcPic->getPredDepthMapTemp()->extendPicBorder   ();
+  }else{
+#endif
+  pcPic->getPredDepthMap()->setBorderExtension( false );
+  pcPic->getPredDepthMap()->extendPicBorder   ();
+#if PDM_REMOVE_DEPENDENCE
+  }
+#endif
+  return  bUndefined;
+}
+
+
+Bool
+TComDepthMapGenerator::xFillDepthMapHoles( TComPic* pcPic )
+{
+  Bool        bUndefined  = false;      
+  TComPicYuv* pcDepthMap  = pcPic->getPredDepthMap  ();
+#if PDM_REMOVE_DEPENDENCE
+  if(pcPic->getViewId()==0 && pcPic->getStoredPDMforV2()==1)
+    pcDepthMap  = pcPic->getPredDepthMapTemp  ();
+#endif
+  Int         iWidth      = pcDepthMap->getWidth    ();
+  Int         iHeight     = pcDepthMap->getHeight   ();
+  Int         iStride     = pcDepthMap->getStride   ();
+  Pel*        pDMSamples  = pcDepthMap->getLumaAddr ( 0 );
+  // horizontal
+  for( Int iY = 0; iY < iHeight && !bUndefined; iY++, pDMSamples += iStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      if( pDMSamples[ iX ] == PDM_UNDEFINED_DEPTH )
+      {
+        Int  iE;
+        for( iE = iX + 1; iE < iWidth; iE++ )
+        {
+          if( pDMSamples[ iE ] != PDM_UNDEFINED_DEPTH )
+          {
+            break;
+          }
+        }
+        if( iX > 0 || iE < iWidth )
+        {
+          Int iDepth;
+          if     ( iX > 0 && iE < iWidth )  iDepth  = ( pDMSamples[ iX-1 ] < pDMSamples[ iE ] ? pDMSamples[ iX-1 ] : pDMSamples[ iE ] ); 
+          else if( iX > 0 )                 iDepth  =   pDMSamples[ iX-1 ]; 
+          else /*( iE < iWidth )*/          iDepth  =   pDMSamples[ iE   ]; 
+          for( Int iZ = iX; iZ < iE; iZ++ )
+          {
+            pDMSamples[ iZ ] = iDepth;
+          }
+        }
+        else
+        {
+          bUndefined = true;
+          break;
+        }
+        iX = iE - 1;
+      }
+    }
+  }
+  
+  if( bUndefined && m_uiCurrViewId )
+  {
+    pDMSamples          = pcDepthMap->getLumaAddr( 0 );
+    Int  iMiddleOrgDpth = ( 1 << m_uiOrgDepthBitDepth ) >> 1;
+    Int  iMiddleDepth   = xGetVirtDepthFromOrigDepth( m_uiCurrViewId, iMiddleOrgDpth );
+    for( Int iY = 0; iY < iHeight; iY++, pDMSamples += iStride )
+    {
+      for( Int iX = 0; iX < iWidth; iX++ )
+      {
+        pDMSamples[ iX ] = iMiddleDepth;
+       }
+    }
+  }
+  return bUndefined;
+}
+
+
+Void
+TComDepthMapGenerator::xClearDepthMap( TComPic* pcPic, Int iVal 
+#if PDM_REMOVE_DEPENDENCE
+,
+Int forFirstNonBaseView
+#endif
+)
+{
+  TComPicYuv* pcDepthMap  = pcPic->getPredDepthMap  ();
+  Int         iWidth      = pcDepthMap->getWidth    ();
+  Int         iHeight     = pcDepthMap->getHeight   ();
+  Int         iStride     = pcDepthMap->getStride   ();
+  Pel*        pDMSamples  = pcDepthMap->getLumaAddr ( 0 );
+#if PDM_REMOVE_DEPENDENCE
+  if( forFirstNonBaseView == 1)
+  {
+    pcDepthMap  = pcPic->getPredDepthMapTemp  ();
+    pDMSamples  = pcDepthMap->getLumaAddr ( 0 );
+  }
+#endif
+  for( Int iY = 0; iY < iHeight; iY++, pDMSamples += iStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pDMSamples[ iX ] = iVal;
+    }
+  }
+  pcDepthMap->setBorderExtension( false );
+  pcDepthMap->extendPicBorder   ();
+}
+
+Void  
+TComDepthMapGenerator::xSetChroma( TComPicYuv* pcPic, Int iVal )
+{
+  Int   iWidth      = pcPic->getWidth   () >> 1;
+  Int   iHeight     = pcPic->getHeight  () >> 1;
+  Int   iStride     = pcPic->getCStride ();
+  Pel*  pCbSamples  = pcPic->getCbAddr  ( 0 );
+  Pel*  pCrSamples  = pcPic->getCrAddr  ( 0 );
+  for( Int iY = 0; iY < iHeight; iY++, pCbSamples += iStride, pCrSamples += iStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pCbSamples[ iX ] = pCrSamples[ iX ] = iVal;
+    }
+  }
+}
+
+
+
+
+
+
+
+/*===============================================*
+ *=====                                     =====*
+ *=====     C U   p r e d i c t i o n s     =====*
+ *=====                                     =====*
+ *===============================================*/
+
+Void
+TComDepthMapGenerator::xPredictCUDepthMap( TComDataCU* pcCU, UInt uiDepth, UInt uiAbsPartIdx )
+{
+  UInt  uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  UInt  uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  UInt  uiRPelX   = uiLPelX           + ( g_uiMaxCUWidth  >> uiDepth ) - 1;
+  UInt  uiBPelY   = uiTPelY           + ( g_uiMaxCUHeight >> uiDepth ) - 1;
+  Bool  bBoundary = ( uiRPelX >= pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() || uiBPelY >= pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() );
+  Bool  bSplit    = ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) && uiDepth < ( g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary );
+  if(   bSplit )
+  {
+    UInt uiQNumParts = ( pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 ) ) >> 2;
+    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  bInside = ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() && uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() );
+      if(   bInside )
+      {
+        xPredictCUDepthMap( pcCU, uiDepth + 1, uiAbsPartIdx );
+      }
+    }
+    return;
+  }
+
+  //--- set sub-CU and sub-depth-map ---
+  TComDataCU* pcSubCU   = m_ppcCU [ uiDepth ];
+  TComYuv*    pcSubDM   = m_ppcYuv[ uiDepth ];
+  TComPicYuv* pcPicDM   = pcCU->getPic()->getPredDepthMap();
+#if PDM_REMOVE_DEPENDENCE
+  if( pcCU->getPic()->getStoredPDMforV2() == 1)
+    pcPicDM   = pcCU->getPic()->getPredDepthMapTemp();
+#endif
+  UInt        uiCUAddr  = pcCU->getAddr();
+  pcSubCU->copySubCU( pcCU, uiAbsPartIdx, uiDepth );
+
+  //--- update depth map ---
+  switch( pcSubCU->getPredictionMode( 0 ) )
+  {
+  case MODE_INTRA:
+    xIntraPredictCUDepthMap( pcSubCU, pcSubDM );
+    break;
+  case MODE_SKIP:
+  case MODE_INTER:
+    xInterPredictCUDepthMap( pcSubCU, pcSubDM );
+    break;
+  default:
+    AOT( true );
+    break;
+  }
+
+  //--- copy sub-depth-map ---
+  pcSubDM->copyToPicYuv( pcPicDM, uiCUAddr, uiAbsPartIdx );
+}
+
+
+Void
+TComDepthMapGenerator::xIntraPredictCUDepthMap( TComDataCU* pcCU, TComYuv* pcCUDepthMap )
+{
+  UInt  uiInitTrDepth = ( pcCU->getPartitionSize( 0 ) == SIZE_2Nx2N ? 0 : 1 );
+  UInt  uiNumPart     =   pcCU->getNumPartInter ();
+  UInt  uiNumQParts   =   pcCU->getTotalNumPart () >> 2;
+  for( UInt uiPU = 0; uiPU < uiNumPart; uiPU++ )
+  {
+    xIntraPredictBlkDepthMap( pcCU, pcCUDepthMap, uiPU * uiNumQParts, uiInitTrDepth );
+  }
+}
+
+
+Void
+TComDepthMapGenerator::xInterPredictCUDepthMap( TComDataCU* pcCU, TComYuv* pcCUDepthMap )
+{
+  for( UInt uiPartIdx = 0; uiPartIdx < pcCU->getNumPartInter(); uiPartIdx++ )
+  {
+    xInterPredictPUDepthMap( pcCU, pcCUDepthMap, uiPartIdx );
+  }
+}
+
+
+
+
+
+
+
+/*=====================================================================*
+ *=====                                                           =====*
+ *=====     P U -   a n d   B l o c k   p r e d i c t i o n s     =====*
+ *=====                                                           =====*
+ *=====================================================================*/
+
+Void
+TComDepthMapGenerator::xIntraPredictBlkDepthMap( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiAbsPartIdx, UInt uiTrDepth )
+{
+  UInt uiFullDepth  = pcCU->getDepth( 0 ) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if( uiTrMode == uiTrDepth )
+  {
+    UInt  uiWidth         = pcCU->getWidth ( 0 ) >> ( uiTrDepth + m_uiSubSampExpX );
+    UInt  uiHeight        = pcCU->getHeight( 0 ) >> ( uiTrDepth + m_uiSubSampExpY );
+    UInt  uiStride        = pcCUDepthMap->getStride  ();
+    UInt  uiBlkX          = g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ] >> m_uiSubSampExpX;
+    UInt  uiBlkY          = g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ] >> m_uiSubSampExpY;
+    Pel*  pDepthMap       = pcCUDepthMap->getLumaAddr() + uiBlkY * pcCUDepthMap->getStride() + uiBlkX;
+    UInt  uiLumaPredMode  = pcCU->getLumaIntraDir    ( uiAbsPartIdx );
+    Bool  bAboveAvail     = false;
+    Bool  bLeftAvail      = false;
+    pcCU->getPattern()->initPattern   ( pcCU, uiTrDepth, uiAbsPartIdx, true );
+    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, 
+                                        m_pcPrediction->getPredicBuf       (),
+                                        m_pcPrediction->getPredicBufWidth  (),
+                                        m_pcPrediction->getPredicBufHeight (),
+                                        bAboveAvail, bLeftAvail, false, true, m_uiSubSampExpX, m_uiSubSampExpY );
+    m_pcPrediction->predIntraDepthAng ( pcCU->getPattern(), uiLumaPredMode, pDepthMap, uiStride, uiWidth, uiHeight ); // could be replaced with directional intra prediction
+                                                                                                                      // using "predIntraLumaAng", but note: 
+                                                                                                                      //  - need to take care of neighbours with undefined depth
+                                                                                                                      //  - special case for wedgelet mode (if available in normal views)
+    // copy to picture array (for next intra prediction block)
+    UInt  uiZOrderIdx     = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+    Pel*  pPicDepthMap    = pcCU->getPic()->getPredDepthMap()->getLumaAddr( pcCU->getAddr(), uiZOrderIdx );
+#if PDM_REMOVE_DEPENDENCE
+    if(pcCU->getPic()->getStoredPDMforV2()==1)
+      pPicDepthMap    = pcCU->getPic()->getPredDepthMapTemp()->getLumaAddr( pcCU->getAddr(), uiZOrderIdx );
+#endif
+    Int   iPicStride      = pcCU->getPic()->getPredDepthMap()->getStride  ();
+    for( UInt uiY = 0; uiY < uiHeight; uiY++, pDepthMap += uiStride, pPicDepthMap += iPicStride )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pPicDepthMap[ uiX ] = pDepthMap[ uiX ];
+      }
+    }
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xIntraPredictBlkDepthMap( pcCU, pcCUDepthMap, uiAbsPartIdx + uiPart * uiNumQPart, uiTrDepth + 1 );
+    }
+  }
+}
+
+
+Void  
+TComDepthMapGenerator::xInterPredictPUDepthMap( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx )
+{
+  if ( pcCU->getSlice()->getSPS()->getViewId() )
+  {
+    AOF( m_uiCurrViewId == pcCU->getSlice()->getSPS()->getViewId() );
+    // check for interview prediction
+    Int             iWidth;
+    Int             iHeight;
+    UInt            uiAbsPartIdx;
+    pcCU->getPartIndexAndSize( uiPartIdx, uiAbsPartIdx, iWidth, iHeight );
+    TComCUMvField*  aiCurrMvField[2]  = { pcCU->getCUMvField( REF_PIC_LIST_0 ),        pcCU->getCUMvField( REF_PIC_LIST_1 )        };
+    Int             aiCurrRefIdx [2]  = { aiCurrMvField[0]->getRefIdx( uiAbsPartIdx ), aiCurrMvField[1]->getRefIdx( uiAbsPartIdx ) };
+    Bool            abCurrIntView[2]  = { aiCurrRefIdx[0] >= 0 && pcCU->getSlice()->getRefPic( REF_PIC_LIST_0, aiCurrRefIdx[0] )->getSPS()->getViewId() != m_uiCurrViewId,
+                                          aiCurrRefIdx[1] >= 0 && pcCU->getSlice()->getRefPic( REF_PIC_LIST_1, aiCurrRefIdx[1] )->getSPS()->getViewId() != m_uiCurrViewId };
+    Bool            bUsesInterViewPrd = ( abCurrIntView[0] || abCurrIntView[1] );
+    if( bUsesInterViewPrd )
+    {
+      xIViewPUDepthMapUpdate  ( pcCU, pcCUDepthMap, uiPartIdx );
+    }
+    else
+    { 
+#if PDM_NO_INTER_UPDATE
+      xInterPUDepthMapPrediction( pcCU, pcCUDepthMap, uiPartIdx );
+#else
+      xInterPUDepthMapUpdate  ( pcCU, pcCUDepthMap, uiPartIdx );
+#endif
+    }
+  }
+  else
+  {
+    xInterPUDepthMapPrediction( pcCU, pcCUDepthMap, uiPartIdx );
+  }
+}
+
+
+Void  
+TComDepthMapGenerator::xIViewPUDepthMapUpdate( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx )
+{
+  // get width, height, and part address
+  Int   iWidth;
+  Int   iHeight;
+  UInt  uiAbsPartIdx;
+  pcCU->getPartIndexAndSize( uiPartIdx, uiAbsPartIdx, iWidth, iHeight );
+  iWidth  >>= m_uiSubSampExpX;
+  iHeight >>= m_uiSubSampExpY;
+
+  // get depth values
+  Int   iDepthValue   = PDM_UNDEFINED_DEPTH;
+  Int   aiPrdDepth[2] = { PDM_UNDEFINED_DEPTH, PDM_UNDEFINED_DEPTH };
+  for( Int iRefListId = 0; iRefListId < 2; iRefListId++ )
+  {
+    RefPicList      eRefPicList = RefPicList( iRefListId );
+    TComCUMvField*  pcCUMvField = pcCU->getCUMvField( eRefPicList );
+    Int             iRefIdx     = pcCUMvField->getRefIdx( uiAbsPartIdx );
+    UInt            uiBaseId    = ( iRefIdx >= 0 ? pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getSPS()->getViewId() : MAX_VIEW_NUM ); 
+    Bool            bInterview  = ( iRefIdx >= 0 && uiBaseId < m_uiCurrViewId );
+    if( bInterview )
+    {
+      Int           iMvX        = pcCUMvField->getMv( uiAbsPartIdx ).getHor();
+      aiPrdDepth[ iRefListId ]  = xGetVirtDepthFromDisparity( uiBaseId, iMvX );
+    }
+  }
+  if( aiPrdDepth[ 0 ] != PDM_UNDEFINED_DEPTH && aiPrdDepth[ 1 ] != PDM_UNDEFINED_DEPTH )
+  {
+    iDepthValue = ( aiPrdDepth[ 0 ] + aiPrdDepth[ 1 ] + 1 ) >> 1;
+  }
+  else
+  {
+    iDepthValue = ( aiPrdDepth[ 0 ] != PDM_UNDEFINED_DEPTH ? aiPrdDepth[ 0 ] : aiPrdDepth[ 1 ] );
+    AOT( iDepthValue == PDM_UNDEFINED_DEPTH );
+  }
+  iDepthValue   = Max( 0, Min( PDM_MAX_ABS_VIRT_DEPTH, iDepthValue ) );
+
+  // set depth map for PU
+  UInt  uiBlkX      = g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ] >> m_uiSubSampExpX;
+  UInt  uiBlkY      = g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ] >> m_uiSubSampExpY;
+  Pel*  pDMSamples  = pcCUDepthMap->getLumaAddr() + uiBlkY * pcCUDepthMap->getStride() + uiBlkX;
+  Int   iStride     = pcCUDepthMap->getStride  ();
+  for( Int iY = 0; iY < iHeight; iY++, pDMSamples += iStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++)
+    {
+      pDMSamples[ iX ] = (Pel)iDepthValue;
+    }
+  }
+}
+
+
+Void
+TComDepthMapGenerator::xInterPUDepthMapUpdate( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx )
+{
+  const Int       iMaxAbsDeltaMvY   = 8 << 2;
+
+  //===== determine block parameters for current access unit and current view =====
+  Int             iWidth;
+  Int             iHeight;
+  UInt            uiAbsPartIdx;
+  pcCU->getPartIndexAndSize ( uiPartIdx, uiAbsPartIdx, iWidth, iHeight );
+  UInt            uiCurrViewId      = pcCU->getSlice()->getSPS()->getViewId();  
+  Int             iNum4x4BlksY      = iHeight >> 2;
+  Int             iNum4x4BlksX      = iWidth  >> 2;
+  iWidth  >>= m_uiSubSampExpX;
+  iHeight >>= m_uiSubSampExpY;
+
+  TComPicYuv*     pcCurrDepthMap    = pcCU->getPic()->getPredDepthMap();
+  Pel*            piCurrDepthMap    = pcCurrDepthMap->getLumaAddr();
+  Int             iCurrStride       = pcCurrDepthMap->getStride();
+  TComCUMvField*  aiCurrMvField[2]  = { pcCU->getCUMvField( REF_PIC_LIST_0 ),        pcCU->getCUMvField( REF_PIC_LIST_1 )        };
+  Int             aiCurrRefIdx [2]  = { aiCurrMvField[0]->getRefIdx( uiAbsPartIdx ), aiCurrMvField[1]->getRefIdx( uiAbsPartIdx ) };
+  Int             iMinCurrListId    = ( aiCurrRefIdx [0] < 0 ? 1 : 0 );
+  Int             iMaxCurrListId    = ( aiCurrRefIdx [1] < 0 ? 0 : 1 );
+  Int             iCurrPUPosX;
+  Int             iCurrPUPosY;
+  pcCurrDepthMap->getTopLeftSamplePos( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiAbsPartIdx, iCurrPUPosX, iCurrPUPosY );
+  AOT( uiCurrViewId    != m_uiCurrViewId );
+  AOT( iMinCurrListId  >  iMaxCurrListId );
+  AOT( aiCurrRefIdx[0] >= 0 && pcCU->getSlice()->getRefPic( REF_PIC_LIST_0, aiCurrRefIdx[0] )->getSPS()->getViewId() != uiCurrViewId );
+  AOT( aiCurrRefIdx[1] >= 0 && pcCU->getSlice()->getRefPic( REF_PIC_LIST_1, aiCurrRefIdx[1] )->getSPS()->getViewId() != uiCurrViewId );
+
+  //===== determine parameters for current access unit and base view =====
+  AOF( m_auiBaseIdList.size() );
+  UInt            uiBaseId          = m_auiBaseIdList[ 0 ];
+  TComPic*        pcBasePic         = m_pcAUPicAccess->getPic( uiBaseId );
+  AOF( pcBasePic );
+  TComPicYuv*     pcBaseDepthMap    = pcBasePic->getPredDepthMap();
+  TComPicYuv*     pcBaseRecPic      = pcBasePic->getPicYuvRec   ();
+  Pel*            piBaseDepthMap    = pcBaseDepthMap->getLumaAddr();
+  Int             iBaseStride       = pcBaseDepthMap->getStride();
+  Int             iShiftX           = m_uiSubSampExpX + 2;
+  Int             iShiftY           = m_uiSubSampExpY + 2;
+  Int             iAddX             = ( 1 << iShiftX ) >> 1;
+  Int             iAddY             = ( 1 << iShiftY ) >> 1;
+
+  //===== initialize 4x4 block arrays =====
+  for( Int i4x4BlkY = 0; i4x4BlkY < iNum4x4BlksY; i4x4BlkY++ )
+  {
+    for( Int i4x4BlkX = 0; i4x4BlkX < iNum4x4BlksX; i4x4BlkX++ )
+    {
+      m_aabDepthSet[ i4x4BlkY ][ i4x4BlkX ] = false;
+      m_aai4x4Depth[ i4x4BlkY ][ i4x4BlkX ] = PDM_UNDEFINED_DEPTH;
+    }
+  }
+  Int iNum4x4Set = 0;
+
+  //===== determine depth based on 4x4 blocks =====
+  for( Int i4x4BlkY = 0; i4x4BlkY < iNum4x4BlksY; i4x4BlkY++ )
+  {
+    for( Int i4x4BlkX = 0; i4x4BlkX < iNum4x4BlksX; i4x4BlkX++ )
+    {
+      // position parameters
+      Int               iCurrBlkPosX        = iCurrPUPosX + ( ( i4x4BlkX << 2 ) >> m_uiSubSampExpX );
+      Int               iCurrBlkPosY        = iCurrPUPosY + ( ( i4x4BlkY << 2 ) >> m_uiSubSampExpY );
+      Int               iCurrSamplePosX     = iCurrBlkPosX + ( 1 >> m_uiSubSampExpX );
+      Int               iCurrSamplePosY     = iCurrBlkPosY + ( 1 >> m_uiSubSampExpY );
+      Int               iCurrPredDepth      = piCurrDepthMap[ iCurrSamplePosY * iCurrStride + iCurrSamplePosX ];
+      Int               iCurrPredDisp       = xGetDisparityFromVirtDepth( uiBaseId, iCurrPredDepth );
+      Int               iBaseSamplePosX     = iCurrSamplePosX + ( ( iCurrPredDisp + iAddX ) >> iShiftX );
+      Int               iBaseSamplePosY     = iCurrSamplePosY;
+      iBaseSamplePosX                       = Clip3( 0, pcBaseDepthMap->getWidth () - 1, iBaseSamplePosX );
+      iBaseSamplePosY                       = Clip3( 0, pcBaseDepthMap->getHeight() - 1, iBaseSamplePosY );
+
+      // check for occlusion
+      if( piBaseDepthMap[ iBaseSamplePosY * iBaseStride + iBaseSamplePosX ] != iCurrPredDepth )
+      {
+        continue;
+      }
+
+      // determine base motion data and check prediction mode
+      Int               iBaseCUAddr;
+      Int               iBaseAbsPartIdx;
+      pcBaseRecPic->getCUAddrAndPartIdx( iBaseSamplePosX << m_uiSubSampExpX, iBaseSamplePosY << m_uiSubSampExpY, iBaseCUAddr, iBaseAbsPartIdx );
+      TComDataCU*       pcBaseCU            = pcBasePic->getCU( iBaseCUAddr );
+      if( pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) != MODE_INTER && pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) != MODE_SKIP )
+      {
+        continue;
+      }
+
+      // check whether base was inter-view predicted
+      TComCUMvField*    aiBaseMvField[2]    = { pcBaseCU->getCUMvField( REF_PIC_LIST_0 ),       pcBaseCU->getCUMvField( REF_PIC_LIST_1 )       };
+      Int               aiBaseRefIdx [2]    = { aiBaseMvField[0]->getRefIdx( iBaseAbsPartIdx ), aiBaseMvField[1]->getRefIdx( iBaseAbsPartIdx ) };
+      Bool              abBaseIntView[2]    = { aiBaseRefIdx[0] >= 0 && pcBaseCU->getSlice()->getRefPic( REF_PIC_LIST_0, aiBaseRefIdx[0] )->getSPS()->getViewId() != uiBaseId,
+                                                aiBaseRefIdx[1] >= 0 && pcBaseCU->getSlice()->getRefPic( REF_PIC_LIST_1, aiBaseRefIdx[1] )->getSPS()->getViewId() != uiBaseId };
+      if( abBaseIntView[0] || abBaseIntView[1] )
+      { // current depth is reliable
+        m_aai4x4Depth[i4x4BlkY][i4x4BlkX]   = iCurrPredDepth;
+        m_aabDepthSet[i4x4BlkY][i4x4BlkX]   = true;
+        iNum4x4Set++;
+        continue;
+      }
+      
+      // determine depth candidates using an approximate 4-point relationship (if appropriate)
+      std::vector<Int>  aiDepthCand;
+      Int               iMinBaseListId      = ( aiBaseRefIdx [0] < 0 ? 1 : 0 );
+      Int               iMaxBaseListId      = ( aiBaseRefIdx [1] < 0 ? 0 : 1 );
+      AOT( iMinBaseListId > iMaxBaseListId );
+      for( Int iCurrRefListId  = iMinCurrListId; iCurrRefListId <= iMaxCurrListId; iCurrRefListId++ )
+      {
+        RefPicList      eCurrRefPicList     = RefPicList( iCurrRefListId );
+        Int             iCurrRefPoc         = pcCU->getSlice()->getRefPOC( eCurrRefPicList, aiCurrRefIdx[ iCurrRefListId ] );
+        TComPic*        pcCurrRefPic        = pcCU->getSlice()->getRefPic( eCurrRefPicList, aiCurrRefIdx[ iCurrRefListId ] );
+        TComPicYuv*     pcCurrRefDMap       = pcCurrRefPic->getPredDepthMap();
+        Pel*            piCurrRefDMap       = pcCurrRefDMap->getLumaAddr();
+        Int             iCurrRefStride      = pcCurrRefDMap->getStride();
+        TComMv          rcCurrMv            = aiCurrMvField[ iCurrRefListId ]->getMv( uiAbsPartIdx );
+        Int             iCurrRefSamplePosX  = iCurrSamplePosX + ( ( rcCurrMv.getHor() + iAddX ) >> iShiftX );
+        Int             iCurrRefSamplePosY  = iCurrSamplePosY + ( ( rcCurrMv.getVer() + iAddY ) >> iShiftY );
+        Int             iCurrRefSamplePosXC = Clip3( 0, pcCurrRefDMap->getWidth () - 1, iCurrRefSamplePosX );
+        Int             iCurrRefSamplePosYC = Clip3( 0, pcCurrRefDMap->getHeight() - 1, iCurrRefSamplePosY );
+        Int             iCurrRefDepth       = piCurrRefDMap[ iCurrRefSamplePosYC * iCurrRefStride + iCurrRefSamplePosXC ];
+
+        for( Int iBaseRefListId = iMinBaseListId; iBaseRefListId <= iMaxBaseListId; iBaseRefListId++ )
+        {
+          RefPicList    eBaseRefPicList     = RefPicList( iBaseRefListId );
+          Int           iBaseRefPoc         = pcBaseCU->getSlice()->getRefPOC( eBaseRefPicList, aiBaseRefIdx[ iBaseRefListId ] );
+
+          if( iCurrRefPoc == iBaseRefPoc )
+          {
+            // location and depth for path currView/currAU -> currView/refAU -> baseView/refAU
+            Int         iCurrRefDisp        = xGetDisparityFromVirtDepth( uiBaseId, iCurrRefDepth );
+            Int         iBaseRefSamplePosX  = iCurrRefSamplePosX + ( ( iCurrRefDisp + iAddX ) >> iShiftX );
+            Int         iBaseRefSamplePosY  = iCurrRefSamplePosY;
+            TComPic*    pcBaseRefPic        = pcBaseCU->getSlice()->getRefPic( eBaseRefPicList, aiBaseRefIdx[ iBaseRefListId ] );
+            TComPicYuv* pcBaseRefDMap       = pcBaseRefPic->getPredDepthMap();
+            Pel*        piBaseRefDMap       = pcBaseRefDMap->getLumaAddr();
+            Int         iBaseRefStride      = pcBaseRefDMap->getStride();
+            iBaseRefSamplePosX              = Clip3( 0, pcBaseRefDMap->getWidth () - 1, iBaseRefSamplePosX );
+            iBaseRefSamplePosY              = Clip3( 0, pcBaseRefDMap->getHeight() - 1, iBaseRefSamplePosY );
+            Int         iBaseRefDepth       = piBaseRefDMap[ iBaseRefSamplePosY * iBaseRefStride + iBaseRefSamplePosX ];
+
+            // location and depth for path currView/currAU ->baseView/currAU -> baseView/refAU
+            TComMv     rcBaseMv            = aiBaseMvField[ iBaseRefListId ]->getMv( iBaseAbsPartIdx );
+            Int         iAbsDeltaMvY        = ( rcBaseMv.getAbsVer() > rcCurrMv.getVer() ? rcBaseMv.getAbsVer() - rcCurrMv.getVer() : rcCurrMv.getVer() - rcBaseMv.getAbsVer() );
+
+            // check reliability (occlusion in reference access unit / vertical motion vector difference)
+            if( iBaseRefDepth != iCurrRefDepth || iAbsDeltaMvY > iMaxAbsDeltaMvY )
+            {
+              continue;
+            }
+
+            // determine new depth
+            Int         iCurrCandDisp       = iCurrRefDisp + rcCurrMv.getHor() - rcBaseMv.getHor();
+            Int         iCurrCandDepth      = xGetVirtDepthFromDisparity( uiBaseId, iCurrCandDisp );
+            aiDepthCand.push_back( iCurrCandDepth );
+          } // iCurrRefPoc == iBaseRefPoc
+        } // iBaseRefListId
+      } // iCurrRefListId
+      
+      // set depth for 4x4 block
+      if( aiDepthCand.size() )
+      { // get depth with minimum change (probably most reliable)
+        Int             iMinAbsDepthChange  = (1<<30);
+        Int             iDepthForMinChange  = (1<<30);
+        for( UInt uiCandId = 0; uiCandId < (UInt)aiDepthCand.size(); uiCandId++ )
+        {
+          Int           iAbsDeltaDepth      = ( aiDepthCand[uiCandId] > iCurrPredDepth ? aiDepthCand[uiCandId] > iCurrPredDepth : iCurrPredDepth - aiDepthCand[uiCandId] );
+          if( iAbsDeltaDepth < iMinAbsDepthChange )
+          {
+            iMinAbsDepthChange              = iAbsDeltaDepth;
+            iDepthForMinChange              = aiDepthCand[uiCandId];
+          }
+        }
+        m_aai4x4Depth[i4x4BlkY][i4x4BlkX]   = Min( Max( 0, iDepthForMinChange ), PDM_MAX_ABS_VIRT_DEPTH );
+        m_aabDepthSet[i4x4BlkY][i4x4BlkX]   = true;
+        iNum4x4Set++;
+      }
+    } // i4x4BlkX
+  } // i4x4BlkY
+
+  //===== fall back (take original depth for 4x4 blocks) ====
+  if( iNum4x4Set < Max( 1, ( iNum4x4BlksY * iNum4x4BlksX ) >> 2 ) )
+  {
+    iNum4x4Set = 0;
+    for( Int i4x4BlkY = 0; i4x4BlkY < iNum4x4BlksY; i4x4BlkY++ )
+    {
+      for( Int i4x4BlkX = 0; i4x4BlkX < iNum4x4BlksX; i4x4BlkX++ )
+      {
+        Int             iCurrSamplePosX     = iCurrPUPosX + ( ( ( i4x4BlkX << 2 ) + 1 ) >> m_uiSubSampExpX );
+        Int             iCurrSamplePosY     = iCurrPUPosY + ( ( ( i4x4BlkY << 2 ) + 1 ) >> m_uiSubSampExpY );
+        m_aai4x4Depth[i4x4BlkY][i4x4BlkX]   = piCurrDepthMap[ iCurrSamplePosY * iCurrStride + iCurrSamplePosX ];
+        m_aabDepthSet[i4x4BlkY][i4x4BlkX]   = true;
+        iNum4x4Set++;
+      }
+    }
+  }
+
+#if PDM_ONE_DEPTH_PER_PU
+  //===== set average in 4x4 depth array =====
+  Int   iSum        = 0;
+  for( Int i4x4BlkY = 0; i4x4BlkY < iNum4x4BlksY; i4x4BlkY++ )
+  {
+    for( Int i4x4BlkX = 0; i4x4BlkX < iNum4x4BlksX; i4x4BlkX++ )
+    {
+      if( m_aabDepthSet[ i4x4BlkY ][ i4x4BlkX ] )
+      {
+        iSum += m_aai4x4Depth[ i4x4BlkY ][ i4x4BlkX ];
+      }
+    }
+  }
+  Int   iDepth      = ( iSum + ( iNum4x4Set >> 1 ) ) / iNum4x4Set;
+  iNum4x4Set        = iNum4x4BlksY * iNum4x4BlksX;
+  for( Int i4x4BlkY = 0; i4x4BlkY < iNum4x4BlksY; i4x4BlkY++ )
+  {
+    for( Int i4x4BlkX = 0; i4x4BlkX < iNum4x4BlksX; i4x4BlkX++ )
+    {
+      m_aai4x4Depth[ i4x4BlkY ][ i4x4BlkX ] = iDepth;
+      m_aabDepthSet[ i4x4BlkY ][ i4x4BlkX ] = true;
+    }
+  }
+#endif
+ 
+  //===== complete depth arrays =====
+  while( iNum4x4BlksY * iNum4x4BlksX - iNum4x4Set )
+  {
+    for( Int i4x4BlkY = 0; i4x4BlkY < iNum4x4BlksY; i4x4BlkY++ )
+    {
+      for( Int i4x4BlkX = 0; i4x4BlkX < iNum4x4BlksX; i4x4BlkX++ )
+      {
+        if( !m_aabDepthSet[ i4x4BlkY ][ i4x4BlkX ] )
+        { // could also use minimum of neighbours (occlusions)
+          Int iNumNeighbours  = 0;
+          Int iSumNeighbours  = 0;
+          if( i4x4BlkY > 0              && m_aabDepthSet[ i4x4BlkY-1 ][ i4x4BlkX   ] ) { iSumNeighbours += m_aai4x4Depth[ i4x4BlkY-1 ][ i4x4BlkX   ]; iNumNeighbours++; }
+          if( i4x4BlkY < iNum4x4BlksY-1 && m_aabDepthSet[ i4x4BlkY+1 ][ i4x4BlkX   ] ) { iSumNeighbours += m_aai4x4Depth[ i4x4BlkY+1 ][ i4x4BlkX   ]; iNumNeighbours++; }
+          if( i4x4BlkX > 0              && m_aabDepthSet[ i4x4BlkY   ][ i4x4BlkX-1 ] ) { iSumNeighbours += m_aai4x4Depth[ i4x4BlkY   ][ i4x4BlkX-1 ]; iNumNeighbours++; }
+          if( i4x4BlkX < iNum4x4BlksX-1 && m_aabDepthSet[ i4x4BlkY   ][ i4x4BlkX+1 ] ) { iSumNeighbours += m_aai4x4Depth[ i4x4BlkY   ][ i4x4BlkX+1 ]; iNumNeighbours++; }
+          if( iNumNeighbours )
+          {
+            m_aai4x4Depth[ i4x4BlkY ][ i4x4BlkX ] = ( iSumNeighbours + ( iNumNeighbours >> 1 ) ) / iNumNeighbours;
+            m_aabDepthSet[ i4x4BlkY ][ i4x4BlkX ] = true;
+            iNum4x4Set++;
+          }
+        }
+      }
+    }
+  }
+
+  //===== set depth values =====
+  UInt uiBlkX     = g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ] >> m_uiSubSampExpX;
+  UInt uiBlkY     = g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ] >> m_uiSubSampExpY;
+  Pel* piDepthMap = pcCUDepthMap->getLumaAddr() + uiBlkY * pcCUDepthMap->getStride() + uiBlkX;
+  Int  iCUStride  = pcCUDepthMap->getStride  ();
+  for( Int iRow = 0; iRow < iHeight; iRow++, piDepthMap += iCUStride )
+  {
+    for( Int iCol = 0; iCol < iWidth; iCol++ )
+    {
+      piDepthMap[ iCol ] = m_aai4x4Depth[ (iRow << m_uiSubSampExpY) >> 2  ][ (iCol << m_uiSubSampExpX) >> 2 ];
+    }
+  }
+}
+
+
+Void
+TComDepthMapGenerator::xInterPUDepthMapPrediction( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx )
+{
+  m_pcPrediction->motionCompensation( pcCU, pcCUDepthMap, REF_PIC_LIST_X, (Int)uiPartIdx, true, m_uiSubSampExpX, m_uiSubSampExpY );  
+}
+
+
+Bool
+TComDepthMapGenerator::xGetPredDepth( TComDataCU* pcCU, UInt uiPartIdx, Int& riPrdDepth, Int* piPosX, Int* piPosY )
+{
+  AOF  ( m_bCreated && m_bInit );
+  AOF  ( pcCU );
+  ROFRS( m_bPDMAvailable, false );
+
+  TComSlice*    pcSlice     = pcCU->getSlice ();
+  TComPic*      pcPic       = pcCU->getPic   ();
+  TComSPS*      pcSPS       = pcSlice->getSPS();
+  AOF  ( pcPic->getPredDepthMap() );
+  AOF  ( pcSPS->getViewId() == m_uiCurrViewId );
+  
+  //===== get predicted depth and disprity for middle position of current PU =====  
+  UInt          uiPartAddr;
+  Int           iWidth;
+  Int           iHeight;
+  pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iWidth, iHeight );
+  TComPicYuv*   pcPredDepthMap  = pcPic->getPredDepthMap();
+  Pel*          piPredDepthMap  = pcPredDepthMap->getLumaAddr ( 0 );
+  Int           iCurrStride     = pcPredDepthMap->getStride   ();
+  Int           iCurrPosX;
+  Int           iCurrPosY;
+  pcPredDepthMap->getTopLeftSamplePos( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr, iCurrPosX, iCurrPosY );
+#if H3D_IVMP // max disparity within PU
+  Int DiWidth  = iCurrPosX+(iWidth  >> m_uiSubSampExpX);
+  Int DiHeight = iCurrPosY+(iHeight >> m_uiSubSampExpY);
+  Int maxDepth = MIN_INT;
+
+  for(Int y=iCurrPosY; y<DiHeight ;y++)
+  {
+    for(Int x=iCurrPosX; x<DiWidth; x++)
+    {
+      if(piPredDepthMap[ x + y * iCurrStride ] > maxDepth)
+      {
+        maxDepth = piPredDepthMap[ x + y * iCurrStride ];
+      }
+    }
+  }
+  iCurrPosX  += ( ( iWidth  >> m_uiSubSampExpX ) - 1 ) >> 1;
+  iCurrPosY  += ( ( iHeight >> m_uiSubSampExpY ) - 1 ) >> 1;
+  riPrdDepth  = maxDepth;
+#else
+  iCurrPosX  += ( ( iWidth  >> m_uiSubSampExpX ) - 1 ) >> 1;
+  iCurrPosY  += ( ( iHeight >> m_uiSubSampExpY ) - 1 ) >> 1;
+  riPrdDepth  = piPredDepthMap[ iCurrPosX + iCurrPosY * iCurrStride ];
+#endif
+  if( piPosX )
+  {
+    *piPosX   = iCurrPosX;
+  }
+  if( piPosY )
+  {
+    *piPosY   = iCurrPosY;
+  }
+  return        true;
+}
+#endif // H3D_NBDV
+
+#endif // DEPTH_MAP_GENERATION
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDepthMapGenerator.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDepthMapGenerator.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComDepthMapGenerator.h	(revision 341)
@@ -0,0 +1,268 @@
+/* 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-2011, 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 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     TComDepthMapGenerator.h
+    \brief    depth map generator class (header)
+*/
+
+
+#ifndef __TCOM_DEPTH_MAP_GENERATOR__
+#define __TCOM_DEPTH_MAP_GENERATOR__
+
+
+#include "CommonDef.h"
+#include "TComPic.h"
+#include "TComPrediction.h"
+#include "TComSlice.h"
+
+
+#if DEPTH_MAP_GENERATION
+#if VIDYO_VPS_INTEGRATION
+class TComVPSAccess // would be better to have a real VPS buffer
+{
+public:
+  TComVPSAccess ()  { clear(); }
+  ~TComVPSAccess()  {}
+
+  Void      clear   ()                                { ::memset( m_aacVPS, 0x00, sizeof( m_aacVPS ) ); m_uiActiceVPSId = 0;}
+  Void      addVPS  ( TComVPS* pcVPS )                { m_aacVPS[ pcVPS->getVPSId() ] = pcVPS; }
+  TComVPS*  getVPS  ( UInt uiVPSId )                  { return m_aacVPS[ uiVPSId ]; }
+  TComVPS*  getActiveVPS  ( )                         { return m_aacVPS[ m_uiActiceVPSId ]; }
+  Void      setActiveVPSId  ( UInt activeVPSId )      { m_uiActiceVPSId = activeVPSId; }
+private:
+  TComVPS*  m_aacVPS[ MAX_NUM_VPS ];
+  UInt      m_uiActiceVPSId;
+};
+#endif
+
+class TComSPSAccess // would be better to have a real SPS buffer
+{
+public:
+  TComSPSAccess ()  { clear(); }
+  ~TComSPSAccess()  {}
+
+  Void      clear   ()                            { ::memset( m_aacActiveSPS, 0x00, sizeof( m_aacActiveSPS ) ); }
+  Void      addSPS  ( TComSPS* pcSPS    )         { m_aacActiveSPS[ pcSPS->isDepth() ? 1 : 0 ][ pcSPS->getViewId() ] = pcSPS; }
+  TComSPS*  getSPS  ( UInt     uiViewId, 
+                      Bool     bIsDepth = false ) { return m_aacActiveSPS[ bIsDepth ? 1 : 0 ][ uiViewId ]; }
+
+  UInt      getPdm  ()                            { if( m_aacActiveSPS[0][1] ) { return m_aacActiveSPS[0][1]->getPredDepthMapGeneration(); } return 0; }
+#if H3D_IVRP
+  UInt      getResPrd ()                          { if( m_aacActiveSPS[0][1] ) { return m_aacActiveSPS[0][1]->getMultiviewResPredMode  (); } return 0; }
+#endif
+
+private:
+  TComSPS*  m_aacActiveSPS[ 2 ][ MAX_VIEW_NUM ];
+};
+
+
+
+class TComAUPicAccess // would be better to have a real decoded picture buffer
+{
+public:
+  TComAUPicAccess () : m_iLastPoc( 0 ), m_uiMaxViewId( 0 ) { clear(); }
+  ~TComAUPicAccess()                   {}
+
+  Void      clear   ()                            { ::memset( m_aacCurrAUPics, 0x00, sizeof( m_aacCurrAUPics ) ); }
+  Void      addPic    ( TComPic* pcPic    )         { if( m_iLastPoc != pcPic->getPOC() ) 
+                                                      { 
+                                                        clear(); 
+                                                        m_iLastPoc = pcPic->getPOC(); 
+                                                      } 
+                                                      m_aacCurrAUPics[ pcPic->getSPS()->isDepth() ? 1 : 0 ][ pcPic->getSPS()->getViewId() ] = pcPic; 
+                                                      if( pcPic->getSPS()->getViewId() > m_uiMaxViewId )
+                                                      {
+                                                        m_uiMaxViewId = pcPic->getSPS()->getViewId();
+                                                      }
+                                                    }
+  TComPic*  getPic  ( UInt     uiViewId,
+                      Bool     bIsDepth = false ) { return m_aacCurrAUPics[ bIsDepth ? 1 : 0 ][ uiViewId ]; }
+  UInt      getMaxVId ()                            { return m_uiMaxViewId; }
+
+private:
+  Int       m_iLastPoc;
+  UInt      m_uiMaxViewId;
+  TComPic*  m_aacCurrAUPics[ 2 ][ MAX_VIEW_NUM ];
+};
+
+
+
+class TComDepthMapGenerator
+{
+public:
+  TComDepthMapGenerator ();
+  ~TComDepthMapGenerator();
+
+  Void  create                ( Bool bDecoder, UInt uiPicWidth, UInt uiPicHeight, UInt uiMaxCUDepth, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiOrgBitDepth, UInt uiSubSampExpX, UInt uiSubSampExpY );
+  Void  destroy               ();
+
+#if VIDYO_VPS_INTEGRATION
+  Void  init( TComPrediction* pcPrediction, TComVPSAccess* pcVPSAccess, TComSPSAccess* pcSPSAccess, TComAUPicAccess* pcAUPicAccess );
+#endif
+  Void  init                  ( TComPrediction* pcPrediction, TComSPSAccess* pcSPSAccess, TComAUPicAccess* pcAUPicAccess );
+  Void  uninit                ();
+
+  Void  initViewComponent     ( TComPic*      pcPic );
+#if !H3D_NBDV
+  Bool  predictDepthMap       ( TComPic*      pcPic );
+  Void  updateDepthMap        ( TComPic*      pcPic );
+  Void  dumpDepthMap          ( TComPic*      pcPic, char* pFilenameBase );
+#endif
+
+#if H3D_IVMP
+  Void  covertOrgDepthMap     ( TComPic*      pcPic );
+#endif
+
+  UInt  getBaseViewId         ( UInt          uiIdx ) { AOF( uiIdx < m_auiBaseIdList.size() );  return m_auiBaseIdList[uiIdx]; }
+  UInt  getSubSampExpX        ()                      { return m_uiSubSampExpX; }
+  UInt  getSubSampExpY        ()                      { return m_uiSubSampExpY; }
+  Int   getDisparity          ( TComPic*      pcPic, Int iPosX, Int iPosY, UInt uiRefViewId );
+#if H3D_IVMP
+#if H3D_NBDV
+  Bool  getPdmCandidate       ( TComDataCU*   pcCU, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* iPdm, Bool bMerge );
+#else
+  Int   getPdmMergeCandidate  ( TComDataCU*   pcCU, UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv );
+  Bool  getPdmMvPred          ( TComDataCU*   pcCU, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv, Bool bMerge );
+#endif
+  Bool  getIViewOrgDepthMvPred( TComDataCU*   pcCU, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv );
+#endif
+
+  TComPrediction*   getPrediction ()  { return m_pcPrediction;  }
+#if VIDYO_VPS_INTEGRATION
+  TComVPSAccess*    getVPSAccess  ()  { return m_pcVPSAccess;   }
+#endif
+  TComSPSAccess*    getSPSAccess  ()  { return m_pcSPSAccess;   }
+  TComAUPicAccess*  getAUPicAccess()  { return m_pcAUPicAccess; }
+
+private:
+  // picture operations
+#if !H3D_NBDV
+  Bool  xConvertDepthMapCurr2Ref  ( TComPic*    pcRef, TComPic* pcCur );
+  Bool  xConvertDepthMapRef2Curr  ( TComPic*    pcCur, TComPic* pcRef );
+  Bool  xPredictDepthMap          ( TComPic*    pcPic );
+  Bool  xFillDepthMapHoles        ( TComPic*    pcPic );
+  Void  xClearDepthMap            ( TComPic*    pcPic, Int      iVal  = PDM_UNDEFINED_DEPTH
+#if PDM_REMOVE_DEPENDENCE
+  ,
+  Int forFirstNonBaseView = 0
+#endif
+  );
+  Void  xSetChroma                ( TComPicYuv* pcPic, Int      iVal  );
+
+  // CU operations  
+  Void  xPredictCUDepthMap        ( TComDataCU* pcCU, UInt uiDepth, UInt uiAbsPartIdx );                            // CU depth map prediction
+  Void  xIntraPredictCUDepthMap   ( TComDataCU* pcCU, TComYuv* pcCUDepthMap );                                      // CU intra prediction
+  Void  xInterPredictCUDepthMap   ( TComDataCU* pcCU, TComYuv* pcCUDepthMap );                                      // CU inter prediction
+  
+  // PU and block operations  
+  Void  xIntraPredictBlkDepthMap  ( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiAbsPartIdx, UInt uiTrDepth );   // block intra prediction
+  Void  xInterPredictPUDepthMap   ( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx );                      // PU inter prediction/update
+  Void  xIViewPUDepthMapUpdate    ( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx );                      // PU interview update
+  Void  xInterPUDepthMapUpdate    ( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx );                      // PU inter update
+  Void  xInterPUDepthMapPrediction( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx );                      // PU inter prediction
+  Bool  xGetPredDepth             ( TComDataCU* pcCU, UInt uiPartIdx, Int& riPrdDepth, Int* piPosX = 0, Int* piPosY = 0 );
+#endif
+  // conversion functions
+  Int   xGetVirtDepthFromDisparity( UInt uiBaseId, Int iDisparity )
+  {
+    AOF( uiBaseId < m_uiCurrViewId );
+    Int*   pPar = m_aaiConvParsDisparity2VirtDepth[ uiBaseId ];
+    Int    iRes = ( pPar[ 0 ] * iDisparity + pPar[ 1 ] ) >> pPar[ 2 ];
+    return iRes;
+  }
+  Int   xGetDisparityFromVirtDepth( UInt uiBaseId, Int iVirtDepth )
+  {
+    AOF( uiBaseId < m_uiCurrViewId );
+    Int*   pPar = m_aaiConvParsVirtDepth2Disparity[ uiBaseId ];
+    Int    iRes = ( pPar[ 0 ] * iVirtDepth + pPar[ 1 ] ) >> pPar[ 2 ];
+    return iRes;
+  }
+  Int   xGetVirtDepthFromOrigDepth( UInt uiViewId, Int iOrigDepth )
+  {
+    AOF( uiViewId <= m_uiCurrViewId );
+    Int*   pPar = m_aaiConvParsOrigDepth2VirtDepth[ uiViewId ];
+    Int    iRes = ( pPar[ 0 ] * iOrigDepth + pPar[ 1 ] ) >> pPar[ 2 ];
+    return iRes;
+  }
+  Int   xGetOrigDepthFromVirtDepth( UInt uiViewId, Int iVirtDepth )
+  {
+    AOF( uiViewId <= m_uiCurrViewId );
+    Int*   pPar = m_aaiConvParsVirtDepth2OrigDepth[ uiViewId ];
+    Int    iRes = ( pPar[ 0 ] * iVirtDepth + pPar[ 1 ] ) >> pPar[ 2 ];
+    return iRes;
+  }
+
+
+private:
+  // general parameters
+  Bool              m_bCreated;
+  Bool              m_bInit;
+  Bool              m_bDecoder;
+  TComPrediction*   m_pcPrediction;
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  TComVPSAccess*    m_pcVPSAccess;
+#endif
+  TComSPSAccess*    m_pcSPSAccess;
+  TComAUPicAccess*  m_pcAUPicAccess;
+  UInt              m_uiMaxDepth;
+  UInt              m_uiOrgDepthBitDepth;
+  UInt              m_uiSubSampExpX;
+  UInt              m_uiSubSampExpY;
+  TComYuv**         m_ppcYuv;
+  TComDataCU**      m_ppcCU;
+  TComPicYuv        m_cTmpPic;
+
+  // conversion parameters
+  UInt              m_uiCurrViewId;
+  Bool              m_bPDMAvailable;
+  std::vector<UInt> m_auiBaseIdList;
+  Int               m_aaiConvParsDisparity2VirtDepth[ MAX_VIEW_NUM ][ 3 ];  // disparity      ==> virtual  depth   (0:scale, 1:add, 2:shift)
+  Int               m_aaiConvParsVirtDepth2Disparity[ MAX_VIEW_NUM ][ 3 ];  // virtual  depth ==> disparity        (0:scale, 1:add, 2:shift)
+  Int               m_aaiConvParsOrigDepth2VirtDepth[ MAX_VIEW_NUM ][ 3 ];  // original depth ==> virtual  depth   (0:scale, 1:add, 2:shift)
+  Int               m_aaiConvParsVirtDepth2OrigDepth[ MAX_VIEW_NUM ][ 3 ];  // virtual  depth ==> original depth   (0:scale, 1:add, 2:shift)
+
+  // temporary arrays
+  Bool              m_aabDepthSet[ MAX_CU_SIZE >> 2 ][ MAX_CU_SIZE >> 2 ];
+  Int               m_aai4x4Depth[ MAX_CU_SIZE >> 2 ][ MAX_CU_SIZE >> 2 ];
+};
+
+
+#endif // DEPTH_MAP_GENERATION
+
+#endif // __TCOM_DEPTH_MAP_GENERATOR__
+
+
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 341)
@@ -0,0 +1,416 @@
+/* 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-2012, 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
+ * \brief Implementation of TComInterpolationFilter class
+ */
+
+// ====================================================================================================================
+// Includes
+// ====================================================================================================================
+
+#include "TComRom.h"
+#include "TComInterpolationFilter.h"
+#include <assert.h>
+
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const Short TComInterpolationFilter::m_lumaFilter[4][NTAPS_LUMA] =
+{
+  {  0, 0,   0, 64,  0,   0, 0,  0 },
+  { -1, 4, -10, 58, 17,  -5, 1,  0 },
+  { -1, 4, -11, 40, 40, -11, 4, -1 },
+  {  0, 1,  -5, 17, 58, -10, 4, -1 }
+};
+
+const Short TComInterpolationFilter::m_chromaFilter[8][NTAPS_CHROMA] =
+{
+  {  0, 64,  0,  0 },
+  { -2, 58, 10, -2 },
+  { -4, 54, 16, -2 },
+  { -6, 46, 28, -4 },
+  { -4, 36, 36, -4 },
+  { -4, 28, 46, -6 },
+  { -2, 16, 54, -4 },
+  { -2, 10, 58, -2 }
+};
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+/**
+ * \brief Apply unit FIR filter to a block of samples
+ *
+ * \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 isFirst    Flag indicating whether it is the first filtering operation
+ * \param isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterCopy(const Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast)
+{
+  Int row, col;
+  
+  if ( isFirst == isLast )
+  {
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        dst[col] = src[col];
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }              
+  }
+  else if ( isFirst )
+  {
+    Int shift = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+    
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        Short val = src[col] << shift;
+        dst[col] = val - (Short)IF_INTERNAL_OFFS;
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }          
+  }
+  else
+  {
+    Int shift = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+    Short offset = IF_INTERNAL_OFFS + (1 << (shift - 1));
+    Short maxVal = g_uiIBDI_MAX;
+    Short 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;
+        dst[col] = val;
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }              
+  }
+}
+
+/**
+ * \brief Apply FIR filter to a block of samples
+ *
+ * \tparam N          Number of taps
+ * \tparam isVertical Flag indicating filtering along vertical direction
+ * \tparam isFirst    Flag indicating whether it is the first filtering operation
+ * \tparam isLast     Flag indicating whether it is the last filtering operation
+ * \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  coeff      Pointer to filter taps
+ */
+template<int N, bool isVertical, bool isFirst, bool isLast>
+Void TComInterpolationFilter::filter(Short const *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Short const *coeff)
+{
+  Int row, col;
+  
+  Short c[8];
+  c[0] = coeff[0];
+  c[1] = coeff[1];
+  if ( N >= 4 )
+  {
+    c[2] = coeff[2];
+    c[3] = coeff[3];
+  }
+  if ( N >= 6 )
+  {
+    c[4] = coeff[4];
+    c[5] = coeff[5];
+  }
+  if ( N == 8 )
+  {
+    c[6] = coeff[6];
+    c[7] = coeff[7];
+  }
+  
+  Int cStride = ( isVertical ) ? srcStride : 1;
+  src -= ( N/2 - 1 ) * cStride;
+
+  Int offset;
+  Short maxVal;
+  Int headRoom = IF_INTERNAL_PREC - (g_uiBitDepth + g_uiBitIncrement);
+  Int shift = IF_FILTER_PREC;
+  if ( isLast )
+  {
+    shift += (isFirst) ? 0 : headRoom;
+    offset = 1 << (shift - 1);
+    offset += (isFirst) ? 0 : IF_INTERNAL_OFFS << IF_FILTER_PREC;
+    maxVal = g_uiIBDI_MAX;
+  }
+  else
+  {
+    shift -= (isFirst) ? headRoom : 0;
+    offset = (isFirst) ? -IF_INTERNAL_OFFS << shift : 0;
+    maxVal = 0;
+  }
+  
+  for (row = 0; row < height; row++)
+  {
+    for (col = 0; col < width; col++)
+    {
+      Int sum;
+      
+      sum  = src[ col + 0 * cStride] * c[0];
+      sum += src[ col + 1 * cStride] * c[1];
+      if ( N >= 4 )
+      {
+        sum += src[ col + 2 * cStride] * c[2];
+        sum += src[ col + 3 * cStride] * c[3];
+      }
+      if ( N >= 6 )
+      {
+        sum += src[ col + 4 * cStride] * c[4];
+        sum += src[ col + 5 * cStride] * c[5];
+      }
+      if ( N == 8 )
+      {
+        sum += src[ col + 6 * cStride] * c[6];
+        sum += src[ col + 7 * cStride] * c[7];        
+      }
+      
+      Short val = ( sum + offset ) >> shift;
+      if ( isLast )
+      {
+        val = ( val < 0 ) ? 0 : val;
+        val = ( val > maxVal ) ? maxVal : val;        
+      }
+      dst[col] = val;
+    }
+    
+    src += srcStride;
+    dst += dstStride;
+  }    
+}
+
+/**
+ * \brief Filter a block of samples (horizontal)
+ *
+ * \tparam N          Number of taps
+ * \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  isLast     Flag indicating whether it is the last filtering operation
+ * \param  coeff      Pointer to filter taps
+ */
+template<int N>
+Void TComInterpolationFilter::filterHor(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isLast, Short const *coeff)
+{
+  if ( isLast )
+  {
+    filter<N, false, true, true>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else
+  {
+    filter<N, false, true, false>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+}
+
+/**
+ * \brief Filter a block of samples (vertical)
+ *
+ * \tparam N          Number of taps
+ * \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  isFirst    Flag indicating whether it is the first filtering operation
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ * \param  coeff      Pointer to filter taps
+ */
+template<int N>
+Void TComInterpolationFilter::filterVer(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, Short const *coeff)
+{
+  if ( isFirst && isLast )
+  {
+    filter<N, true, true, true>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else if ( isFirst && !isLast )
+  {
+    filter<N, true, true, false>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else if ( !isFirst && isLast )
+  {
+    filter<N, true, false, true>(src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else
+  {
+    filter<N, true, false, false>(src, srcStride, dst, dstStride, width, height, coeff);    
+  }      
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * \brief Filter a block of luma 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::filterHorLuma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast )
+{
+  assert(frac >= 0 && frac < 4);
+  
+  if ( frac == 0 )
+  {
+    filterCopy( src, srcStride, dst, dstStride, width, height, true, isLast );
+  }
+  else
+  {
+    filterHor<NTAPS_LUMA>(src, srcStride, dst, dstStride, width, height, isLast, m_lumaFilter[frac]);
+  }
+}
+
+/**
+ * \brief Filter a block of luma 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::filterVerLuma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast )
+{
+  assert(frac >= 0 && frac < 4);
+  
+  if ( frac == 0 )
+  {
+    filterCopy( src, srcStride, dst, dstStride, width, height, isFirst, isLast );
+  }
+  else
+  {
+    filterVer<NTAPS_LUMA>(src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilter[frac]);    
+  }
+}
+
+/**
+ * \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 < 8);
+  
+  if ( frac == 0 )
+  {
+    filterCopy( src, srcStride, dst, dstStride, width, height, true, isLast );
+  }
+  else
+  {
+    filterHor<NTAPS_CHROMA>(src, srcStride, dst, dstStride, width, height, isLast, m_chromaFilter[frac]);
+  }
+}
+
+/**
+ * \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 )
+{
+  assert(frac >= 0 && frac < 8);
+  
+  if ( frac == 0 )
+  {
+    filterCopy( src, srcStride, dst, dstStride, width, height, isFirst, isLast );
+  }
+  else
+  {
+    filterVer<NTAPS_CHROMA>(src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilter[frac]);    
+  }
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 341)
@@ -0,0 +1,83 @@
+/* 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-2012, 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
+ * \brief Declaration of TComInterpolationFilter class
+ */
+
+#ifndef __HM_TCOMINTERPOLATIONFILTER_H__
+#define __HM_TCOMINTERPOLATIONFILTER_H__
+
+#include "TypeDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#define NTAPS_LUMA        8 ///< Number of taps for luma
+#define NTAPS_CHROMA      4 ///< Number of taps for chroma
+#define IF_INTERNAL_PREC 14 ///< Number of bits for internal precision
+#define IF_FILTER_PREC    6 ///< Log2 of sum of filter taps
+#define IF_INTERNAL_OFFS (1<<(IF_INTERNAL_PREC-1)) ///< Offset used internally
+
+/**
+ * \brief Interpolation filter class
+ */
+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 Void filterCopy(const Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast);
+  
+  template<int N, bool isVertical, bool isFirst, bool isLast>
+  static Void filter(Pel const *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Short const *coeff);
+
+  template<int N>
+  static Void filterHor(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height,               Bool isLast, Short const *coeff);
+  template<int N>
+  static Void filterVer(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, Short const *coeff);
+
+public:
+  TComInterpolationFilter() {}
+  ~TComInterpolationFilter() {}
+
+  Void filterHorLuma  (Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast );
+  Void filterVerLuma  (Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast );
+  Void filterHorChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast );
+  Void filterVerChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast );
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComList.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComList.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComList.h	(revision 341)
@@ -0,0 +1,115 @@
+/* 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-2012, 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     TComList.h
+    \brief    general list class (header)
+*/
+
+#ifndef _TCOMLIST_
+#define _TCOMLIST_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <list>
+#include <assert.h>
+#include "CommonDef.h"
+
+#include <cstdlib>
+using namespace std;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// list template
+template< class C >
+class TComList : public std::list< C >
+{
+public:
+  typedef typename std::list<C>::iterator TComIterator;
+  
+  TComList& operator += ( const TComList& rcTComList)
+  {
+    if( ! rcTComList.empty() )
+    {
+      insert( this->end(), rcTComList.begin(), rcTComList.end());
+    }
+    return *this;
+  } // leszek
+  
+  C popBack()
+  {
+    C cT = this->back();
+    this->pop_back();
+    return cT;
+  }
+  
+  C popFront()
+  {
+    C cT = this->front();
+    this->pop_front();
+    return cT;
+  }
+  
+  Void pushBack( const C& rcT )
+  {
+    /*assert( sizeof(C) == 4);*/
+    if( rcT != NULL )
+    {
+      this->push_back( rcT);
+    }
+  }
+  
+  Void pushFront( const C& rcT )
+  {
+    /*assert( sizeof(C) == 4);*/
+    if( rcT != NULL )
+    {
+      this->push_front( rcT);
+    }
+  }
+  
+  TComIterator find( const C& rcT ) // leszek
+  {
+    return find( this->begin(), this->end(), rcT );
+  }
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 341)
@@ -0,0 +1,920 @@
+/* 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-2012, 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     TComLoopFilter.cpp
+    \brief    deblocking filter
+*/
+
+#include "TComLoopFilter.h"
+#include "TComSlice.h"
+#include "TComMv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define   EDGE_VER    0
+#define   EDGE_HOR    1
+#define   QpUV(iQpY)  ( g_aucChromaScale[ max( min( (iQpY), MAX_QP ), MIN_QP ) ] )
+
+#define DEFAULT_INTRA_TC_OFFSET 2 ///< Default intra TC offset
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar tctable_8x8[56] =
+{
+  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,9,10,10,11,11,12,12,13,13,14,14
+};
+
+const UChar betatable_8x8[52] =
+{
+  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
+};
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComLoopFilter::TComLoopFilter()
+: m_uiNumPartitions( 0 )
+{
+  m_uiDisableDeblockingFilterIdc = 0;
+  m_bLFCrossTileBoundary = true;
+}
+
+TComLoopFilter::~TComLoopFilter()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+Void TComLoopFilter::setCfg( Bool DeblockingFilterControlPresent, UInt uiDisableDblkIdc, Int iBetaOffset_div2, Int iTcOffset_div2, Bool bLFCrossTileBoundary)
+{
+  m_bLFCrossTileBoundary = bLFCrossTileBoundary;
+
+  if (DeblockingFilterControlPresent)
+  {
+    m_uiDisableDeblockingFilterIdc  = uiDisableDblkIdc;
+    m_betaOffsetDiv2 = iBetaOffset_div2;
+    m_tcOffsetDiv2 = iTcOffset_div2;
+  } 
+  else // use default values
+  {
+    m_uiDisableDeblockingFilterIdc = 0;
+    m_betaOffsetDiv2 = 0;
+    m_tcOffsetDiv2 = 0;
+  }
+}
+
+Void TComLoopFilter::create( UInt uiMaxCUDepth )
+{
+  m_uiNumPartitions = 1 << ( uiMaxCUDepth<<1 );
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    m_aapucBS       [uiDir] = new UChar[m_uiNumPartitions];
+    for( UInt uiPlane = 0; uiPlane < 3; uiPlane++ )
+    {
+      m_aapbEdgeFilter[uiDir][uiPlane] = new Bool [m_uiNumPartitions];
+    }
+  }
+}
+
+Void TComLoopFilter::destroy()
+{
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    delete [] m_aapucBS       [uiDir];
+    for( UInt uiPlane = 0; uiPlane < 3; uiPlane++ )
+    {
+      delete [] m_aapbEdgeFilter[uiDir][uiPlane];
+    }
+  }
+}
+
+/**
+ - call deblocking function for every CU
+ .
+ \param  pcPic   picture class (TComPic) pointer
+ */
+Void TComLoopFilter::loopFilterPic( TComPic* pcPic )
+{
+  if (m_uiDisableDeblockingFilterIdc == 1)
+  {
+    return;
+  }
+  
+  // Horizontal filtering
+  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+
+    ::memset( m_aapucBS       [EDGE_VER], 0, sizeof( UChar ) * m_uiNumPartitions );
+    for( Int iPlane = 0; iPlane < 3; iPlane++ )
+    {
+      ::memset( m_aapbEdgeFilter[EDGE_VER][iPlane], 0, sizeof( bool  ) * m_uiNumPartitions );
+    }
+
+    // CU-based deblocking
+    xDeblockCU( pcCU, 0, 0, EDGE_VER );
+  }
+
+  // Vertical filtering
+  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+
+      ::memset( m_aapucBS       [EDGE_HOR], 0, sizeof( UChar ) * m_uiNumPartitions );
+    for( Int iPlane = 0; iPlane < 3; iPlane++ )
+    {
+      ::memset( m_aapbEdgeFilter[EDGE_HOR][iPlane], 0, sizeof( bool  ) * m_uiNumPartitions );
+    }
+
+    // CU-based deblocking
+    xDeblockCU( pcCU, 0, 0, EDGE_HOR );
+  }
+}
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - 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
+*/
+Void TComLoopFilter::xDeblockCU( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge )
+{
+  if(pcCU->getPic()==0||pcCU->getPartitionSize(uiAbsZorderIdx)==SIZE_NONE)
+  {
+    return;
+  }
+  TComPic* pcPic     = pcCU->getPic();
+  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts   = uiCurNumParts>>2;
+  
+  if( pcCU->getDepth(uiAbsZorderIdx) > uiDepth )
+  {
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      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 );
+      }
+    }
+    return;
+  }
+  
+  xSetLoopfilterParam( pcCU, uiAbsZorderIdx );
+  
+  xSetEdgefilterTU   ( pcCU, uiAbsZorderIdx , uiAbsZorderIdx, uiDepth );
+  xSetEdgefilterPU   ( pcCU, uiAbsZorderIdx );
+  
+  Int iDir = Edge;
+  for( UInt uiPartIdx = uiAbsZorderIdx; uiPartIdx < uiAbsZorderIdx + uiCurNumParts; uiPartIdx++ )
+  {
+    UInt uiBSCheck = ((iDir == EDGE_VER && uiPartIdx%2 == 0) || (iDir == EDGE_HOR && (uiPartIdx-((uiPartIdx>>2)<<2))/2 == 0));
+    if ( m_aapbEdgeFilter[iDir][0][uiPartIdx] && uiBSCheck )
+    {
+      xGetBoundaryStrengthSingle ( pcCU, uiAbsZorderIdx, iDir, uiPartIdx );
+    }
+  }
+  
+  UInt uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  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 ( (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, Bool nonSquare )
+{  
+  if ( uiWidthInBaseUnits == 0 )
+  {
+    uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
+  }
+  if ( uiHeightInBaseUnits == 0 )
+  {
+    uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> uiDepth;
+  }
+  const UInt uiNumElem = iDir == 0 ? uiHeightInBaseUnits : uiWidthInBaseUnits;
+  assert( uiNumElem > 0 );
+  assert( uiWidthInBaseUnits > 0 );
+  assert( uiHeightInBaseUnits > 0 );
+  for( UInt ui = 0; ui < uiNumElem; ui++ )
+  {
+    const UInt uiBsIdx = xCalcBsIdx( pcCU, uiScanIdx, iDir, iEdgeIdx, ui );
+    m_aapbEdgeFilter[iDir][0][uiBsIdx] = bValue;
+    m_aapbEdgeFilter[iDir][1][uiBsIdx] = bValue;
+    m_aapbEdgeFilter[iDir][2][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;
+    const UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      UInt nsAddr = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrSize - 1, uiAbsZorderIdx, absTUPartIdx, uiPartIdx, uiDepth + 1 - pcCU->getDepth( uiAbsZorderIdx ) );
+      xSetEdgefilterTU( pcCU,nsAddr, uiAbsZorderIdx, uiDepth + 1 );
+    }
+    return;
+  }
+
+  Int trWidth  = pcCU->getWidth( uiAbsZorderIdx ) >> pcCU->getTransformIdx( uiAbsZorderIdx );
+  Int trHeight = pcCU->getHeight( uiAbsZorderIdx ) >> pcCU->getTransformIdx( uiAbsZorderIdx );
+  pcCU->getNSQTSize( uiDepth - pcCU->getDepth( uiAbsZorderIdx ), uiAbsZorderIdx, trWidth, trHeight );
+
+  UInt uiWidthInBaseUnits  = trWidth >> 2;
+  UInt uiHeightInBaseUnits = trHeight >> 2;
+
+  xSetEdgefilterMultiple( pcCU, absTUPartIdx, uiDepth, EDGE_VER, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits );
+  xSetEdgefilterMultiple( pcCU, absTUPartIdx, uiDepth, EDGE_HOR, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits );
+}
+
+Void TComLoopFilter::xSetEdgefilterPU( TComDataCU* pcCU, UInt uiAbsZorderIdx )
+{
+  const UInt uiDepth = pcCU->getDepth( uiAbsZorderIdx );
+  const UInt uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
+  const UInt uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> 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 ) )
+  {
+    case SIZE_2Nx2N:
+    {
+      break;
+    }
+    case SIZE_2NxN:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiHWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_NxN:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiHWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_2NxnU:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiQHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_2NxnD:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHeightInBaseUnits - uiQHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_nLx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiQWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_nRx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiWidthInBaseUnits - uiQWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    default:
+    {
+      break;
+    }
+  }
+}
+
+
+Void TComLoopFilter::xSetLoopfilterParam( TComDataCU* pcCU, UInt uiAbsZorderIdx )
+{
+  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 = m_uiDisableDeblockingFilterIdc ? false : true ;
+  
+  if ( (uiX == 0) || (m_uiDisableDeblockingFilterIdc == 1) )
+  {
+    m_stLFCUParam.bLeftEdge = false;
+  }
+  else
+  {
+    m_stLFCUParam.bLeftEdge = true;
+  }
+  if ( m_stLFCUParam.bLeftEdge )
+  {
+    pcTempCU = pcCU->getPULeft( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+    if ( pcTempCU )
+    {
+      m_stLFCUParam.bLeftEdge = true;
+    }
+    else
+    {
+      m_stLFCUParam.bLeftEdge = false;
+    }
+  }
+  
+  if ( (uiY == 0 ) || (m_uiDisableDeblockingFilterIdc == 1) )
+  {
+    m_stLFCUParam.bTopEdge = false;
+  }
+  else
+  {
+    m_stLFCUParam.bTopEdge = true;
+  }
+  if ( m_stLFCUParam.bTopEdge )
+  {
+    pcTempCU = pcCU->getPUAbove( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false , false, false, !m_bLFCrossTileBoundary);
+    if ( pcTempCU )
+    {
+      m_stLFCUParam.bTopEdge = true;
+    }
+    else
+    {
+      m_stLFCUParam.bTopEdge = false;
+    }
+  }
+}
+
+Void TComLoopFilter::xGetBoundaryStrengthSingle ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, UInt uiAbsPartIdx )
+{
+  TComSlice* const pcSlice = pcCU->getSlice();
+  
+  const UInt uiPartQ = uiAbsPartIdx;
+  TComDataCU* const pcCUQ = pcCU;
+  
+  UInt uiPartP;
+  TComDataCU* pcCUP;
+  UInt uiBs = 0;
+  
+  //-- Calculate Block Index
+  if (iDir == EDGE_VER)
+  {
+    pcCUP = pcCUQ->getPULeft(uiPartP, uiPartQ, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false, false, false, !m_bLFCrossTileBoundary);
+  }
+  
+  //-- Set BS for Intra MB : BS = 4 or 3
+  if ( pcCUP->isIntra(uiPartP) || pcCUQ->isIntra(uiPartQ) 
+#if MERL_VSP_C0152
+    || pcCUP->getVSPIndex(uiPartP) || pcCUQ->getVSPIndex(uiPartQ)
+#endif
+     )
+  {
+    uiBs = 2;
+  }
+  
+  //-- Set BS for not Intra MB : BS = 2 or 1 or 0
+  if ( !pcCUP->isIntra(uiPartP) && !pcCUQ->isIntra(uiPartQ) 
+#if MERL_VSP_C0152
+    && !pcCUP->getVSPIndex(uiPartP) && !pcCUQ->getVSPIndex(uiPartQ)
+#endif
+  )
+  {
+    UInt nsPartQ = uiPartQ;
+    UInt nsPartP = uiPartP;
+    if(pcCUQ->getPredictionMode(uiPartQ) == MODE_INTER && pcCUQ->useNonSquarePU(uiPartQ))
+    {
+      nsPartQ = pcCUQ->getNSQTPartIdx( uiAbsPartIdx );
+    }
+    if(pcCUP->getPredictionMode(uiPartP) == MODE_INTER && pcCUP->useNonSquarePU(uiPartP))
+    {
+      nsPartP = pcCUP->getNSQTPartIdx( uiPartP );
+    }
+
+    if ( m_aapucBS[iDir][uiAbsPartIdx] && (pcCUQ->getCbf( nsPartQ, TEXT_LUMA, pcCUQ->getTransformIdx(nsPartQ)) != 0 || pcCUP->getCbf( nsPartP, TEXT_LUMA, pcCUP->getTransformIdx(nsPartP) ) != 0) )
+    {
+      uiBs = 1;
+    }
+    else
+    {
+      if (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false, true, false, !m_bLFCrossTileBoundary);
+      }
+      if (pcSlice->isInterB())
+      {
+        Int iRefIdx;
+        Int *piRefP0, *piRefP1, *piRefQ0, *piRefQ1;
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartP);
+        piRefP0 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartP);
+        piRefP1 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartQ);
+        piRefQ0 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartQ);
+        piRefQ1 = (iRefIdx < 0) ? NULL :  (Int*) 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);
+        TComMv pcMvQ0 = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartQ);
+        TComMv pcMvQ1 = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getMv(uiPartQ);
+        
+        if ( ((piRefP0==piRefQ0)&&(piRefP1==piRefQ1)) || ((piRefP0==piRefQ1)&&(piRefP1==piRefQ0)) )
+        {
+          uiBs = 0;
+          if ( piRefP0 != piRefP1 )   // Different L0 & L1
+          {
+            if ( piRefP0 == piRefQ0 )
+            {
+              pcMvP0 -= pcMvQ0;   pcMvP1 -= pcMvQ1;
+              uiBs = (pcMvP0.getAbsHor() >= 4) | (pcMvP0.getAbsVer() >= 4) |
+              (pcMvP1.getAbsHor() >= 4) | (pcMvP1.getAbsVer() >= 4);
+            }
+            else
+            {
+              pcMvP0 -= pcMvQ1;   pcMvP1 -= pcMvQ0;
+              uiBs = (pcMvP0.getAbsHor() >= 4) | (pcMvP0.getAbsVer() >= 4) |
+              (pcMvP1.getAbsHor() >= 4) | (pcMvP1.getAbsVer() >= 4);
+            }
+          }
+          else    // Same L0 & L1
+          {
+            TComMv pcMvSub0 = pcMvP0 - pcMvQ0;
+            TComMv pcMvSub1 = pcMvP1 - pcMvQ1;
+            pcMvP0 -= pcMvQ1;   pcMvP1 -= pcMvQ0;
+            uiBs = ( (pcMvP0.getAbsHor() >= 4) | (pcMvP0.getAbsVer() >= 4) |
+                    (pcMvP1.getAbsHor() >= 4) | (pcMvP1.getAbsVer() >= 4) ) &&
+            ( (pcMvSub0.getAbsHor() >= 4) | (pcMvSub0.getAbsVer() >= 4) |
+             (pcMvSub1.getAbsHor() >= 4) | (pcMvSub1.getAbsVer() >= 4) );
+          }
+        }
+        else // for all different Ref_Idx
+        {
+          uiBs = 1;
+        }
+      }
+      else  // pcSlice->isInterP()
+      {
+        Int iRefIdx;
+        Int *piRefP0, *piRefQ0;
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartP);
+        piRefP0 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartQ);
+        piRefQ0 = (iRefIdx < 0) ? NULL :  (Int*) pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        TComMv pcMvP0 = pcCUP->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartP);
+        TComMv pcMvQ0 = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartQ);
+        
+        pcMvP0 -= pcMvQ0;
+        uiBs = (piRefP0 != piRefQ0) | (pcMvP0.getAbsHor() >= 4) | (pcMvP0.getAbsVer() >= 4);
+      }
+    }   // enf of "if( one of BCBP == 0 )"
+  }   // enf of "if( not Intra )"
+  
+#if MERL_VSP_C0152
+  if ( pcCUP->getVSPIndex(uiPartP) || pcCUQ->getVSPIndex(uiPartQ))
+  {
+    uiBs = 0;
+  }
+#endif
+
+  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();
+  Int iQP = 0;
+  Int iQP_P = 0;
+  Int iQP_Q = 0;
+  UInt uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
+  
+  UInt  uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt  uiBsAbsIdx = 0, uiBs = 0;
+  Int   iOffset, iSrcStep;
+  
+  Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
+  Bool  bPartPNoFilter = false;
+  Bool  bPartQNoFilter = false; 
+  UInt  uiPartPIdx = 0;
+  UInt  uiPartQIdx = 0;
+  TComDataCU* pcCUP = pcCU; 
+  TComDataCU* pcCUQ = pcCU;
+  
+  if (iDir == EDGE_VER)
+  {
+    iOffset = 1;
+    iSrcStep = iStride;
+    piTmpSrc += iEdge*uiPelsInPart;
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    iOffset = iStride;
+    iSrcStep = 1;
+    piTmpSrc += iEdge*uiPelsInPart*iStride;
+  }
+  
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
+  {
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
+    uiBs = m_aapucBS[iDir][uiBsAbsIdx];
+    if ( uiBs )
+    {
+      iQP_Q = pcCU->getQP( uiBsAbsIdx );
+      uiPartQIdx = uiBsAbsIdx;
+      // Derive neighboring PU index
+      if (iDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+      }
+      else  // (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false, false, false, !m_bLFCrossTileBoundary);
+      }
+
+      iQP_P = pcCUP->getQP(uiPartPIdx);
+      
+      if(pcCU->getIPCMFlag(uiPartQIdx)) 
+      {
+        iQP_Q = 0; 
+      }
+      if(pcCUP->getIPCMFlag(uiPartPIdx)) 
+      {
+        iQP_P = 0; 
+      }
+      
+      iQP = (iQP_P + iQP_Q + 1) >> 1;
+      Int iBitdepthScale = (1<<(g_uiBitIncrement+g_uiBitDepth-8));
+      
+      Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, Int(iQP + DEFAULT_INTRA_TC_OFFSET*(uiBs-1) + (m_tcOffsetDiv2 << 1)));
+      Int iIndexB = Clip3(0, MAX_QP, iQP + (m_betaOffsetDiv2 << 1));
+      
+      Int iTc =  tctable_8x8[iIndexTC]*iBitdepthScale;
+      Int iBeta = betatable_8x8[iIndexB]*iBitdepthScale;
+      Int iSideThreshold = (iBeta+(iBeta>>1))>>3;
+      Int iThrCut = iTc*10;
+      
+      
+        Int dp0 = xCalcDP( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+0), iOffset);
+        Int dq0 = xCalcDQ( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+0), iOffset);
+        Int dp3 = xCalcDP( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+3), iOffset);
+        Int dq3 = xCalcDQ( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+3), iOffset);
+        Int d0 = dp0 + dq0;
+        Int d3 = dp3 + dq3;
+
+        Int dp = dp0 + dp3;
+        Int dq = dq0 + dq3;
+        Int d =  d0 + d3;
+        
+        if (bPCMFilter)
+        {
+          // Check if each of PUs is I_PCM
+          bPartPNoFilter = (pcCUP->getIPCMFlag(uiPartPIdx));
+          bPartQNoFilter = (pcCUQ->getIPCMFlag(uiPartQIdx));
+        }
+#if LOSSLESS_CODING
+        // check if each of PUs is lossless coded
+        bPartPNoFilter = bPartPNoFilter || (pcCU->isLosslessCoded(uiAbsZorderIdx) );
+        bPartQNoFilter = bPartQNoFilter || (pcCU->isLosslessCoded(uiAbsZorderIdx) );
+#endif 
+        if (d < iBeta)
+        { 
+          Bool bFilterP = (dp < iSideThreshold);
+          Bool bFilterQ = (dq < iSideThreshold);
+
+          Bool sw =  xUseStrongFiltering( iOffset, 2*d0, iBeta, iTc, piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+0))
+                  && xUseStrongFiltering( iOffset, 2*d3, iBeta, iTc, piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+3));
+
+          for ( Int i = 0; i < DEBLOCK_SMALLEST_BLOCK/2; i++)
+          {
+            xPelFilterLuma( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+i), iOffset, d, iBeta, iTc, sw, bPartPNoFilter, bPartQNoFilter, iThrCut, bFilterP, bFilterQ);
+
+          }
+        }
+    }
+  }
+}
+
+
+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 );
+  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();
+  
+  Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
+  Bool  bPartPNoFilter = false;
+  Bool  bPartQNoFilter = false; 
+  UInt  uiPartPIdx;
+  UInt  uiPartQIdx;
+  TComDataCU* pcCUP; 
+  TComDataCU* pcCUQ = pcCU;
+  
+  // Vertical Position
+  UInt uiEdgeNumInLCUVert = g_auiZscanToRaster[uiAbsZorderIdx]%uiLCUWidthInBaseUnits + iEdge;
+  UInt uiEdgeNumInLCUHor = g_auiZscanToRaster[uiAbsZorderIdx]/uiLCUWidthInBaseUnits + iEdge;
+  
+  if ( ( (uiEdgeNumInLCUVert%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChroma))&&(iDir==0) ) || ( (uiEdgeNumInLCUHor%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChroma))&& iDir ) )
+  {
+    return;
+  }
+  
+  UInt  uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
+  
+  UInt  uiBsAbsIdx;
+  UChar ucBs;
+  
+  Pel* piTmpSrcCb = piSrcCb;
+  Pel* piTmpSrcCr = piSrcCr;
+  
+  
+  if (iDir == EDGE_VER)
+  {
+    iOffset   = 1;
+    iSrcStep  = iStride;
+    piTmpSrcCb += iEdge*uiPelsInPartChroma;
+    piTmpSrcCr += iEdge*uiPelsInPartChroma;
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    iOffset   = iStride;
+    iSrcStep  = 1;
+    piTmpSrcCb += iEdge*iStride*uiPelsInPartChroma;
+    piTmpSrcCr += iEdge*iStride*uiPelsInPartChroma;
+  }
+  
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
+  {
+    ucBs = 0;
+    
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
+    ucBs = m_aapucBS[iDir][uiBsAbsIdx];
+    
+    if ( ucBs > 1)
+    {
+      iQP_Q = pcCU->getQP( uiBsAbsIdx );
+      uiPartQIdx = uiBsAbsIdx;
+      // Derive neighboring PU index
+      if (iDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+      }
+      else  // (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false, false, false, !m_bLFCrossTileBoundary);
+      }
+
+      iQP_P = pcCUP->getQP(uiPartPIdx);
+      
+      if(pcCU->getIPCMFlag(uiPartQIdx)) 
+      {
+        iQP_Q = 0; 
+      }
+      if(pcCUP->getIPCMFlag(uiPartPIdx)) 
+      {
+        iQP_P = 0; 
+      }
+      
+      iQP = QpUV((iQP_P + iQP_Q + 1) >> 1);
+      Int iBitdepthScale = (1<<(g_uiBitIncrement+g_uiBitDepth-8));
+      
+      Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, iQP + DEFAULT_INTRA_TC_OFFSET*(ucBs - 1) + (m_tcOffsetDiv2 << 1));
+      Int iTc =  tctable_8x8[iIndexTC]*iBitdepthScale;
+      
+      if(bPCMFilter)
+      {
+        // Check if each of PUs is IPCM
+        bPartPNoFilter = (pcCUP->getIPCMFlag(uiPartPIdx));
+        bPartQNoFilter = (pcCUQ->getIPCMFlag(uiPartQIdx));
+      }
+      
+#if LOSSLESS_CODING
+      // check if each of PUs is lossless coded
+      bPartPNoFilter = bPartPNoFilter || (pcCU->isLosslessCoded(uiAbsZorderIdx) );
+      bPartQNoFilter = bPartQNoFilter || (pcCU->isLosslessCoded(uiAbsZorderIdx) );
+#endif
+      for ( UInt uiStep = 0; uiStep < uiPelsInPartChroma; uiStep++ )
+      {
+        xPelFilterChroma( piTmpSrcCb + iSrcStep*(uiStep+iIdx*uiPelsInPartChroma), iOffset, iTc , bPartPNoFilter, bPartQNoFilter);
+        xPelFilterChroma( piTmpSrcCr + iSrcStep*(uiStep+iIdx*uiPelsInPartChroma), iOffset, iTc , bPartPNoFilter, bPartQNoFilter);
+      }
+    }
+  }
+}
+
+/**
+ - Deblocking for the luminance component with strong or weak filter
+ .
+ \param piSrc           pointer to picture data
+ \param iOffset         offset value for picture data
+ \param d               d value
+ \param beta            beta value
+ \param tc              tc value
+ \param sw              decision strong/weak filter
+ \param bPartPNoFilter  indicator to disable filtering on partP
+ \param bPartQNoFilter  indicator to disable filtering on partQ
+ \param iThrCut         threshold value for weak filter decision
+ \param bFilterSecondP  decision weak filter/no filter for partP
+ \param bFilterSecondQ  decision weak filter/no filter for partQ
+*/
+__inline Void TComLoopFilter::xPelFilterLuma( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc , Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ)
+{
+  Int delta;
+  
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-iOffset];
+  Pel m5  = piSrc[ iOffset];
+  Pel m2  = piSrc[-iOffset*2];
+  Pel m6  = piSrc[ iOffset*2];
+  Pel m1  = piSrc[-iOffset*3];
+  Pel m7  = piSrc[ iOffset*3];
+  Pel m0  = piSrc[-iOffset*4];
+
+  if (sw)
+  {
+    piSrc[-iOffset]   = Clip3(m3-2*tc, m3+2*tc, ((m1 + 2*m2 + 2*m3 + 2*m4 + m5 + 4) >> 3));
+    piSrc[0]          = Clip3(m4-2*tc, m4+2*tc, ((m2 + 2*m3 + 2*m4 + 2*m5 + m6 + 4) >> 3));
+    piSrc[-iOffset*2] = Clip3(m2-2*tc, m2+2*tc, ((m1 + m2 + m3 + m4 + 2)>>2));
+    piSrc[ iOffset]   = Clip3(m5-2*tc, m5+2*tc, ((m3 + m4 + m5 + m6 + 2)>>2));
+    piSrc[-iOffset*3] = Clip3(m1-2*tc, m1+2*tc, ((2*m0 + 3*m1 + m2 + m3 + m4 + 4 )>>3));
+    piSrc[ iOffset*2] = Clip3(m6-2*tc, m6+2*tc, ((m3 + m4 + m5 + 3*m6 + 2*m7 +4 )>>3));
+  }
+  else
+  {
+    /* Weak filter */
+    delta = (9*(m4-m3) -3*(m5-m2) + 8)>>4 ;
+
+    if ( abs(delta) < iThrCut )
+    {
+      delta = Clip3(-tc, tc, delta);        
+      piSrc[-iOffset] = Clip((m3+delta));
+      piSrc[0] = Clip((m4-delta));
+
+      Int tc2 = tc>>1;
+      if(bFilterSecondP)
+      {
+        Int delta1 = Clip3(-tc2, tc2, (( ((m1+m3+1)>>1)- m2+delta)>>1));
+        piSrc[-iOffset*2] = Clip((m2+delta1));
+      }
+      if(bFilterSecondQ)
+      {
+        Int delta2 = Clip3(-tc2, tc2, (( ((m6+m4+1)>>1)- m5-delta)>>1));
+        piSrc[ iOffset] = Clip((m5+delta2));
+      }
+    }
+  }
+
+  if(bPartPNoFilter)
+  {
+    piSrc[-iOffset] = m3;
+    piSrc[-iOffset*2] = m2;
+    piSrc[-iOffset*3] = m1;
+  }
+  if(bPartQNoFilter)
+  {
+    piSrc[0] = m4;
+    piSrc[ iOffset] = m5;
+    piSrc[ iOffset*2] = m6;
+  }
+}
+
+/**
+ - Deblocking of one line/column for the chrominance component
+ .
+ \param piSrc           pointer to picture data
+ \param iOffset         offset value for picture data
+ \param tc              tc value
+ \param bPartPNoFilter  indicator to disable filtering on partP
+ \param bPartQNoFilter  indicator to disable filtering on partQ
+ */
+__inline Void TComLoopFilter::xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter)
+{
+  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] = Clip(m3+delta);
+  piSrc[0] = Clip(m4-delta);
+
+  if(bPartPNoFilter)
+  {
+    piSrc[-iOffset] = m3;
+  }
+  if(bPartQNoFilter)
+  {
+    piSrc[0] = m4;
+  }
+}
+
+/**
+ - Decision between strong and weak filter
+ .
+ \param offset         offset value for picture data
+ \param d               d value
+ \param beta            beta value
+ \param tc              tc value
+ \param piSrc           pointer to picture data
+ */
+__inline Bool TComLoopFilter::xUseStrongFiltering( Int offset, Int d, Int beta, Int tc, Pel* piSrc)
+{
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-offset];
+  Pel m7  = piSrc[ offset*3];
+  Pel m0  = piSrc[-offset*4];
+
+  Int d_strong = abs(m0-m3) + abs(m7-m4);
+
+  return ( (d_strong < (beta>>3)) && (d<(beta>>2)) && ( abs(m3-m4) < ((tc*5+1)>>1)) );
+}
+
+__inline Int TComLoopFilter::xCalcDP( Pel* piSrc, Int iOffset)
+{
+  return abs( piSrc[-iOffset*3] - 2*piSrc[-iOffset*2] + piSrc[-iOffset] ) ;
+}
+  
+__inline Int TComLoopFilter::xCalcDQ( Pel* piSrc, Int iOffset)
+{
+  return abs( piSrc[0] - 2*piSrc[iOffset] + piSrc[iOffset*2] );
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComLoopFilter.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComLoopFilter.h	(revision 341)
@@ -0,0 +1,117 @@
+/* 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-2012, 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     TComLoopFilter.h
+    \brief    deblocking filter (header)
+*/
+
+#ifndef __TCOMLOOPFILTER__
+#define __TCOMLOOPFILTER__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#define DEBLOCK_SMALLEST_BLOCK  8
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// deblocking filter class
+class TComLoopFilter
+{
+private:
+  UInt      m_uiDisableDeblockingFilterIdc; ///< deblocking filter idc
+  Int       m_betaOffsetDiv2;
+  Int       m_tcOffsetDiv2;
+
+  UInt      m_uiNumPartitions;
+  UChar*    m_aapucBS[2];              ///< Bs for [Ver/Hor][Y/U/V][Blk_Idx]
+  Bool*     m_aapbEdgeFilter[2][3];
+  LFCUParam m_stLFCUParam;                  ///< status structure
+  
+  Bool      m_bLFCrossTileBoundary;
+
+protected:
+  /// CU-level deblocking function
+  Void xDeblockCU                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge );
+
+  // set / get functions
+  Void xSetLoopfilterParam        ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  // filtering functions
+  Void xSetEdgefilterTU           ( TComDataCU* pcCU, UInt absTUPartIdx, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void xSetEdgefilterPU           ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  Void xGetBoundaryStrengthSingle ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, UInt uiPartIdx );
+  UInt xCalcBsIdx                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, Int iEdgeIdx, Int iBaseUnitIdx )
+  {
+    TComPic* const pcPic = pcCU->getPic();
+    const UInt uiLCUWidthInBaseUnits = pcPic->getNumPartInWidth();
+    if( iDir == 0 )
+      return g_auiRasterToZscan[g_auiZscanToRaster[uiAbsZorderIdx] + iBaseUnitIdx * uiLCUWidthInBaseUnits + iEdgeIdx ];
+    else
+      return g_auiRasterToZscan[g_auiZscanToRaster[uiAbsZorderIdx] + iEdgeIdx * uiLCUWidthInBaseUnits + iBaseUnitIdx ];
+  } 
+  
+  Void xSetEdgefilterMultiple( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdgeIdx, Bool bValue ,UInt uiWidthInBaseUnits = 0, UInt uiHeightInBaseUnits = 0, Bool nonSquare = false );
+  
+  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 d, Int beta, 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);
+  
+
+  __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);
+  
+public:
+  TComLoopFilter();
+  virtual ~TComLoopFilter();
+  
+  Void  create                    ( UInt uiMaxCUDepth );
+  Void  destroy                   ();
+  
+  /// set configuration
+  Void setCfg( Bool DeblockingFilterControlPresent, UInt uiDisableDblkIdc, Int betaOffsetDiv2, Int tcOffsetDiv2, Bool bLFCrossTileBoundary);
+  
+  /// picture-level deblocking filter
+  Void loopFilterPic( TComPic* pcPic );
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 341)
@@ -0,0 +1,399 @@
+/* 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-2012, 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     TComMotionInfo.cpp
+    \brief    motion information handling classes
+*/
+
+#include <memory.h>
+#include "TComMotionInfo.h"
+#include "assert.h"
+#include <stdlib.h>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// Create / destroy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::create( UInt uiNumPartition )
+{
+  assert(m_pcMv     == NULL);
+  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;
+}
+
+Void TComCUMvField::destroy()
+{
+  assert(m_pcMv     != NULL);
+  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;
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Clear / copy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::clearMvField()
+{
+  for ( Int i = 0; i < m_uiNumPartition; i++ )
+  {
+    m_pcMv [ i ].setZero();
+    m_pcMvd[ i ].setZero();      
+  }
+  assert( sizeof( *m_piRefIdx ) == 1 );
+  memset( m_piRefIdx, NOT_VALID, m_uiNumPartition * sizeof( *m_piRefIdx ) );
+}
+
+Void TComCUMvField::copyFrom( TComCUMvField const * pcCUMvFieldSrc, Int iNumPartSrc, Int iPartAddrDst )
+{
+  Int iSizeInTComMv = sizeof( TComMv ) * iNumPartSrc;
+  
+  memcpy( m_pcMv     + iPartAddrDst, pcCUMvFieldSrc->m_pcMv,     iSizeInTComMv );
+  memcpy( m_pcMvd    + iPartAddrDst, pcCUMvFieldSrc->m_pcMvd,    iSizeInTComMv );
+  memcpy( m_piRefIdx + iPartAddrDst, pcCUMvFieldSrc->m_piRefIdx, sizeof( *m_piRefIdx ) * iNumPartSrc );
+}
+
+Void TComCUMvField::copyTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst ) const
+{
+  copyTo( pcCUMvFieldDst, iPartAddrDst, 0, m_uiNumPartition );
+}
+
+Void TComCUMvField::copyTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst, UInt uiOffset, UInt uiNumPart ) const
+{
+  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 );
+  memcpy( pcCUMvFieldDst->m_piRefIdx + iOffset, m_piRefIdx + uiOffset, sizeof( *m_piRefIdx ) * uiNumPart );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Set
+// --------------------------------------------------------------------------------------------------------------------
+
+template <typename T>
+Void TComCUMvField::setAll( T *p, T const & val, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx  )
+{
+  Int i;
+  p += iPartAddr;
+  Int numElements = m_uiNumPartition >> ( 2 * uiDepth );
+  
+  switch( eCUMode )
+  {
+    case SIZE_2Nx2N:
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i ] = val;
+      }
+      break;
+      
+    case SIZE_2NxN:
+      numElements >>= 1;
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i ] = val;
+      }
+      break;
+      
+    case SIZE_Nx2N:
+      numElements >>= 2;
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i                   ] = val;
+        p[ i + 2 * numElements ] = val;
+      }
+      break;
+      
+    case SIZE_NxN:
+      numElements >>= 2;
+      for ( i = 0; i < numElements; i++)
+      {
+        p[ i ] = val;
+      }
+      break;
+    case SIZE_2NxnU:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + iCurrPartNumQ;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT[i] = val;
+        }
+
+        pT = p + iCurrPartNumQ;
+        for (i = 0; i < ( (iCurrPartNumQ>>1) + (iCurrPartNumQ<<1) ); i++)
+        {
+          pT[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_2NxnD:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        for (i = 0; i < ( (iCurrPartNumQ>>1) + (iCurrPartNumQ<<1) ); i++)
+        {
+          pT[i] = val;
+        }
+        pT = p + ( numElements - iCurrPartNumQ );
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + iCurrPartNumQ;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_nLx2N:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        T *pT3 = p + (iCurrPartNumQ>>1);
+        T *pT4 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+          pT3[i] = val;
+          pT4[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+
+        pT  = p + (iCurrPartNumQ>>1);
+        pT2 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+        for (i = 0; i < ( (iCurrPartNumQ>>2) + iCurrPartNumQ ); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_nRx2N:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        for (i = 0; i < ( (iCurrPartNumQ>>2) + iCurrPartNumQ ); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+
+        pT  = p + iCurrPartNumQ + (iCurrPartNumQ>>1);
+        pT2 = p + numElements - iCurrPartNumQ + (iCurrPartNumQ>>1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ>>1);
+        T *pT3 = p + (iCurrPartNumQ<<1);
+        T *pT4 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+          pT3[i] = val;
+          pT4[i] = val;
+        }
+      }
+      break;
+    }
+    default:
+      assert(0);
+      break;
+  }
+}
+
+Void TComCUMvField::setAllMv( TComMv const & mv, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_pcMv, mv, eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllMvd( TComMv const & mvd, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_pcMvd, mvd, eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllRefIdx ( Int iRefIdx, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_piRefIdx, static_cast<Char>(iRefIdx), eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllMvField( TComMvField const & mvField, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAllMv    ( mvField.getMv(),     eCUMode, iPartAddr, uiDepth, iPartIdx );
+  setAllRefIdx( mvField.getRefIdx(), eCUMode, iPartAddr, uiDepth, iPartIdx );
+}
+
+/**Subsampling of the stored prediction mode, reference index and motion vector
+ * \param pePredMode Pointer to prediction modes
+ * \param scale      Factor by which to subsample motion information
+ */
+#if HHI_MPI
+Void TComCUMvField::compress(Char* pePredMode, UChar* puhInterDir, Int scale)
+#else
+Void TComCUMvField::compress(Char* pePredMode, Int scale)
+#endif
+{
+  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;
+    Int iRefIdx = 0;
+    
+    cMv = m_pcMv[ uiPartIdx ];
+    predMode = static_cast<PredMode>( pePredMode[ uiPartIdx ] );
+    iRefIdx = m_piRefIdx[ uiPartIdx ];
+    for ( Int i = 0; i < N; i++ )
+    {
+      m_pcMv[ uiPartIdx + i ] = cMv;
+      pePredMode[ uiPartIdx + i ] = predMode;
+      m_piRefIdx[ uiPartIdx + i ] = iRefIdx;
+#if HHI_MPI
+      puhInterDir[ uiPartIdx + i ] = puhInterDir[ uiPartIdx ];
+#endif
+    }
+  }
+} 
+
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+Void TComCUMvField::decreaseMvAccuracy( Int iPartAddr, Int iNumPart, Int iShift )
+{
+  assert( iShift > 0 );
+  const TComMv cAdd( 1 << ( iShift - 1 ), 1 << ( iShift - 1 ) );
+
+  for ( Int i = 0; i < iNumPart; i++ )
+  {
+    m_pcMv[iPartAddr+i] += cAdd;
+    m_pcMv[iPartAddr+i] >>= iShift;
+
+    m_pcMvd[iPartAddr+i] += cAdd;
+    m_pcMvd[iPartAddr+i] >>= iShift;
+  }
+}
+#endif
+
+
+
+#if MTK_UNCONSTRAINED_MVI_B0083
+Void TComCUMvField::setUndefinedMv( Int iPartAddr, Int iNumPart, Char* pePredMode, UChar* puhInterDir, Int refIdx, Int InterDir 
+                                   )
+{
+  PredMode predMode = MODE_INTRA;
+  TComMv cMv(0,0); 
+
+  for ( Int i = 0; i < iNumPart; i++ )
+  { 
+    predMode = static_cast<PredMode>( pePredMode[ iPartAddr+i ] );
+    if( predMode == MODE_INTRA )
+    {
+      m_pcMv[iPartAddr+i] = cMv;
+      puhInterDir[iPartAddr+i] = InterDir; 
+      m_piRefIdx[iPartAddr+i] = refIdx;
+    }
+  }
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMotionInfo.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMotionInfo.h	(revision 341)
@@ -0,0 +1,194 @@
+/* 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-2012, 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     TComMotionInfo.h
+    \brief    motion information handling classes (header)
+    \todo     TComMvField seems to be better to be inherited from TComMv
+*/
+
+#ifndef __TCOMMOTIONINFO__
+#define __TCOMMOTIONINFO__
+
+#include <memory.h>
+#include "CommonDef.h"
+#include "TComMv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+/// parameters for AMVP
+typedef struct _AMVPInfo
+{
+  TComMv m_acMvCand[ AMVP_MAX_NUM_CANDS_MEM ];  ///< array of motion vector predictor candidates
+  Int    iN;                                ///< number of motion vector predictor candidates
+} AMVPInfo;
+
+// ====================================================================================================================
+#if H3D_NBDV
+typedef struct _DisCand
+{
+  TComMv m_acMvCand[ DIS_CANS ];            ///< array of motion vector predictor candidates
+  Int    m_aVIdxCan[ DIS_CANS ];            ///< array of motion vector predictor candidates
+  Int    iN;                                ///< number of motion vector predictor candidates
+} DisInfo;
+
+typedef struct _McpDisCand
+{
+  TComMv m_acMvCand[2][ MCP_DIS_CANS ];            ///< array of motion vector predictor candidates
+  Int    m_aVIdxCan[2][ MCP_DIS_CANS ];            ///< array of motion vector predictor candidates
+  Bool   m_bAvailab[2][ MCP_DIS_CANS ];
+  Bool   m_bFound;                                 ///< number of motion vector predictor candidates
+} McpDisInfo;
+
+#endif 
+// Class definition
+// ====================================================================================================================
+
+/// class for motion vector with reference index
+class TComMvField
+{
+private:
+  TComMv    m_acMv;
+  Int       m_iRefIdx;
+  
+public:
+  TComMvField() : m_iRefIdx( NOT_VALID ) {}
+  
+  Void setMvField( TComMv const & cMv, Int iRefIdx )
+  {
+    m_acMv    = cMv;
+    m_iRefIdx = iRefIdx;
+  }
+  
+  Void setRefIdx( Int refIdx ) { m_iRefIdx = refIdx; }
+  
+  TComMv const & getMv() const { return  m_acMv; }
+  TComMv       & getMv()       { return  m_acMv; }
+  
+  Int getRefIdx() const { return  m_iRefIdx;       }
+  Int getHor   () const { return  m_acMv.getHor(); }
+  Int getVer   () const { return  m_acMv.getVer(); }
+#if H3D_IVMP
+  Bool operator== ( const TComMvField& rcMv ) const
+  {
+    return (m_acMv.getHor()==rcMv.getHor() && m_acMv.getVer()==rcMv.getVer() && m_iRefIdx == rcMv.getRefIdx());
+  }
+#endif
+};
+
+/// class for motion information in one CU
+class TComCUMvField
+{
+private:
+  TComMv*   m_pcMv;
+  TComMv*   m_pcMvd;
+  Char*     m_piRefIdx;
+  UInt      m_uiNumPartition;
+  AMVPInfo  m_cAMVPInfo;
+    
+  template <typename T>
+  Void setAll( T *p, T const & val, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx );
+
+public:
+  TComCUMvField() : m_pcMv(NULL), m_pcMvd(NULL), m_piRefIdx(NULL), m_uiNumPartition(0) {}
+  ~TComCUMvField() {}
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // create / destroy
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    create( UInt uiNumPartition );
+  Void    destroy();
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // clear / copy
+  // ------------------------------------------------------------------------------------------------------------------
+
+  Void    clearMvField();
+  
+  Void    copyFrom( TComCUMvField const * pcCUMvFieldSrc, Int iNumPartSrc, Int iPartAddrDst );
+  Void    copyTo  ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst ) const;
+  Void    copyTo  ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst, UInt uiOffset, UInt uiNumPart ) const;
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // get
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv const & getMv    ( Int iIdx ) const { return  m_pcMv    [iIdx]; }
+  TComMv const & getMvd   ( Int iIdx ) const { return  m_pcMvd   [iIdx]; }
+  Int            getRefIdx( Int iIdx ) const { return  m_piRefIdx[iIdx]; }
+  
+  AMVPInfo* getAMVPInfo () { return &m_cAMVPInfo; }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // set
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    setAllMv     ( TComMv const & rcMv,         PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+  Void    setAllMvd    ( TComMv const & rcMvd,        PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+  Void    setAllRefIdx ( Int iRefIdx,                 PartSize eMbMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+  Void    setAllMvField( TComMvField const & mvField, PartSize eMbMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+
+  Void setNumPartition( Int iNumPart )
+  {
+    m_uiNumPartition = iNumPart;
+  }
+  
+  Void linkToWithOffset( TComCUMvField const * src, Int offset )
+  {
+    m_pcMv     = src->m_pcMv     + offset;
+    m_pcMvd    = src->m_pcMvd    + offset;
+    m_piRefIdx = src->m_piRefIdx + offset;
+  }
+  
+#if HHI_MPI
+  Void compress(Char* pePredMode, UChar* puhInterDir, Int scale);
+#else
+  Void compress(Char* pePredMode, Int scale); 
+#endif
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  Void decreaseMvAccuracy( Int iPartAddr, Int iNumPart, Int iShift );
+#endif
+
+#if MTK_UNCONSTRAINED_MVI_B0083
+  Void setUndefinedMv( Int iPartAddr, Int iNumPart, Char* pePredMode, UChar* puhInterDir, Int refIdx, Int InterDir );
+#endif
+};
+
+//! \}
+
+#endif // __TCOMMOTIONINFO__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMv.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMv.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComMv.h	(revision 341)
@@ -0,0 +1,171 @@
+/* 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-2012, 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     TComMv.h
+    \brief    motion vector class (header)
+*/
+
+#ifndef __TCOMMV__
+#define __TCOMMV__
+
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// basic motion vector class
+class TComMv
+{
+private:
+  Short m_iHor;     ///< horizontal component of motion vector
+  Short m_iVer;     ///< vertical component of motion vector
+  
+public:
+  
+#if H3D_NBDV
+  Bool  m_bDvMcp;       // is dv-mcp ?
+  Int   m_iDvMcpDispX;  // disparity for dv-mcp
+  Int   m_iDvMcpDispY;  // disparity for dv-mcp
+#endif
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // constructors
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv() :
+  m_iHor(0),
+  m_iVer(0)
+#if H3D_NBDV
+  , m_bDvMcp(false)
+  , m_iDvMcpDispX(0)
+  , m_iDvMcpDispY(0)
+#endif
+  {
+  }
+  
+  TComMv( Short iHor, Short iVer ) :
+  m_iHor(iHor),
+  m_iVer(iVer)
+#if H3D_NBDV
+  , m_bDvMcp(false)
+  , m_iDvMcpDispX(0)
+  , m_iDvMcpDispY(0)
+#endif
+  {
+  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // 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;  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // get
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Int   getHor    () const { return m_iHor;          }
+  Int   getVer    () const { return m_iVer;          }
+  Int   getAbsHor () const { return abs( m_iHor );   }
+  Int   getAbsVer () const { return abs( m_iVer );   }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // operations
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  const TComMv& operator += (const TComMv& rcMv)
+  {
+    m_iHor += rcMv.m_iHor;
+    m_iVer += rcMv.m_iVer;
+    return  *this;
+  }
+  
+  const TComMv& operator-= (const TComMv& rcMv)
+  {
+    m_iHor -= rcMv.m_iHor;
+    m_iVer -= rcMv.m_iVer;
+    return  *this;
+  }
+  
+  const TComMv& operator>>= (const Int i)
+  {
+    m_iHor >>= i;
+    m_iVer >>= i;
+    return  *this;
+  }
+  
+  const TComMv& operator<<= (const Int i)
+  {
+    m_iHor <<= i;
+    m_iVer <<= i;
+    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
+  {
+    Int mvx = Clip3( -32768, 32767, (iScale * getHor() + 127 + (iScale * getHor() < 0)) >> 8 );
+    Int mvy = Clip3( -32768, 32767, (iScale * getVer() + 127 + (iScale * getVer() < 0)) >> 8 );
+    return TComMv( mvx, mvy );
+  }
+};// END CLASS DEFINITION TComMV
+
+//! \}
+
+#endif // __TCOMMV__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPattern.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPattern.cpp	(revision 341)
@@ -0,0 +1,870 @@
+/* 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-2012, 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     TComPattern.cpp
+    \brief    neighbouring pixel access classes
+*/
+
+#include "TComPic.h"
+#include "TComPattern.h"
+#include "TComDataCU.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar TComPattern::m_aucIntraFilter[5] =
+{
+  10, //4x4
+  7, //8x8
+  1, //16x16
+  0, //32x32
+  10, //64x64
+};
+
+// ====================================================================================================================
+// Public member functions (TComPatternParam)
+// ====================================================================================================================
+
+/** \param  piTexture     pixel data
+ \param  iRoiWidth     pattern width
+ \param  iRoiHeight    pattern height
+ \param  iStride       buffer stride
+ \param  iOffsetLeft   neighbour offset (left)
+ \param  iOffsetRight  neighbour offset (right)
+ \param  iOffsetAbove  neighbour offset (above)
+ \param  iOffsetBottom neighbour offset (bottom)
+ */
+Void TComPatternParam::setPatternParamPel ( Pel* piTexture,
+                                           Int iRoiWidth,
+                                           Int iRoiHeight,
+                                           Int iStride,
+                                           Int iOffsetLeft,
+                                           Int iOffsetRight,
+                                           Int iOffsetAbove,
+                                           Int iOffsetBottom )
+{
+  m_piPatternOrigin = piTexture;
+  m_iROIWidth       = iRoiWidth;
+  m_iROIHeight      = iRoiHeight;
+  m_iPatternStride  = iStride;
+  m_iOffsetLeft     = iOffsetLeft;
+  m_iOffsetAbove    = iOffsetAbove;
+  m_iOffsetRight    = iOffsetRight;
+  m_iOffsetBottom   = iOffsetBottom;
+}
+
+/**
+ \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  iOffsetRight  neighbour offset (right)
+ \param  iOffsetAbove  neighbour offset (above)
+ \param  iOffsetBottom neighbour offset (bottom)
+ \param  uiPartDepth   CU depth
+ \param  uiAbsPartIdx  part index
+ */
+Void TComPatternParam::setPatternParamCU( TComDataCU* pcCU,
+                                         UChar       iComp,
+                                         UChar       iRoiWidth,
+                                         UChar       iRoiHeight,
+                                         Int         iOffsetLeft,
+                                         Int         iOffsetRight,
+                                         Int         iOffsetAbove,
+                                         Int         iOffsetBottom,
+                                         UInt        uiPartDepth,
+                                         UInt        uiAbsPartIdx 
+#if DEPTH_MAP_GENERATION
+                                         ,Bool        bPrdDepthMap
+#endif
+                                         )
+{
+  m_iOffsetLeft   = iOffsetLeft;
+  m_iOffsetRight  = iOffsetRight;
+  m_iOffsetAbove  = iOffsetAbove;
+  m_iOffsetBottom = iOffsetBottom;
+  
+  m_iROIWidth     = iRoiWidth;
+  m_iROIHeight    = iRoiHeight;
+  
+  UInt uiAbsZorderIdx = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  
+#if DEPTH_MAP_GENERATION
+  TComPicYuv* pcPic = ( bPrdDepthMap ? pcCU->getPic()->getPredDepthMap() : pcCU->getPic()->getPicYuvRec() );
+#else
+  TComPicYuv* pcPic = pcCU->getPic()->getPicYuvRec();
+#endif
+
+  if ( iComp == 0 )
+  {
+#if DEPTH_MAP_GENERATION
+    m_iPatternStride  = ( bPrdDepthMap ? pcCU->getPic()->getPredDepthMap()->getStride() : pcCU->getPic()->getStride() );
+#else
+    m_iPatternStride  = pcCU->getPic()->getStride();
+#endif
+    m_piPatternOrigin = pcPic->getLumaAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+  }
+  else
+  {
+#if DEPTH_MAP_GENERATION
+    m_iPatternStride  = ( bPrdDepthMap ? pcCU->getPic()->getPredDepthMap()->getCStride() : pcCU->getPic()->getCStride() );
+#else
+    m_iPatternStride = pcCU->getPic()->getCStride();
+#endif
+    if ( iComp == 1 )
+    {
+      m_piPatternOrigin = pcPic->getCbAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+    }
+    else
+    {
+      m_piPatternOrigin = pcPic->getCrAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+    }
+  }
+}
+
+// ====================================================================================================================
+// Public member functions (TComPattern)
+// ====================================================================================================================
+
+Void TComPattern::initPattern ( Pel* piY,
+                               Pel* piCb,
+                               Pel* piCr,
+                               Int iRoiWidth,
+                               Int iRoiHeight,
+                               Int iStride,
+                               Int iOffsetLeft,
+                               Int iOffsetRight,
+                               Int iOffsetAbove,
+                               Int iOffsetBottom )
+{
+  m_cPatternY. setPatternParamPel( piY,  iRoiWidth,      iRoiHeight,      iStride,      iOffsetLeft,      iOffsetRight,      iOffsetAbove,      iOffsetBottom );
+  m_cPatternCb.setPatternParamPel( piCb, iRoiWidth >> 1, iRoiHeight >> 1, iStride >> 1, iOffsetLeft >> 1, iOffsetRight >> 1, iOffsetAbove >> 1, iOffsetBottom >> 1 );
+  m_cPatternCr.setPatternParamPel( piCr, iRoiWidth >> 1, iRoiHeight >> 1, iStride >> 1, iOffsetLeft >> 1, iOffsetRight >> 1, iOffsetAbove >> 1, iOffsetBottom >> 1 );
+  
+  return;
+}
+
+Void TComPattern::initPattern( TComDataCU* pcCU, UInt uiPartDepth, UInt uiAbsPartIdx 
+#if DEPTH_MAP_GENERATION
+                              , Bool bPrdDepthMap 
+#endif
+                              )
+{
+  Int   uiOffsetLeft  = 0;
+  Int   uiOffsetRight = 0;
+  Int   uiOffsetAbove = 0;
+  
+  TComPic* pcPic         = pcCU->getPic();
+  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 )
+  {
+    UInt uiNumPartInWidth = ( uiWidth/pcPic->getMinCUWidth() );
+    uiOffsetAbove = 1;
+    
+    if( uiCurrPicPelX + uiWidth < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() )
+    {
+      if( ( g_auiZscanToRaster[uiAbsZorderIdx] + uiNumPartInWidth ) % pcPic->getNumPartInWidth() ) // Not CU boundary
+      {
+        if( g_auiRasterToZscan[ (Int)g_auiZscanToRaster[uiAbsZorderIdx] - (Int)pcPic->getNumPartInWidth() + (Int)uiNumPartInWidth ] < uiAbsZorderIdx )
+        {
+          uiOffsetRight = 1;
+        }
+      }
+      else // if it is CU boundary
+      {
+        if( g_auiZscanToRaster[uiAbsZorderIdx] < pcPic->getNumPartInWidth() && (uiCurrPicPelX+uiWidth) < pcPic->getPicYuvRec()->getWidth() ) // first line
+        {
+          uiOffsetRight = 1;
+        }
+      }
+    }
+  }
+  
+#if DEPTH_MAP_GENERATION
+  m_cPatternY .setPatternParamCU( pcCU, 0, uiWidth,      uiHeight,      uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx, bPrdDepthMap );
+  m_cPatternCb.setPatternParamCU( pcCU, 1, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx, bPrdDepthMap );
+  m_cPatternCr.setPatternParamCU( pcCU, 2, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx, bPrdDepthMap );
+#else
+  m_cPatternY .setPatternParamCU( pcCU, 0, uiWidth,      uiHeight,      uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx );
+  m_cPatternCb.setPatternParamCU( pcCU, 1, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx );
+  m_cPatternCr.setPatternParamCU( pcCU, 2, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetRight, uiOffsetAbove, 0, uiPartDepth, uiAbsPartIdx );
+#endif
+}
+
+  Void TComPattern::initAdiPattern( TComDataCU* pcCU, UInt uiZorderIdxInPart, UInt uiPartDepth, Int* piAdiBuf, Int iOrgBufStride, Int iOrgBufHeight, Bool& bAbove, Bool& bLeft, Bool bLMmode 
+#if DEPTH_MAP_GENERATION
+                                  , Bool bPrdDepthMap, UInt uiSubSampExpX, UInt uiSubSampExpY
+#endif
+    )
+{
+  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;
+#if DEPTH_MAP_GENERATION
+  Int   iPicStride = ( bPrdDepthMap ? pcCU->getPic()->getPredDepthMap()->getStride() : pcCU->getPic()->getStride() );
+#else
+  Int   iPicStride = pcCU->getPic()->getStride();
+#endif
+  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;
+  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 );
+  
+  bAbove = true;
+  bLeft  = true;
+
+#if DEPTH_MAP_GENERATION
+  if ( bPrdDepthMap )
+  {
+    uiWidth  = ( uiCuWidth2  >> uiSubSampExpX ) + 1;
+    uiHeight = ( uiCuHeight2 >> uiSubSampExpY ) + 1;
+  }
+  else
+  {
+    uiWidth=uiCuWidth2+1;
+    uiHeight=uiCuHeight2+1;
+  }
+#else
+  uiWidth=uiCuWidth2+1;
+  uiHeight=uiCuHeight2+1;
+#endif
+  
+  if (((uiWidth<<2)>iOrgBufStride)||((uiHeight<<2)>iOrgBufHeight))
+  {
+    return;
+  }
+  
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf;
+
+#if DEPTH_MAP_GENERATION
+  if( bPrdDepthMap )
+  {
+    piRoiOrigin = pcCU->getPic()->getPredDepthMap()->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiZorderIdxInPart );
+  }
+#endif
+
+#if DEPTH_MAP_GENERATION
+  if ( bPrdDepthMap )
+    fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize >> uiSubSampExpX, iNumUnitsInCu, iTotalUnits, uiCuWidth >> uiSubSampExpX, uiCuHeight >> uiSubSampExpY, uiWidth, uiHeight, iPicStride, bLMmode, bPrdDepthMap );
+  else
+    fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, bLMmode, bPrdDepthMap );
+#else
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, bLMmode);
+#endif
+
+  
+  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];
+  }
+
+  // 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;
+
+#if DEPTH_MAP_GENERATION
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, false, false );
+#else
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride);
+#endif
+  
+  // get Cr pattern
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf+uiWidth*uiHeight;
+  
+#if DEPTH_MAP_GENERATION
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, false, false );
+#else
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride);
+#endif
+
+}
+
+Void TComPattern::fillReferenceSamples( TComDataCU* pcCU, 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 
+#if DEPTH_MAP_GENERATION
+                                       , Bool bPrdDepthMap 
+#endif
+                                       )
+{
+  Pel* piRoiTemp;
+  Int  i, j;
+#if DEPTH_MAP_GENERATION
+  Int  iDCValue = ( bPrdDepthMap ? PDM_UNDEFINED_DEPTH : ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) ) );
+#else
+  Int  iDCValue = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+#endif
+
+  if (iNumIntraNeighbor == 0)
+  {
+    // Fill border with DC value
+    for (i=0; i<uiWidth; i++)
+    {
+      piAdiTemp[i] = iDCValue;
+    }
+    for (i=1; i<uiHeight; i++)
+    {
+      piAdiTemp[i*uiWidth] = iDCValue;
+    }
+  }
+  else if (iNumIntraNeighbor == iTotalUnits)
+  {
+    // Fill top-left border with rec. samples
+    piRoiTemp = piRoiOrigin - iPicStride - 1;
+    piAdiTemp[0] = piRoiTemp[0];
+
+    // Fill 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];
+      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;
+
+    // Initialize
+    for (i=0; i<iTotalSamples; i++)
+    {
+      piAdiLine[i] = iDCValue;
+    }
+    
+    // Fill top-left sample
+    piRoiTemp = piRoiOrigin - iPicStride - 1;
+    piAdiLineTemp = piAdiLine + (iNumUnits2*iUnitSize);
+    pbNeighborFlags = bNeighborFlags + iNumUnits2;
+    if (*pbNeighborFlags)
+    {
+      piAdiLineTemp[0] = piRoiTemp[0];
+      for (i=1; i<iUnitSize; i++)
+      {
+        piAdiLineTemp[i] = piAdiLineTemp[0];
+      }
+    }
+
+    // Fill left & below-left samples
+    piRoiTemp += iPicStride;
+    if (bLMmode)
+    {
+      piRoiTemp --; // move the second left column
+    }
+    piAdiLineTemp--;
+    pbNeighborFlags--;
+    for (j=0; j<iNumUnits2; j++)
+    {
+      if (*pbNeighborFlags)
+      {
+        for (i=0; i<iUnitSize; i++)
+        {
+          piAdiLineTemp[-i] = piRoiTemp[i*iPicStride];
+        }
+      }
+      piRoiTemp += iUnitSize*iPicStride;
+      piAdiLineTemp -= iUnitSize;
+      pbNeighborFlags--;
+    }
+
+    // Fill above & above-right samples
+    piRoiTemp = piRoiOrigin - iPicStride;
+    piAdiLineTemp = piAdiLine + ((iNumUnits2+1)*iUnitSize);
+    pbNeighborFlags = bNeighborFlags + iNumUnits2 + 1;
+    for (j=0; j<iNumUnits2; j++)
+    {
+      if (*pbNeighborFlags)
+      {
+        for (i=0; i<iUnitSize; i++)
+        {
+          piAdiLineTemp[i] = piRoiTemp[i];
+        }
+      }
+      piRoiTemp += iUnitSize;
+      piAdiLineTemp += iUnitSize;
+      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])
+          {
+            iNext++;
+          }
+          piRef = piAdiLine[iNext*iUnitSize];
+          // Pad unavailable samples with new value
+          while (iCurr < iNext)
+          {
+            for (i=0; i<iUnitSize; i++)
+            {
+              piAdiLineTemp[i] = piRef;
+            }
+            piAdiLineTemp += iUnitSize;
+            iCurr++;
+          }
+        }
+        else
+        {
+          piRef = piAdiLine[iCurr*iUnitSize-1];
+          for (i=0; i<iUnitSize; i++)
+          {
+            piAdiLineTemp[i] = piRef;
+          }
+          piAdiLineTemp += iUnitSize;
+          iCurr++;
+        }
+      }
+      else
+      {
+        piAdiLineTemp += iUnitSize;
+        iCurr++;
+      }
+    }
+
+    // Copy processed samples
+    piAdiLineTemp = piAdiLine + uiHeight + iUnitSize - 2;
+    for (i=0; i<uiWidth; i++)
+    {
+      piAdiTemp[i] = piAdiLineTemp[i];
+    }
+    piAdiLineTemp = piAdiLine + 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;
+#if LGE_EDGE_INTRA_A0070
+  mapEdgeIntratoDC( uiDirMode );
+#endif
+  assert(log2BlkSize >= 2 && log2BlkSize < 7);
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  mapDMMtoIntraMode( uiDirMode );
+#endif
+  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 || uiDirMode == LM_CHROMA_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 )
+{
+  Bool bAboveLeftFlag;
+  UInt uiPartAboveLeft;
+  TComDataCU* pcCUAboveLeft = pcCU->getPUAboveLeft( uiPartAboveLeft, uiPartIdxLT, true, false );
+  if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+  {
+    bAboveLeftFlag = ( pcCUAboveLeft && pcCUAboveLeft->getPredictionMode( uiPartAboveLeft ) == MODE_INTRA );
+  }
+  else
+  {
+    bAboveLeftFlag = (pcCUAboveLeft ? true : false);
+  }
+  return bAboveLeftFlag;
+}
+
+Int TComPattern::isAboveAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+{
+  const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
+  const UInt uiRasterPartEnd = g_auiZscanToRaster[uiPartIdxRT]+1;
+  const UInt uiIdxStep = 1;
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiRasterPart = uiRasterPartBegin; uiRasterPart < uiRasterPartEnd; uiRasterPart += uiIdxStep )
+  {
+    UInt uiPartAbove;
+    TComDataCU* pcCUAbove = pcCU->getPUAbove( uiPartAbove, g_auiRasterToZscan[uiRasterPart], true, false );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUAbove && pcCUAbove->getPredictionMode( uiPartAbove ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if (pcCUAbove)
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags++;
+  }
+  return iNumIntra;
+}
+
+Int TComPattern::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();
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiRasterPart = uiRasterPartBegin; uiRasterPart < uiRasterPartEnd; uiRasterPart += uiIdxStep )
+  {
+    UInt uiPartLeft;
+    TComDataCU* pcCULeft = pcCU->getPULeft( uiPartLeft, g_auiRasterToZscan[uiRasterPart], true, false );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCULeft && pcCULeft->getPredictionMode( uiPartLeft ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCULeft )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags--; // opposite direction
+  }
+
+  return iNumIntra;
+}
+
+Int TComPattern::isAboveRightAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+{
+  const UInt uiNumUnitsInPU = g_auiZscanToRaster[uiPartIdxRT] - g_auiZscanToRaster[uiPartIdxLT] + 1;
+  const UInt uiPuWidth = uiNumUnitsInPU * pcCU->getPic()->getMinCUWidth();
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiOffset = 1; uiOffset <= uiNumUnitsInPU; uiOffset++ )
+  {
+    UInt uiPartAboveRight;
+    TComDataCU* pcCUAboveRight = pcCU->getPUAboveRightAdi( uiPartAboveRight, uiPuWidth, uiPartIdxRT, uiOffset, true, false );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUAboveRight && pcCUAboveRight->getPredictionMode( uiPartAboveRight ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCUAboveRight )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags++;
+  }
+
+  return iNumIntra;
+}
+
+Int TComPattern::isBelowLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+{
+  const UInt uiNumUnitsInPU = (g_auiZscanToRaster[uiPartIdxLB] - g_auiZscanToRaster[uiPartIdxLT]) / pcCU->getPic()->getNumPartInWidth() + 1;
+  const UInt uiPuHeight = uiNumUnitsInPU * pcCU->getPic()->getMinCUHeight();
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiOffset = 1; uiOffset <= uiNumUnitsInPU; uiOffset++ )
+  {
+    UInt uiPartBelowLeft;
+    TComDataCU* pcCUBelowLeft = pcCU->getPUBelowLeftAdi( uiPartBelowLeft, uiPuHeight, uiPartIdxLB, uiOffset, true, false );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUBelowLeft && pcCUBelowLeft->getPredictionMode( uiPartBelowLeft ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCUBelowLeft )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags--; // opposite direction
+  }
+
+  return iNumIntra;
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPattern.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPattern.h	(revision 341)
@@ -0,0 +1,212 @@
+/* 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-2012, 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     TComPattern.h
+    \brief    neighbouring pixel access classes (header)
+*/
+
+#ifndef __TCOMPATTERN__
+#define __TCOMPATTERN__
+
+// Include files
+#include <stdio.h>
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TComDataCU;
+
+/// neighbouring pixel access class for one component
+class TComPatternParam
+{
+private:
+  Int   m_iOffsetLeft;
+  Int   m_iOffsetRight;
+  Int   m_iOffsetAbove;
+  Int   m_iOffsetBottom;
+  Pel*  m_piPatternOrigin;
+  
+public:
+  Int   m_iROIWidth;
+  Int   m_iROIHeight;
+  Int   m_iPatternStride;
+  
+  /// return starting position of buffer
+  Pel*  getPatternOrigin()        { return  m_piPatternOrigin; }
+  
+  /// return starting position of ROI (ROI = &pattern[AboveOffset][LeftOffset])
+  __inline Pel*  getROIOrigin()
+  {
+    return  m_piPatternOrigin + m_iPatternStride * m_iOffsetAbove + m_iOffsetLeft;
+  }
+  
+  /// set parameters from Pel buffer for accessing neighbouring pixels
+  Void setPatternParamPel ( Pel*        piTexture,
+                           Int         iRoiWidth,
+                           Int         iRoiHeight,
+                           Int         iStride,
+                           Int         iOffsetLeft,
+                           Int         iOffsetRight,
+                           Int         iOffsetAbove,
+                           Int         iOffsetBottom );
+  
+  /// 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         iOffsetRight,
+                           Int         iOffsetAbove,
+                           Int         iOffsetBottom,
+                           UInt        uiPartDepth,
+                           UInt        uiAbsZorderIdx 
+#if DEPTH_MAP_GENERATION
+                           ,Bool        bPrdDepthMap = false 
+#endif  
+                           );
+};
+
+/// neighbouring pixel access class for all components
+class TComPattern
+{
+private:
+  TComPatternParam  m_cPatternY;
+  TComPatternParam  m_cPatternCb;
+  TComPatternParam  m_cPatternCr;
+  
+#if LGE_ILLUCOMP_B0045
+  Bool              m_bICFlag;
+#endif
+
+  static const UChar m_aucIntraFilter[5];
+  
+public:
+  
+  // ROI & pattern information, (ROI = &pattern[AboveOffset][LeftOffset])
+  Pel*  getROIY()                 { return m_cPatternY.getROIOrigin();    }
+  Int   getROIYWidth()            { return m_cPatternY.m_iROIWidth;       }
+  Int   getROIYHeight()           { return m_cPatternY.m_iROIHeight;      }
+  Int   getPatternLStride()       { return m_cPatternY.m_iPatternStride;  }
+
+#if LGE_ILLUCOMP_B0045
+  Bool  getICFlag()               { return m_bICFlag; }
+  Void  setICFlag(Bool bICFlag)   { m_bICFlag = bICFlag; }
+#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         iOffsetRight,
+                               Int         iOffsetAbove,
+                               Int         iOffsetBottom );
+  
+  /// set parameters from CU data for accessing neighbouring pixels
+  Void  initPattern           ( TComDataCU* pcCU,
+                               UInt        uiPartDepth,
+                               UInt        uiAbsPartIdx 
+#if DEPTH_MAP_GENERATION
+                               ,Bool        bPrdDepthMap = false 
+#endif
+                               );
+  
+  /// 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
+#if DEPTH_MAP_GENERATION
+                              ,
+                              Bool         bPrdDepthMap = false,
+                              UInt         uiSubSampExpX = 0,
+                              UInt         uiSubSampExpY = 0
+#endif
+                               );
+  
+  /// 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        ( TComDataCU* pcCU, 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
+#if DEPTH_MAP_GENERATION
+                                    , Bool bPrdDepthMap = false 
+#endif
+                                    );
+  
+
+  /// 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 );
+
+};
+
+//! \}
+
+#endif // __TCOMPATTERN__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPic.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPic.cpp	(revision 341)
@@ -0,0 +1,704 @@
+/* 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-2012, 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     TComPic.cpp
+    \brief    picture class
+*/
+
+#include "TComPic.h"
+#include "SEI.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComPic::TComPic()
+{
+  m_uiTLayer          = 0;
+
+  m_apcPicSym         = NULL;
+  m_apcPicYuv[0]      = NULL;
+  m_apcPicYuv[1]      = NULL;
+#if DEPTH_MAP_GENERATION
+  m_pcPredDepthMap    = NULL;
+#if PDM_REMOVE_DEPENDENCE
+  m_pcPredDepthMap_temp    = NULL;
+#endif
+#endif
+#if FCO_DVP_REFINE_C0132_C0170
+  m_bDepthCoded       = false;
+  m_pcRecDepthMap     = NULL;
+#endif
+#if H3D_IVMP
+  m_pcOrgDepthMap     = NULL;
+#endif
+#if H3D_IVRP
+  m_pcResidual        = NULL;
+#endif
+  m_pcPicYuvPred      = NULL;
+  m_pcPicYuvResi      = NULL;
+  m_bIsLongTerm       = false;
+  m_bReconstructed    = false;
+  m_usedForTMVP       = true;
+  m_bNeededForOutput  = false;
+  m_pSliceSUMap       = NULL;
+  m_uiCurrSliceIdx    = 0; 
+#if HHI_INTERVIEW_SKIP
+  m_pcUsedPelsMap     = NULL;
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  m_iViewOrderIdx     = 0;    // will be changed to view_id
+#endif
+  m_aaiCodedScale     = 0;
+  m_aaiCodedOffset    = 0;
+#if H3D_QTL
+  m_bReduceBitsQTL    = 0;
+#endif
+#if H3D_NBDV
+  m_bRapCheck = false;
+  m_eRapRefList = REF_PIC_LIST_0;
+  m_uiRapRefIdx = 0;
+#endif
+
+}
+
+TComPic::~TComPic()
+{
+}
+
+Void TComPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Bool bIsVirtual )
+{
+  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, 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 );
+  
+  /* there are no SEI messages associated with this picture initially */
+  m_SEIs = NULL;
+  m_bUsedByCurr = false;
+  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;
+  }
+#if HHI_INTERVIEW_SKIP
+  if( m_pcUsedPelsMap )
+  {
+    m_pcUsedPelsMap->destroy();
+    delete m_pcUsedPelsMap;
+    m_pcUsedPelsMap = NULL;
+  }
+#endif
+#if DEPTH_MAP_GENERATION
+  if( m_pcPredDepthMap )
+  {
+    m_pcPredDepthMap->destroy();
+    delete m_pcPredDepthMap;
+    m_pcPredDepthMap = NULL;
+  }
+#if PDM_REMOVE_DEPENDENCE
+  if( m_pcPredDepthMap_temp )         //  estimated depth map
+  {
+    m_pcPredDepthMap_temp->destroy();
+    delete m_pcPredDepthMap_temp;
+    m_pcPredDepthMap_temp = NULL;
+  }                     
+#endif
+#endif
+#if H3D_IVMP
+  if( m_pcOrgDepthMap )
+  {
+    m_pcOrgDepthMap->destroy();
+    delete m_pcOrgDepthMap;
+    m_pcOrgDepthMap = NULL;
+  }
+#endif
+#if H3D_IVRP
+  if( m_pcResidual )
+  {
+    m_pcResidual->destroy();
+    delete m_pcResidual;
+    m_pcResidual = NULL;
+  }
+#endif
+  delete m_SEIs;
+}
+
+Void TComPic::compressMotion()
+{
+  TComPicSym* pPicSym = getPicSym(); 
+  for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getFrameHeightInCU()*pPicSym->getFrameWidthInCU(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pPicSym->getCU(uiCUAddr);
+    pcCU->compressMV(); 
+  } 
+}
+
+#if DEPTH_MAP_GENERATION
+Void
+TComPic::addPrdDepthMapBuffer( UInt uiSubSampExpX, UInt uiSubSampExpY )
+{
+  AOT( m_pcPredDepthMap );
+  AOF( m_apcPicYuv[1]   );
+  Int   iWidth        = m_apcPicYuv[1]->getWidth      ();
+  Int   iHeight       = m_apcPicYuv[1]->getHeight     ();
+  UInt  uiMaxCuWidth  = m_apcPicYuv[1]->getMaxCuWidth ();
+  UInt  uiMaxCuHeight = m_apcPicYuv[1]->getMaxCuHeight();
+  UInt  uiMaxCuDepth  = m_apcPicYuv[1]->getMaxCuDepth ();
+  m_pcPredDepthMap    = new TComPicYuv;
+  m_pcPredDepthMap    ->create( iWidth >> uiSubSampExpX, iHeight >> uiSubSampExpY, uiMaxCuWidth >> uiSubSampExpX, uiMaxCuHeight >> uiSubSampExpY, uiMaxCuDepth );
+#if PDM_REMOVE_DEPENDENCE
+  m_pcPredDepthMap_temp    = new TComPicYuv;
+  m_pcPredDepthMap_temp    ->create( iWidth >> uiSubSampExpX, iHeight >> uiSubSampExpY, uiMaxCuWidth >> uiSubSampExpX, uiMaxCuHeight >> uiSubSampExpY, uiMaxCuDepth );
+#endif
+}
+#endif
+
+#if H3D_IVMP
+Void
+TComPic::addOrgDepthMapBuffer()
+{
+  AOT( m_pcOrgDepthMap );
+  AOF( m_apcPicYuv[1]  );
+  Int   iWidth        = m_apcPicYuv[1]->getWidth      ();
+  Int   iHeight       = m_apcPicYuv[1]->getHeight     ();
+  UInt  uiMaxCuWidth  = m_apcPicYuv[1]->getMaxCuWidth ();
+  UInt  uiMaxCuHeight = m_apcPicYuv[1]->getMaxCuHeight();
+  UInt  uiMaxCuDepth  = m_apcPicYuv[1]->getMaxCuDepth ();
+  m_pcOrgDepthMap     = new TComPicYuv;
+  m_pcOrgDepthMap     ->create( iWidth, iHeight, uiMaxCuWidth, uiMaxCuHeight, uiMaxCuDepth );
+}
+#endif
+
+#if H3D_IVRP
+Void
+TComPic::addResidualBuffer()
+{
+  AOT( m_pcResidual   );
+  AOF( m_apcPicYuv[1] );
+  Int   iWidth        = m_apcPicYuv[1]->getWidth      ();
+  Int   iHeight       = m_apcPicYuv[1]->getHeight     ();
+  UInt  uiMaxCuWidth  = m_apcPicYuv[1]->getMaxCuWidth ();
+  UInt  uiMaxCuHeight = m_apcPicYuv[1]->getMaxCuHeight();
+  UInt  uiMaxCuDepth  = m_apcPicYuv[1]->getMaxCuDepth ();
+  m_pcResidual        = new TComPicYuv;
+  m_pcResidual        ->create( iWidth, iHeight, uiMaxCuWidth, uiMaxCuHeight, uiMaxCuDepth );
+}
+#endif
+
+#if DEPTH_MAP_GENERATION
+Void
+TComPic::removePrdDepthMapBuffer()
+{
+  if( m_pcPredDepthMap )
+  {
+    m_pcPredDepthMap->destroy();
+    delete m_pcPredDepthMap;
+    m_pcPredDepthMap = NULL;
+  }
+#if PDM_REMOVE_DEPENDENCE
+  if(m_pcPredDepthMap_temp)
+  {
+    m_pcPredDepthMap_temp->destroy();
+    delete m_pcPredDepthMap_temp;
+    m_pcPredDepthMap_temp = NULL;
+  }
+#endif
+}
+#endif
+
+#if H3D_IVMP
+Void
+TComPic::removeOrgDepthMapBuffer()
+{
+  if( m_pcOrgDepthMap )
+  {
+    m_pcOrgDepthMap->destroy();
+    delete m_pcOrgDepthMap;
+    m_pcOrgDepthMap = NULL;
+  }
+}
+#endif
+
+#if H3D_IVRP
+Void
+TComPic::removeResidualBuffer()
+{
+  if( m_pcResidual )
+  {
+    m_pcResidual->destroy();
+    delete m_pcResidual;
+    m_pcResidual = NULL;
+  }
+}
+#endif
+
+/** Create non-deblocked filter information
+ * \param pSliceStartAddress array for storing slice start addresses
+ * \param numSlices number of slices in picture
+ * \param sliceGranularityDepth slice granularity 
+ * \param bNDBFilterCrossSliceBoundary cross-slice-boundary in-loop filtering; true for "cross".
+ * \param numTiles number of tiles in picture
+ * \param bNDBFilterCrossTileBoundary cross-tile-boundary in-loop filtering; true for "cross".
+ */
+Void TComPic::createNonDBFilterInfo(UInt* pSliceStartAddress, Int numSlices, Int sliceGranularityDepth
+                                    ,Bool bNDBFilterCrossSliceBoundary
+                                    ,Int numTiles
+                                    ,Bool bNDBFilterCrossTileBoundary)
+{
+  UInt maxNumSUInLCU = getNumPartInCU();
+  UInt numLCUInPic   = getNumCUsInFrame();
+  UInt picWidth      = getSlice(0)->getSPS()->getPicWidthInLumaSamples();
+  UInt picHeight     = getSlice(0)->getSPS()->getPicHeightInLumaSamples();
+  Int  numLCUsInPicWidth = getFrameWidthInCU();
+  Int  numLCUsInPicHeight= getFrameHeightInCU();
+  UInt maxNumSUInLCUWidth = getNumPartInWidth();
+  UInt maxNumSUInLCUHeight= getNumPartInHeight();
+
+  m_bIndependentSliceBoundaryForNDBFilter = (bNDBFilterCrossSliceBoundary)?(false):((numSlices > 1)?(true):(false)) ;
+  m_sliceGranularityForNDBFilter = sliceGranularityDepth;
+  m_bIndependentTileBoundaryForNDBFilter  = (bNDBFilterCrossTileBoundary)?(false) :((numTiles > 1)?(true):(false));
+
+  m_pbValidSlice = new Bool[numSlices];
+  for(Int s=0; s< numSlices; s++)
+  {
+    m_pbValidSlice[s] = true;
+  }
+  m_pSliceSUMap = new Int[maxNumSUInLCU * numLCUInPic];
+
+  //initialization
+  for(UInt i=0; i< (maxNumSUInLCU * numLCUInPic); i++ )
+  {
+    m_pSliceSUMap[i] = -1;
+  }
+  for( UInt CUAddr = 0; CUAddr < numLCUInPic ; CUAddr++ )
+  {
+    TComDataCU* pcCU = getCU( CUAddr );
+    pcCU->setSliceSUMap(m_pSliceSUMap + (CUAddr* maxNumSUInLCU)); 
+    pcCU->getNDBFilterBlocks()->clear();
+  }
+  m_vSliceCUDataLink.clear();
+
+  m_vSliceCUDataLink.resize(numSlices);
+
+  UInt startAddr, endAddr, firstCUInStartLCU, startLCU, endLCU, lastCUInEndLCU, uiAddr;
+  UInt LPelX, TPelY, LCUX, LCUY;
+  UInt currSU;
+  UInt startSU, endSU;
+
+  for(Int s=0; s< numSlices; s++)
+  {
+    //1st step: decide the real start address
+    startAddr = pSliceStartAddress[s];
+    endAddr   = pSliceStartAddress[s+1] -1;
+
+    startLCU            = startAddr / maxNumSUInLCU;
+    firstCUInStartLCU   = startAddr % maxNumSUInLCU;
+
+    endLCU              = endAddr   / maxNumSUInLCU;
+    lastCUInEndLCU      = endAddr   % maxNumSUInLCU;   
+
+    uiAddr = m_apcPicSym->getCUOrderMap(startLCU);
+
+    LCUX      = getCU(uiAddr)->getCUPelX();
+    LCUY      = getCU(uiAddr)->getCUPelY();
+    LPelX     = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[firstCUInStartLCU] ];
+    TPelY     = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[firstCUInStartLCU] ];
+    currSU    = firstCUInStartLCU;
+
+    Bool bMoveToNextLCU = false;
+    Bool bSliceInOneLCU = (startLCU == endLCU);
+
+    while(!( LPelX < picWidth ) || !( TPelY < picHeight ))
+    {
+      currSU ++;
+
+      if(bSliceInOneLCU)
+      {
+        if(currSU > lastCUInEndLCU)
+        {
+          m_pbValidSlice[s] = false;
+          break;
+        }
+      }
+
+      if(currSU >= maxNumSUInLCU )
+      {
+        bMoveToNextLCU = true;
+        break;
+      }
+
+      LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+      TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+
+    }
+
+
+    if(!m_pbValidSlice[s])
+    {
+      continue;
+    }
+
+    if(currSU != firstCUInStartLCU)
+    {
+      if(!bMoveToNextLCU)
+      {
+        firstCUInStartLCU = currSU;
+      }
+      else
+      {
+        startLCU++;
+        firstCUInStartLCU = 0;
+        assert( startLCU < getNumCUsInFrame());
+      }
+      assert(startLCU*maxNumSUInLCU + firstCUInStartLCU < endAddr);
+    }
+
+
+    //2nd step: assign NonDBFilterInfo to each processing block
+    for(UInt i= startLCU; i <= endLCU; i++)
+    {
+      startSU = (i == startLCU)?(firstCUInStartLCU):(0);
+      endSU   = (i == endLCU  )?(lastCUInEndLCU   ):(maxNumSUInLCU -1);
+
+      uiAddr = m_apcPicSym->getCUOrderMap(i);
+      Int iTileID= m_apcPicSym->getTileIdxMap(uiAddr);
+
+      TComDataCU* pcCU = getCU(uiAddr);
+      m_vSliceCUDataLink[s].push_back(pcCU);
+
+      createNonDBFilterInfoLCU(iTileID, s, pcCU, startSU, endSU, m_sliceGranularityForNDBFilter, picWidth, picHeight);
+    }
+  }
+
+  //step 3: border availability
+  for(Int s=0; s< numSlices; s++)
+  {
+    if(!m_pbValidSlice[s])
+    {
+      continue;
+    }
+
+    for(Int i=0; i< m_vSliceCUDataLink[s].size(); i++)
+    {
+      TComDataCU* pcCU = m_vSliceCUDataLink[s][i];
+      uiAddr = pcCU->getAddr();
+
+      if(pcCU->getPic()==0)
+      {
+        continue;
+      }
+      Int iTileID= m_apcPicSym->getTileIdxMap(uiAddr);
+      Bool bTopTileBoundary = false, bDownTileBoundary= false, bLeftTileBoundary= false, bRightTileBoundary= false;
+
+      if(m_bIndependentTileBoundaryForNDBFilter)
+      {
+        //left
+        if( uiAddr % numLCUsInPicWidth != 0)
+        {
+          bLeftTileBoundary = ( m_apcPicSym->getTileIdxMap(uiAddr -1) != iTileID )?true:false;
+        }
+        //right
+        if( (uiAddr % numLCUsInPicWidth) != (numLCUsInPicWidth -1) )
+        {
+          bRightTileBoundary = ( m_apcPicSym->getTileIdxMap(uiAddr +1) != iTileID)?true:false;
+        }
+        //top
+        if( uiAddr >= numLCUsInPicWidth)
+        {
+          bTopTileBoundary = (m_apcPicSym->getTileIdxMap(uiAddr - numLCUsInPicWidth) !=  iTileID )?true:false;
+        }
+        //down
+        if( uiAddr + numLCUsInPicWidth < numLCUInPic )
+        {
+          bDownTileBoundary = (m_apcPicSym->getTileIdxMap(uiAddr + numLCUsInPicWidth) != iTileID)?true:false;
+        }
+
+      }
+
+      pcCU->setNDBFilterBlockBorderAvailability(numLCUsInPicWidth, numLCUsInPicHeight, maxNumSUInLCUWidth, maxNumSUInLCUHeight,picWidth, picHeight
+        ,m_bIndependentSliceBoundaryForNDBFilter
+        ,bTopTileBoundary, bDownTileBoundary, bLeftTileBoundary, bRightTileBoundary
+        ,m_bIndependentTileBoundaryForNDBFilter);
+
+    }
+
+  }
+
+  if( m_bIndependentSliceBoundaryForNDBFilter || m_bIndependentTileBoundaryForNDBFilter)
+  {
+    m_pNDBFilterYuvTmp = new TComPicYuv();
+    m_pNDBFilterYuvTmp->create(picWidth, picHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+  }
+}
+#if H3D_NBDV
+Bool TComPic::getDisCandRefPictures(Int iColPOC)
+{
+  UInt uiTempLayerCurr=7;
+  TComSlice* currSlice = getCurrSlice();
+  UInt iPOCCurr=currSlice->getPOC();
+  UInt iPOCDiff = 255;
+  Bool  bRAP=false;
+  Bool bCheck = false;
+  Int MaxRef = currSlice->getNumRefIdx(RefPicList(0));
+  RefPicList eRefPicList = REF_PIC_LIST_0 ;
+  if(currSlice->isInterB())
+  {
+    if(currSlice->getNumRefIdx(RefPicList(0))< currSlice->getNumRefIdx(RefPicList(1)))
+      MaxRef = currSlice->getNumRefIdx(RefPicList(1));
+  }
+  for(Int lpRef = 0; lpRef < MaxRef; lpRef++)
+  {
+    for(Int lpNr = 0; lpNr < (currSlice->isInterB() ? 2: 1); lpNr ++)
+    {
+      eRefPicList = RefPicList(0);
+      if(currSlice->isInterB())
+        eRefPicList = RefPicList(lpNr==0 ? (currSlice->getColDir()): (1-currSlice->getColDir()));
+      if(iColPOC == currSlice->getRefPOC(eRefPicList, lpRef))
+        continue;
+      if(lpRef >= currSlice->getNumRefIdx(eRefPicList)||(currSlice->getViewId() != currSlice->getRefPic( eRefPicList, lpRef)->getViewId()))
+        continue;
+      Int iTempPoc = currSlice->getRefPic(eRefPicList, lpRef)->getPOC();
+      UInt uiTempLayer = currSlice->getRefPic(eRefPicList, lpRef)->getCurrSlice()->getTLayer(); 
+      Int iTempDiff = (iTempPoc > iPOCCurr) ? (iTempPoc - iPOCCurr): (iPOCCurr - iTempPoc);
+#if QC_REM_IDV_B0046
+      TComSlice* refSlice = currSlice->getRefPic(eRefPicList, lpRef)->getCurrSlice();
+      bRAP = (refSlice->getSPS()->getViewId() && (refSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || refSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))? 1: 0;      
+#else
+      bRAP = (currSlice->getRefPic(eRefPicList, lpRef)->getCurrSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDV? 1:0);
+#endif
+      if( bRAP)
+      {
+         bCheck = true;
+         this->setRapRefIdx(lpRef);
+         this->setRapRefList(eRefPicList);
+         return bCheck;
+      }
+      if(uiTempLayerCurr > uiTempLayer)
+      {
+        bCheck = true;
+        if(uiTempLayerCurr == uiTempLayer)
+        {
+          if(iPOCDiff > iTempDiff)
+          {
+            iPOCDiff=iTempDiff;
+            if(iPOCDiff < 255)
+            {
+              this->setRapRefIdx(lpRef);
+              this->setRapRefList(eRefPicList);
+            }
+          }
+        }
+        else
+        {
+          iPOCDiff=iTempDiff;
+          uiTempLayerCurr = uiTempLayer;
+          this->setRapRefIdx(lpRef);
+          this->setRapRefList(eRefPicList);
+        } 
+      }
+    }
+  }
+  return bCheck;
+}
+#endif
+
+#if HHI_INTERVIEW_SKIP
+Void TComPic::addUsedPelsMapBuffer()
+{
+  AOT( m_pcUsedPelsMap );
+  AOF( m_apcPicYuv[1]  );
+  Int   iWidth        = m_apcPicYuv[1]->getWidth      ();
+  Int   iHeight       = m_apcPicYuv[1]->getHeight     ();
+  UInt  uiMaxCuWidth  = m_apcPicSym->getMaxCUWidth();
+  UInt  uiMaxCuHeight = m_apcPicSym->getMaxCUHeight();
+  UInt  uiMaxCuDepth  = m_apcPicSym->getMaxCUDepth ();
+  m_pcUsedPelsMap     = new TComPicYuv;
+  m_pcUsedPelsMap     ->create( iWidth, iHeight, uiMaxCuWidth, uiMaxCuHeight, uiMaxCuDepth );
+
+}
+Void
+TComPic::removeUsedPelsMapBuffer()
+{
+  if( m_pcUsedPelsMap )
+  {
+    m_pcUsedPelsMap->destroy();
+    delete m_pcUsedPelsMap;
+    m_pcUsedPelsMap = NULL;
+  }
+}
+#endif
+
+/** Create non-deblocked filter information for LCU
+ * \param tileID tile index
+ * \param sliceID slice index
+ * \param pcCU CU data pointer
+ * \param startSU start SU index in LCU
+ * \param endSU end SU index in LCU
+ * \param sliceGranularyDepth slice granularity
+ * \param picWidth picture width
+ * \param picHeight picture height
+ */
+Void TComPic::createNonDBFilterInfoLCU(Int tileID, Int sliceID, TComDataCU* pcCU, UInt startSU, UInt endSU, Int sliceGranularyDepth, UInt picWidth, UInt picHeight)
+{
+  UInt LCUX          = pcCU->getCUPelX();
+  UInt LCUY          = pcCU->getCUPelY();
+  Int* pCUSliceMap    = pcCU->getSliceSUMap();
+  UInt maxNumSUInLCU = getNumPartInCU();
+  UInt maxNumSUInSGU = maxNumSUInLCU >> (sliceGranularyDepth << 1);
+  UInt maxNumSUInLCUWidth = getNumPartInWidth();
+  UInt LPelX, TPelY;
+  UInt currSU;
+
+
+  //get the number of valid NBFilterBLock
+  currSU   = startSU;
+  while(currSU <= endSU)
+  {
+    LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+    TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+
+    while(!( LPelX < picWidth ) || !( TPelY < picHeight ))
+    {
+      currSU += maxNumSUInSGU;
+      if(currSU >= maxNumSUInLCU || currSU > endSU)
+      {
+        break;
+      }
+      LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+      TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+    }
+
+    if(currSU >= maxNumSUInLCU || currSU > endSU)
+    {
+      break;
+    }
+
+    NDBFBlockInfo NDBFBlock;
+
+    NDBFBlock.tileID  = tileID;
+    NDBFBlock.sliceID = sliceID;
+    NDBFBlock.posY    = TPelY;
+    NDBFBlock.posX    = LPelX;
+    NDBFBlock.startSU = currSU;
+
+    UInt uiLastValidSU  = currSU;
+    UInt uiIdx, uiLPelX_su, uiTPelY_su;
+    for(uiIdx = currSU; uiIdx < currSU + maxNumSUInSGU; uiIdx++)
+    {
+      if(uiIdx > endSU)
+      {
+        break;        
+      }
+      uiLPelX_su   = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY_su   = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+      if( !(uiLPelX_su < picWidth ) || !( uiTPelY_su < picHeight ))
+      {
+        continue;
+      }
+      pCUSliceMap[uiIdx] = sliceID;
+      uiLastValidSU = uiIdx;
+    }
+    NDBFBlock.endSU = uiLastValidSU;
+
+    UInt rTLSU = g_auiZscanToRaster[ NDBFBlock.startSU ];
+    UInt rBRSU = g_auiZscanToRaster[ NDBFBlock.endSU   ];
+    NDBFBlock.widthSU  = (rBRSU % maxNumSUInLCUWidth) - (rTLSU % maxNumSUInLCUWidth)+ 1;
+    NDBFBlock.heightSU = (UInt)(rBRSU / maxNumSUInLCUWidth) - (UInt)(rTLSU / maxNumSUInLCUWidth)+ 1;
+    NDBFBlock.width    = NDBFBlock.widthSU  * getMinCUWidth();
+    NDBFBlock.height   = NDBFBlock.heightSU * getMinCUHeight();
+
+    pcCU->getNDBFilterBlocks()->push_back(NDBFBlock);
+
+    currSU += maxNumSUInSGU;
+  }
+
+}
+
+/** destroy non-deblocked filter information for LCU
+ */
+Void TComPic::destroyNonDBFilterInfo()
+{
+  if(m_pbValidSlice != NULL)
+  {
+    delete[] m_pbValidSlice;
+    m_pbValidSlice = NULL;
+  }
+
+  if(m_pSliceSUMap != NULL)
+  {
+    delete[] m_pSliceSUMap;
+    m_pSliceSUMap = NULL;
+  }
+  for( UInt CUAddr = 0; CUAddr < getNumCUsInFrame() ; CUAddr++ )
+  {
+    TComDataCU* pcCU = getCU( CUAddr );
+    pcCU->getNDBFilterBlocks()->clear();
+  }
+
+  if( m_bIndependentSliceBoundaryForNDBFilter || m_bIndependentTileBoundaryForNDBFilter)
+  {
+    m_pNDBFilterYuvTmp->destroy();
+    delete m_pNDBFilterYuvTmp;
+    m_pNDBFilterYuvTmp = NULL;
+  }
+
+}
+
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPic.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPic.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPic.h	(revision 341)
@@ -0,0 +1,304 @@
+/* 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-2012, 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     TComPic.h
+    \brief    picture class (header)
+*/
+
+#ifndef __TCOMPIC__
+#define __TCOMPIC__
+
+// Include files
+#include "CommonDef.h"
+#include "TComPicSym.h"
+#include "TComPicYuv.h"
+#include "TComBitStream.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+class SEImessages;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture class (symbol + YUV buffers)
+class TComPic
+{
+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
+  
+#if DEPTH_MAP_GENERATION
+  TComPicYuv*           m_pcPredDepthMap;         //  estimated depth map
+#if PDM_REMOVE_DEPENDENCE
+  TComPicYuv*           m_pcPredDepthMap_temp;         //  estimated depth map
+  Bool                  m_bPDMV2;                       
+#endif
+#endif
+
+#if FCO_DVP_REFINE_C0132_C0170
+  Bool                  m_bDepthCoded;
+  TComPic*              m_pcRecDepthMap;   
+#endif
+
+#if LG_ZEROINTRADEPTHRESI_A0087
+  Int                   m_uiIntraPeriod;
+#endif
+
+#if H3D_IVMP
+  TComPicYuv*           m_pcOrgDepthMap;          //  original depth map
+#if H3D_NBDV
+  Bool        m_checked;
+  UInt        m_uiRapRefIdx;
+  RefPicList  m_eRapRefList;
+  Bool        m_bRapCheck;
+#endif
+#endif
+#if H3D_IVRP
+  TComPicYuv*           m_pcResidual;             //  residual buffer (coded or inter-view predicted residual)
+#endif
+
+  TComPicYuv*           m_pcPicYuvPred;           //  Prediction
+  TComPicYuv*           m_pcPicYuvResi;           //  Residual
+  Bool                  m_bReconstructed;
+  Bool                  m_bNeededForOutput;
+  UInt                  m_uiCurrSliceIdx;         // Index of current slice
+
+  Bool                  m_usedForTMVP;
+  
+  Int*                  m_pSliceSUMap;
+  Bool*                 m_pbValidSlice;
+  Int                   m_sliceGranularityForNDBFilter;
+  Bool                  m_bIndependentSliceBoundaryForNDBFilter;
+  Bool                  m_bIndependentTileBoundaryForNDBFilter;
+  TComPicYuv*           m_pNDBFilterYuvTmp;    //!< temporary picture buffer when non-cross slice/tile boundary in-loop filtering is enabled
+  std::vector<std::vector<TComDataCU*> > m_vSliceCUDataLink;
+
+  SEImessages* m_SEIs; ///< Any SEI messages that have been received.  If !NULL we own the object.
+#if HHI_INTERVIEW_SKIP
+  TComPicYuv*           m_pcUsedPelsMap;
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Int                   m_iViewOrderIdx;    // will be changed to view_id
+#endif
+  Int**                 m_aaiCodedScale;
+  Int**                 m_aaiCodedOffset;
+
+#if H3D_QTL
+  Bool                  m_bReduceBitsQTL;
+#endif
+
+public:
+  TComPic();
+  virtual ~TComPic();
+  
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Bool bIsVirtual = false );
+  virtual Void  destroy();
+  
+  UInt          getTLayer()                { return m_uiTLayer;   }
+  Void          setTLayer( UInt uiTLayer ) { m_uiTLayer = uiTLayer; }
+
+  Bool          getUsedByCurr()             { return m_bUsedByCurr; }
+  Void          setUsedByCurr( Bool bUsed ) { m_bUsedByCurr = bUsed; }
+  Bool          getIsLongTerm()             { return m_bIsLongTerm; }
+  Void          setIsLongTerm( Bool lt ) { m_bIsLongTerm = lt; }
+
+  TComPicSym*   getPicSym()           { return  m_apcPicSym;    }
+  TComSlice*    getSlice(Int i)       { return  m_apcPicSym->getSlice(i);  }
+  TComSlice*    getCurrSlice()        { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx);  }
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  TComVPS*      getVPS()              { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getVPS();  }
+#endif
+#if LG_ZEROINTRADEPTHRESI_A0087
+  Int           getIntraPeriod()                           { return  m_uiIntraPeriod; }
+  Void          setIntraPeriod(Int uiIntraPeriod)          { m_uiIntraPeriod = uiIntraPeriod; }
+#endif
+  TComSPS*      getSPS()              { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getSPS();  }
+  Int           getPOC()              { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getPOC();  }
+  Int           getViewId()           { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getViewId(); }
+  TComDataCU*&  getCU( UInt uiCUAddr ){ return  m_apcPicSym->getCU( uiCUAddr ); }
+  
+  TComPicYuv*   getPicYuvOrg()        { return  m_apcPicYuv[0]; }
+  TComPicYuv*   getPicYuvRec()        { return  m_apcPicYuv[1]; }
+#if HHI_INTERVIEW_SKIP
+  TComPicYuv*   getUsedPelsMap()      { return  m_pcUsedPelsMap; }
+#endif
+  
+#if DEPTH_MAP_GENERATION
+  TComPicYuv*   getPredDepthMap()     { return  m_pcPredDepthMap; }
+#if PDM_REMOVE_DEPENDENCE
+  TComPicYuv*   getPredDepthMapTemp()           { return  m_pcPredDepthMap_temp; }
+  Void          setStoredPDMforV2  (Bool flag)  { m_bPDMV2 = flag;}
+  Bool          getStoredPDMforV2  ()           { return m_bPDMV2;}
+#endif
+
+#endif
+#if H3D_IVMP
+  TComPicYuv*   getOrgDepthMap()      { return  m_pcOrgDepthMap; }
+#if H3D_NBDV
+  Void          setCandPicCheckedFlag (Bool bchecked)   { m_checked = bchecked; }
+  Bool          getCandPicCheckedFlag ()                { return m_checked;}
+#endif
+#endif
+
+#if FCO_DVP_REFINE_C0132_C0170
+  void setRecDepthMap(TComPic * pRecPic)                { m_pcRecDepthMap = pRecPic; }
+  TComPic * getRecDepthMap()                            { return m_pcRecDepthMap; }
+  void setDepthCoded(Bool flag)                         { m_bDepthCoded = flag; }
+  Bool getDepthCoded()                                  { return m_bDepthCoded; }
+#endif
+
+#if H3D_IVRP
+  TComPicYuv*   getResidual()         { return  m_pcResidual; }
+#endif
+#if H3D_NBDV
+  UInt          getRapRefIdx()                         {return m_uiRapRefIdx;}
+  RefPicList    getRapRefList()                        {return m_eRapRefList;}
+  Void          setRapRefIdx(UInt uiRapRefIdx)         {m_uiRapRefIdx = uiRapRefIdx;}
+  Void          setRapRefList(RefPicList eRefPicList)  {m_eRapRefList = eRefPicList;}
+  Bool          getRapbCheck()                         {return m_bRapCheck;}
+  Void          setRapbCheck(Bool bCheck)              {m_bRapCheck = bCheck;}
+  Bool          getDisCandRefPictures(Int iColPOC);
+#endif
+
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Void          setViewOrderIdx(Int i)                        { m_iViewOrderIdx = i; }        // will be changed to view_id
+  Int           getViewOrderIdx()                             { return m_iViewOrderIdx; }    // will be changed to view_id
+#endif
+
+#if H3D_QTL
+  Bool          getReduceBitsFlag ()             { return m_bReduceBitsQTL;     }
+  Void          setReduceBitsFlag ( Bool bFlag ) { m_bReduceBitsQTL = bFlag;    }
+#endif
+
+  Void          setScaleOffset( Int** pS, Int** pO )  { m_aaiCodedScale = pS; m_aaiCodedOffset = pO; }
+  Int**         getCodedScale ()                      { return m_aaiCodedScale;  }
+  Int**         getCodedOffset()                      { return m_aaiCodedOffset; }
+
+  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(); }
+  
+  Void          setReconMark (Bool b) { m_bReconstructed = b;     }
+  Bool          getReconMark ()       { return m_bReconstructed;  }
+
+  Void          setUsedForTMVP( Bool b ) { m_usedForTMVP = b;    }
+  Bool          getUsedForTMVP()         { return m_usedForTMVP; }
+
+  Void          setOutputMark (Bool b) { m_bNeededForOutput = b;     }
+  Bool          getOutputMark ()       { return m_bNeededForOutput;  }
+ 
+  Void          compressMotion(); 
+  UInt          getCurrSliceIdx()            { 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();         }
+#if HHI_INTERVIEW_SKIP
+  Void          addUsedPelsMapBuffer    ();
+  Void          removeUsedPelsMapBuffer ();
+#endif
+  
+  Void          createNonDBFilterInfo   (UInt* pSliceStartAddress = NULL, Int numSlices = 1, Int sliceGranularityDepth= 0
+                                        ,Bool bNDBFilterCrossSliceBoundary = true
+                                        ,Int  numTiles = 1
+                                        ,Bool bNDBFilterCrossTileBoundary = true);
+  Void          createNonDBFilterInfoLCU(Int tileID, Int sliceID, TComDataCU* pcCU, UInt startSU, UInt endSU, Int sliceGranularyDepth, UInt picWidth, UInt picHeight);
+  Void          destroyNonDBFilterInfo();
+
+#if DEPTH_MAP_GENERATION
+  Void          addPrdDepthMapBuffer    ( UInt uiSubSampExpX, UInt uiSubSampExpY );
+#endif
+#if H3D_IVMP
+  Void          addOrgDepthMapBuffer    ();
+#endif
+#if H3D_IVRP
+  Void          addResidualBuffer       ();
+#endif
+#if DEPTH_MAP_GENERATION
+  Void          removePrdDepthMapBuffer ();
+#endif
+#if H3D_IVMP
+  Void          removeOrgDepthMapBuffer ();
+#endif
+#if H3D_IVRP
+  Void          removeResidualBuffer    ();
+#endif
+
+  Bool          getValidSlice                                  (Int sliceID)  {return m_pbValidSlice[sliceID];}
+  Int           getSliceGranularityForNDBFilter                ()             {return m_sliceGranularityForNDBFilter;}
+  Bool          getIndependentSliceBoundaryForNDBFilter        ()             {return m_bIndependentSliceBoundaryForNDBFilter;}
+  Bool          getIndependentTileBoundaryForNDBFilter         ()             {return m_bIndependentTileBoundaryForNDBFilter; }
+  TComPicYuv*   getYuvPicBufferForIndependentBoundaryProcessing()             {return m_pNDBFilterYuvTmp;}
+  std::vector<TComDataCU*>& getOneSliceCUDataForNDBFilter      (Int sliceID) { return m_vSliceCUDataLink[sliceID];}
+
+  /** transfer ownership of seis to this picture */
+  void setSEIs(SEImessages* seis) { m_SEIs = seis; }
+
+  /**
+   * return the current list of SEI messages associated with this picture.
+   * Pointer is valid until this->destroy() is called */
+  SEImessages* getSEIs() { return m_SEIs; }
+
+  /**
+   * return the current list of SEI messages associated with this picture.
+   * Pointer is valid until this->destroy() is called */
+  const SEImessages* getSEIs() const { return m_SEIs; }
+
+};// END CLASS DEFINITION TComPic
+
+//! \}
+
+#endif // __TCOMPIC__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicSym.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicSym.cpp	(revision 341)
@@ -0,0 +1,295 @@
+/* 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-2012, 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     TComPicSym.cpp
+    \brief    picture symbol class
+*/
+
+#include "TComPicSym.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+Void TComPicSym::create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, 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_uiNumPartitions];  
+  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
+#if ADAPTIVE_QP_SELECTION
+      , true
+#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;
+  }
+}
+
+Void TComPicSym::destroy()
+{
+  Int i;
+  
+  if (m_uiNumAllocatedSlice>0)
+  {
+    for ( i=0; i<m_uiNumAllocatedSlice ; i++ )
+    {
+      delete m_apcTComSlice[i];
+    }
+    delete [] m_apcTComSlice;
+  }
+  m_apcTComSlice = NULL;
+  
+  for (i = 0; i < m_uiNumCUsInFrame; i++)
+  {
+    m_apcTComDataCU[i]->destroy();
+    delete m_apcTComDataCU[i];
+    m_apcTComDataCU[i] = NULL;
+  }
+  delete [] m_apcTComDataCU;
+  m_apcTComDataCU = NULL;
+
+
+  for( i=0; i<(m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1); i++ )
+  {
+    if ( m_apcTComTile[i] )  delete m_apcTComTile[i];
+  }
+
+  delete [] m_apcTComTile;
+  m_apcTComTile = NULL;
+
+  delete [] m_puiCUOrderMap;
+  m_puiCUOrderMap = NULL;
+
+  delete [] m_puiTileIdxMap;
+  m_puiTileIdxMap = NULL;
+
+  delete [] m_puiInverseCUOrderMap;
+  m_puiInverseCUOrderMap = NULL;
+}
+
+Void TComPicSym::allocateNewSlice()
+{
+  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_apcTComSlice[m_uiNumAllocatedSlice-1]->initTiles();
+
+  }
+}
+
+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::xCreateTComTileArray()
+{
+  m_apcTComTile = new TComTile*[(m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1)];
+  for( UInt i=0; i<(m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1); i++ )
+  {
+    m_apcTComTile[i] = new TComTile;
+  }
+}
+
+Void TComPicSym::xInitTiles()
+{
+  UInt  uiTileIdx;
+  UInt  uiColumnIdx = 0;
+  UInt  uiRowIdx = 0;
+  UInt  uiRightEdgePosInCU;
+  UInt  uiBottomEdgePosInCU;
+  Int   i, j;
+
+  //initialize each tile of the current picture
+  for( uiRowIdx=0; uiRowIdx < m_iNumRowsMinus1+1; uiRowIdx++ )
+    for( uiColumnIdx=0; uiColumnIdx < m_iNumColumnsMinus1+1; uiColumnIdx++ )
+    {
+      uiTileIdx = uiRowIdx * (m_iNumColumnsMinus1+1) + uiColumnIdx;
+
+      //initialize the RightEdgePosInCU for each tile
+      uiRightEdgePosInCU = 0;
+      for( i=0; i <= uiColumnIdx; i++ )
+      {
+        uiRightEdgePosInCU += this->getTComTile(uiRowIdx * (m_iNumColumnsMinus1+1) + i)->getTileWidth();
+      }
+      this->getTComTile(uiTileIdx)->setRightEdgePosInCU(uiRightEdgePosInCU-1);
+
+      //initialize the BottomEdgePosInCU for each tile
+      uiBottomEdgePosInCU = 0;
+      for( i=0; i <= uiRowIdx; i++ )
+      {
+        uiBottomEdgePosInCU += this->getTComTile(i * (m_iNumColumnsMinus1+1) + uiColumnIdx)->getTileHeight();
+      }
+      this->getTComTile(uiTileIdx)->setBottomEdgePosInCU(uiBottomEdgePosInCU-1);
+
+      //initialize the FirstCUAddr for each tile
+      this->getTComTile(uiTileIdx)->setFirstCUAddr( (this->getTComTile(uiTileIdx)->getBottomEdgePosInCU() - this->getTComTile(uiTileIdx)->getTileHeight() +1)*m_uiWidthInCU + 
+        this->getTComTile(uiTileIdx)->getRightEdgePosInCU() - this->getTComTile(uiTileIdx)->getTileWidth() + 1);
+    }
+
+  //initialize the TileIdxMap
+  for( i=0; i<m_uiNumCUsInFrame; i++)
+  {
+    for(j=0; j < m_iNumColumnsMinus1+1; j++)
+    {
+      if(i % m_uiWidthInCU <= this->getTComTile(j)->getRightEdgePosInCU())
+      {
+        uiColumnIdx = j;
+        j = m_iNumColumnsMinus1+1;
+      }
+    }
+    for(j=0; j < m_iNumRowsMinus1+1; j++)
+    {
+      if(i/m_uiWidthInCU <= this->getTComTile(j*(m_iNumColumnsMinus1 + 1))->getBottomEdgePosInCU())
+      {
+        uiRowIdx = j;
+        j = m_iNumRowsMinus1 + 1;
+      }
+    }
+    m_puiTileIdxMap[i] = uiRowIdx * (m_iNumColumnsMinus1 + 1) + uiColumnIdx;
+  }
+
+  // Determine bits required for tile index
+  Int uiTilesCount = (m_iNumRowsMinus1+1) * (m_iNumColumnsMinus1+1);
+  m_uiBitsUsedByTileIdx = 0;
+  while (uiTilesCount)
+  {
+    m_uiBitsUsedByTileIdx++;
+    uiTilesCount >>= 1;
+  }
+}
+
+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;
+    }
+    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;
+    }
+    else
+    {
+      uiNxtCUAddr = uiCurrCUAddr + 1;
+    }
+  }
+
+  return uiNxtCUAddr;
+}
+
+TComTile::TComTile()
+{
+}
+
+TComTile::~TComTile()
+{
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicSym.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicSym.h	(revision 341)
@@ -0,0 +1,157 @@
+/* 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-2012, 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     TComPicSym.h
+    \brief    picture symbol class (header)
+*/
+
+#ifndef __TCOMPICSYM__
+#define __TCOMPICSYM__
+
+
+// Include files
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComDataCU.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TComTile
+{
+private:
+  UInt      m_uiTileWidth;
+  UInt      m_uiTileHeight;
+  UInt      m_uiRightEdgePosInCU;
+  UInt      m_uiBottomEdgePosInCU;
+  UInt      m_uiFirstCUAddr;
+
+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; }
+};
+
+/// picture symbol class
+class TComPicSym
+{
+private:
+  UInt          m_uiWidthInCU;
+  UInt          m_uiHeightInCU;
+  
+  UInt          m_uiMaxCUWidth;
+  UInt          m_uiMaxCUHeight;
+  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_iTileBoundaryIndependenceIdr;
+  Int           m_iNumColumnsMinus1; 
+  Int           m_iNumRowsMinus1;
+  TComTile**    m_apcTComTile;
+  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_uiBitsUsedByTileIdx;
+
+public:
+  Void        create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
+  Void        destroy ();
+  
+  TComPicSym  ()                        { m_uiNumAllocatedSlice = 0;            }
+  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;               }
+#if HHI_INTERVIEW_SKIP
+  UInt        getMaxCUWidth()           { return m_uiMaxCUWidth;                }
+  UInt        getMaxCUHeight()          { return m_uiMaxCUHeight;               }
+  UInt        getMaxCUDepth()           { return m_uhTotalDepth;                }
+#endif
+  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_apcTComTile + 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         xCreateTComTileArray();
+  Void         xInitTiles();
+  UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
+  UInt         getBitsUsedByTileIdx()                                { return m_uiBitsUsedByTileIdx; }
+};// END CLASS DEFINITION TComPicSym
+
+//! \}
+
+#endif // __TCOMPICSYM__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 341)
@@ -0,0 +1,491 @@
+/* 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-2012, 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     TComPicYuv.cpp
+    \brief    picture YUV buffer class
+*/
+
+#include <cstdlib>
+#include <assert.h>
+#include <memory.h>
+
+#ifdef __APPLE__
+#include <malloc/malloc.h>
+#else
+#include <malloc.h>
+#endif
+
+#include "TComPicYuv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+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;
+
+#if FIX_APPENCTOP_T_ONLY
+  m_cuOffsetY       = NULL;
+  m_cuOffsetC       = NULL;
+  m_buOffsetY       = NULL;
+  m_buOffsetC       = NULL;
+#endif  
+
+  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;
+
+  m_iNumCuInWidth   = m_iPicWidth / m_iCuWidth;
+  m_iNumCuInWidth  += ( m_iPicWidth % m_iCuWidth ) ? 1 : 0;
+
+  m_uiMaxCuDepth = uiMaxCUDepth;
+
+  m_iBaseUnitWidth  = uiMaxCUWidth  >> uiMaxCUDepth;
+  m_iBaseUnitHeight = uiMaxCUHeight >> uiMaxCUDepth;
+
+  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  + PICYUV_PAD; // for 16-byte alignment
+  m_iLumaMarginY    = g_uiMaxCUHeight + PICYUV_PAD;  // 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_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);
+    }
+  }
+  return;
+}
+
+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; }
+#if FIX_APPENCTOP_T_ONLY
+  if( m_cuOffsetY )
+  {
+#endif
+  delete[] m_cuOffsetY;
+  delete[] m_cuOffsetC;
+  delete[] m_buOffsetY;
+  delete[] m_buOffsetC;
+#if FIX_APPENCTOP_T_ONLY
+  }
+#endif
+}
+
+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;
+  m_uiMaxCuDepth    = uiMaxCUDepth;
+
+  m_iNumCuInWidth   = m_iPicWidth / m_iCuWidth;
+  m_iNumCuInWidth  += ( m_iPicWidth % m_iCuWidth ) ? 1 : 0;
+
+  m_iBaseUnitWidth  = uiMaxCUWidth  >> uiMaxCUDepth;
+  m_iBaseUnitHeight = uiMaxCUHeight >> uiMaxCUDepth;
+
+  
+  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  + PICYUV_PAD; // for 16-byte alignment
+  m_iLumaMarginY    = g_uiMaxCUHeight + PICYUV_PAD;  // 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);
+    }
+  }
+  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::getLumaMinMax( Int *pMin, Int *pMax )
+{
+  Pel*  piY   = getLumaAddr();
+  Int   iMin  = (1<<(g_uiBitDepth))-1;
+  Int   iMax  = 0;
+  Int   x, y;
+  
+  for ( y = 0; y < m_iPicHeight; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth; x++ )
+    {
+      if ( piY[x] < iMin ) iMin = piY[x];
+      if ( piY[x] > iMax ) iMax = piY[x];
+    }
+    piY += getStride();
+  }
+  
+  *pMin = iMin;
+  *pMax = iMax;
+}
+
+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 );
+  
+  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)
+{
+  FILE* pFile;
+  if (!bAdd)
+  {
+    pFile = fopen (pFileName, "wb");
+  }
+  else
+  {
+    pFile = fopen (pFileName, "ab");
+  }
+  
+  Int     shift = g_uiBitIncrement;
+  Int     offset = (shift>0)?(1<<(shift-1)):0;
+  
+  Int   x, y;
+  UChar uc;
+  
+  Pel*  piY   = getLumaAddr();
+  Pel*  piCb  = getCbAddr();
+  Pel*  piCr  = getCrAddr();
+  
+  Pel  iMax = ((1<<(g_uiBitDepth))-1);
+  
+  for ( y = 0; y < m_iPicHeight; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth; x++ )
+    {
+      uc = (UChar)Clip3<Pel>(0, iMax, (piY[x]+offset)>>shift);
+      
+      fwrite( &uc, sizeof(UChar), 1, pFile );
+    }
+    piY += getStride();
+  }
+  
+  for ( y = 0; y < m_iPicHeight >> 1; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth >> 1; x++ )
+    {
+      uc = (UChar)Clip3<Pel>(0, iMax, (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, iMax, (piCr[x]+offset)>>shift);
+      fwrite( &uc, sizeof(UChar), 1, pFile );
+    }
+    piCr += getCStride();
+  }
+  
+  fclose(pFile);
+}
+
+#if FIXED_ROUNDING_FRAME_MEMORY
+Void TComPicYuv::xFixedRoundingPic()
+{
+  Int   x, y;
+  Pel*  pRec    = getLumaAddr();
+  Int   iStride = getStride();
+  Int   iWidth  = getWidth();
+  Int   iHeight = getHeight();
+#if FULL_NBIT
+  Int   iOffset  = ((g_uiBitDepth-8)>0)?(1<<(g_uiBitDepth-8-1)):0;
+  Int   iMask   = (~0<<(g_uiBitDepth-8));
+  Int   iMaxBdi = g_uiBASE_MAX<<(g_uiBitDepth-8);
+#else
+  Int   iOffset  = (g_uiBitIncrement>0)?(1<<(g_uiBitIncrement-1)):0;
+  Int   iMask   = (~0<<g_uiBitIncrement);
+  Int   iMaxBdi = g_uiBASE_MAX<<g_uiBitIncrement;
+#endif
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_NOCLIP_RANGE
+      pRec[x] = ( pRec[x] + iOffset ) & iMask;
+#else
+      pRec[x] = ( pRec[x]+iOffset>iMaxBdi)? iMaxBdi : ((pRec[x]+iOffset) & iMask);
+#endif
+    }
+    pRec += iStride;
+  }
+
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  pRec  = getCbAddr();
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_NOCLIP_RANGE
+      pRec[x] = ( pRec[x] + iOffset ) & iMask;
+#else
+      pRec[x] = ( pRec[x]+iOffset>iMaxBdi)? iMaxBdi : ((pRec[x]+iOffset) & iMask);
+#endif
+    }
+    pRec += iStride;
+  }
+
+  pRec  = getCrAddr();
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_NOCLIP_RANGE
+      pRec[x] = ( pRec[x] + iOffset ) & iMask;
+#else
+      pRec[x] = ( pRec[x]+iOffset>iMaxBdi)? iMaxBdi : ((pRec[x]+iOffset) & iMask);
+#endif
+    }
+    pRec += iStride;
+  }
+}
+#endif
+
+Void
+TComPicYuv::getTopLeftSamplePos( Int iCuAddr, Int iAbsZorderIdx, Int& riX, Int& riY )
+{
+  Int iRastPartIdx    = g_auiZscanToRaster[iAbsZorderIdx];
+  Int iCuSizeInBases  = m_iCuWidth   / m_iBaseUnitWidth;
+  Int iCuX            = iCuAddr      % m_iNumCuInWidth;
+  Int iCuY            = iCuAddr      / m_iNumCuInWidth;
+  Int iBaseX          = iRastPartIdx % iCuSizeInBases;
+  Int iBaseY          = iRastPartIdx / iCuSizeInBases;
+  riX                 = iCuX * m_iCuWidth  + iBaseX * m_iBaseUnitWidth;
+  riY                 = iCuY * m_iCuHeight + iBaseY * m_iBaseUnitHeight; 
+}
+
+Void
+TComPicYuv::getCUAddrAndPartIdx( Int iX, Int iY, Int& riCuAddr, Int& riAbsZorderIdx )
+{
+  Int iCuX            = iX / m_iCuWidth;
+  Int iCuY            = iY / m_iCuHeight;
+  Int iBaseX          = ( iX - iCuX * m_iCuWidth  ) / m_iBaseUnitWidth;
+  Int iBaseY          = ( iY - iCuY * m_iCuHeight ) / m_iBaseUnitHeight;
+  Int iCuSizeInBases  = m_iCuWidth                  / m_iBaseUnitWidth;
+  riCuAddr            = iCuY   * m_iNumCuInWidth + iCuX;
+  Int iRastPartIdx    = iBaseY * iCuSizeInBases  + iBaseX;
+  riAbsZorderIdx      = g_auiRasterToZscan[ iRastPartIdx ];
+}
+
+Void TComPicYuv::setLumaTo( Pel pVal )
+{
+  xSetPels( getLumaAddr(), getStride(), getWidth(), getHeight(), pVal );
+}
+
+Void TComPicYuv::setChromaTo( Pel pVal )
+{
+  xSetPels( getCbAddr(), getCStride(), getWidth() >> 1, getHeight() >> 1, pVal ); 
+  xSetPels( getCrAddr(), getCStride(), getWidth() >> 1, getHeight() >> 1, pVal );
+}
+
+Void TComPicYuv::xSetPels( Pel* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal )
+{
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for (Int iXPos = 0; iXPos < iWidth; iXPos++)
+    {
+      piPelSource[iXPos] = iVal; 
+    }
+    piPelSource += iSourceStride; 
+  }
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuv.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuv.h	(revision 341)
@@ -0,0 +1,192 @@
+/* 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-2012, 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     TComPicYuv.h
+    \brief    picture YUV buffer class (header)
+*/
+
+#ifndef __TCOMPICYUV__
+#define __TCOMPICYUV__
+
+#include <stdio.h>
+#include "CommonDef.h"
+#include "TComRom.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture YUV buffer class
+class TComPicYuv
+{
+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;
+  
+  // ------------------------------------------------------------------------------------------------
+  //  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)
+  UInt  m_uiMaxCuDepth;         ///< maximum coding unit depth
+  Int   m_iBaseUnitWidth;       ///< Width of Base Unit (with maximum depth or minimum size, m_iCuWidth >> Max. Depth)
+  Int   m_iBaseUnitHeight;      ///< Height of Base Unit (with maximum depth or minimum size, m_iCuHeight >> Max. Depth)
+  Int   m_iNumCuInWidth;
+  
+  Int*  m_cuOffsetY;
+  Int*  m_cuOffsetC;
+  Int*  m_buOffsetY;
+  Int*  m_buOffsetC;
+  
+  Int   m_iLumaMarginX;
+  Int   m_iLumaMarginY;
+  Int   m_iChromaMarginX;
+  Int   m_iChromaMarginY;
+  
+  Bool  m_bIsBorderExtended;
+  
+protected:
+  Void  xExtendPicCompBorder (Pel* piTxt, Int iStride, Int iWidth, Int iHeight, Int iMarginX, Int iMarginY);
+  Void  xSetPels( Pel* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal );
+  
+public:
+  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 ();
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Get information of picture
+  // ------------------------------------------------------------------------------------------------
+  
+  Int   getWidth    ()     { return  m_iPicWidth;    }
+  Int   getHeight   ()     { return  m_iPicHeight;   }
+  
+  UInt  getMaxCuWidth ()   { return  (UInt)m_iCuWidth;   }
+  UInt  getMaxCuHeight()   { return  (UInt)m_iCuHeight;  }
+  UInt  getMaxCuDepth ()   { return  m_uiMaxCuDepth;     }
+
+  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;}
+  
+  Void  getLumaMinMax( Int* pMin, Int* pMax );
+  
+  // ------------------------------------------------------------------------------------------------
+  //  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;   }
+  
+  //  Access starting position of original picture
+  Pel*  getLumaAddr ()     { return  m_piPicOrgY;    }
+  Pel*  getCbAddr   ()     { return  m_piPicOrgU;    }
+  Pel*  getCrAddr   ()     { return  m_piPicOrgV;    }
+  
+  //  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]]; }
+  
+
+  // ------------------------------------------------------------------------------------------------
+  //  Miscellaneous
+  // ------------------------------------------------------------------------------------------------
+  
+  // sample to block and block to sample conversion
+  Void  getTopLeftSamplePos( Int iCuAddr, Int iAbsZorderIdx, Int& riX, Int& riY );
+  Void  getCUAddrAndPartIdx( Int iX, Int iY, Int& riCuAddr, Int& riAbsZorderIdx );
+
+
+  //  Copy function to picture
+  Void  copyToPic       ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicLuma   ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicCb     ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicCr     ( TComPicYuv*  pcPicYuvDst );
+  
+  //  Extend function of picture buffer
+  Void  extendPicBorder      ();
+  
+  //  Dump picture
+  Void  dump (char* pFileName, Bool bAdd = false);
+  
+  // Set border extension flag
+  Void  setBorderExtension(Bool b) { m_bIsBorderExtended = b; }
+#if FIXED_ROUNDING_FRAME_MEMORY
+  Void  xFixedRoundingPic();
+#endif  
+
+  // Set Function 
+  Void  setLumaTo    ( Pel pVal );  
+  Void  setChromaTo  ( Pel pVal );  
+
+};// END CLASS DEFINITION TComPicYuv
+
+void calcMD5(TComPicYuv& pic, unsigned char digest[16]);
+
+//! \}
+
+#endif // __TCOMPICYUV__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 341)
@@ -0,0 +1,117 @@
+/* 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-2012, 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 "TComPicYuv.h"
+#include "libmd5/MD5.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * Update md5 using n samples from plane, each sample is adjusted to
+ * OUTBIT_BITDEPTH_DIV8.
+ */
+template<unsigned OUTPUT_BITDEPTH_DIV8>
+static void md5_block(MD5& md5, const Pel* plane, unsigned n)
+{
+  /* create a 64 byte buffer for packing Pel's into */
+  unsigned char buf[64/OUTPUT_BITDEPTH_DIV8][OUTPUT_BITDEPTH_DIV8];
+  for (unsigned i = 0; i < n; i++)
+  {
+    Pel pel = plane[i];
+    /* perform bitdepth and endian conversion */
+    for (unsigned d = 0; d < OUTPUT_BITDEPTH_DIV8; d++)
+    {
+      buf[i][d] = pel >> (d*8);
+    }
+  }
+  md5.update((unsigned char*)buf, n * OUTPUT_BITDEPTH_DIV8);
+}
+
+/**
+ * Update md5 with all samples in plane in raster order, each sample
+ * is adjusted to OUTBIT_BITDEPTH_DIV8.
+ */
+template<unsigned OUTPUT_BITDEPTH_DIV8>
+static void md5_plane(MD5& md5, const Pel* plane, unsigned width, unsigned height, unsigned stride)
+{
+  /* N is the number of samples to process per md5 update.
+   * All N samples must fit in buf */
+  unsigned N = 32;
+  unsigned width_modN = width % N;
+  unsigned width_less_modN = width - width_modN;
+
+  for (unsigned y = 0; y < height; y++)
+  {
+    /* convert pel's into unsigned chars in little endian byte order.
+     * NB, for 8bit data, data is truncated to 8bits. */
+    for (unsigned 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 */
+    md5_block<OUTPUT_BITDEPTH_DIV8>(md5, &plane[y*stride + width_less_modN], width_modN);
+  }
+}
+
+/**
+ * Calculate the MD5sum of pic, storing the result in digest.
+ * MD5 calculation is performed on Y' then Cb, then Cr; each in raster order.
+ * Pel data is inserted into the MD5 function in little-endian byte order,
+ * using sufficient bytes to represent the picture bitdepth.  Eg, 10bit data
+ * uses little-endian two byte words; 8bit data uses single byte words.
+ */
+void calcMD5(TComPicYuv& pic, unsigned char digest[16])
+{
+  unsigned bitdepth = g_uiBitDepth + g_uiBitIncrement;
+  /* choose an md5_plane packing function based on the system bitdepth */
+  typedef void (*MD5PlaneFunc)(MD5&, const Pel*, unsigned, unsigned, unsigned);
+  MD5PlaneFunc md5_plane_func;
+  md5_plane_func = bitdepth <= 8 ? (MD5PlaneFunc)md5_plane<1> : (MD5PlaneFunc)md5_plane<2>;
+
+  MD5 md5;
+  unsigned width = pic.getWidth();
+  unsigned height = pic.getHeight();
+  unsigned stride = pic.getStride();
+
+  md5_plane_func(md5, pic.getLumaAddr(), width, height, stride);
+
+  width >>= 1;
+  height >>= 1;
+  stride >>= 1;
+
+  md5_plane_func(md5, pic.getCbAddr(), width, height, stride);
+  md5_plane_func(md5, pic.getCrAddr(), width, height, stride);
+
+  md5.finalize(digest);
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPrediction.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPrediction.cpp	(revision 341)
@@ -0,0 +1,3604 @@
+/* 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-2012, 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     TComPrediction.cpp
+    \brief    prediction class
+*/
+
+#include <memory.h>
+#include "TComPrediction.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialize
+// ====================================================================================================================
+
+#if LGE_EDGE_INTRA_A0070
+#define MAX_DISTANCE_EDGEINTRA 255
+#endif
+
+TComPrediction::TComPrediction()
+: m_pLumaRecBuffer(0)
+{
+  m_piYuvExt = NULL;
+#if MERL_VSP_C0152
+  m_pDepth = (Int*) malloc(64*64*sizeof(Int)); // TODO: Use a smart way to determine the size of the array
+  if (m_pDepth == NULL)
+  {
+      printf("ERROR: UKTGHU, No memory allocated.\n");
+  }
+#endif
+}
+
+TComPrediction::~TComPrediction()
+{
+  
+#if MERL_VSP_C0152
+  if (m_pDepth != NULL)
+  {
+      free(m_pDepth);
+  }
+#endif
+  delete[] m_piYuvExt;
+
+  m_acYuvPred[0].destroy();
+  m_acYuvPred[1].destroy();
+
+  m_cYuvPredTemp.destroy();
+
+  if( m_pLumaRecBuffer )
+  {
+    delete [] m_pLumaRecBuffer;
+  }
+  
+  Int i, j;
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 4; j++)
+    {
+      m_filteredBlock[i][j].destroy();
+    }
+    m_filteredBlockTmp[i].destroy();
+  }
+}
+
+Void TComPrediction::initTempBuff()
+{
+  if( m_piYuvExt == NULL )
+  {
+    Int extWidth  = g_uiMaxCUWidth + 16; 
+    Int extHeight = g_uiMaxCUHeight + 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  = ((g_uiMaxCUHeight + 2) << 4);
+    m_iYuvExtStride = ((g_uiMaxCUWidth  + 8) << 4);
+    m_piYuvExt = new Int[ m_iYuvExtStride * m_iYuvExtHeight ];
+
+    // new structure
+    m_acYuvPred[0] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+    m_acYuvPred[1] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+
+    m_cYuvPredTemp.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+  }
+
+  m_iLumaRecStride =  (g_uiMaxCUWidth>>1) + 1;
+  m_pLumaRecBuffer = new Pel[ m_iLumaRecStride * m_iLumaRecStride ];
+
+  for( Int i = 1; i < 64; i++ )
+  {
+    m_uiaShift[i-1] = ( (1 << 15) + i/2 ) / i;
+  }
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// 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 )
+{
+  Int iInd, iSum = 0;
+  Pel pDcVal;
+
+  if (bAbove)
+  {
+    for (iInd = 0;iInd < iWidth;iInd++)
+    {
+      iSum += pSrc[iInd-iSrcStride];
+    }
+  }
+  if (bLeft)
+  {
+    for (iInd = 0;iInd < iHeight;iInd++)
+    {
+      iSum += pSrc[iInd*iSrcStride-1];
+    }
+  }
+
+  if (bAbove && bLeft)
+  {
+    pDcVal = (iSum + iWidth) / (iWidth + iHeight);
+  }
+  else if (bAbove)
+  {
+    pDcVal = (iSum + iWidth/2) / iWidth;
+  }
+  else if (bLeft)
+  {
+    pDcVal = (iSum + iHeight/2) / iHeight;
+  }
+  else
+  {
+    pDcVal = pSrc[-1]; // Default DC value already calculated and placed in the prediction array if no neighbors are available
+  }
+  
+  return pDcVal;
+}
+
+// Function for deriving the angular Intra predictions
+
+/** 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
+ *
+ * This function derives the prediction samples for the angular mode based on the prediction direction indicated by
+ * the prediction mode index. The prediction direction is given by the displacement of the bottom row of the block and
+ * the reference row above the block in the case of vertical prediction or displacement of the rightmost column
+ * of the block and reference column left from the block in the case of the horizontal prediction. The displacement
+ * is signalled at 1/32 pixel accuracy. When projection of the predicted pixel falls inbetween reference samples,
+ * the predicted value for the pixel is linearly interpolated from the reference samples. All reference samples are taken
+ * from the extended main reference.
+ */
+Void TComPrediction::xPredIntraAng( 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;
+
+  // 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;
+
+  // 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
+  {
+    Pel* refMain;
+    Pel* refSide;
+    Pel  refAbove[2*MAX_CU_SIZE+1];
+    Pel  refLeft[2*MAX_CU_SIZE+1];
+
+    // Initialise the Main and Left reference array.
+    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);
+
+      // Extend the Main reference to the left.
+      Int invAngleSum    = 128;       // rounding for (shift by 8)
+      for (k=-1; k>blkSize*intraPredAngle>>5; k--)
+      {
+        invAngleSum += invAngle;
+        refMain[k] = refSide[invAngleSum>>8];
+      }
+    }
+    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++)
+        {
+          pDst[k*dstStride+l] = refMain[l+1];
+        }
+      }
+
+      if ( bFilter )
+      {
+        for (k=0;k<blkSize;k++)
+        {
+          pDst[k*dstStride] = Clip ( pDst[k*dstStride] + (( refSide[k+1] - refSide[0] ) >> 1) );
+        }
+      }
+    }
+    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);
+
+        if (deltaFract)
+        {
+          // Do linear filtering
+          for (l=0;l<blkSize;l++)
+          {
+            refMainIndex        = l+deltaInt+1;
+            pDst[k*dstStride+l] = (Pel) ( ((32-deltaFract)*refMain[refMainIndex]+deltaFract*refMain[refMainIndex+1]+16) >> 5 );
+          }
+        }
+        else
+        {
+          // Just copy the integer samples
+          for (l=0;l<blkSize;l++)
+          {
+            pDst[k*dstStride+l] = refMain[l+deltaInt+1];
+          }
+        }
+      }
+    }
+
+    // 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++)
+        {
+          tmp                 = pDst[k*dstStride+l];
+          pDst[k*dstStride+l] = pDst[l*dstStride+k];
+          pDst[l*dstStride+k] = tmp;
+        }
+      }
+    }
+  }
+}
+
+Void TComPrediction::predIntraLumaAng(TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight,  TComDataCU* pcCU, Bool bAbove, Bool bLeft )
+{
+  Pel *pDst = piPred;
+  Int *ptrSrc;
+
+  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 );
+
+  // 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 );
+  }
+  else
+  {
+    xPredIntraAng( 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( TComPattern* pcTComPattern, Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, TComDataCU* pcCU, 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( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, false );
+  }
+}
+
+/** Function for checking identical motion.
+ * \param TComDataCU* pcCU
+ * \param UInt PartAddr
+ */
+Bool TComPrediction::xCheckIdenticalMotion ( TComDataCU* pcCU, UInt PartAddr )
+{
+  if( pcCU->getSlice()->isInterB() && pcCU->getSlice()->getPPS()->getWPBiPredIdc() == 0 )
+  {
+    if( pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr) >= 0 && pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr) >= 0)
+    {
+      Int RefPOCL0    = pcCU->getSlice()->getRefPic(REF_PIC_LIST_0, pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr))->getPOC();
+      Int RefViewIdL0 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_0, pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr))->getViewId();
+      Int RefPOCL1    = pcCU->getSlice()->getRefPic(REF_PIC_LIST_1, pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr))->getPOC();
+      Int RefViewIdL1 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_1, pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr))->getViewId();
+      if(RefPOCL0 == RefPOCL1 && RefViewIdL0 == RefViewIdL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
+      {
+        return true;
+      }
+    }
+  }
+  return false;
+}
+
+#if LGE_EDGE_INTRA_A0070
+Void TComPrediction::predIntraLumaEdge ( TComDataCU* pcCU, TComPattern* pcTComPattern, UInt uiAbsPartIdx, Int iWidth, Int iHeight, Pel* piPred, UInt uiStride, Bool bDelta )
+{
+  Pel *piDst = piPred;
+  Int *piSrc;
+  Int iSrcStride = ( iWidth<<1 ) + 1;
+  Int iDstStride = uiStride;
+
+  piSrc = pcTComPattern->getPredictorPtr( 0, g_aucConvertToBit[ iWidth ] + 2, m_piYuvExt );
+
+  xPredIntraEdge ( pcCU, uiAbsPartIdx, iWidth, iHeight, piSrc, iSrcStride, piDst, iDstStride
+#if LGE_EDGE_INTRA_DELTA_DC
+    , bDelta
+#endif
+    );
+}
+
+Pel  TComPrediction::xGetNearestNeighbor( Int x, Int y, Int* pSrc, Int srcStride, Int iWidth, Int iHeight, Bool* bpRegion )
+{
+  Bool bLeft = (x < y) ? true : false;
+  Bool bFound = false;
+  Int  iFoundX = -1, iFoundY = -1;
+  Int  cResult = 0;
+
+  UChar* piTopDistance = new UChar[iWidth];
+  UChar* piLeftDistance = new UChar[iHeight];
+
+  for( Int i = 0; i < iWidth; i++ )
+  {
+    int Abs = x > i ? x - i : i - x;
+    piTopDistance[ i ] = y + Abs;
+
+    Abs = y > i ? y - i : i - y;
+    piLeftDistance[ i ] = x + Abs;
+  }
+
+  for( Int dist = 0; dist < MAX_DISTANCE_EDGEINTRA && !bFound; dist++ )
+  {
+    if( !bLeft )
+    {
+      for( Int i = 0; i < iWidth; i++ )
+      {
+        if( piTopDistance[ i ] == dist )
+        {
+          if( bpRegion[ i ] == bpRegion[ x + y * iWidth ] )
+          {
+            iFoundX = i;
+            iFoundY = 0;
+            bFound = true;
+          }
+        }
+      }
+      for( Int i = 0; i < iHeight; i++ )
+      {
+        if( piLeftDistance[ i ] == dist )
+        {
+          if( bpRegion[ i * iWidth ] == bpRegion[ x + y * iWidth ] )
+          {
+            iFoundX = 0;
+            iFoundY = i;
+            bFound = true;
+          }
+        }
+      }
+    }
+    else
+    {
+      for( Int i = 0; i < iHeight; i++ )
+      {
+        if( piLeftDistance[ i ] == dist )
+        {
+          if( bpRegion[ i * iWidth ] == bpRegion[ x + y * iWidth ] )
+          {
+            iFoundX = 0;
+            iFoundY = i;
+            bFound = true;
+          }
+        }
+      }
+      for( Int i = 0; i < iWidth; i++ )
+      {
+        if( piTopDistance[ i ] == dist )
+        {
+          if( bpRegion[ i ] == bpRegion[ x + y * iWidth ] )
+          {
+            iFoundX = i;
+            iFoundY = 0;
+            bFound = true;
+          }
+        }
+      }
+    }
+  }
+
+  if( iFoundY == 0 )
+  {
+    cResult = pSrc[ iFoundX + 1 ];
+  }
+  else // iFoundX == 0
+  {
+    cResult = pSrc[ (iFoundY + 1) * srcStride ];
+  }
+
+  delete[] piTopDistance;  piTopDistance = NULL;
+  delete[] piLeftDistance; piLeftDistance = NULL;
+
+  assert( bFound );
+
+  return cResult;
+}
+
+Void TComPrediction::xPredIntraEdge( TComDataCU* pcCU, UInt uiAbsPartIdx, Int iWidth, Int iHeight, Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, Bool bDelta )
+{
+  Pel* pDst = rpDst;
+  Bool* pbRegion = pcCU->getEdgePartition( uiAbsPartIdx );
+
+  // Do prediction
+  {
+    //UInt uiSum0 = 0, uiSum1 = 0;
+    Int iSum0 = 0, iSum1 = 0;
+    //UInt uiMean0, uiMean1;
+    Int iMean0, iMean1;
+    //UInt uiCount0 = 0, uiCount1 = 0;
+    Int iCount0 = 0, iCount1 = 0;
+    for( UInt ui = 0; ui < iWidth; ui++ )
+    {
+      if( pbRegion[ ui ] == false )
+      {
+        iSum0 += (pSrc[ ui + 1 ]);
+        iCount0++;
+      }
+      else
+      {
+        iSum1 += (pSrc[ ui + 1 ]);
+        iCount1++;
+      }
+    }
+    for( UInt ui = 0; ui < iHeight; ui++ ) // (0,0) recount (to avoid division)
+    {
+      if( pbRegion[ ui * iWidth ] == false )
+      {
+        iSum0 += (pSrc[ (ui + 1) * srcStride ]);
+        iCount0++;
+      }
+      else
+      {
+        iSum1 += (pSrc[ (ui + 1) * srcStride ]);
+        iCount1++;
+      }
+    }
+    if( iCount0 == 0 )
+      assert(false);
+    if( iCount1 == 0 )
+      assert(false);
+    iMean0 = iSum0 / iCount0; // TODO : integer op.
+    iMean1 = iSum1 / iCount1;
+#if LGE_EDGE_INTRA_DELTA_DC
+    if( bDelta ) 
+    {
+      Int iDeltaDC0 = pcCU->getEdgeDeltaDC0( uiAbsPartIdx );
+      Int iDeltaDC1 = pcCU->getEdgeDeltaDC1( uiAbsPartIdx );
+      xDeltaDCQuantScaleUp( pcCU, iDeltaDC0 );
+      xDeltaDCQuantScaleUp( pcCU, iDeltaDC1 );
+      iMean0 = Clip( iMean0 + iDeltaDC0 );
+      iMean1 = Clip( iMean1 + iDeltaDC1 );
+    }
+#endif
+    for( UInt ui = 0; ui < iHeight; ui++ )
+    {
+      for( UInt uii = 0; uii < iWidth; uii++ )
+      {
+        if( pbRegion[ uii + ui * iWidth ] == false )
+          pDst[ uii + ui * dstStride ] = iMean0;
+        else
+          pDst[ uii + ui * dstStride ] = iMean1;
+      }
+    }
+  }
+}
+#endif
+
+#if DEPTH_MAP_GENERATION
+#if MERL_VSP_C0152 
+Void TComPrediction::motionCompensation( TComDataCU* pcCU, TComYuv* pcYuvPred, UInt uiAbsPartIdx, RefPicList eRefPicList, Int iPartIdx, Bool bPrdDepthMap, UInt uiSubSampExpX, UInt uiSubSampExpY )
+#else
+Void TComPrediction::motionCompensation( TComDataCU* pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList, Int iPartIdx, Bool bPrdDepthMap, UInt uiSubSampExpX, UInt uiSubSampExpY )
+#endif
+#else
+#if MERL_VSP_C0152
+Void TComPrediction::motionCompensation ( TComDataCU* pcCU, TComYuv* pcYuvPred, UInt uiAbsPartIdx, RefPicList eRefPicList, Int iPartIdx )
+#else
+Void TComPrediction::motionCompensation ( TComDataCU* pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList, Int iPartIdx )
+#endif
+#endif
+{
+  Int         iWidth;
+  Int         iHeight;
+  UInt        uiPartAddr;
+
+  if ( iPartIdx >= 0 )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+
+#if DEPTH_MAP_GENERATION
+    if( bPrdDepthMap )
+    {
+      iWidth  >>= uiSubSampExpX;
+      iHeight >>= uiSubSampExpY;
+    }
+#endif
+
+    if ( eRefPicList != REF_PIC_LIST_X )
+    {
+#if LGE_ILLUCOMP_B0045
+      if( pcCU->getSlice()->getPPS()->getUseWP() && !pcCU->getICFlag(uiPartAddr))
+#else
+      if( pcCU->getSlice()->getPPS()->getUseWP())
+#endif
+      {
+#if MERL_VSP_C0152
+        xPredInterUni (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, true );
+#else
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, true );
+#endif
+      }
+      else
+      {
+#if MERL_VSP_C0152
+        xPredInterUni (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#else        
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#endif
+      }
+#if LGE_ILLUCOMP_B0045
+      if( pcCU->getSlice()->getPPS()->getUseWP() && !pcCU->getICFlag(uiPartAddr) )
+#else
+      if ( pcCU->getSlice()->getPPS()->getUseWP() )
+#endif
+      {
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx );
+      }
+    }
+    else
+    {
+      if( xCheckIdenticalMotion( pcCU, uiPartAddr ) && !bPrdDepthMap )
+      {
+#if MERL_VSP_C0152
+        xPredInterUni (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#else
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#endif
+      }
+      else
+      {
+#if MERL_VSP_C0152
+        xPredInterBi  (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY, pcYuvPred, iPartIdx, bPrdDepthMap );
+#else
+        xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY, pcYuvPred, iPartIdx, bPrdDepthMap );
+#endif
+      }
+    }
+    return;
+  }
+
+  for ( iPartIdx = 0; iPartIdx < pcCU->getNumPartInter(); iPartIdx++ )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+
+    if( bPrdDepthMap )
+    {
+      iWidth  >>= uiSubSampExpX;
+      iHeight >>= uiSubSampExpY;
+    }
+
+    if ( eRefPicList != REF_PIC_LIST_X )
+    {
+#if LGE_ILLUCOMP_B0045
+      if( pcCU->getSlice()->getPPS()->getUseWP() && !pcCU->getICFlag(uiPartAddr))
+#else
+      if( pcCU->getSlice()->getPPS()->getUseWP())
+#endif
+      {
+#if MERL_VSP_C0152
+        xPredInterUni (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, true );
+#else
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, true );
+#endif 
+  }
+  else
+  {
+#if MERL_VSP_C0152
+        xPredInterUni (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#else
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#endif
+      }
+#if MERL_VSP_C0152
+      xPredInterUni (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#else
+      xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#endif
+
+#if LGE_ILLUCOMP_B0045
+      if( pcCU->getSlice()->getPPS()->getUseWP() && !pcCU->getICFlag(uiPartAddr))
+#else
+      if( pcCU->getSlice()->getPPS()->getUseWP())
+#endif
+      {
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx );
+      }
+    }
+    else
+    {
+      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+      {
+#if MERL_VSP_C0152
+        xPredInterUni (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#else
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#endif
+      }
+      else
+      {
+#if MERL_VSP_C0152
+        xPredInterBi  (pcCU, uiPartAddr, uiAbsPartIdx+uiPartAddr, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY, pcYuvPred, iPartIdx, bPrdDepthMap );
+#else
+        xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY, pcYuvPred, iPartIdx, bPrdDepthMap );
+#endif   
+      }
+    }
+  }
+  return;
+}
+
+#if H3D_IVRP
+Void TComPrediction::residualPrediction(TComDataCU* pcCU, TComYuv* pcYuvPred, TComYuv* pcYuvResPred)
+{
+  Int         iWidth;
+  Int         iHeight;
+  UInt        uiPartAddr;
+
+  pcCU->getPartIndexAndSize( 0, uiPartAddr, iWidth, iHeight );
+
+  Bool bResAvail = false;
+
+  bResAvail = pcCU->getResidualSamples( 0, true, pcYuvResPred );
+
+  assert (bResAvail);
+
+  pcYuvPred->add(pcYuvResPred, iWidth, iHeight);
+}
+#endif
+
+#if MERL_VSP_C0152
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, UInt uiAbsPartIdx, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap, UInt uiSubSampExpX, UInt uiSubSampExpY, Bool bi )
+#else
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap, UInt uiSubSampExpX, UInt uiSubSampExpY, Bool bi )
+#endif
+{
+#if MERL_VSP_C0152
+  Int  iRefIdx = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );    
+  Int  vspIdx  = pcCU->getVSPIndex(uiPartAddr);
+  if (vspIdx != 0)
+  {
+    if (iRefIdx >= 0)
+    {
+      printf("vspIdx = %d, iRefIdx = %d\n", vspIdx, iRefIdx);
+    }
+    assert (iRefIdx < 0); // assert (iRefIdx == NOT_VALID);
+  }
+  else
+  {
+    assert (iRefIdx >= 0);
+  }
+#else
+  Int         iRefIdx     = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           assert (iRefIdx >= 0);
+#endif
+
+  TComMv cMv = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
+  pcCU->clipMv(cMv);
+
+#if DEPTH_MAP_GENERATION
+  if( bPrdDepthMap )
+  {
+    UInt uiRShift = 0;
+    if( pcCU->getPic()->getStoredPDMforV2() == 1 )
+      xPredInterPrdDepthMap( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPredDepthMapTemp(), uiPartAddr, &cMv, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY, rpcYuvPred, uiRShift, 0 );
+    else
+      xPredInterPrdDepthMap( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPredDepthMap(), uiPartAddr, &cMv, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY, rpcYuvPred, uiRShift, 0 );
+
+    return;
+  }
+#endif
+
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getSPS()->isDepth() )
+  {
+#if MERL_VSP_C0152
+    if (vspIdx != 0)
+    { // depth, vsp
+      // get depth estimator here
+      TComPic* pRefPicBaseDepth = pcCU->getSlice()->getRefPicBaseDepth();
+      TComPicYuv* pcBaseViewDepthPicYuv = NULL;
+      if (vspIdx < 4) // spatial
+      {
+        pcBaseViewDepthPicYuv = pRefPicBaseDepth->getPicYuvRec();
+      }
+      Int iBlkX = ( pcCU->getAddr() % pRefPicBaseDepth->getFrameWidthInCU() ) * g_uiMaxCUWidth  + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+      Int iBlkY = ( pcCU->getAddr() / pRefPicBaseDepth->getFrameWidthInCU() ) * g_uiMaxCUHeight + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+      Int* pShiftLUT;
+      Int iShiftPrec;
+      pcCU->getSlice()->getBWVSPLUTParam(pShiftLUT, iShiftPrec);
+      //using disparity to find the depth block of the base view as the depth block estimator of the current block
+      //using depth block estimator and base view texture to get Backward warping
+      xPredInterLumaBlkFromDM  ( pcBaseViewDepthPicYuv, pcBaseViewDepthPicYuv, pShiftLUT, iShiftPrec, &cMv, uiPartAddr, iBlkX,    iBlkY,    iWidth,    iHeight,     pcCU->getSlice()->getSPS()->isDepth(), vspIdx, rpcYuvPred );
+      xPredInterChromaBlkFromDM( pcBaseViewDepthPicYuv, pcBaseViewDepthPicYuv, pShiftLUT, iShiftPrec, &cMv, uiPartAddr, iBlkX>>1, iBlkY>>1, iWidth>>1, iHeight>>1,  pcCU->getSlice()->getSPS()->isDepth(), vspIdx, rpcYuvPred );
+    }
+    else
+    {
+#endif
+      UInt uiRShift = ( bi ? 14-g_uiBitDepth-g_uiBitIncrement : 0 );
+      UInt uiOffset = bi ? IF_INTERNAL_OFFS : 0;
+#if LGE_ILLUCOMP_DEPTH_C0046
+    Bool bICFlag = pcCU->getICFlag(uiPartAddr) && (pcCU->getSlice()->getRefViewId( eRefPicList, iRefIdx ) != pcCU->getSlice()->getViewId());
+#endif
+#if DEPTH_MAP_GENERATION
+    xPredInterPrdDepthMap( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, 0, 0, rpcYuvPred, uiRShift, uiOffset 
+#if LGE_ILLUCOMP_DEPTH_C0046
+        , bICFlag
+#endif
+        );
+#else
+      xPredInterPrdDepthMap( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, uiRShift, uiOffset );
+#endif
+#if MERL_VSP_C0152
+    }
+#endif// MERL_VSP_C0152 //else
+  }
+  else
+  {
+#endif
+#if MERL_VSP_C0152
+    if ( vspIdx != 0 )
+    { // texture, vsp
+      TComPic*    pRefPicBaseTxt        = pcCU->getSlice()->getRefPicBaseTxt();
+      TComPicYuv* pcBaseViewTxtPicYuv   = pRefPicBaseTxt->getPicYuvRec();
+      TComPicYuv* pcBaseViewDepthPicYuv = NULL;
+      if (vspIdx < 4) // spatial
+      {
+        TComPic* pRefPicBaseDepth = pcCU->getSlice()->getRefPicBaseDepth();
+        pcBaseViewDepthPicYuv     = pRefPicBaseDepth->getPicYuvRec();
+      }
+      Int iBlkX = ( pcCU->getAddr() % pRefPicBaseTxt->getFrameWidthInCU() ) * g_uiMaxCUWidth  + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+      Int iBlkY = ( pcCU->getAddr() / pRefPicBaseTxt->getFrameWidthInCU() ) * g_uiMaxCUHeight + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+      Int* pShiftLUT;
+      Int iShiftPrec;
+      pcCU->getSlice()->getBWVSPLUTParam(pShiftLUT, iShiftPrec);
+
+      //using disparity to find the depth block of the base view as the depth block estimator of the current block
+      //using depth block estimator and base view texture to get Backward warping
+      xPredInterLumaBlkFromDM  ( pcBaseViewTxtPicYuv, pcBaseViewDepthPicYuv, pShiftLUT, iShiftPrec, &cMv, uiPartAddr, iBlkX,    iBlkY,    iWidth,    iHeight,    pcCU->getSlice()->getSPS()->isDepth(), vspIdx, rpcYuvPred );
+      xPredInterChromaBlkFromDM( pcBaseViewTxtPicYuv, pcBaseViewDepthPicYuv, pShiftLUT, iShiftPrec, &cMv, uiPartAddr, iBlkX>>1, iBlkY>>1, iWidth>>1, iHeight>>1, pcCU->getSlice()->getSPS()->isDepth(), vspIdx, rpcYuvPred );
+    }
+    else//texture not VSP
+    {
+#endif //MERL_VSP_C0152
+#if LGE_ILLUCOMP_B0045
+      Bool bICFlag = pcCU->getICFlag(uiPartAddr) && (pcCU->getSlice()->getRefViewId( eRefPicList, iRefIdx ) != pcCU->getSlice()->getViewId());
+
+      xPredInterLumaBlk  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi, bICFlag);
+#else
+      xPredInterLumaBlk  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
+#endif
+#if MERL_VSP_C0152
+     } //texture not VSP
+#endif 
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  }
+#endif
+
+#if MERL_VSP_C0152
+  if ( vspIdx == 0 )//Not VSP
+  {
+#endif
+#if LGE_ILLUCOMP_B0045
+  Bool bICFlag = pcCU->getICFlag(uiPartAddr) && (pcCU->getSlice()->getRefViewId( eRefPicList, iRefIdx ) != pcCU->getSlice()->getViewId());
+
+  xPredInterChromaBlk( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi, bICFlag );
+#else
+  xPredInterChromaBlk( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
+#endif
+#if MERL_VSP_C0152
+   }
+#endif
+}
+
+
+#if MERL_VSP_C0152
+Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, UInt uiAbsPartIdx, Int iWidth, Int iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap )
+#else
+Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap )
+#endif
+{
+  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 MERL_VSP_C0152
+    if(!pcCU->getVSPIndex(uiPartAddr))
+    {
+      if ( iRefIdx[iRefList] < 0 )
+      {
+        continue;
+      }
+    }
+    else
+    {
+      if ( iRefList== REF_PIC_LIST_1 && iRefIdx[iRefList] < 0 ) // iRefIdx[iRefList] ==NOT_VALID
+      {
+        continue;
+      }
+    }
+#else
+    if ( iRefIdx[iRefList] < 0 )
+    {
+      continue;
+    }
+#endif
+
+    assert( iRefIdx[iRefList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );
+
+    pcMbYuv = &m_acYuvPred[iRefList];
+    if( pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiPartAddr ) >= 0 && pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiPartAddr ) >= 0 )
+    {
+#if MERL_VSP_C0152
+      xPredInterUni ( pcCU, uiPartAddr, uiAbsPartIdx, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, true );
+#else
+      xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, true );
+#endif
+    }
+    else
+    {
+#if FIX_LGE_WP_FOR_3D_C0223
+      if ( ( pcCU->getSlice()->getPPS()->getUseWP()      && pcCU->getSlice()->getSliceType() == P_SLICE ) || 
+         ( pcCU->getSlice()->getPPS()->getWPBiPredIdc() && pcCU->getSlice()->getSliceType() == B_SLICE ) )
+#else
+      if ( pcCU->getSlice()->getPPS()->getWPBiPredIdc() )
+#endif
+      {
+#if MERL_VSP_C0152
+        xPredInterUni ( pcCU, uiPartAddr, uiAbsPartIdx, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, true );
+#else
+        xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, true );
+#endif
+      }
+      else
+      {
+#if MERL_VSP_C0152
+        xPredInterUni ( pcCU, uiPartAddr, uiAbsPartIdx, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#else
+        xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap, uiSubSampExpX, uiSubSampExpY, false );
+#endif
+      }
+    }
+  }
+#if FIX_LGE_WP_FOR_3D_C0223
+  if ( pcCU->getSlice()->getPPS()->getWPBiPredIdc() && pcCU->getSlice()->getSliceType() == B_SLICE  )
+#else
+  if ( pcCU->getSlice()->getPPS()->getWPBiPredIdc() )
+#endif
+  {
+#if MERL_VSP_C0152
+    if(pcCU->getVSPIndex(uiPartAddr))
+      m_acYuvPred[0].copyPartToPartYuv( rpcYuvPred, uiPartAddr, iWidth, iHeight );
+    else
+#endif
+    xWeightedPredictionBi( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+  }
+#if FIX_LGE_WP_FOR_3D_C0223
+  else if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType() == P_SLICE )
+
+  {
+#if MERL_VSP_C0152
+    if(pcCU->getVSPIndex(uiPartAddr))
+      m_acYuvPred[0].copyPartToPartYuv( rpcYuvPred, uiPartAddr, iWidth, iHeight );
+    else
+#endif
+      xWeightedPredictionUni( pcCU, &m_acYuvPred[0], uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, rpcYuvPred, iPartIdx ); 
+  }
+#endif
+  else
+  {
+    if ( bPrdDepthMap )
+    {
+      xWeightedAveragePdm( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred, uiSubSampExpX, uiSubSampExpY );
+    }
+    else
+    {
+#if MERL_VSP_C0152
+      if(pcCU->getVSPIndex(uiPartAddr))
+        m_acYuvPred[0].copyPartToPartYuv( rpcYuvPred, uiPartAddr, iWidth, iHeight );
+      else
+#endif
+      xWeightedAverage( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+    }
+  }
+}
+
+
+
+Void 
+TComPrediction::xPredInterPrdDepthMap( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY, TComYuv*& rpcYuv, UInt uiRShift, UInt uiOffset 
+#if LGE_ILLUCOMP_DEPTH_C0046
+, Bool bICFlag
+#endif
+)
+{
+  Int     iShiftX     = 2 + uiSubSampExpX;
+  Int     iShiftY     = 2 + uiSubSampExpY;
+  Int     iAddX       = ( 1 << iShiftX ) >> 1;
+  Int     iAddY       = ( 1 << iShiftY ) >> 1;
+  Int     iHor        = ( pcMv->getHor() + iAddX ) >> iShiftX;
+  Int     iVer        = ( pcMv->getVer() + iAddY ) >> iShiftY;
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getSPS()->isDepth() )
+  {
+    iHor = pcMv->getHor();
+    iVer = pcMv->getVer();
+  }
+#endif
+  Int     iRefStride  = pcPicYuvRef->getStride();
+  Int     iDstStride  = rpcYuv->getStride();
+  Int     iRefOffset  = iHor + iVer * iRefStride;
+
+  Pel*    piRefY      = pcPicYuvRef->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+  Pel*    piDstY      = rpcYuv->getLumaAddr( uiPartAddr );
+
+  for( Int y = 0; y < iHeight; y++, piDstY += iDstStride, piRefY += iRefStride )
+  {
+    for( Int x = 0; x < iWidth; x++ )
+    {
+      piDstY[ x ] = ( piRefY[ x ] << uiRShift ) - uiOffset;
+    }
+  }
+
+#if LGE_ILLUCOMP_DEPTH_C0046
+  if(bICFlag)
+  {
+    Int a, b, iShift;
+    TComMv tTmpMV(pcMv->getHor()<<2, pcMv->getVer()<<2);
+
+    piRefY      = pcPicYuvRef->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+    piDstY      = rpcYuv->getLumaAddr( uiPartAddr );
+
+    xGetLLSICPrediction(pcCU, &tTmpMV, pcPicYuvRef, a, b, iShift);
+
+    for( Int y = 0; y < iHeight; y++, piDstY += iDstStride, piRefY += iRefStride )
+    {
+      for( Int x = 0; x < iWidth; x++ )
+      {
+        if(uiOffset)
+        {
+          Int iIFshift = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+          piDstY[ x ] = ( (a*piDstY[ x ]+a*IF_INTERNAL_OFFS) >> iShift ) + b*(1<<iIFshift) - IF_INTERNAL_OFFS;
+        }
+        else
+          piDstY[ x ] = Clip( ( (a*piDstY[ x ]) >> iShift ) + b );
+      }
+    }
+  }
+#endif
+}
+
+
+/**
+ * \brief Generate motion-compensated luma 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
+ */
+#if LGE_ILLUCOMP_B0045
+Void TComPrediction::xPredInterLumaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi, Bool bICFlag)
+#else
+Void TComPrediction::xPredInterLumaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi )
+#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;
+
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  assert( ! cu->getSlice()->getIsDepth() || ( xFrac == 0 && yFrac == 0 ) );
+#endif
+
+  if ( yFrac == 0 )
+  {
+    m_if.filterHorLuma( ref, refStride, dst, dstStride, width, height, xFrac,       !bi );
+  }
+  else if ( xFrac == 0 )
+  {
+    m_if.filterVerLuma( ref, refStride, dst, dstStride, width, height, yFrac, true, !bi );
+  }
+  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     );
+    m_if.filterVerLuma(tmp + (halfFilterSize-1)*tmpStride, tmpStride, dst, dstStride, width, height,              yFrac, false, !bi);    
+  }
+
+#if LGE_ILLUCOMP_B0045
+  if(bICFlag)
+  {
+    Int a, b, iShift, i, j;
+
+    xGetLLSICPrediction(cu, mv, refPic, a, b, iShift);
+
+    for (i = 0; i < height; i++)
+    {
+      for (j = 0; j < width; j++)
+      {
+        if(bi)
+        {
+          Int iIFshift = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+          dst[j] = ( (a*dst[j]+a*IF_INTERNAL_OFFS) >> iShift ) + b*(1<<iIFshift) - IF_INTERNAL_OFFS;
+        }
+        else
+          dst[j] = Clip( ( (a*dst[j]) >> iShift ) + b );
+      }
+      dst += dstStride;
+    }
+  }
+#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
+ */
+#if LGE_ILLUCOMP_B0045
+Void TComPrediction::xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi, Bool bICFlag )
+#else
+Void TComPrediction::xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi )
+#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 )
+  {
+    m_if.filterHorChroma(refCb, refStride, dstCb,  dstStride, cxWidth, cxHeight, xFrac, !bi);    
+    m_if.filterHorChroma(refCr, refStride, dstCr,  dstStride, cxWidth, cxHeight, xFrac, !bi);    
+  }
+  else if ( xFrac == 0 )
+  {
+    m_if.filterVerChroma(refCb, refStride, dstCb, dstStride, cxWidth, cxHeight, yFrac, true, !bi);    
+    m_if.filterVerChroma(refCr, refStride, dstCr, dstStride, cxWidth, cxHeight, yFrac, true, !bi);    
+  }
+  else
+  {
+    m_if.filterHorChroma(refCb - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false);
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCb, dstStride, cxWidth, cxHeight  , yFrac, false, !bi);
+    
+    m_if.filterHorChroma(refCr - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false);
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCr, dstStride, cxWidth, cxHeight  , yFrac, false, !bi);    
+  }
+#if LGE_ILLUCOMP_B0045
+  if(bICFlag)
+  {
+    Int a, b, iShift, i, j;
+    xGetLLSICPredictionChroma(cu, mv, refPic, a, b, iShift, 0); // Cb
+    for (i = 0; i < cxHeight; i++)
+    {
+      for (j = 0; j < cxWidth; j++)
+      {
+        if(bi)
+        {
+          Int iIFshift = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+          dstCb[j] = ( (a*dstCb[j]+a*IF_INTERNAL_OFFS) >> iShift ) + b*(1<<iIFshift) - IF_INTERNAL_OFFS;
+        }
+        else
+          dstCb[j] = Clip3(0, 255, ((a*dstCb[j])>>iShift)+b);
+      }
+      dstCb += dstStride;
+    }
+
+    xGetLLSICPredictionChroma(cu, mv, refPic, a, b, iShift, 1); // Cr
+    for (i = 0; i < cxHeight; i++)
+    {
+      for (j = 0; j < cxWidth; j++)
+      {
+        if(bi)
+        {
+          Int iIFshift = IF_INTERNAL_PREC - ( g_uiBitDepth + g_uiBitIncrement );
+          dstCr[j] = ( (a*dstCr[j]+a*IF_INTERNAL_OFFS) >> iShift ) + b*(1<<iIFshift) - IF_INTERNAL_OFFS;
+        }
+        else
+          dstCr[j] = Clip3(0, 255, ((a*dstCr[j])>>iShift)+b);
+      }
+      dstCr += dstStride;
+    }
+  }
+#endif
+}
+
+#if MERL_VSP_C0152
+// Input:
+// refPic: Ref picture. Full picture, with padding
+// posX, posY:     PU position, texture
+// size_x, size_y: PU size
+// partAddr: z-order index
+// mv: disparity vector. derived from neighboring blocks
+//
+// Output: dstPic, PU predictor 64x64
+Void TComPrediction::xPredInterLumaBlkFromDM( TComPicYuv *refPic, TComPicYuv *pPicBaseDepth, Int* pShiftLUT, Int iShiftPrec, TComMv* mv, UInt partAddr,Int posX, Int posY, Int size_x, Int size_y, Bool isDepth, Int vspIdx
+                                            , TComYuv *&dstPic )
+{
+  Int widthLuma;
+  Int heightLuma;
+
+  if (isDepth)
+  {
+    widthLuma   =  pPicBaseDepth->getWidth();
+    heightLuma  =  pPicBaseDepth->getHeight();
+  }
+  else
+  {
+    widthLuma   =  refPic->getWidth();
+    heightLuma  =  refPic->getHeight();
+  }
+
+#if MERL_VSP_BLOCKSIZE_C0152 != 1
+  Int widthDepth  = pPicBaseDepth->getWidth();
+  Int heightDepth = pPicBaseDepth->getHeight();
+#endif
+
+  Int nTxtPerDepthX = widthLuma  / ( pPicBaseDepth->getWidth() );  // texture pixel # per depth pixel
+  Int nTxtPerDepthY = heightLuma / ( pPicBaseDepth->getHeight() );
+
+  Int refStride = refPic->getStride();
+  Int dstStride = dstPic->getStride();
+  Int depStride =  pPicBaseDepth->getStride();
+  Int depthPosX = Clip3(0,   widthLuma - size_x,  (posX/nTxtPerDepthX) + (mv->getHor()>>2));
+  Int depthPosY = Clip3(0,   heightLuma- size_y,  (posY/nTxtPerDepthY) + (mv->getVer()>>2));
+  Pel *ref    = refPic->getLumaAddr() + posX + posY * refStride;
+  Pel *dst    = dstPic->getLumaAddr(partAddr);
+  Pel *depth  = pPicBaseDepth->getLumaAddr() + depthPosX + depthPosY * depStride;
+
+#if MERL_VSP_BLOCKSIZE_C0152 != 1
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+  Int  dW = size_x>>1;
+  Int  dH = size_y>>1;
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 4
+  Int  dW = size_x>>2;
+  Int  dH = size_y>>2;
+#endif
+  {
+    Pel* depthi = depth;
+    for (Int j = 0; j < dH; j++)
+    {
+      for (Int i = 0; i < dW; i++)
+      {
+        Pel* depthTmp;
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+        if (depthPosX + (i<<1) < widthDepth)
+          depthTmp = depthi + (i << 1);
+        else
+          depthTmp = depthi + (widthDepth - depthPosX - 1);
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 4
+        if (depthPosX + (i<<2) < widthDepth)
+          depthTmp = depthi + (i << 2);
+        else
+          depthTmp = depthi + (widthDepth - depthPosX - 1);
+#endif
+        Int maxV = 0;
+        for (Int blockj = 0; blockj < MERL_VSP_BLOCKSIZE_C0152; blockj++)
+        {
+          Int iX = 0;
+          for (Int blocki = 0; blocki < MERL_VSP_BLOCKSIZE_C0152; blocki++)
+          {
+            if (maxV < depthTmp[iX])
+              maxV = depthTmp[iX];
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+            if (depthPosX + (i<<1) + blocki < widthDepth - 1)
+#else // MERL_VSP_BLOCKSIZE_C0152 == 4
+            if (depthPosX + (i<<2) + blocki < widthDepth - 1)
+#endif
+              iX++;
+          }
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+          if (depthPosY + (j<<1) + blockj < heightDepth - 1)
+#else // MERL_VSP_BLOCKSIZE_C0152 == 4
+          if (depthPosY + (j<<2) + blockj < heightDepth - 1)
+#endif
+            depthTmp += depStride;
+        }
+        m_pDepth[i+j*dW] = maxV;
+      } // end of i < dW
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+      if (depthPosY + ((j+1)<<1) < heightDepth)
+        depthi += (depStride << 1);
+      else
+        depthi  = depth + (heightDepth-depthPosY-1)*depStride;
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 4
+      if (depthPosY + ((j+1)<<2) < heightDepth) // heightDepth-1
+        depthi += (depStride << 2);
+      else
+        depthi  = depth + (heightDepth-depthPosY-1)*depStride; // the last line
+#endif
+    }
+  }
+#endif
+  
+#if MERL_VSP_BLOCKSIZE_C0152 != 1
+  Int yDepth = 0;
+#endif
+  for ( Int yTxt = 0; yTxt < size_y; yTxt += nTxtPerDepthY )
+  {
+    for ( Int xTxt = 0, xDepth = 0; xTxt < size_x; xTxt += nTxtPerDepthX, xDepth++ )
+    {
+      Pel rep_depth = 0; // to store the depth value used for warping
+#if MERL_VSP_BLOCKSIZE_C0152 == 1
+      rep_depth = depth[xDepth];
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+      rep_depth = m_pDepth[(xTxt>>1) + (yTxt>>1)*dW];
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 4
+      rep_depth = m_pDepth[(xTxt>>2) + (yTxt>>2)*dW];
+#endif
+
+      assert( rep_depth >= 0 && rep_depth <= 255 );
+      Int disparity = pShiftLUT[ rep_depth ] << iShiftPrec;
+      Int refOffset = xTxt + (disparity >> 2);
+      Int xFrac = disparity & 0x3;
+      Int absX  = posX + refOffset;
+
+      if (xFrac == 0)
+        absX = Clip3(0, widthLuma-1, absX);
+      else
+        absX = Clip3(4, widthLuma-5, absX);
+
+      refOffset = absX - posX;
+
+      assert( ref[refOffset] >= 0 && ref[refOffset]<= 255 );
+      m_if.filterHorLuma( &ref[refOffset], refStride, &dst[xTxt], dstStride, nTxtPerDepthX, nTxtPerDepthY, xFrac, true );
+    }
+    ref   += refStride*nTxtPerDepthY;
+    dst   += dstStride*nTxtPerDepthY;
+    depth += depStride;
+#if MERL_VSP_BLOCKSIZE_C0152 != 1
+    yDepth++;
+#endif
+  }
+}
+
+Void TComPrediction::xPredInterChromaBlkFromDM ( TComPicYuv *refPic, TComPicYuv *pPicBaseDepth, Int* pShiftLUT, Int iShiftPrec, TComMv*mv, UInt partAddr, Int posX, Int posY, Int size_x, Int size_y, Bool isDepth, Int vspIdx
+                                               , TComYuv *&dstPic )
+{
+  Int refStride = refPic->getCStride();
+  Int dstStride = dstPic->getCStride();
+  Int depStride = pPicBaseDepth->getStride();
+
+  Int widthChroma, heightChroma;
+  if( isDepth)
+  {
+     widthChroma   = pPicBaseDepth->getWidth()>>1;
+     heightChroma  = pPicBaseDepth->getHeight()>>1;
+  }
+  else
+  {
+     widthChroma   = refPic->getWidth()>>1;
+     heightChroma  = refPic->getHeight()>>1;
+  }
+
+  // Below is only for Texture chroma component
+
+  Int widthDepth  = pPicBaseDepth->getWidth();
+  Int heightDepth = pPicBaseDepth->getHeight();
+
+  Int nTxtPerDepthX, nTxtPerDepthY;  // Number of texture samples per one depth sample
+  Int nDepthPerTxtX, nDepthPerTxtY;  // Number of depth samples per one texture sample
+
+  Int depthPosX;  // Starting position in depth image
+  Int depthPosY;
+
+  if ( widthChroma > widthDepth )
+  {
+    nTxtPerDepthX = widthChroma / widthDepth;
+    nDepthPerTxtX = 1;
+    depthPosX = posX / nTxtPerDepthX + (mv->getHor()>>2);        //mv denotes the disparity for VSP
+  }
+  else
+  {
+    nTxtPerDepthX = 1;
+    nDepthPerTxtX = widthDepth / widthChroma;
+    depthPosX = posX * nDepthPerTxtX + (mv->getHor()>>2);        //mv denotes the disparity for VSP
+  }
+  depthPosX = Clip3(0, widthDepth - (size_x<<1), depthPosX);
+  if ( heightChroma > heightDepth )
+  {
+    nTxtPerDepthY = heightChroma / heightDepth;
+    nDepthPerTxtY = 1;
+    depthPosY = posY / nTxtPerDepthY + (mv->getVer()>>2);     //mv denotes the disparity for VSP
+  }
+  else
+  {
+    nTxtPerDepthY = 1;
+    nDepthPerTxtY = heightDepth / heightChroma;
+    depthPosY = posY * nDepthPerTxtY + (mv->getVer()>>2);     //mv denotes the disparity for VSP
+  }
+  depthPosY = Clip3(0, heightDepth - (size_y<<1), depthPosY);
+
+  Pel *refCb  = refPic->getCbAddr() + posX + posY * refStride;
+  Pel *refCr  = refPic->getCrAddr() + posX + posY * refStride;
+  Pel *dstCb  = dstPic->getCbAddr(partAddr);
+  Pel *dstCr  = dstPic->getCrAddr(partAddr);
+  Pel *depth  = pPicBaseDepth->getLumaAddr() + depthPosX + depthPosY * depStride;  // move the pointer to the current depth pixel position
+  
+  Int refStrideBlock = refStride * nTxtPerDepthY;
+  Int dstStrideBlock = dstStride * nTxtPerDepthY;
+  Int depStrideBlock = depStride * nDepthPerTxtY;
+
+  if (isDepth)
+  {
+     // DT: Since the call for this function is redundant, ..
+     for (Int y = 0; y < size_y; y++)
+     {
+       for (Int x = 0; x < size_x; x++)
+       {
+         dstCb[x] = 128;
+         dstCr[x] = 128;
+       }
+       dstCb += dstStride;
+       dstCr += dstStride;
+     }
+     return;
+  }
+  
+  if ( widthChroma > widthDepth ) // We assume
+  {
+    assert( heightChroma > heightDepth );
+    printf("This branch should never been reached.\n");
+    exit(0);
+  }
+  else
+  {
+#if MERL_VSP_BLOCKSIZE_C0152 == 1
+  Int  dW = size_x;
+  Int  dH = size_y;
+  Int  sW = 2; // search window size
+  Int  sH = 2;
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+  Int  dW = size_x;
+  Int  dH = size_y;
+  Int  sW = 2; // search window size
+  Int  sH = 2;
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 4
+  Int  dW = size_x>>1;
+  Int  dH = size_y>>1;
+  Int  sW = 4; // search window size
+  Int  sH = 4;
+#endif
+
+  {
+    Pel* depthi = depth;
+    for (Int j = 0; j < dH; j++)
+    {
+      for (Int i = 0; i < dW; i++)
+      {
+        Pel* depthTmp;
+#if MERL_VSP_BLOCKSIZE_C0152 == 1
+        depthTmp = depthi + (i << 1);
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+        if (depthPosX + (i<<1) < widthDepth)
+          depthTmp = depthi + (i << 1);
+        else
+          depthTmp = depthi + (widthDepth - depthPosX - 1);
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 4
+        if (depthPosX + (i<<2) < widthDepth)
+          depthTmp = depthi + (i << 2);
+        else
+          depthTmp = depthi + (widthDepth - depthPosX - 1);
+#endif
+        Int maxV = 0;
+        for (Int blockj = 0; blockj < sH; blockj++)
+        {
+          Int iX = 0;
+          for (Int blocki = 0; blocki < sW; blocki++)
+          {
+            if (maxV < depthTmp[iX])
+              maxV = depthTmp[iX];
+            if (depthPosX + i*sW + blocki < widthDepth - 1)
+              iX++;
+          }
+          if (depthPosY + j*sH + blockj < heightDepth - 1)
+            depthTmp += depStride;
+        }
+        m_pDepth[i+j*dW] = maxV;
+      } // end of i < dW
+#if MERL_VSP_BLOCKSIZE_C0152 == 1
+      if (depthPosY + ((j+1)<<1) < heightDepth)
+        depthi += (depStride << 1);
+      else
+        depthi  = depth + (heightDepth-1)*depStride;
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+      if (depthPosY + ((j+1)<<1) < heightDepth)
+        depthi += (depStride << 1);
+      else
+        depthi  = depth + (heightDepth-depthPosY-1)*depStride;
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 4
+      if (depthPosY + ((j+1)<<2) < heightDepth) // heightDepth-1
+        depthi += (depStride << 2);
+      else
+        depthi  = depth + (heightDepth-depthPosY-1)*depStride; // the last line
+#endif
+    }
+  }
+
+
+    // (size_x, size_y) is Chroma block size
+    for ( Int yTxt = 0, yDepth = 0; yTxt < size_y; yTxt += nTxtPerDepthY, yDepth += nDepthPerTxtY )
+    {
+      for ( Int xTxt = 0, xDepth = 0; xTxt < size_x; xTxt += nTxtPerDepthX, xDepth += nDepthPerTxtX )
+      {
+        Pel rep_depth = 0; // to store the depth value used for warping
+#if MERL_VSP_BLOCKSIZE_C0152 == 1
+        rep_depth = m_pDepth[(xTxt) + (yTxt)*dW];
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 2
+        rep_depth = m_pDepth[(xTxt) + (yTxt)*dW];
+#endif
+#if MERL_VSP_BLOCKSIZE_C0152 == 4
+        rep_depth = m_pDepth[(xTxt>>1) + (yTxt>>1)*dW];
+#endif
+
+      // calculate the offset in the reference picture
+        Int disparity = pShiftLUT[ rep_depth ] << iShiftPrec;
+        Int refOffset = xTxt + (disparity >> 3); // in integer pixel in chroma image
+        Int xFrac = disparity & 0x7;
+        Int absX  = posX + refOffset;
+
+        if (xFrac == 0)
+          absX = Clip3(0, widthChroma-1, absX);
+        else
+          absX = Clip3(4, widthChroma-5, absX);
+
+        refOffset = absX - posX;
+
+        assert( refCb[refOffset] >= 0 && refCb[refOffset]<= 255 );
+        assert( refCr[refOffset] >= 0 && refCr[refOffset]<= 255 );
+        m_if.filterHorChroma(&refCb[refOffset], refStride, &dstCb[xTxt],  dstStride, nTxtPerDepthX, nTxtPerDepthY, xFrac, true);
+        m_if.filterHorChroma(&refCr[refOffset], refStride, &dstCr[xTxt],  dstStride, nTxtPerDepthX, nTxtPerDepthY, xFrac, true);
+      }
+      refCb += refStrideBlock;
+      refCr += refStrideBlock;
+      dstCb += dstStrideBlock;
+      dstCr += dstStrideBlock;
+      depth += depStrideBlock;
+    }
+  }
+}
+
+#endif // MERL_VSP_C0152
+
+#if DEPTH_MAP_GENERATION
+Void TComPrediction::xWeightedAveragePdm( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst, UInt uiSubSampExpX, UInt uiSubSampExpY )
+{
+  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
+  {
+    rpcYuvDst->addAvgPdm( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY );
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    pcYuvSrc0->copyPartToPartYuvPdm( rpcYuvDst, uiPartIdx, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    pcYuvSrc1->copyPartToPartYuvPdm( rpcYuvDst, uiPartIdx, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY );
+  }
+  else
+  {
+    assert (0);
+  }
+}
+#endif
+
+Void TComPrediction::xWeightedAverage( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst )
+{
+  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
+  {
+    rpcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    pcYuvSrc0->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    pcYuvSrc1->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+}
+
+// AMVP
+Void TComPrediction::getMvPredAMVP( TComDataCU* pcCU, UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred )
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+
+  if( pcCU->getAMVPMode(uiPartAddr) == AM_NONE || (pcAMVPInfo->iN <= 1 && pcCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+  {
+    rcMvPred = pcAMVPInfo->m_acMvCand[0];
+
+    pcCU->setMVPIdxSubParts( 0, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    return;
+  }
+
+  assert(pcCU->getMVPIdx(eRefPicList,uiPartAddr) >= 0);
+  rcMvPred = pcAMVPInfo->m_acMvCand[pcCU->getMVPIdx(eRefPicList,uiPartAddr)];
+  return;
+}
+
+/** 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
+ *
+ * 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;
+  Int leftColumn[MAX_CU_SIZE], topRow[MAX_CU_SIZE], bottomRow[MAX_CU_SIZE], rightColumn[MAX_CU_SIZE];
+  UInt blkSize = width;
+  UInt offset2D = width;
+  UInt shift1D = g_aucConvertToBit[ width ] + 2;
+  UInt shift2D = shift1D + 1;
+
+  // Get left and above reference column and row
+  for(k=0;k<blkSize+1;k++)
+  {
+    topRow[k] = pSrc[k-srcStride];
+    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;
+  }
+
+  // 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 );
+    }
+  }
+}
+
+/** Function for deriving chroma LM intra prediction.
+ * \param pcPattern pointer to neighbouring pixel access pattern
+ * \param piSrc pointer to reconstructed chroma sample array
+ * \param pPred pointer for the prediction sample array
+ * \param uiPredStride the stride of the prediction sample array
+ * \param uiCWidth the width of the chroma block
+ * \param uiCHeight the height of the chroma block
+ * \param uiChromaId boolean indication of chroma component
+ *
+ * This function derives the prediction samples for chroma LM mode (chroma intra coding)
+ */
+Void TComPrediction::predLMIntraChroma( TComPattern* pcPattern, Int* piSrc, Pel* pPred, UInt uiPredStride, UInt uiCWidth, UInt uiCHeight, UInt uiChromaId )
+{
+  UInt uiWidth  = 2 * uiCWidth;
+
+  xGetLLSPrediction( pcPattern, piSrc+uiWidth+2, uiWidth+1, pPred, uiPredStride, uiCWidth, uiCHeight, 1 );  
+}
+
+/** Function for deriving downsampled luma sample of current chroma block and its above, left causal pixel
+ * \param pcPattern pointer to neighbouring pixel access pattern
+ * \param uiCWidth the width of the chroma block
+ * \param uiCHeight the height of the chroma block
+ *
+ * This function derives downsampled luma sample of current chroma block and its above, left causal pixel
+ */
+Void TComPrediction::getLumaRecPixels( TComPattern* pcPattern, UInt uiCWidth, UInt uiCHeight )
+{
+  UInt uiWidth  = 2 * uiCWidth;
+  UInt uiHeight = 2 * uiCHeight;  
+
+  Pel* pRecSrc = pcPattern->getROIY();
+  Pel* pDst0 = m_pLumaRecBuffer + m_iLumaRecStride + 1;
+
+  Int iRecSrcStride = pcPattern->getPatternLStride();
+  Int iRecSrcStride2 = iRecSrcStride << 1;
+  Int iDstStride = m_iLumaRecStride;
+  Int iSrcStride = ( max( uiWidth, uiHeight ) << 1 ) + 1;
+
+  Int* ptrSrc = pcPattern->getAdiOrgBuf( uiWidth, uiHeight, m_piYuvExt );
+
+  // initial pointers
+  Pel* pDst = pDst0 - 1 - iDstStride;  
+  Int* piSrc = ptrSrc;
+
+  // top left corner downsampled from ADI buffer
+  // don't need this point
+
+  // top row downsampled from ADI buffer
+  pDst++;     
+  piSrc ++;
+  for (Int i = 0; i < uiCWidth; i++)
+  {
+    pDst[i] = ((piSrc[2*i] * 2 ) + piSrc[2*i - 1] + piSrc[2*i + 1] + 2) >> 2;
+  }
+
+  // left column downsampled from ADI buffer
+  pDst = pDst0 - 1; 
+  piSrc = ptrSrc + iSrcStride;
+  for (Int j = 0; j < uiCHeight; j++)
+  {
+    pDst[0] = ( piSrc[0] + piSrc[iSrcStride] ) >> 1;
+    piSrc += iSrcStride << 1; 
+    pDst += iDstStride;    
+  }
+
+  // inner part from reconstructed picture buffer
+  for( Int j = 0; j < uiCHeight; j++ )
+  {
+    for (Int i = 0; i < uiCWidth; i++)
+    {
+      pDst0[i] = (pRecSrc[2*i] + pRecSrc[2*i + iRecSrcStride]) >> 1;
+    }
+
+    pDst0 += iDstStride;
+    pRecSrc += iRecSrcStride2;
+  }
+}
+
+/** Function for deriving the positon of first non-zero binary bit of a value
+ * \param x input value
+ *
+ * This function derives the positon of first non-zero binary bit of a value
+ */
+Int GetMSB( UInt x )
+{
+  Int iMSB = 0, bits = ( sizeof( Int ) << 3 ), y = 1;
+
+  while( x > 1 )
+  {
+    bits >>= 1;
+    y = x >> bits;
+
+    if( y )
+    {
+      x = y;
+      iMSB += bits;
+    }
+  }
+
+  iMSB+=y;
+
+  return iMSB;
+}
+
+/** Function for counting leading number of zeros/ones
+ * \param x input value
+ \ This function counts leading number of zeros for positive numbers and
+ \ leading number of ones for negative numbers. This can be implemented in
+ \ single instructure cycle on many processors.
+ */
+
+Short CountLeadingZerosOnes (Short x)
+{
+  Short clz;
+  Short i;
+
+  if(x == 0)
+  {
+    clz = 0;
+  }
+  else
+  {
+    if (x == -1)
+    {
+      clz = 15;
+    }
+    else
+    {
+      if(x < 0)
+      {
+        x = ~x;
+      }
+      clz = 15;
+      for(i = 0;i < 15;++i)
+      {
+        if(x) 
+        {
+          clz --;
+        }
+        x = x >> 1;
+      }
+    }
+  }
+  return clz;
+}
+
+/** Function for deriving LM intra prediction.
+ * \param pcPattern pointer to neighbouring pixel access pattern
+ * \param pSrc0 pointer to reconstructed chroma sample array
+ * \param iSrcStride the stride of reconstructed chroma sample array
+ * \param pDst0 reference to pointer for the prediction sample array
+ * \param iDstStride the stride of the prediction sample array
+ * \param uiWidth the width of the chroma block
+ * \param uiHeight the height of the chroma block
+ * \param uiExt0 line number of neiggboirng pixels for calculating LM model parameter, default value is 1
+ *
+ * This function derives the prediction samples for chroma LM mode (chroma intra coding)
+ */
+Void TComPrediction::xGetLLSPrediction( TComPattern* pcPattern, Int* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0 )
+{
+
+  Pel  *pDst, *pLuma;
+  Int  *pSrc;
+
+  Int  iLumaStride = m_iLumaRecStride;
+  Pel* pLuma0 = m_pLumaRecBuffer + uiExt0 * iLumaStride + uiExt0;
+
+  Int i, j, iCountShift = 0;
+
+  UInt uiExt = uiExt0;
+
+  // LLS parameters estimation -->
+
+  Int x = 0, y = 0, xx = 0, xy = 0;
+
+  pSrc  = pSrc0  - iSrcStride;
+  pLuma = pLuma0 - iLumaStride;
+
+  for( j = 0; j < uiWidth; j++ )
+  {
+    x += pLuma[j];
+    y += pSrc[j];
+    xx += pLuma[j] * pLuma[j];
+    xy += pLuma[j] * pSrc[j];
+  }
+  iCountShift += g_aucConvertToBit[ uiWidth ] + 2;
+
+  pSrc  = pSrc0 - uiExt;
+  pLuma = pLuma0 - uiExt;
+
+  for( i = 0; i < uiHeight; i++ )
+  {
+    x += pLuma[0];
+    y += pSrc[0];
+    xx += pLuma[0] * pLuma[0];
+    xy += pLuma[0] * pSrc[0];
+
+    pSrc  += iSrcStride;
+    pLuma += iLumaStride;
+  }
+  iCountShift += iCountShift > 0 ? 1 : ( g_aucConvertToBit[ uiWidth ] + 2 );
+
+  Int iTempShift = ( g_uiBitDepth + g_uiBitIncrement ) + g_aucConvertToBit[ uiWidth ] + 3 - 15;
+
+  if(iTempShift > 0)
+  {
+    x  = ( x +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    y  = ( y +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xx = ( xx + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xy = ( xy + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    iCountShift -= iTempShift;
+  }
+
+  Int a, b, iShift = 13;
+
+  if( iCountShift == 0 )
+  {
+    a = 0;
+    b = 1 << (g_uiBitDepth + g_uiBitIncrement - 1);
+    iShift = 0;
+  }
+  else
+  {
+    Int a1 = ( xy << iCountShift ) - y * x;
+    Int a2 = ( xx << iCountShift ) - x * x;              
+
+    {
+      const Int iShiftA2 = 6;
+      const Int iShiftA1 = 15;
+      const Int iAccuracyShift = 15;
+
+      Int iScaleShiftA2 = 0;
+      Int iScaleShiftA1 = 0;
+      Int a1s = a1;
+      Int a2s = a2;
+
+      iScaleShiftA1 = GetMSB( abs( a1 ) ) - iShiftA1;
+      iScaleShiftA2 = GetMSB( abs( a2 ) ) - iShiftA2;  
+
+      if( iScaleShiftA1 < 0 )
+      {
+        iScaleShiftA1 = 0;
+      }
+      
+      if( iScaleShiftA2 < 0 )
+      {
+        iScaleShiftA2 = 0;
+      }
+      
+      Int iScaleShiftA = iScaleShiftA2 + iAccuracyShift - iShift - iScaleShiftA1;
+
+      a2s = a2 >> iScaleShiftA2;
+
+      a1s = a1 >> iScaleShiftA1;
+
+      if (a2s >= 1)
+      {
+        a = a1s * m_uiaShift[ a2s - 1];
+      }
+      else
+      {
+        a = 0;
+      }
+      
+      if( iScaleShiftA < 0 )
+      {
+        a = a << -iScaleShiftA;
+      }
+      else
+      {
+        a = a >> iScaleShiftA;
+      }
+      
+       a = Clip3(-( 1 << 15 ), ( 1 << 15 ) - 1, a); 
+     
+      Int minA = -(1 << (6));
+      Int maxA = (1 << 6) - 1;
+      if( a <= maxA && a >= minA )
+      {
+        // do nothing
+      }
+      else
+      {
+        Short n = CountLeadingZerosOnes(a);
+        a = a >> (9-n);
+        iShift -= (9-n);
+      }
+
+      b = (  y - ( ( a * x ) >> iShift ) + ( 1 << ( iCountShift - 1 ) ) ) >> iCountShift;
+    }
+  }   
+
+  // <-- end of LLS parameters estimation
+
+  // get prediction -->
+  uiExt = uiExt0;
+  pLuma = pLuma0;
+  pDst = pDst0;
+
+  for( i = 0; i < uiHeight; i++ )
+  {
+    for( j = 0; j < uiWidth; j++ )
+    {
+      pDst[j] = Clip( ( ( a * pLuma[j] ) >> iShift ) + b );
+    }
+    
+    pDst  += iDstStride;
+    pLuma += iLumaStride;
+  }
+  // <-- end of get prediction
+
+}
+
+
+#if LGE_ILLUCOMP_B0045
+/** Function for deriving LM illumination compensation.
+ */
+Void TComPrediction::xGetLLSICPrediction(TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, Int &iShift)
+{
+  TComPicYuv *pRecPic = pcCU->getPic()->getPicYuvRec();
+  Pel *pRec, *pRef;
+  UInt uiWidth, uiHeight, uiTmpPartIdx;
+  Int iRecStride = pRecPic->getStride(), iRefStride = pRefPic->getStride();
+  Int iCUPelX, iCUPelY, iRefX, iRefY, iRefOffset;
+
+  iCUPelX = pcCU->getCUPelX() + g_auiRasterToPelX[g_auiZscanToRaster[pcCU->getZorderIdxInCU()]];
+  iCUPelY = pcCU->getCUPelY() + g_auiRasterToPelY[g_auiZscanToRaster[pcCU->getZorderIdxInCU()]];
+  iRefX   = iCUPelX + (pMv->getHor() >> 2);
+  iRefY   = iCUPelY + (pMv->getVer() >> 2);
+  uiWidth = pcCU->getWidth(0);
+  uiHeight = pcCU->getHeight(0);
+
+  Int i, j, iCountShift = 0;
+
+  // LLS parameters estimation -->
+
+  Int x = 0, y = 0, xx = 0, xy = 0;
+
+  if(pcCU->getPUAbove(uiTmpPartIdx, pcCU->getZorderIdxInCU()) && iCUPelY > 0 && iRefY > 0)
+  {
+    iRefOffset = ( pMv->getHor() >> 2 ) + ( pMv->getVer() >> 2 ) * iRefStride - iRefStride;
+    pRef = pRefPic->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+    pRec = pRecPic->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - iRecStride;
+
+    for( j = 0; j < uiWidth; j++ )
+    {
+      x += pRef[j];
+      y += pRec[j];
+      xx += pRef[j] * pRef[j];
+      xy += pRef[j] * pRec[j];
+    }
+    iCountShift += g_aucConvertToBit[ uiWidth ] + 2;
+  }
+
+
+  if(pcCU->getPULeft(uiTmpPartIdx, pcCU->getZorderIdxInCU()) && iCUPelX > 0 && iRefX > 0)
+  {
+    iRefOffset = ( pMv->getHor() >> 2 ) + ( pMv->getVer() >> 2 ) * iRefStride - 1;
+    pRef = pRefPic->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+    pRec = pRecPic->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - 1;
+
+    for( i = 0; i < uiHeight; i++ )
+    {
+      x += pRef[0];
+      y += pRec[0];
+      xx += pRef[0] * pRef[0];
+      xy += pRef[0] * pRec[0];
+
+      pRef += iRefStride;
+      pRec += iRecStride;
+    }
+    iCountShift += iCountShift > 0 ? 1 : ( g_aucConvertToBit[ uiWidth ] + 2 );
+  }
+
+  Int iTempShift = ( g_uiBitDepth + g_uiBitIncrement ) + g_aucConvertToBit[ uiWidth ] + 3 - 15;
+
+  if(iTempShift > 0)
+  {
+    x  = ( x +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    y  = ( y +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xx = ( xx + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xy = ( xy + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    iCountShift -= iTempShift;
+  }
+
+  iShift = 13;
+
+  if( iCountShift == 0 )
+  {
+    a = 1;
+    b = 0;
+    iShift = 0;
+  }
+  else
+  {
+    Int a1 = ( xy << iCountShift ) - y * x;
+    Int a2 = ( xx << iCountShift ) - x * x;              
+
+    {
+      const Int iShiftA2 = 6;
+      const Int iShiftA1 = 15;
+      const Int iAccuracyShift = 15;
+
+      Int iScaleShiftA2 = 0;
+      Int iScaleShiftA1 = 0;
+      Int a1s = a1;
+      Int a2s = a2;
+
+      iScaleShiftA1 = GetMSB( abs( a1 ) ) - iShiftA1;
+      iScaleShiftA2 = GetMSB( abs( a2 ) ) - iShiftA2;  
+
+      if( iScaleShiftA1 < 0 )
+      {
+        iScaleShiftA1 = 0;
+      }
+
+      if( iScaleShiftA2 < 0 )
+      {
+        iScaleShiftA2 = 0;
+      }
+
+      Int iScaleShiftA = iScaleShiftA2 + iAccuracyShift - iShift - iScaleShiftA1;
+
+      a2s = a2 >> iScaleShiftA2;
+
+      a1s = a1 >> iScaleShiftA1;
+
+      if (a2s >= 1)
+      {
+        a = a1s * m_uiaShift[ a2s - 1];
+      }
+      else
+      {
+        a = 0;
+      }
+
+      if( iScaleShiftA < 0 )
+      {
+        a = a << -iScaleShiftA;
+      }
+      else
+      {
+        a = a >> iScaleShiftA;
+      }
+
+      a = Clip3(-( 1 << 15 ), ( 1 << 15 ) - 1, a); 
+
+      Int minA = -(1 << (6));
+      Int maxA = (1 << 6) - 1;
+      if( a <= maxA && a >= minA )
+      {
+        // do nothing
+      }
+      else
+      {
+        Short n = CountLeadingZerosOnes(a);
+        a = a >> (9-n);
+        iShift -= (9-n);
+      }
+
+      b = (  y - ( ( a * x ) >> iShift ) + ( 1 << ( iCountShift - 1 ) ) ) >> iCountShift;
+    }
+  }   
+}
+
+Void TComPrediction::xGetLLSICPredictionChroma(TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, Int &iShift, Int iChromaId)
+{
+  TComPicYuv *pRecPic = pcCU->getPic()->getPicYuvRec();
+  Pel *pRec = NULL, *pRef = NULL;
+  UInt uiWidth, uiHeight, uiTmpPartIdx;
+  Int iRecStride = pRecPic->getCStride(), iRefStride = pRefPic->getCStride();
+  Int iCUPelX, iCUPelY, iRefX, iRefY, iRefOffset;
+
+  iCUPelX = pcCU->getCUPelX() + g_auiRasterToPelX[g_auiZscanToRaster[pcCU->getZorderIdxInCU()]];
+  iCUPelY = pcCU->getCUPelY() + g_auiRasterToPelY[g_auiZscanToRaster[pcCU->getZorderIdxInCU()]];
+  iRefX   = iCUPelX + (pMv->getHor() >> 2);
+  iRefY   = iCUPelY + (pMv->getVer() >> 2);
+  uiWidth = pcCU->getWidth(0) >> 1;
+  uiHeight = pcCU->getHeight(0) >> 1;
+
+  Int i, j, iCountShift = 0;
+
+  // LLS parameters estimation -->
+
+  Int x = 0, y = 0, xx = 0, xy = 0;
+
+  if(pcCU->getPUAbove(uiTmpPartIdx, pcCU->getZorderIdxInCU()) && iCUPelY > 0 && iRefY > 0)
+  {
+    iRefOffset = ( pMv->getHor() >> 3 ) + ( pMv->getVer() >> 3 ) * iRefStride - iRefStride;
+    if (iChromaId == 0) // Cb
+    {
+      pRef = pRefPic->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - iRecStride;
+    }
+    else if (iChromaId == 1) // Cr
+    {
+      pRef = pRefPic->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - iRecStride;
+    }
+
+    for( j = 0; j < uiWidth; j++ )
+    {
+      x += pRef[j];
+      y += pRec[j];
+      xx += pRef[j] * pRef[j];
+      xy += pRef[j] * pRec[j];
+    }
+    iCountShift += g_aucConvertToBit[ uiWidth ] + 2;
+  }
+
+
+  if(pcCU->getPULeft(uiTmpPartIdx, pcCU->getZorderIdxInCU()) && iCUPelX > 0 && iRefX > 0)
+  {
+    iRefOffset = ( pMv->getHor() >> 3 ) + ( pMv->getVer() >> 3 ) * iRefStride - 1;
+    if (iChromaId == 0) // Cb
+    {
+      pRef = pRefPic->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - 1;
+    }
+    else if (iChromaId == 1) // Cr
+    {
+      pRef = pRefPic->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - 1;
+    }
+
+    for( i = 0; i < uiHeight; i++ )
+    {
+      x += pRef[0];
+      y += pRec[0];
+      xx += pRef[0] * pRef[0];
+      xy += pRef[0] * pRec[0];
+
+      pRef += iRefStride;
+      pRec += iRecStride;
+    }
+    iCountShift += iCountShift > 0 ? 1 : ( g_aucConvertToBit[ uiWidth ] + 2 );
+  }
+
+  Int iTempShift = ( g_uiBitDepth + g_uiBitIncrement ) + g_aucConvertToBit[ uiWidth ] + 3 - 15;
+
+  if(iTempShift > 0)
+  {
+    x  = ( x +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    y  = ( y +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xx = ( xx + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xy = ( xy + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    iCountShift -= iTempShift;
+  }
+
+  iShift = 13;
+
+  if( iCountShift == 0 )
+  {
+    a = 1;
+    b = 0;
+    iShift = 0;
+  }
+  else
+  {
+    Int a1 = ( xy << iCountShift ) - y * x;
+    Int a2 = ( xx << iCountShift ) - x * x;              
+
+    {
+      const Int iShiftA2 = 6;
+      const Int iShiftA1 = 15;
+      const Int iAccuracyShift = 15;
+
+      Int iScaleShiftA2 = 0;
+      Int iScaleShiftA1 = 0;
+      Int a1s = a1;
+      Int a2s = a2;
+
+      iScaleShiftA1 = GetMSB( abs( a1 ) ) - iShiftA1;
+      iScaleShiftA2 = GetMSB( abs( a2 ) ) - iShiftA2;  
+
+      if( iScaleShiftA1 < 0 )
+      {
+        iScaleShiftA1 = 0;
+      }
+
+      if( iScaleShiftA2 < 0 )
+      {
+        iScaleShiftA2 = 0;
+      }
+
+      Int iScaleShiftA = iScaleShiftA2 + iAccuracyShift - iShift - iScaleShiftA1;
+
+      a2s = a2 >> iScaleShiftA2;
+
+      a1s = a1 >> iScaleShiftA1;
+
+      if (a2s >= 1)
+      {
+        a = a1s * m_uiaShift[ a2s - 1];
+      }
+      else
+      {
+        a = 0;
+      }
+
+      if( iScaleShiftA < 0 )
+      {
+        a = a << -iScaleShiftA;
+      }
+      else
+      {
+        a = a >> iScaleShiftA;
+      }
+
+      a = Clip3(-( 1 << 15 ), ( 1 << 15 ) - 1, a); 
+
+      Int minA = -(1 << (6));
+      Int maxA = (1 << 6) - 1;
+      if( a <= maxA && a >= minA )
+      {
+        // do nothing
+      }
+      else
+      {
+        Short n = CountLeadingZerosOnes(a);
+        a = a >> (9-n);
+        iShift -= (9-n);
+      }
+
+      b = (  y - ( ( a * x ) >> iShift ) + ( 1 << ( iCountShift - 1 ) ) ) >> iCountShift;
+    }
+  }   
+}
+#endif
+/** Function for filtering intra DC predictor.
+ * \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 iDstStride the stride of the prediction sample array
+ * \param iWidth the width of the block
+ * \param iHeight the height of the block
+ *
+ * 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;
+  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);
+  }
+
+  return;
+}
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+Void TComPrediction::predIntraLumaDMM( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder )
+{
+#if HHI_DMM_WEDGE_INTRA
+  if( uiMode == DMM_WEDGE_FULL_IDX        ) { xPredIntraWedgeFull ( pcCU, uiAbsPartIdx, piPred, uiStride, iWidth, iHeight, bAbove, bLeft, bEncoder, false, pcCU->getWedgeFullTabIdx ( uiAbsPartIdx ) ); }
+  if( uiMode == DMM_WEDGE_FULL_D_IDX      ) { xPredIntraWedgeFull ( pcCU, uiAbsPartIdx, piPred, uiStride, iWidth, iHeight, bAbove, bLeft, bEncoder, true,  pcCU->getWedgeFullTabIdx( uiAbsPartIdx ), pcCU->getWedgeFullDeltaDC1( uiAbsPartIdx ), pcCU->getWedgeFullDeltaDC2( uiAbsPartIdx ) ); }
+  if( uiMode == DMM_WEDGE_PREDDIR_IDX     ) { xPredIntraWedgeDir  ( pcCU, uiAbsPartIdx, piPred, uiStride, iWidth, iHeight, bAbove, bLeft, bEncoder, false, pcCU->getWedgePredDirDeltaEnd( uiAbsPartIdx ) ); }
+  if( uiMode == DMM_WEDGE_PREDDIR_D_IDX   ) { xPredIntraWedgeDir  ( pcCU, uiAbsPartIdx, piPred, uiStride, iWidth, iHeight, bAbove, bLeft, bEncoder, true,  pcCU->getWedgePredDirDeltaEnd( uiAbsPartIdx ), pcCU->getWedgePredDirDeltaDC1( uiAbsPartIdx ), pcCU->getWedgePredDirDeltaDC2( uiAbsPartIdx ) ); }
+#endif
+#if HHI_DMM_PRED_TEX
+  if( uiMode == DMM_WEDGE_PREDTEX_IDX     ) { xPredIntraWedgeTex  ( pcCU, uiAbsPartIdx, piPred, uiStride, iWidth, iHeight, bAbove, bLeft, bEncoder, false ); }
+  if( uiMode == DMM_WEDGE_PREDTEX_D_IDX   ) { xPredIntraWedgeTex  ( pcCU, uiAbsPartIdx, piPred, uiStride, iWidth, iHeight, bAbove, bLeft, bEncoder, true, pcCU->getWedgePredTexDeltaDC1( uiAbsPartIdx ), pcCU->getWedgePredTexDeltaDC2( uiAbsPartIdx ) ); }
+  if( uiMode == DMM_CONTOUR_PREDTEX_IDX   ) { xPredIntraContourTex( pcCU, uiAbsPartIdx, piPred, uiStride, iWidth, iHeight, bAbove, bLeft, bEncoder, false ); }
+  if( uiMode == DMM_CONTOUR_PREDTEX_D_IDX ) { xPredIntraContourTex( pcCU, uiAbsPartIdx, piPred, uiStride, iWidth, iHeight, bAbove, bLeft, bEncoder, true, pcCU->getContourPredTexDeltaDC1( uiAbsPartIdx ), pcCU->getContourPredTexDeltaDC2( uiAbsPartIdx ) ); }
+#endif
+}
+
+Void TComPrediction::getWedgePredDCs( TComWedgelet* pcWedgelet, Int* piMask, Int iMaskStride, Int& riPredDC1, Int& riPredDC2, Bool bAbove, Bool bLeft )
+{
+  riPredDC1 = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) ); //pred val, if no neighbors are available
+  riPredDC2 = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+
+  if( !bAbove && !bLeft ) { return; }
+
+  UInt uiNumSmpDC1 = 0, uiNumSmpDC2 = 0;
+  Int iPredDC1 = 0, iPredDC2 = 0;
+
+  Bool* pabWedgePattern = pcWedgelet->getPattern();
+  UInt  uiWedgeStride   = pcWedgelet->getStride();
+
+#if HS_REFERENCE_SUBSAMPLE_C0154
+  Int subSamplePix;
+  if ( pcWedgelet->getWidth() == 32 )
+  {
+    subSamplePix = 2;
+  }
+  else
+  {
+    subSamplePix = 1;
+  }
+#endif
+
+  if( bAbove )
+  {
+#if HS_REFERENCE_SUBSAMPLE_C0154
+    for( Int k = 0; k < pcWedgelet->getWidth(); k+=subSamplePix )
+#else
+    for( Int k = 0; k < pcWedgelet->getWidth(); k++ )
+#endif
+    {
+      if( true == pabWedgePattern[k] )
+      {
+        iPredDC2 += piMask[k-iMaskStride];
+        uiNumSmpDC2++;
+      }
+      else
+      {
+        iPredDC1 += piMask[k-iMaskStride];
+        uiNumSmpDC1++;
+      }
+    }
+  }
+  if( bLeft )
+  {
+#if HS_REFERENCE_SUBSAMPLE_C0154
+    for( Int k = 0; k < pcWedgelet->getHeight(); k+=subSamplePix )
+#else
+    for( Int k = 0; k < pcWedgelet->getHeight(); k++ )
+#endif
+    {
+      if( true == pabWedgePattern[k*uiWedgeStride] )
+      {
+        iPredDC2 += piMask[k*iMaskStride-1];
+        uiNumSmpDC2++;
+      } 
+      else
+      {
+        iPredDC1 += piMask[k*iMaskStride-1];
+        uiNumSmpDC1++;
+      }
+    }
+  }
+
+  if( uiNumSmpDC1 > 0 )
+  {
+    iPredDC1 /= uiNumSmpDC1;
+    riPredDC1 = iPredDC1;
+  }
+  if( uiNumSmpDC2 > 0 )
+  {
+    iPredDC2 /= uiNumSmpDC2;
+    riPredDC2 = iPredDC2;
+  }
+}
+
+Void TComPrediction::calcWedgeDCs( TComWedgelet* pcWedgelet, Pel* piOrig, UInt uiStride, Int& riDC1, Int& riDC2 )
+{
+  UInt uiDC1 = 0;
+  UInt uiDC2 = 0;
+  UInt uiNumPixDC1 = 0, uiNumPixDC2 = 0;
+  Bool* pabWedgePattern = pcWedgelet->getPattern();
+  if( uiStride == pcWedgelet->getStride() )
+  {
+    for( UInt k = 0; k < (pcWedgelet->getWidth() * pcWedgelet->getHeight()); k++ )
+    {
+      if( true == pabWedgePattern[k] ) 
+      {
+        uiDC2 += piOrig[k];
+        uiNumPixDC2++;
+      }
+      else
+      {
+        uiDC1 += piOrig[k];
+        uiNumPixDC1++;
+      }
+    }
+  }
+  else
+  {
+    Pel* piTemp = piOrig;
+    UInt uiWedgeStride = pcWedgelet->getStride();
+    for( UInt uiY = 0; uiY < pcWedgelet->getHeight(); uiY++ )
+    {
+      for( UInt uiX = 0; uiX < pcWedgelet->getWidth(); uiX++ )
+      {
+        if( true == pabWedgePattern[uiX] ) 
+        {
+          uiDC2 += piTemp[uiX];
+          uiNumPixDC2++;
+        }
+        else
+        {
+          uiDC1 += piTemp[uiX];
+          uiNumPixDC1++;
+        }
+      }
+      piTemp          += uiStride;
+      pabWedgePattern += uiWedgeStride;
+    }
+  }
+
+  if( uiNumPixDC1 > 0 ) { riDC1 = uiDC1 / uiNumPixDC1; }
+  else                  { riDC1 = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) ); }
+
+  if( uiNumPixDC2 > 0 ) { riDC2 = uiDC2 / uiNumPixDC2; }
+  else                  { riDC2 = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) ); }
+}
+
+Void TComPrediction::assignWedgeDCs2Pred( TComWedgelet* pcWedgelet, Pel* piPred, UInt uiStride, Int iDC1, Int iDC2 )
+{
+  Bool* pabWedgePattern = pcWedgelet->getPattern();
+
+  if( uiStride == pcWedgelet->getStride() )
+  {
+    for( UInt k = 0; k < (pcWedgelet->getWidth() * pcWedgelet->getHeight()); k++ )
+    {
+      if( true == pabWedgePattern[k] ) 
+      {
+        piPred[k] = iDC2;
+      }
+      else
+      {
+        piPred[k] = iDC1;
+      }
+    }
+  }
+  else
+  {
+    Pel* piTemp = piPred;
+    UInt uiWedgeStride = pcWedgelet->getStride();
+    for( UInt uiY = 0; uiY < pcWedgelet->getHeight(); uiY++ )
+    {
+      for( UInt uiX = 0; uiX < pcWedgelet->getWidth(); uiX++ )
+      {
+        if( true == pabWedgePattern[uiX] ) 
+        {
+          piTemp[uiX] = iDC2;
+        }
+        else
+        {
+          piTemp[uiX] = iDC1;
+        }
+      }
+      piTemp          += uiStride;
+      pabWedgePattern += uiWedgeStride;
+    }
+  }
+}
+
+Void TComPrediction::xDeltaDCQuantScaleUp( TComDataCU* pcCU, Int& riDeltaDC )
+{
+  Int  iSign  = riDeltaDC < 0 ? -1 : 1;
+  UInt uiAbs  = abs( riDeltaDC );
+
+  Int iQp = pcCU->getQP(0);
+  Double dMax = (Double)( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+  Double dStepSize = Clip3( 1.0, dMax, pow( 2.0, iQp/10.0 + g_iDeltaDCsQuantOffset ) );
+
+  riDeltaDC = iSign * roftoi( uiAbs * dStepSize );
+  return;
+}
+
+Void TComPrediction::xDeltaDCQuantScaleDown( TComDataCU*  pcCU, Int& riDeltaDC )
+{
+  Int  iSign  = riDeltaDC < 0 ? -1 : 1;
+  UInt uiAbs  = abs( riDeltaDC );
+
+  Int iQp = pcCU->getQP(0);
+  Double dMax = (Double)( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+  Double dStepSize = Clip3( 1.0, dMax, pow( 2.0, iQp/10.0 + g_iDeltaDCsQuantOffset ) );
+
+  riDeltaDC = iSign * roftoi( uiAbs / dStepSize );
+  return;
+}
+#endif
+
+#if HHI_DMM_PRED_TEX
+Void TComPrediction::getBestContourFromTex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, TComWedgelet* pcContourWedge )
+{
+  pcContourWedge->clear();
+
+  // get copy of co-located texture luma block
+  TComYuv cTempYuv;
+  cTempYuv.create( uiWidth, uiHeight ); 
+  cTempYuv.clear();
+  Pel* piRefBlkY = cTempYuv.getLumaAddr();
+  copyTextureLumaBlock( pcCU, uiAbsPartIdx, piRefBlkY, uiWidth, uiHeight );
+  piRefBlkY = cTempYuv.getLumaAddr();
+
+  // find contour for texture luma block
+  UInt iDC = 0;
+  for( UInt k = 0; k < (uiWidth*uiHeight); k++ ) 
+  { 
+    iDC += piRefBlkY[k]; 
+  }
+  iDC /= (uiWidth*uiHeight);
+  piRefBlkY = cTempYuv.getLumaAddr();
+
+  Bool* pabContourPattern = pcContourWedge->getPattern();
+  for( UInt k = 0; k < (uiWidth*uiHeight); k++ ) 
+  { 
+    pabContourPattern[k] = (piRefBlkY[k] > iDC) ? true : false;
+  }
+
+  cTempYuv.destroy();
+}
+
+#if LGE_DMM3_SIMP_C0044
+/**
+ - fetch best Wedgelet pattern at decoder
+ */
+UInt TComPrediction::getBestWedgeFromTex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt IntraTabIdx)
+{
+  assert( uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+
+  UInt          uiBestTabIdx = 0;
+  TComPic*      pcPicTex = pcCU->getSlice()->getTexturePic();
+  TComDataCU*   pcColTexCU = pcPicTex->getCU(pcCU->getAddr());
+  UInt          uiTexPartIdx = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Int           uiColTexIntraDir = pcColTexCU->isIntra( uiTexPartIdx ) ? pcColTexCU->getLumaIntraDir( uiTexPartIdx ) : 255;
+
+  std::vector< std::vector<UInt> > pauiWdgLstSz = g_aauiWdgLstM3[g_aucConvertToBit[uiWidth]];
+
+  if( uiColTexIntraDir > DC_IDX && uiColTexIntraDir < 35 )
+  {
+    std::vector<UInt>* pauiWdgLst = &pauiWdgLstSz[uiColTexIntraDir-2];
+    uiBestTabIdx    =   pauiWdgLst->at(IntraTabIdx);
+  }
+  else
+  {
+    WedgeNodeList* pacWedgeNodeList = &g_aacWedgeNodeLists[(g_aucConvertToBit[uiWidth])];
+    uiBestTabIdx = pacWedgeNodeList->at(IntraTabIdx).getPatternIdx();
+  }
+
+  return uiBestTabIdx;
+}
+#endif
+
+#if LGE_DMM3_SIMP_C0044
+/**
+ - calculate best Wedgelet pattern at encoder
+ */
+UInt TComPrediction::getBestWedgeFromTex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Pel* piOrigi, UInt uiStride, UInt & ruiIntraTabIdx)
+#else
+UInt TComPrediction::getBestWedgeFromTex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight )
+#endif
+{
+  assert( uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+
+  // get copy of co-located texture luma block
+  TComYuv cTempYuv; 
+  cTempYuv.create( uiWidth, uiHeight ); 
+  cTempYuv.clear();
+  Pel* piRefBlkY = cTempYuv.getLumaAddr();
+
+  copyTextureLumaBlock( pcCU, uiAbsPartIdx, piRefBlkY, uiWidth, uiHeight );
+  piRefBlkY = cTempYuv.getLumaAddr();
+
+  // local pred buffer
+  TComYuv cPredYuv; 
+  cPredYuv.create( uiWidth, uiHeight ); 
+  cPredYuv.clear();
+  Pel* piPred = cPredYuv.getLumaAddr();
+
+  UInt uiPredStride = cPredYuv.getStride();
+
+  // wedge search
+  TComWedgeDist cWedgeDist;
+  UInt uiBestDist = MAX_UINT;
+  UInt uiBestTabIdx = 0;
+  Int  iDC1 = 0;
+  Int  iDC2 = 0;
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+#if LGE_DMM3_SIMP_C0044
+  ruiIntraTabIdx  = 0;
+#endif
+  TComPic*      pcPicTex = pcCU->getSlice()->getTexturePic();
+  TComDataCU* pcColTexCU = pcPicTex->getCU(pcCU->getAddr());
+  UInt      uiTexPartIdx = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Int   uiColTexIntraDir = pcColTexCU->isIntra( uiTexPartIdx ) ? pcColTexCU->getLumaIntraDir( uiTexPartIdx ) : 255;
+
+  std::vector< std::vector<UInt> > pauiWdgLstSz = g_aauiWdgLstM3[g_aucConvertToBit[uiWidth]];
+  if( uiColTexIntraDir > DC_IDX && uiColTexIntraDir < 35 )
+  {
+    std::vector<UInt>* pauiWdgLst = &pauiWdgLstSz[uiColTexIntraDir-2];
+    for( UInt uiIdxW = 0; uiIdxW < pauiWdgLst->size(); uiIdxW++ )
+    {
+      UInt uiIdx     =   pauiWdgLst->at(uiIdxW);
+#if LGE_DMM3_SIMP_C0044
+      calcWedgeDCs       ( &(pacWedgeList->at(uiIdx)), piOrigi,   uiWidth,      iDC1, iDC2 );
+#else
+      calcWedgeDCs       ( &(pacWedgeList->at(uiIdx)), piRefBlkY, uiWidth,      iDC1, iDC2 );
+#endif
+      assignWedgeDCs2Pred( &(pacWedgeList->at(uiIdx)), piPred,    uiPredStride, iDC1, iDC2 );
+
+#if LGE_DMM3_SIMP_C0044
+      UInt uiActDist = cWedgeDist.getDistPart( piPred, uiPredStride, piOrigi, uiStride, uiWidth, uiHeight, WedgeDist_SAD );
+#else
+      UInt uiActDist = cWedgeDist.getDistPart( piPred, uiPredStride, piRefBlkY, uiWidth, uiWidth, uiHeight, WedgeDist_SAD );
+#endif
+
+      if( uiActDist < uiBestDist || uiBestDist == MAX_UINT )
+      {
+        uiBestDist   = uiActDist;
+        uiBestTabIdx = uiIdx;
+#if LGE_DMM3_SIMP_C0044
+        ruiIntraTabIdx = uiIdxW;
+#endif
+      }
+    }
+  }
+  else
+  {
+    WedgeNodeList* pacWedgeNodeList = &g_aacWedgeNodeLists[(g_aucConvertToBit[uiWidth])];
+    UInt uiBestNodeDist = MAX_UINT;
+    UInt uiBestNodeId   = 0;
+    for( UInt uiNodeId = 0; uiNodeId < pacWedgeNodeList->size(); uiNodeId++ )
+    {
+#if LGE_DMM3_SIMP_C0044
+      calcWedgeDCs       ( &(pacWedgeList->at(pacWedgeNodeList->at(uiNodeId).getPatternIdx())), piOrigi, uiWidth,      iDC1, iDC2 );
+#else
+      calcWedgeDCs       ( &(pacWedgeList->at(pacWedgeNodeList->at(uiNodeId).getPatternIdx())), piRefBlkY, uiWidth,      iDC1, iDC2 );
+#endif
+      assignWedgeDCs2Pred( &(pacWedgeList->at(pacWedgeNodeList->at(uiNodeId).getPatternIdx())), piPred,    uiPredStride, iDC1, iDC2 );
+
+#if LGE_DMM3_SIMP_C0044
+      UInt uiActDist = cWedgeDist.getDistPart( piPred, uiPredStride, piOrigi, uiStride, uiWidth, uiHeight, WedgeDist_SAD );
+#else
+      UInt uiActDist = cWedgeDist.getDistPart( piPred, uiPredStride, piRefBlkY, uiWidth, uiWidth, uiHeight, WedgeDist_SAD );
+#endif
+
+      if( uiActDist < uiBestNodeDist || uiBestNodeDist == MAX_UINT )
+      {
+        uiBestNodeDist = uiActDist;
+        uiBestNodeId   = uiNodeId;
+#if LGE_DMM3_SIMP_C0044
+        ruiIntraTabIdx = uiNodeId;
+#endif
+      }
+    }
+#if LGE_DMM3_SIMP_C0044
+    uiBestTabIdx = pacWedgeNodeList->at(uiBestNodeId).getPatternIdx();
+#else
+    // refinement
+    uiBestDist   = uiBestNodeDist;
+    uiBestTabIdx = pacWedgeNodeList->at(uiBestNodeId).getPatternIdx();
+    for( UInt uiRefId = 0; uiRefId < NUM_WEDGE_REFINES; uiRefId++ )
+    {
+      if( pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId ) != NO_IDX )
+      {
+        calcWedgeDCs       ( &(pacWedgeList->at(pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId ))), piRefBlkY, uiWidth,      iDC1, iDC2 );
+        assignWedgeDCs2Pred( &(pacWedgeList->at(pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId ))), piPred,    uiPredStride, iDC1, iDC2 );
+
+        UInt uiActDist = cWedgeDist.getDistPart( piPred, uiPredStride, piRefBlkY, uiWidth, uiWidth, uiHeight, WedgeDist_SAD );
+
+        if( uiActDist < uiBestDist || uiBestDist == MAX_UINT )
+        {
+          uiBestDist   = uiActDist;
+          uiBestTabIdx = pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId );
+        }
+      }
+    }
+#endif
+  }
+
+  cPredYuv.destroy();
+  cTempYuv.destroy();
+  return uiBestTabIdx;
+}
+
+Void TComPrediction::copyTextureLumaBlock( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piDestBlockY, UInt uiWidth, UInt uiHeight )
+{
+  TComPicYuv* pcPicYuvRef = pcCU->getSlice()->getTexturePic()->getPicYuvRec();
+  Int         iRefStride = pcPicYuvRef->getStride();
+  Pel*        piRefY;
+
+  piRefY = pcPicYuvRef->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+
+  for ( Int y = 0; y < uiHeight; y++ )
+  {
+    ::memcpy(piDestBlockY, piRefY, sizeof(Pel)*uiWidth);
+//    ::memset(piDestBlockY, 128, sizeof(Pel)*uiWidth);
+    piDestBlockY += uiWidth;
+    piRefY += iRefStride;
+  }
+}
+
+Void TComPrediction::xPredIntraWedgeTex( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder, Bool bDelta, Int iDeltaDC1, Int iDeltaDC2 )
+{
+  assert( iWidth >= DMM_WEDGEMODEL_MIN_SIZE && iWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[iWidth])];
+
+  // get wedge pattern
+  UInt uiTextureWedgeTabIdx = 0;
+  if( bEncoder ) 
+  {
+    // encoder: load stored wedge pattern from CU
+    uiTextureWedgeTabIdx = pcCU->getWedgePredTexTabIdx( uiAbsPartIdx );
+  }
+  else
+  {
+    // decoder: get and store wedge pattern in CU
+      // decoder: get and store wedge pattern in CU
+#if LGE_DMM3_SIMP_C0044
+    UInt uiIntraTabIdx   = pcCU->getWedgePredTexIntraTabIdx ( uiAbsPartIdx );
+    uiTextureWedgeTabIdx = getBestWedgeFromTex( pcCU, uiAbsPartIdx, (UInt)iWidth, (UInt)iHeight, uiIntraTabIdx );
+#else
+    uiTextureWedgeTabIdx = getBestWedgeFromTex( pcCU, uiAbsPartIdx, (UInt)iWidth, (UInt)iHeight );
+#endif
+
+    UInt uiDepth = (pcCU->getDepth(0)) + (pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1);
+    pcCU->setWedgePredTexTabIdxSubParts( uiTextureWedgeTabIdx, uiAbsPartIdx, uiDepth );
+  }
+  TComWedgelet* pcWedgelet = &(pacWedgeList->at(uiTextureWedgeTabIdx));
+
+  // get wedge pred DCs
+  Int iPredDC1 = 0;
+  Int iPredDC2 = 0;
+  Int* piMask = pcCU->getPattern()->getAdiOrgBuf( iWidth, iHeight, m_piYuvExt );
+  Int iMaskStride = ( iWidth<<1 ) + 1;
+  piMask += iMaskStride+1;
+  getWedgePredDCs( pcWedgelet, piMask, iMaskStride, iPredDC1, iPredDC2, bAbove, bLeft );
+
+  // assign wedge pred DCs to prediction
+  if( bDelta ) { assignWedgeDCs2Pred( pcWedgelet, piPred, uiStride, Clip ( iPredDC1+iDeltaDC1 ), Clip( iPredDC2+iDeltaDC2 ) ); }
+  else         { assignWedgeDCs2Pred( pcWedgelet, piPred, uiStride,        iPredDC1,                   iPredDC2           ); }
+}
+
+Void TComPrediction::xPredIntraContourTex( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder, Bool bDelta, Int iDeltaDC1, Int iDeltaDC2 )
+{
+  // get contour pattern
+  TComWedgelet* pcContourWedge = new TComWedgelet( iWidth, iHeight );
+  getBestContourFromTex( pcCU, uiAbsPartIdx, (UInt)iWidth, (UInt)iHeight, pcContourWedge );
+
+  // get wedge pred DCs
+  Int iPredDC1 = 0;
+  Int iPredDC2 = 0;
+  Int* piMask = pcCU->getPattern()->getAdiOrgBuf( iWidth, iHeight, m_piYuvExt );
+  Int iMaskStride = ( iWidth<<1 ) + 1;
+  piMask += iMaskStride+1;
+  getWedgePredDCs( pcContourWedge, piMask, iMaskStride, iPredDC1, iPredDC2, bAbove, bLeft );
+
+  // assign wedge pred DCs to prediction
+  if( bDelta ) { assignWedgeDCs2Pred( pcContourWedge, piPred, uiStride, Clip ( iPredDC1+iDeltaDC1 ), Clip( iPredDC2+iDeltaDC2 ) ); }
+  else         { assignWedgeDCs2Pred( pcContourWedge, piPred, uiStride,        iPredDC1,                   iPredDC2           ); }
+
+  pcContourWedge->destroy();
+  delete pcContourWedge;
+}
+#endif // HHI_DMM_PRED_TEX
+
+#if HHI_DMM_WEDGE_INTRA
+UInt TComPrediction::getBestContinueWedge( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Int iDeltaEnd )
+{
+  UInt uiThisBlockSize = uiWidth;
+  assert( uiThisBlockSize >= DMM_WEDGEMODEL_MIN_SIZE && uiThisBlockSize <= DMM_WEDGEMODEL_MAX_SIZE );
+  WedgeRefList* pacContDWedgeRefList = &g_aacWedgeRefLists[(g_aucConvertToBit[uiThisBlockSize])];
+
+  UInt uiPredDirWedgeTabIdx = 0;
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  // 1st: try continue above wedgelet
+  pcTempCU = pcCU->getPUAbove( uiTempPartIdx, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  if( pcTempCU )
+  {
+    UChar uhLumaIntraDir = pcTempCU->getLumaIntraDir( uiTempPartIdx );
+    if( DMM_WEDGE_FULL_IDX      == uhLumaIntraDir || 
+        DMM_WEDGE_FULL_D_IDX    == uhLumaIntraDir || 
+        DMM_WEDGE_PREDDIR_IDX   == uhLumaIntraDir || 
+        DMM_WEDGE_PREDDIR_D_IDX == uhLumaIntraDir
+#if HHI_DMM_PRED_TEX
+        ||
+        DMM_WEDGE_PREDTEX_IDX   == uhLumaIntraDir ||
+        DMM_WEDGE_PREDTEX_D_IDX == uhLumaIntraDir    
+#endif
+      )
+    {
+      UInt uiRefWedgeSize = (UInt)g_aucIntraSizeIdxToWedgeSize[pcTempCU->getIntraSizeIdx( uiTempPartIdx )];
+      WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiRefWedgeSize])];
+
+      // get offset between current and reference block
+      UInt uiOffsetX = 0;
+      UInt uiOffsetY = 0;
+      xGetBlockOffset( pcCU, uiAbsPartIdx, pcTempCU, uiTempPartIdx, uiOffsetX, uiOffsetY );
+
+      // get reference wedgelet
+      UInt uiRefWedgeTabIdx = 0;
+      switch( uhLumaIntraDir )
+      {
+      case( DMM_WEDGE_FULL_IDX      ): { uiRefWedgeTabIdx = pcTempCU->getWedgeFullTabIdx   ( uiTempPartIdx ); } break;
+      case( DMM_WEDGE_FULL_D_IDX    ): { uiRefWedgeTabIdx = pcTempCU->getWedgeFullTabIdx   ( uiTempPartIdx ); } break;
+      case( DMM_WEDGE_PREDDIR_IDX   ): { uiRefWedgeTabIdx = pcTempCU->getWedgePredDirTabIdx( uiTempPartIdx ); } break;
+      case( DMM_WEDGE_PREDDIR_D_IDX ): { uiRefWedgeTabIdx = pcTempCU->getWedgePredDirTabIdx( uiTempPartIdx ); } break;
+#if HHI_DMM_PRED_TEX
+      case( DMM_WEDGE_PREDTEX_IDX   ): { uiRefWedgeTabIdx = pcTempCU->getWedgePredTexTabIdx( uiTempPartIdx ); } break;
+      case( DMM_WEDGE_PREDTEX_D_IDX ): { uiRefWedgeTabIdx = pcTempCU->getWedgePredTexTabIdx( uiTempPartIdx ); } break;
+#endif
+      default: { assert( 0 ); return uiPredDirWedgeTabIdx; }
+      }
+      TComWedgelet* pcRefWedgelet;
+      pcRefWedgelet = &(pacWedgeList->at( uiRefWedgeTabIdx ));
+
+      // find reference wedgelet, if direction is suitable for continue wedge
+      if( pcRefWedgelet->checkPredDirAbovePossible( uiThisBlockSize, uiOffsetX ) )
+      {
+        UChar uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye;
+        pcRefWedgelet->getPredDirStartEndAbove( uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye, uiThisBlockSize, uiOffsetX, iDeltaEnd );
+        getWedgePatternIdx( pacContDWedgeRefList, uiPredDirWedgeTabIdx, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye );
+        return uiPredDirWedgeTabIdx;
+      }
+    }
+  }
+
+  // 2nd: try continue left wedglelet
+  pcTempCU = pcCU->getPULeft( uiTempPartIdx, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  if( pcTempCU )
+  {
+    UChar uhLumaIntraDir = pcTempCU->getLumaIntraDir( uiTempPartIdx );
+    if( DMM_WEDGE_FULL_IDX      == uhLumaIntraDir || 
+        DMM_WEDGE_FULL_D_IDX    == uhLumaIntraDir || 
+        DMM_WEDGE_PREDDIR_IDX   == uhLumaIntraDir || 
+        DMM_WEDGE_PREDDIR_D_IDX == uhLumaIntraDir
+#if HHI_DMM_PRED_TEX
+        ||
+        DMM_WEDGE_PREDTEX_IDX   == uhLumaIntraDir ||
+        DMM_WEDGE_PREDTEX_D_IDX == uhLumaIntraDir    
+#endif
+      )
+    {
+      UInt uiRefWedgeSize = (UInt)g_aucIntraSizeIdxToWedgeSize[pcTempCU->getIntraSizeIdx( uiTempPartIdx )];
+      WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiRefWedgeSize])];
+
+      // get offset between current and reference block
+      UInt uiOffsetX = 0;
+      UInt uiOffsetY = 0;
+      xGetBlockOffset( pcCU, uiAbsPartIdx, pcTempCU, uiTempPartIdx, uiOffsetX, uiOffsetY );
+
+      // get reference wedgelet
+      UInt uiRefWedgeTabIdx = 0;
+      switch( uhLumaIntraDir )
+      {
+      case( DMM_WEDGE_FULL_IDX      ): { uiRefWedgeTabIdx = pcTempCU->getWedgeFullTabIdx   ( uiTempPartIdx ); } break;
+      case( DMM_WEDGE_FULL_D_IDX    ): { uiRefWedgeTabIdx = pcTempCU->getWedgeFullTabIdx   ( uiTempPartIdx ); } break;
+      case( DMM_WEDGE_PREDDIR_IDX   ): { uiRefWedgeTabIdx = pcTempCU->getWedgePredDirTabIdx( uiTempPartIdx ); } break;
+      case( DMM_WEDGE_PREDDIR_D_IDX ): { uiRefWedgeTabIdx = pcTempCU->getWedgePredDirTabIdx( uiTempPartIdx ); } break;
+#if HHI_DMM_PRED_TEX
+      case( DMM_WEDGE_PREDTEX_IDX   ): { uiRefWedgeTabIdx = pcTempCU->getWedgePredTexTabIdx( uiTempPartIdx ); } break;
+      case( DMM_WEDGE_PREDTEX_D_IDX ): { uiRefWedgeTabIdx = pcTempCU->getWedgePredTexTabIdx( uiTempPartIdx ); } break;
+#endif
+      default: { assert( 0 ); return uiPredDirWedgeTabIdx; }
+      }
+      TComWedgelet* pcRefWedgelet;
+      pcRefWedgelet = &(pacWedgeList->at( uiRefWedgeTabIdx ));
+
+      // find reference wedgelet, if direction is suitable for continue wedge
+      if( pcRefWedgelet->checkPredDirLeftPossible( uiThisBlockSize, uiOffsetY ) )
+      {
+        UChar uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye;
+        pcRefWedgelet->getPredDirStartEndLeft( uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye, uiThisBlockSize, uiOffsetY, iDeltaEnd );
+        getWedgePatternIdx( pacContDWedgeRefList, uiPredDirWedgeTabIdx, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye );
+        return uiPredDirWedgeTabIdx;
+      }
+    }
+  }
+
+  // 3rd: (default) make wedglet from intra dir and max slope point
+  Int iSlopeX = 0;
+  Int iSlopeY = 0;
+  UInt uiStartPosX = 0;
+  UInt uiStartPosY = 0;
+  if( xGetWedgeIntraDirPredData( pcCU, uiAbsPartIdx, uiThisBlockSize, iSlopeX, iSlopeY, uiStartPosX, uiStartPosY ) )
+  {
+    UChar uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye;
+    xGetWedgeIntraDirStartEnd( pcCU, uiAbsPartIdx, uiThisBlockSize, iSlopeX, iSlopeY, uiStartPosX, uiStartPosY, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye, iDeltaEnd );
+    getWedgePatternIdx( pacContDWedgeRefList, uiPredDirWedgeTabIdx, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye );
+    return uiPredDirWedgeTabIdx;
+  }
+
+  return uiPredDirWedgeTabIdx;
+}
+
+Bool TComPrediction::getWedgePatternIdx( WedgeRefList* pcWedgeRefList, UInt& ruiTabIdx, UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe )
+{
+  ruiTabIdx = 0;
+
+  for( UInt uiIdx = 0; uiIdx < pcWedgeRefList->size(); uiIdx++ )
+  {
+    TComWedgeRef* pcTestWedgeRef = &(pcWedgeRefList->at(uiIdx));
+
+    if( pcTestWedgeRef->getStartX() == uhXs &&
+      pcTestWedgeRef->getStartY() == uhYs &&
+      pcTestWedgeRef->getEndX()   == uhXe &&
+      pcTestWedgeRef->getEndY()   == uhYe    )
+    {
+      ruiTabIdx = pcTestWedgeRef->getRefIdx();
+      return true;
+    }
+  }
+
+  return false;
+}
+
+Void TComPrediction::xPredIntraWedgeFull( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder, Bool bDelta, UInt uiTabIdx, Int iDeltaDC1, Int iDeltaDC2 )
+{
+  assert( iWidth >= DMM_WEDGEMODEL_MIN_SIZE && iWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[iWidth])];
+  TComWedgelet* pcWedgelet = &(pacWedgeList->at(uiTabIdx));
+
+  // get wedge pred DCs
+  Int iPredDC1 = 0;
+  Int iPredDC2 = 0;
+
+  Int* piMask = pcCU->getPattern()->getAdiOrgBuf( iWidth, iHeight, m_piYuvExt );
+  Int iMaskStride = ( iWidth<<1 ) + 1;
+  piMask += iMaskStride+1;
+  getWedgePredDCs( pcWedgelet, piMask, iMaskStride, iPredDC1, iPredDC2, bAbove, bLeft );
+
+  // assign wedge pred DCs to prediction
+  if( bDelta ) { assignWedgeDCs2Pred( pcWedgelet, piPred, uiStride, Clip( iPredDC1+iDeltaDC1 ), Clip( iPredDC2+iDeltaDC2 ) ); }
+  else         { assignWedgeDCs2Pred( pcWedgelet, piPred, uiStride, iPredDC1,           iPredDC2           ); }
+}
+
+Void TComPrediction::xPredIntraWedgeDir( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder, Bool bDelta, Int iWedgeDeltaEnd, Int iDeltaDC1, Int iDeltaDC2 )
+{
+  assert( iWidth >= DMM_WEDGEMODEL_MIN_SIZE && iWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[iWidth])];
+
+  // get wedge pattern
+  UInt uiDirWedgeTabIdx = 0;
+  if( bEncoder )
+  {
+    // encoder: load stored wedge pattern from CU
+    uiDirWedgeTabIdx = pcCU->getWedgePredDirTabIdx( uiAbsPartIdx );
+  }
+  else
+  {
+    uiDirWedgeTabIdx = getBestContinueWedge( pcCU, uiAbsPartIdx, iWidth, iHeight, iWedgeDeltaEnd );
+
+    UInt uiDepth = (pcCU->getDepth(0)) + (pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1);
+    pcCU->setWedgePredDirTabIdxSubParts( uiDirWedgeTabIdx, uiAbsPartIdx, uiDepth );
+  }
+  TComWedgelet* pcWedgelet = &(pacWedgeList->at(uiDirWedgeTabIdx));
+
+  // get wedge pred DCs
+  Int iPredDC1 = 0;
+  Int iPredDC2 = 0;
+
+  Int* piMask = pcCU->getPattern()->getAdiOrgBuf( iWidth, iHeight, m_piYuvExt );
+  Int iMaskStride = ( iWidth<<1 ) + 1;
+  piMask += iMaskStride+1;
+  getWedgePredDCs( pcWedgelet, piMask, iMaskStride, iPredDC1, iPredDC2, bAbove, bLeft );
+
+  // assign wedge pred DCs to prediction
+  if( bDelta ) { assignWedgeDCs2Pred( pcWedgelet, piPred, uiStride, Clip( iPredDC1+iDeltaDC1 ), Clip( iPredDC2+iDeltaDC2 ) ); }
+  else         { assignWedgeDCs2Pred( pcWedgelet, piPred, uiStride,       iPredDC1,                   iPredDC2             ); }
+}
+
+Void TComPrediction::xGetBlockOffset( TComDataCU* pcCU, UInt uiAbsPartIdx, TComDataCU* pcRefCU, UInt uiRefAbsPartIdx, UInt& ruiOffsetX, UInt& ruiOffsetY )
+{
+  ruiOffsetX = 0;
+  ruiOffsetY = 0;
+
+  // get offset between current and above/left block
+  UInt uiThisOriginX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiThisOriginY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+
+  UInt uiNumPartInRefCU = pcRefCU->getTotalNumPart();
+  UInt uiMaxDepthRefCU = 0;
+  while( uiNumPartInRefCU > 1 )
+  {
+    uiNumPartInRefCU >>= 2;
+    uiMaxDepthRefCU++;
+  }
+
+  UInt uiDepthRefPU = (pcRefCU->getDepth(uiRefAbsPartIdx)) + (pcRefCU->getPartitionSize(uiRefAbsPartIdx) == SIZE_2Nx2N ? 0 : 1);
+  UInt uiShifts = (uiMaxDepthRefCU - uiDepthRefPU)*2;
+  UInt uiRefBlockOriginPartIdx = (uiRefAbsPartIdx>>uiShifts)<<uiShifts;
+
+  UInt uiRefOriginX = pcRefCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiRefBlockOriginPartIdx] ];
+  UInt uiRefOriginY = pcRefCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiRefBlockOriginPartIdx] ];
+
+  if( (uiThisOriginX - uiRefOriginX) > 0 ) { ruiOffsetX = (UInt)(uiThisOriginX - uiRefOriginX); }
+  if( (uiThisOriginY - uiRefOriginY) > 0 ) { ruiOffsetY = (UInt)(uiThisOriginY - uiRefOriginY); }
+}
+
+Bool TComPrediction::xGetWedgeIntraDirPredData( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiBlockSize, Int& riSlopeX, Int& riSlopeY, UInt& ruiStartPosX, UInt& ruiStartPosY )
+{
+  riSlopeX     = 0;
+  riSlopeY     = 0;
+  ruiStartPosX = 0;
+  ruiStartPosY = 0;
+
+  // 1st step: get wedge start point (max. slope)
+  Int* piSource = pcCU->getPattern()->getAdiOrgBuf( uiBlockSize, uiBlockSize, m_piYuvExt );
+  Int iSourceStride = ( uiBlockSize<<1 ) + 1;
+
+  UInt uiSlopeMaxAbove = 0;
+  UInt uiPosSlopeMaxAbove = 0;
+  for( UInt uiPosHor = 0; uiPosHor < (uiBlockSize-1); uiPosHor++ )
+  {
+    if( abs( piSource[uiPosHor+1] - piSource[uiPosHor] ) > uiSlopeMaxAbove )
+    {
+      uiSlopeMaxAbove = abs( piSource[uiPosHor+1] - piSource[uiPosHor] );
+      uiPosSlopeMaxAbove = uiPosHor;
+    }
+  }
+
+  UInt uiSlopeMaxLeft = 0;
+  UInt uiPosSlopeMaxLeft = 0;
+  for( UInt uiPosVer = 0; uiPosVer < (uiBlockSize-1); uiPosVer++ )
+  {
+    if( abs( piSource[(uiPosVer+1)*iSourceStride] - piSource[uiPosVer*iSourceStride] ) > uiSlopeMaxLeft )
+    {
+      uiSlopeMaxLeft = abs( piSource[(uiPosVer+1)*iSourceStride] - piSource[uiPosVer*iSourceStride] );
+      uiPosSlopeMaxLeft = uiPosVer;
+    }
+  }
+
+  if( uiSlopeMaxAbove == 0 && uiSlopeMaxLeft == 0 ) 
+  { 
+    return false; 
+  }
+
+  if( uiSlopeMaxAbove > uiSlopeMaxLeft )
+  {
+    ruiStartPosX = uiPosSlopeMaxAbove;
+    ruiStartPosY = 0;
+  }
+  else
+  {
+    ruiStartPosX = 0;
+    ruiStartPosY = uiPosSlopeMaxLeft;
+  }
+
+  // 2nd step: derive wedge direction
+  Int uiPreds[3] = {-1, -1, -1};
+  Int iMode = -1;
+  Int iPredNum = pcCU->getIntraDirLumaPredictor( uiAbsPartIdx, uiPreds, &iMode );  
+
+  UInt uiDirMode = 0;
+  if( iMode >= 0 ) { iPredNum = iMode; }
+  if( iPredNum == 1 ) { uiDirMode = uiPreds[0]; }
+  if( iPredNum == 2 ) { uiDirMode = uiPreds[1]; }
+
+  if( uiDirMode < 2 ) { return false; } // no planar & DC
+
+  Bool modeHor       = (uiDirMode < 18);
+  Bool modeVer       = !modeHor;
+  Int intraPredAngle = modeVer ? (Int)uiDirMode - VER_IDX : modeHor ? -((Int)uiDirMode - HOR_IDX) : 0;
+  Int absAng         = abs(intraPredAngle);
+  Int signAng        = intraPredAngle < 0 ? -1 : 1;
+  Int angTable[9]    = {0,2,5,9,13,17,21,26,32};
+  absAng             = angTable[absAng];
+  intraPredAngle     = signAng * absAng;
+
+  // 3rd step: set slope for direction
+  if( modeHor )
+  {
+    if( intraPredAngle > 0 )
+    {
+      riSlopeX = -32;
+      riSlopeY = intraPredAngle;
+    }
+    else
+    {
+      riSlopeX = 32;
+      riSlopeY = -intraPredAngle;
+    }
+  }
+  else if( modeVer )
+  {
+    if( intraPredAngle > 0 )
+    {
+      riSlopeX = intraPredAngle;
+      riSlopeY = -32;
+    }
+    else
+    {
+      riSlopeX = -intraPredAngle;
+      riSlopeY = 32;
+    }
+  }
+
+  return true;
+}
+
+Void TComPrediction::xGetWedgeIntraDirStartEnd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiBlockSize, Int iDeltaX, Int iDeltaY, UInt uiPMSPosX, UInt uiPMSPosY, UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, Int iDeltaEnd )
+{
+  ruhXs = 0;
+  ruhYs = 0;
+  ruhXe = 0;
+  ruhYe = 0;
+
+  // scaling of start pos and block size to wedge resolution
+  UInt uiScaledStartPosX = 0;
+  UInt uiScaledStartPosY = 0;
+  UInt uiScaledBlockSize = 0;
+  WedgeResolution eWedgeRes = g_aeWedgeResolutionList[(UInt)g_aucConvertToBit[uiBlockSize]];
+  switch( eWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiScaledStartPosX = (uiPMSPosX>>1); uiScaledStartPosY = (uiPMSPosY>>1); uiScaledBlockSize = (uiBlockSize>>1); break; }
+  case(   FULL_PEL ): { uiScaledStartPosX =  uiPMSPosX;     uiScaledStartPosY =  uiPMSPosY;     uiScaledBlockSize =  uiBlockSize;     break; }
+  case(   HALF_PEL ): { uiScaledStartPosX = (uiPMSPosX<<1); uiScaledStartPosY = (uiPMSPosY<<1); uiScaledBlockSize = (uiBlockSize<<1); break; }
+  }
+  Int iMaxPos = (Int)uiScaledBlockSize - 1;
+
+  // case above
+  if( uiScaledStartPosX > 0 && uiScaledStartPosY == 0 )
+  {
+    ruhXs = (UChar)uiScaledStartPosX;
+    ruhYs = 0;
+
+    if( iDeltaY == 0 )
+    {
+      if( iDeltaX < 0 )
+      {
+        ruhXe = 0;
+        ruhYe = (UChar)std::min( std::max( iDeltaEnd, 0 ), iMaxPos );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::min( std::max( -iDeltaEnd, 0 ), iMaxPos );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+
+    // regular case
+    Int iVirtualEndX = (Int)ruhXs + roftoi( (Double)iMaxPos * ((Double)iDeltaX / (Double)iDeltaY) );
+
+    if( iVirtualEndX < 0 )
+    {
+      Int iYe = roftoi( (Double)(0 - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) + iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = 0;
+        ruhYe = (UChar)std::max( iYe, 0 );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)std::min( (iYe - iMaxPos), iMaxPos );
+        ruhYe = (UChar)iMaxPos;
+        return;
+      }
+    }
+    else if( iVirtualEndX > iMaxPos )
+    {
+      Int iYe = roftoi( (Double)(iMaxPos - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) - iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::max( iYe, 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)std::max( (iMaxPos - (iYe - iMaxPos)), 0 );
+        ruhYe = (UChar)iMaxPos;
+        return;
+      }
+    }
+    else
+    {
+      Int iXe = iVirtualEndX + iDeltaEnd;
+      if( iXe < 0 )
+      {
+        ruhXe = 0;
+        ruhYe = (UChar)std::max( (iMaxPos + iXe), 0 );
+        return;
+      }
+      else if( iXe > iMaxPos )
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::max( (iMaxPos - (iXe - iMaxPos)), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iXe;
+        ruhYe = (UChar)iMaxPos;
+        return;
+      }
+    }
+  }
+
+  // case left
+  if( uiScaledStartPosY > 0 && uiScaledStartPosX == 0 )
+  {
+    ruhXs = 0;
+    ruhYs = (UChar)uiScaledStartPosY;
+
+    if( iDeltaX == 0 )
+    {
+      if( iDeltaY < 0 )
+      {
+        ruhXe = (UChar)std::min( std::max( -iDeltaEnd, 0 ), iMaxPos );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)std::min( std::max( iDeltaEnd, 0 ), iMaxPos );
+        ruhYe = (UChar)iMaxPos;
+        return; 
+      }
+    }
+
+    // regular case
+    Int iVirtualEndY = (Int)ruhYs + roftoi( (Double)iMaxPos * ((Double)iDeltaY / (Double)iDeltaX) );
+
+    if( iVirtualEndY < 0 )
+    {
+      Int iXe = roftoi( (Double)(0 - (Int)ruhYs ) * ((Double)iDeltaX / (Double)iDeltaY) ) - iDeltaEnd;
+      if( iXe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = (UChar)std::max( iXe, 0 );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::min( (iXe - iMaxPos), iMaxPos );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+    else if( iVirtualEndY > (uiScaledBlockSize-1) )
+    {
+      Int iXe = roftoi( (Double)((Int)(uiScaledBlockSize-1) - (Int)ruhYs ) * ((Double)iDeltaX / (Double)iDeltaY) ) + iDeltaEnd;
+      if( iXe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = (UChar)std::max( iXe, 0 );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::max( (iMaxPos - (iXe - iMaxPos)), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+    else
+    {
+      Int iYe = iVirtualEndY - iDeltaEnd;
+      if( iYe < 0 )
+      {
+        ruhXe = (UChar)std::max( (iMaxPos + iYe), 0 );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else if( iYe > iMaxPos )
+      {
+        ruhXe = (UChar)std::max( (iMaxPos - (iYe - iMaxPos)), 0 );
+        ruhYe = (UChar)iMaxPos;
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)iYe;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+  }
+
+  // case origin
+  if( uiScaledStartPosX == 0 && uiScaledStartPosY == 0 )
+  {
+    if( iDeltaX*iDeltaY < 0 )
+    {
+      return;
+    }
+
+    ruhXs = 0;
+    ruhYs = 0;
+
+    if( iDeltaY == 0 )
+    {
+      ruhXe = (UChar)iMaxPos;
+      ruhYe = 0;
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+
+    if( iDeltaX == 0 )
+    {
+      ruhXe = 0;
+      ruhYe = (UChar)iMaxPos;
+      return;
+    }
+
+    Int iVirtualEndX = (Int)ruhXs + roftoi( (Double)iMaxPos * ((Double)iDeltaX / (Double)iDeltaY) );
+
+    if( iVirtualEndX > iMaxPos )
+    {
+      Int iYe = roftoi( (Double)((Int)iMaxPos - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) - iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)std::max( iYe, 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)std::max( (iMaxPos - (iYe - iMaxPos)), 0 );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+    else
+    {
+      Int iXe = iVirtualEndX + iDeltaEnd;
+      if( iXe < 0 )
+      {
+        ruhXe = 0;
+        ruhYe = (UChar)std::max( (iMaxPos + iXe), 0 );
+        return;
+      }
+      else if( iXe > iMaxPos )
+      {
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)std::max( (iMaxPos - (iXe - iMaxPos)), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iXe;
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+  }
+}
+#endif
+
+Void 
+TComPrediction::predIntraDepthAng(TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight )
+{
+  Pel*  pDst    = piPred;
+  Int*  ptrSrc  = pcTComPattern->getAdiOrgBuf( iWidth, iHeight, m_piYuvExt );
+  Int   sw      = ( iWidth<<1 ) + 1;
+  xPredIntraAngDepth( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode );
+}
+
+Int
+TComPrediction::xGetDCDepth( Int* pSrc, Int iDelta, Int iBlkSize )
+{
+  Int iDC    = PDM_UNDEFINED_DEPTH;
+  Int iSum   = 0;
+  Int iNum   = 0;
+  for( Int k = 0; k < iBlkSize; k++, pSrc += iDelta )
+  {
+    if( *pSrc != PDM_UNDEFINED_DEPTH )
+    {
+      iSum += *pSrc;
+      iNum ++;
+    }
+  }
+  if( iNum )
+  {
+    iDC = ( iSum + ( iNum >> 1 ) ) / iNum;
+  }
+  return iDC;
+}
+
+Int
+TComPrediction::xGetDCValDepth( Int iVal1, Int iVal2, Int iVal3, Int iVal4 )
+{
+  if     ( iVal1 != PDM_UNDEFINED_DEPTH )   return iVal1;
+  else if( iVal2 != PDM_UNDEFINED_DEPTH )   return iVal2;
+  else if( iVal3 != PDM_UNDEFINED_DEPTH )   return iVal3;
+  return   iVal4;
+}
+
+Void 
+TComPrediction::xPredIntraAngDepth( Int* pSrc, Int srcStride, Pel* pDst, Int dstStride, UInt width, UInt height, UInt dirMode )
+{
+  AOF( width == height );
+  Int blkSize       = width;
+  Int iDCAbove      = xGetDCDepth( pSrc - srcStride,                               1, blkSize );
+  Int iDCAboveRight = xGetDCDepth( pSrc - srcStride + blkSize,                     1, blkSize );
+  Int iDCLeft       = xGetDCDepth( pSrc -         1,                       srcStride, blkSize );
+  Int iDCBelowLeft  = xGetDCDepth( pSrc -         1 + blkSize * srcStride, srcStride, blkSize );
+  Int iWgt, iDC1, iDC2;
+  if( dirMode < 2 ) // 1..2
+  {
+    iDC1  = xGetDCValDepth( iDCAbove, iDCAboveRight, iDCLeft,  iDCBelowLeft  );
+    iDC2  = xGetDCValDepth( iDCLeft,  iDCBelowLeft,  iDCAbove, iDCAboveRight );
+    iWgt  = 8;
+  }
+  else if( dirMode < 11 ) // 3..10
+  {
+    iDC1  = xGetDCValDepth( iDCLeft,  iDCBelowLeft,  iDCAbove, iDCAboveRight );
+    iDC2  = xGetDCValDepth( iDCBelowLeft,  iDCLeft,  iDCAbove, iDCAboveRight );
+    iWgt  = 6 + dirMode; 
+  }
+  else if( dirMode < 27 ) // 11..26
+  {
+    iDC1  = xGetDCValDepth( iDCAbove, iDCAboveRight, iDCLeft,  iDCBelowLeft  );
+    iDC2  = xGetDCValDepth( iDCLeft,  iDCBelowLeft,  iDCAbove, iDCAboveRight );
+    iWgt  = dirMode - 10;
+  }
+  else if( dirMode < 35 ) // 27..34
+  {
+    iDC1  = xGetDCValDepth( iDCAbove, iDCAboveRight, iDCLeft,  iDCBelowLeft  );
+    iDC2  = xGetDCValDepth( iDCAboveRight, iDCAbove, iDCLeft,  iDCBelowLeft  );
+    iWgt  = 42 - dirMode;
+  }
+  else // (wedgelet -> use simple DC prediction
+  {
+    iDC1  = xGetDCValDepth( iDCAbove, iDCAboveRight, iDCLeft,  iDCBelowLeft  );
+    iDC2  = xGetDCValDepth( iDCLeft,  iDCBelowLeft,  iDCAbove, iDCAboveRight );
+    iWgt  = 8;
+  }
+  Int iWgt2   = 16 - iWgt;
+  Int iDCVal  = ( iWgt * iDC1 + iWgt2 * iDC2 + 8 ) >> 4;
+
+  // set depth
+  for( Int iY = 0; iY < blkSize; iY++, pDst += dstStride )
+  {
+    for( Int iX = 0; iX < blkSize; iX++ )
+    {
+      pDst[ iX ] = iDCVal;
+    }
+  }
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPrediction.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComPrediction.h	(revision 341)
@@ -0,0 +1,226 @@
+/* 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-2012, 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     TComPrediction.h
+    \brief    prediction class (header)
+*/
+
+#ifndef __TCOMPREDICTION__
+#define __TCOMPREDICTION__
+
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+#include "TComPattern.h"
+#include "TComTrQuant.h"
+#include "TComInterpolationFilter.h"
+#include "TComWeightPrediction.h"
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#include <math.h>
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// prediction class
+class TComPrediction : public TComWeightPrediction
+{
+protected:
+  Int*      m_piYuvExt;
+  Int       m_iYuvExtStride;
+  Int       m_iYuvExtHeight;
+  
+  TComYuv   m_acYuvPred[2];
+  TComYuv   m_cYuvPredTemp;
+  TComYuv m_filteredBlock[4][4];
+  TComYuv m_filteredBlockTmp[4];
+  
+  TComInterpolationFilter m_if;
+  
+  Pel*   m_pLumaRecBuffer;       ///< array for downsampled reconstructed luma sample 
+  Int    m_iLumaRecStride;       ///< stride of #m_pLumaRecBuffer array
+  UInt   m_uiaShift[ 63 ];       // Table for multiplication to substitue of division operation
+
+#if MERL_VSP_C0152
+  Int*   m_pDepth; ///< Local variable, to store a depth block, just to prevent allocate memory every time
+#endif
+
+  Void xPredIntraAng            ( 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 );
+  
+  // motion compensation functions
+#if MERL_VSP_C0152
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,       UInt uiAbsPartIdx,        Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap, UInt uiSubSampExpX = 0, UInt uiSubSampExpY = 0, Bool bi=false );
+#else
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap, UInt uiSubSampExpX = 0, UInt uiSubSampExpY = 0, Bool bi=false );
+#endif
+
+#if MERL_VSP_C0152
+  Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,       UInt uiAbsPartIdx,   Int iWidth, Int iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap );
+#else
+  Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap );
+#endif
+  Void xPredInterPrdDepthMap    ( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY, TComYuv*& rpcYuv, UInt uiRShift, UInt uiOffset 
+#if LGE_ILLUCOMP_DEPTH_C0046
+      , Bool bICFlag = false
+#endif
+      );
+
+#if MERL_VSP_C0152
+  Void xPredInterUniBWVSP         ( TComDataCU* pcCU,                          UInt uiPartAddr, UInt uiAbsPartIdx,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap, UInt uiSubSampExpX, UInt uiSubSampExpY, Bool bi=false );
+  Void xPredInterBiBWVSP          ( TComDataCU* pcCU,                          UInt uiPartAddr, UInt uiAbsPartIdx,               Int iWidth, Int iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap );
+#endif
+
+#if DEPTH_MAP_GENERATION
+  Void xWeightedAveragePdm      ( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst, UInt uiSubSampExpX, UInt uiSubSampExpY );
+#endif
+
+#if LGE_ILLUCOMP_B0045
+  Void xPredInterLumaBlk  ( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi, Bool bICFlag = false );
+  Void xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi, Bool bICFlag = false );
+#else
+  Void xPredInterLumaBlk  ( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi );
+  Void xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi );
+#endif
+  Void xWeightedAverage         ( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst );
+
+#if MERL_VSP_C0152
+  Void xPredInterLumaBlkFromDM    ( TComPicYuv *refPic, TComPicYuv *pPicBaseDepth, Int* pShiftLUT, Int iShiftPrec, TComMv *mv, UInt partAddr,Int posX, Int posY, Int size_x, Int size_y, Bool isDepth, Int vspIdx
+                                  , TComYuv *&dstPic );
+  Void xPredInterChromaBlkFromDM  ( TComPicYuv *refPic, TComPicYuv *pPicBaseDepth, Int* pShiftLUT, Int iShiftPrec, TComMv *mv, UInt partAddr,Int posX, Int posY, Int size_x, Int size_y, Bool isDepth, Int vspIdx
+                                  , TComYuv *&dstPic );
+#endif
+  Void xGetLLSPrediction ( TComPattern* pcPattern, Int* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0 );
+#if LGE_ILLUCOMP_B0045
+  Void xGetLLSICPrediction(TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, Int &iShift);
+  Void xGetLLSICPredictionChroma(TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, Int &iShift, Int iChromaId);
+#endif
+  Void xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight );
+  Bool xCheckIdenticalMotion    ( TComDataCU* pcCU, UInt PartAddr);
+
+#if HHI_DMM_WEDGE_INTRA
+  Void xPredIntraWedgeFull       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder, Bool bDelta, UInt uiTabIdx, Int iDeltaDC1 = 0, Int iDeltaDC2 = 0 );
+  Void xPredIntraWedgeDir        ( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder, Bool bDelta, Int iWedgeDeltaEnd, Int iDeltaDC1 = 0, Int iDeltaDC2 = 0 );
+  Void xGetBlockOffset           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComDataCU* pcRefCU, UInt uiRefAbsPartIdx, UInt& ruiOffsetX, UInt& ruiOffsetY );
+  Bool xGetWedgeIntraDirPredData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiBlockSize, Int& riSlopeX, Int& riSlopeY, UInt& ruiStartPosX, UInt& ruiStartPosY );
+  Void xGetWedgeIntraDirStartEnd ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiBlockSize, Int iDeltaX, Int iDeltaY, UInt uiPMSPosX, UInt uiPMSPosY, UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, Int iDeltaEnd = 0 );
+#endif
+#if HHI_DMM_PRED_TEX
+  Void xPredIntraWedgeTex        ( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder, Bool bDelta, Int iDeltaDC1 = 0, Int iDeltaDC2 = 0 );
+  Void xPredIntraContourTex      ( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder, Bool bDelta, Int iDeltaDC1 = 0, Int iDeltaDC2 = 0 );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void xDeltaDCQuantScaleUp      ( TComDataCU* pcCU, Int& riDeltaDC );
+  Void xDeltaDCQuantScaleDown    ( TComDataCU* pcCU, Int& riDeltaDC );
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+  Pel  xGetNearestNeighbor  ( Int x, Int y, Int* pSrc, Int srcStride, Int iWidth, Int iHeight, Bool* bpRegion );
+  Void xPredIntraEdge       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Int iWidth, Int iHeight, Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, Bool bDelta = false );
+#endif
+
+public:
+  TComPrediction();
+  virtual ~TComPrediction();
+  
+  Void    initTempBuff();
+  
+  // inter
+#if MERL_VSP_C0152
+  Void motionCompensation         ( TComDataCU*  pcCU, TComYuv* pcYuvPred, UInt uiAbsPartIdx, RefPicList eRefPicList = REF_PIC_LIST_X, Int iPartIdx = -1, Bool bPrdDepthMap = false, UInt uiSubSampExpX = 0, UInt uiSubSampExpY = 0 );
+#else
+  Void motionCompensation         ( TComDataCU*  pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList = REF_PIC_LIST_X, Int iPartIdx = -1, Bool bPrdDepthMap = false, UInt uiSubSampExpX = 0, UInt uiSubSampExpY = 0 );
+#endif
+
+#if H3D_IVRP
+  Void residualPrediction         (TComDataCU* pcCU, TComYuv* pcYuvPred, TComYuv* pcYuvResPred);
+#endif
+
+  // motion vector prediction
+  Void getMvPredAMVP              ( TComDataCU* pcCU, UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred );
+  
+  // Angular Intra
+  Void predIntraLumaAng           ( TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight,  TComDataCU* pcCU, Bool bAbove, Bool bLeft );
+  Void predIntraChromaAng         ( TComPattern* pcTComPattern, Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, TComDataCU* pcCU, Bool bAbove, Bool bLeft );
+  
+  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; }
+
+  Void predLMIntraChroma( TComPattern* pcPattern, Int* piSrc, Pel* pPred, UInt uiPredStride, UInt uiCWidth, UInt uiCHeight, UInt uiChromaId );
+  Void getLumaRecPixels  ( TComPattern* pcPattern, UInt uiWidth0, UInt uiHeight0 );
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void  predIntraLumaDMM        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft, Bool bEncoder );
+
+  Void  getWedgePredDCs         ( TComWedgelet* pcWedgelet, Int* piMask, Int iMaskStride, Int& riPredDC1, Int& riPredDC2, Bool bAbove, Bool bLeft );
+  Void  calcWedgeDCs            ( TComWedgelet* pcWedgelet, Pel* piOrig, UInt uiStride, Int& riDC1, Int& riDC2 );
+  Void  assignWedgeDCs2Pred     ( TComWedgelet* pcWedgelet, Pel* piPred,  UInt uiStride, Int   iDC1, Int   iDC2 );
+#endif
+#if HHI_DMM_PRED_TEX
+  Void  getBestContourFromTex   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, TComWedgelet* pcContourWedge );
+#if LGE_DMM3_SIMP_C0044
+  UInt  getBestWedgeFromTex     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Pel * piOrgi, UInt uiStride, UInt &ruiIntraTabIdx);//encoder
+  UInt  getBestWedgeFromTex     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt IntraTabIdx);//decoder
+#else 
+  UInt  getBestWedgeFromTex     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight );
+#endif
+  Void  copyTextureLumaBlock    ( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piDestBlockY, UInt uiWidth, UInt uiHeight );
+#endif
+#if HHI_DMM_WEDGE_INTRA
+  UInt  getBestContinueWedge    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Int iDeltaEnd = 0 );
+  Bool  getWedgePatternIdx      ( WedgeRefList* pcWedgeRefList, UInt& ruiTabIdx, UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe );
+#endif
+#if LGE_EDGE_INTRA_A0070
+  Void predIntraLumaEdge          ( TComDataCU* pcCU, TComPattern* pcTComPattern, UInt uiAbsPartIdx, Int iWidth, Int iHeight, Pel* piPred, UInt uiStride, Bool bDelta = false );
+#endif
+
+  // simplified intra pred for "virtual" depth maps
+  Void  predIntraDepthAng ( TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight );
+  Int   xGetDCDepth       ( Int* pSrc, Int iDelta, Int iBlkSize );
+  Int   xGetDCValDepth    ( Int iVal1, Int iVal2, Int iVal3, Int iVal4 );
+  Void  xPredIntraAngDepth( Int* pSrc, Int srcStride, Pel* pDst, Int dstStride, UInt width, UInt height, UInt dirMode );
+
+};
+
+//! \}
+
+#endif // __TCOMPREDICTION__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCost.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCost.cpp	(revision 341)
@@ -0,0 +1,4401 @@
+/* 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-2012, 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     TComRdCost.cpp
+    \brief    RD cost computation class
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRom.h"
+#include "TComRdCost.h"
+#include "TComDataCU.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#if SAIT_VSO_EST_A0033
+Double TComRdCost::m_dDisparityCoeff = 1.0;
+#endif
+
+TComRdCost::TComRdCost()
+{
+  init();
+}
+
+TComRdCost::~TComRdCost()
+{
+#if !FIX203
+  xUninit();
+#endif
+}
+
+// Calculate RD functions
+Double TComRdCost::calcRdCost( UInt uiBits, UInt uiDistortion, Bool bFlag, DFunc eDFunc )
+{
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;
+  
+  switch ( eDFunc )
+  {
+    case DF_SSE:
+      assert(0);
+      break;
+    case DF_SAD:
+      dLambda = (Double)m_uiLambdaMotionSAD;
+      break;
+    case DF_DEFAULT:
+      dLambda =         m_dLambda;
+      break;
+    case DF_SSE_FRAME:
+      dLambda =         m_dFrameLambda;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  dLambda = m_dLambdaScale * dLambda ;
+#endif
+  if (bFlag)
+  {
+    // Intra8x8, Intra4x4 Block only...
+#if LOSSLESS_CODING && SEQUENCE_LEVEL_LOSSLESS
+    dRdCost = (Double)(uiBits);
+#else
+    dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
+#endif
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+    }
+    else
+    {
+#if LOSSLESS_CODING && SEQUENCE_LEVEL_LOSSLESS
+      dRdCost = (Double)(uiBits);
+#else
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+#endif
+    }
+  }
+  
+  return dRdCost;
+}
+
+Double TComRdCost::calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag, DFunc eDFunc )
+{
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;
+  
+  switch ( eDFunc )
+  {
+    case DF_SSE:
+      assert(0);
+      break;
+    case DF_SAD:
+      dLambda = (Double)m_uiLambdaMotionSAD;
+      break;
+    case DF_DEFAULT:
+      dLambda =         m_dLambda;
+      break;
+    case DF_SSE_FRAME:
+      dLambda =         m_dFrameLambda;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  if (bFlag)
+  {
+    // Intra8x8, Intra4x4 Block only...
+#if LOSSLESS_CODING && SEQUENCE_LEVEL_LOSSLESS
+    dRdCost = (Double)(uiBits);
+#else
+    dRdCost = (((Double)(Int64)uiDistortion) + ((Double)(Int64)uiBits * dLambda));
+#endif
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+    }
+    else
+    {
+#if LOSSLESS_CODING && SEQUENCE_LEVEL_LOSSLESS
+      dRdCost = (Double)(uiBits);
+#else
+      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+#endif
+    }
+  }
+  
+  return dRdCost;
+}
+
+Void TComRdCost::setLambda( Double dLambda )
+{
+  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 H3D_IVMP
+Void
+TComRdCost::setLambdaMVReg( Double dLambda )
+{
+  m_uiLambdaMVRegSAD = (UInt)floor( 65536.0 * sqrt( dLambda ) );
+  m_uiLambdaMVRegSSE = (UInt)floor( 65536.0 *       dLambda   );
+}
+#endif
+
+// Initalize Function Pointer by [eDFunc]
+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 SAIT_VSO_EST_A0033
+  m_afpDistortFunc[29]  = TComRdCost::xGetVSD;
+  m_afpDistortFunc[30]  = TComRdCost::xGetVSD4;
+  m_afpDistortFunc[31]  = TComRdCost::xGetVSD8;
+  m_afpDistortFunc[32]  = TComRdCost::xGetVSD16;
+  m_afpDistortFunc[33]  = TComRdCost::xGetVSD32;
+  m_afpDistortFunc[34]  = TComRdCost::xGetVSD64;
+  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;
+
+#if HHI_VSO
+  m_apRefPics               = NULL;
+  m_paaiShiftLUTs           = NULL; 
+  m_uiNumberRefPics         = 0;
+  m_bUseVSO                 = false;
+#if SAIT_VSO_EST_A0033
+  m_bUseEstimatedVSD        = false; 
+#endif
+  m_uiVSOMode               = 0; 
+  m_fpDistortFuncVSO        = NULL; 
+  m_pcRenModel              = NULL; 
+#endif
+
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  m_dLambdaScale            = 1;
+#endif
+#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 ];
+    m_puiMultiviewRegCostHorOrgP  = new UInt[ 4 * iSubPelSearchLimit ];
+    m_puiMultiviewRegCostVerOrgP  = new UInt[ 4 * iSubPelSearchLimit ];
+
+    iSubPelSearchLimit *= 2;
+    
+    m_puiComponentCost = m_puiComponentCostOriginP + iSubPelSearchLimit;
+
+    m_puiMultiviewRegCostHor = m_puiMultiviewRegCostHorOrgP + iSubPelSearchLimit;
+    m_puiMultiviewRegCostVer = m_puiMultiviewRegCostVerOrgP + iSubPelSearchLimit;
+
+    
+    for( Int n = -iSubPelSearchLimit; n < iSubPelSearchLimit; n++)
+    {
+      m_puiComponentCost[n] = xGetComponentBits( n );
+      m_puiMultiviewRegCostHor[n] = xGetComponentBits( n );  // first version
+      m_puiMultiviewRegCostVer[n] = xGetComponentBits( n );  // first version
+    }
+  }
+}
+
+Void TComRdCost::xUninit()
+{
+  if( NULL != m_puiComponentCostOriginP )
+  {
+    delete [] m_puiComponentCostOriginP;
+    m_puiComponentCostOriginP = NULL;
+  }
+
+  if( m_puiMultiviewRegCostHorOrgP )
+    {
+      delete [] m_puiMultiviewRegCostHorOrgP;
+      m_puiMultiviewRegCostHorOrgP = NULL;
+    }
+  if( m_puiMultiviewRegCostVerOrgP )
+  {
+    delete [] m_puiMultiviewRegCostVerOrgP;
+    m_puiMultiviewRegCostVerOrgP = NULL;
+  }
+}
+#endif
+
+UInt TComRdCost::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;
+}
+
+Void TComRdCost::setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam )
+{
+  // set Block Width / Height
+  rcDistParam.iCols    = uiBlkWidth;
+  rcDistParam.iRows    = uiBlkHeight;
+  rcDistParam.DistFunc = m_afpDistortFunc[eDFunc + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  
+  // initialize
+  rcDistParam.iSubShift  = 0;
+#if HHI_INTERVIEW_SKIP
+  rcDistParam.pUsed       = 0;
+  rcDistParam.iStrideUsed = 0;
+#endif
+}
+
+// Setting the Distortion Parameter for Inter (ME)
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, DistParam& rcDistParam )
+{
+  // set Original & Curr Pointer / Stride
+  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 ];
+  }
+  else if (rcDistParam.iCols == 24)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[44 ];
+  }
+  else if (rcDistParam.iCols == 48)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[45 ];
+  }
+#endif
+
+  // initialize
+  rcDistParam.iSubShift  = 0;
+#if HHI_INTERVIEW_SKIP
+  rcDistParam.pUsed       = 0;
+  rcDistParam.iStrideUsed = 0;
+#endif
+}
+
+// Setting the Distortion Parameter for Inter (subpel ME with step)
+#if NS_HAD
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME, Bool bUseNSHAD )
+#else
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
+#endif
+{
+  // set Original & Curr Pointer / Stride
+  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();
+#if NS_HAD
+  rcDistParam.bUseNSHAD = bUseNSHAD;
+#endif
+  
+  // 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 ];
+    }
+    else if (rcDistParam.iCols == 24)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[47 ];
+    }
+    else if (rcDistParam.iCols == 48)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[48 ];
+    }
+#endif
+  }
+  else
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_HADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  }
+  
+  // initialize
+  rcDistParam.iSubShift  = 0;
+#if HHI_INTERVIEW_SKIP
+  rcDistParam.pUsed       = 0;
+  rcDistParam.iStrideUsed = 0;
+#endif
+}
+
+Void
+#if NS_HAD
+TComRdCost::setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard, Bool bUseNSHAD )
+#else
+TComRdCost::setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
+#endif
+{
+  rcDP.pOrg       = p1;
+  rcDP.pCur       = p2;
+  rcDP.iStrideOrg = iStride1;
+  rcDP.iStrideCur = iStride2;
+  rcDP.iCols      = iWidth;
+  rcDP.iRows      = iHeight;
+  rcDP.iStep      = 1;
+  rcDP.iSubShift  = 0;
+  rcDP.DistFunc   = m_afpDistortFunc[ ( bHadamard ? DF_HADS : DF_SADS ) + g_aucConvertToBit[ iWidth ] + 1 ];
+#if HHI_INTERVIEW_SKIP
+  rcDP.pUsed       = 0;
+  rcDP.iStrideUsed = 0;
+#endif
+#if NS_HAD
+  rcDP.bUseNSHAD  = bUseNSHAD;
+#endif
+}
+
+UInt TComRdCost::calcHAD( Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight )
+{
+  UInt uiSum = 0;
+  Int x, y;
+  
+  if ( ( (iWidth % 8) == 0 ) && ( (iHeight % 8) == 0 ) )
+  {
+    for ( y=0; y<iHeight; y+= 8 )
+    {
+      for ( x=0; x<iWidth; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*8;
+      pi1 += iStride1*8;
+    }
+  }
+  else if ( ( (iWidth % 4) == 0 ) && ( (iHeight % 4) == 0 ) )
+  {
+    for ( y=0; y<iHeight; y+= 4 )
+    {
+      for ( x=0; x<iWidth; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*4;
+      pi1 += iStride1*4;
+    }
+  }
+  else
+  {
+    for ( y=0; y<iHeight; y+= 2 )
+    {
+      for ( x=0; x<iWidth; x+= 2 )
+      {
+        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*2;
+      pi1 += iStride1*2;
+    }
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+#if HHI_INTERVIEW_SKIP
+UInt TComRdCost::getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, Pel* piUsed, Int iUsedStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc )
+{
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eDFunc, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.pUsed      = piUsed;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+  cDtParam.iStrideUsed= iUsedStride;
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix since DistParam is lacking a constructor and the variable iStep is not initialized
+  cDtParam.iStep      = 1;
+#endif
+#ifdef WEIGHT_PRED
+  cDtParam.applyWeight  = false;
+  cDtParam.uiComp       = 255;    // just for assert: to be sure it was set before use, since only values 0,1 or 2 are allowed.
+#endif
+#if LGE_ILLUCOMP_B0045
+  cDtParam.bUseIC = false;
+#endif
+  return cDtParam.DistFunc( &cDtParam );
+}
+#endif
+
+#if WEIGHTED_CHROMA_DISTORTION
+UInt TComRdCost::getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bWeighted, DFunc eDFunc )
+#else
+UInt TComRdCost::getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc )
+#endif
+{
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eDFunc, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+  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.
+
+#if WEIGHTED_CHROMA_DISTORTION
+#if LGE_ILLUCOMP_B0045
+  cDtParam.bUseIC = false;
+#endif
+  if (bWeighted)
+  {
+    return ((int) (m_chromaDistortionWeight * cDtParam.DistFunc( &cDtParam )));
+  }
+  else
+  {
+    return cDtParam.DistFunc( &cDtParam );
+  }
+#else
+  return cDtParam.DistFunc( &cDtParam );
+#endif
+}
+
+
+#if SAIT_VSO_EST_A0033
+UInt TComRdCost::getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, Pel* piVirRec, Pel* piVirOrg, Int iVirStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc )
+{
+  AOT( ( m_dDisparityCoeff <= 0 ) || ( m_dDisparityCoeff > 10 ) );
+
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eDFunc, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.pVirRec    = piVirRec;
+  cDtParam.pVirOrg    = piVirOrg;
+  cDtParam.iStrideVir = iVirStride;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+  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.
+
+#if LGE_ILLUCOMP_B0045
+  cDtParam.bUseIC = false;
+#endif
+  return cDtParam.DistFunc( &cDtParam );
+}
+#endif
+
+UInt TComRdCost::xGetSAD( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSADic( pcDtParam );
+  }
+#endif
+  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 uiSum = 0;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      uiSum += abs( piOrg[n] - piCur[n] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight ) 
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD4ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD8ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD16( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD16ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD12( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD12ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+UInt TComRdCost::xGetSAD16N( DistParam* pcDtParam )
+{
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD16Nic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      uiSum += abs( piOrg[n+ 0] - piCur[n+ 0] );
+      uiSum += abs( piOrg[n+ 1] - piCur[n+ 1] );
+      uiSum += abs( piOrg[n+ 2] - piCur[n+ 2] );
+      uiSum += abs( piOrg[n+ 3] - piCur[n+ 3] );
+      uiSum += abs( piOrg[n+ 4] - piCur[n+ 4] );
+      uiSum += abs( piOrg[n+ 5] - piCur[n+ 5] );
+      uiSum += abs( piOrg[n+ 6] - piCur[n+ 6] );
+      uiSum += abs( piOrg[n+ 7] - piCur[n+ 7] );
+      uiSum += abs( piOrg[n+ 8] - piCur[n+ 8] );
+      uiSum += abs( piOrg[n+ 9] - piCur[n+ 9] );
+      uiSum += abs( piOrg[n+10] - piCur[n+10] );
+      uiSum += abs( piOrg[n+11] - piCur[n+11] );
+      uiSum += abs( piOrg[n+12] - piCur[n+12] );
+      uiSum += abs( piOrg[n+13] - piCur[n+13] );
+      uiSum += abs( piOrg[n+14] - piCur[n+14] );
+      uiSum += abs( piOrg[n+15] - piCur[n+15] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD32( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD32ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD24( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD24ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#endif
+
+UInt TComRdCost::xGetSAD64( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD64ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+    uiSum += abs( piOrg[32] - piCur[32] );
+    uiSum += abs( piOrg[33] - piCur[33] );
+    uiSum += abs( piOrg[34] - piCur[34] );
+    uiSum += abs( piOrg[35] - piCur[35] );
+    uiSum += abs( piOrg[36] - piCur[36] );
+    uiSum += abs( piOrg[37] - piCur[37] );
+    uiSum += abs( piOrg[38] - piCur[38] );
+    uiSum += abs( piOrg[39] - piCur[39] );
+    uiSum += abs( piOrg[40] - piCur[40] );
+    uiSum += abs( piOrg[41] - piCur[41] );
+    uiSum += abs( piOrg[42] - piCur[42] );
+    uiSum += abs( piOrg[43] - piCur[43] );
+    uiSum += abs( piOrg[44] - piCur[44] );
+    uiSum += abs( piOrg[45] - piCur[45] );
+    uiSum += abs( piOrg[46] - piCur[46] );
+    uiSum += abs( piOrg[47] - piCur[47] );
+    uiSum += abs( piOrg[48] - piCur[48] );
+    uiSum += abs( piOrg[49] - piCur[49] );
+    uiSum += abs( piOrg[50] - piCur[50] );
+    uiSum += abs( piOrg[51] - piCur[51] );
+    uiSum += abs( piOrg[52] - piCur[52] );
+    uiSum += abs( piOrg[53] - piCur[53] );
+    uiSum += abs( piOrg[54] - piCur[54] );
+    uiSum += abs( piOrg[55] - piCur[55] );
+    uiSum += abs( piOrg[56] - piCur[56] );
+    uiSum += abs( piOrg[57] - piCur[57] );
+    uiSum += abs( piOrg[58] - piCur[58] );
+    uiSum += abs( piOrg[59] - piCur[59] );
+    uiSum += abs( piOrg[60] - piCur[60] );
+    uiSum += abs( piOrg[61] - piCur[61] );
+    uiSum += abs( piOrg[62] - piCur[62] );
+    uiSum += abs( piOrg[63] - piCur[63] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD48( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetSAD48ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+    uiSum += abs( piOrg[32] - piCur[32] );
+    uiSum += abs( piOrg[33] - piCur[33] );
+    uiSum += abs( piOrg[34] - piCur[34] );
+    uiSum += abs( piOrg[35] - piCur[35] );
+    uiSum += abs( piOrg[36] - piCur[36] );
+    uiSum += abs( piOrg[37] - piCur[37] );
+    uiSum += abs( piOrg[38] - piCur[38] );
+    uiSum += abs( piOrg[39] - piCur[39] );
+    uiSum += abs( piOrg[40] - piCur[40] );
+    uiSum += abs( piOrg[41] - piCur[41] );
+    uiSum += abs( piOrg[42] - piCur[42] );
+    uiSum += abs( piOrg[43] - piCur[43] );
+    uiSum += abs( piOrg[44] - piCur[44] );
+    uiSum += abs( piOrg[45] - piCur[45] );
+    uiSum += abs( piOrg[46] - piCur[46] );
+    uiSum += abs( piOrg[47] - piCur[47] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+// ====================================================================================================================
+// Distortion functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+#if LGE_ILLUCOMP_B0045
+UInt TComRdCost::xGetSADic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( 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;
+  
+  UInt uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      iOrigAvg += piOrg[n];
+      iCurAvg  += piCur[n];
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = (iOrigAvg - iCurAvg)/iCols/iRows;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      uiSum += abs( piOrg[n] - piCur[n] - iDeltaC );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD4ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight ) 
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/4) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD8ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/8) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD16ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  Int iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+    iOrigAvg += piOrg[8];
+    iOrigAvg += piOrg[9];
+    iOrigAvg += piOrg[10];
+    iOrigAvg += piOrg[11];
+    iOrigAvg += piOrg[12];
+    iOrigAvg += piOrg[13];
+    iOrigAvg += piOrg[14];
+    iOrigAvg += piOrg[15];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+    iCurAvg  += piCur[8];
+    iCurAvg  += piCur[9];
+    iCurAvg  += piCur[10];
+    iCurAvg  += piCur[11];
+    iCurAvg  += piCur[12];
+    iCurAvg  += piCur[13];
+    iCurAvg  += piCur[14];
+    iCurAvg  += piCur[15];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/16) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD12ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+    iOrigAvg += piOrg[8];
+    iOrigAvg += piOrg[9];
+    iOrigAvg += piOrg[10];
+    iOrigAvg += piOrg[11];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+    iCurAvg  += piCur[8];
+    iCurAvg  += piCur[9];
+    iCurAvg  += piCur[10];
+    iCurAvg  += piCur[11];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/12) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+UInt TComRdCost::xGetSAD16Nic( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+
+  Int iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0, uiColCnt = (iCols-1)/16 + 1;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      iOrigAvg += piOrg[n + 0];
+      iOrigAvg += piOrg[n + 1];
+      iOrigAvg += piOrg[n + 2];
+      iOrigAvg += piOrg[n + 3];
+      iOrigAvg += piOrg[n + 4];
+      iOrigAvg += piOrg[n + 5];
+      iOrigAvg += piOrg[n + 6];
+      iOrigAvg += piOrg[n + 7];
+      iOrigAvg += piOrg[n + 8];
+      iOrigAvg += piOrg[n + 9];
+      iOrigAvg += piOrg[n + 10];
+      iOrigAvg += piOrg[n + 11];
+      iOrigAvg += piOrg[n + 12];
+      iOrigAvg += piOrg[n + 13];
+      iOrigAvg += piOrg[n + 14];
+      iOrigAvg += piOrg[n + 15];
+
+      iCurAvg  += piCur[n + 0];
+      iCurAvg  += piCur[n + 1];
+      iCurAvg  += piCur[n + 2];
+      iCurAvg  += piCur[n + 3];
+      iCurAvg  += piCur[n + 4];
+      iCurAvg  += piCur[n + 5];
+      iCurAvg  += piCur[n + 6];
+      iCurAvg  += piCur[n + 7];
+      iCurAvg  += piCur[n + 8];
+      iCurAvg  += piCur[n + 9];
+      iCurAvg  += piCur[n + 10];
+      iCurAvg  += piCur[n + 11];
+      iCurAvg  += piCur[n + 12];
+      iCurAvg  += piCur[n + 13];
+      iCurAvg  += piCur[n + 14];
+      iCurAvg  += piCur[n + 15];
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = (uiRowCnt && uiColCnt) ? ((iOrigAvg - iCurAvg)/uiRowCnt/uiColCnt/16) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      uiSum += abs( piOrg[n+ 0] - piCur[n+ 0] - iDeltaC );
+      uiSum += abs( piOrg[n+ 1] - piCur[n+ 1] - iDeltaC );
+      uiSum += abs( piOrg[n+ 2] - piCur[n+ 2] - iDeltaC );
+      uiSum += abs( piOrg[n+ 3] - piCur[n+ 3] - iDeltaC );
+      uiSum += abs( piOrg[n+ 4] - piCur[n+ 4] - iDeltaC );
+      uiSum += abs( piOrg[n+ 5] - piCur[n+ 5] - iDeltaC );
+      uiSum += abs( piOrg[n+ 6] - piCur[n+ 6] - iDeltaC );
+      uiSum += abs( piOrg[n+ 7] - piCur[n+ 7] - iDeltaC );
+      uiSum += abs( piOrg[n+ 8] - piCur[n+ 8] - iDeltaC );
+      uiSum += abs( piOrg[n+ 9] - piCur[n+ 9] - iDeltaC );
+      uiSum += abs( piOrg[n+10] - piCur[n+10] - iDeltaC );
+      uiSum += abs( piOrg[n+11] - piCur[n+11] - iDeltaC );
+      uiSum += abs( piOrg[n+12] - piCur[n+12] - iDeltaC );
+      uiSum += abs( piOrg[n+13] - piCur[n+13] - iDeltaC );
+      uiSum += abs( piOrg[n+14] - piCur[n+14] - iDeltaC );
+      uiSum += abs( piOrg[n+15] - piCur[n+15] - iDeltaC );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD32ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+    iOrigAvg += piOrg[8];
+    iOrigAvg += piOrg[9];
+    iOrigAvg += piOrg[10];
+    iOrigAvg += piOrg[11];
+    iOrigAvg += piOrg[12];
+    iOrigAvg += piOrg[13];
+    iOrigAvg += piOrg[14];
+    iOrigAvg += piOrg[15];
+    iOrigAvg += piOrg[16];
+    iOrigAvg += piOrg[17];
+    iOrigAvg += piOrg[18];
+    iOrigAvg += piOrg[19];
+    iOrigAvg += piOrg[20];
+    iOrigAvg += piOrg[21];
+    iOrigAvg += piOrg[22];
+    iOrigAvg += piOrg[23];
+    iOrigAvg += piOrg[24];
+    iOrigAvg += piOrg[25];
+    iOrigAvg += piOrg[26];
+    iOrigAvg += piOrg[27];
+    iOrigAvg += piOrg[28];
+    iOrigAvg += piOrg[29];
+    iOrigAvg += piOrg[30];
+    iOrigAvg += piOrg[31];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+    iCurAvg  += piCur[8];
+    iCurAvg  += piCur[9];
+    iCurAvg  += piCur[10];
+    iCurAvg  += piCur[11];
+    iCurAvg  += piCur[12];
+    iCurAvg  += piCur[13];
+    iCurAvg  += piCur[14];
+    iCurAvg  += piCur[15];
+    iCurAvg  += piCur[16];
+    iCurAvg  += piCur[17];
+    iCurAvg  += piCur[18];
+    iCurAvg  += piCur[19];
+    iCurAvg  += piCur[20];
+    iCurAvg  += piCur[21];
+    iCurAvg  += piCur[22];
+    iCurAvg  += piCur[23];
+    iCurAvg  += piCur[24];
+    iCurAvg  += piCur[25];
+    iCurAvg  += piCur[26];
+    iCurAvg  += piCur[27];
+    iCurAvg  += piCur[28];
+    iCurAvg  += piCur[29];
+    iCurAvg  += piCur[30];
+    iCurAvg  += piCur[31];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/32) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+    uiSum += abs( piOrg[16] - piCur[16] - iDeltaC );
+    uiSum += abs( piOrg[17] - piCur[17] - iDeltaC );
+    uiSum += abs( piOrg[18] - piCur[18] - iDeltaC );
+    uiSum += abs( piOrg[19] - piCur[19] - iDeltaC );
+    uiSum += abs( piOrg[20] - piCur[20] - iDeltaC );
+    uiSum += abs( piOrg[21] - piCur[21] - iDeltaC );
+    uiSum += abs( piOrg[22] - piCur[22] - iDeltaC );
+    uiSum += abs( piOrg[23] - piCur[23] - iDeltaC );
+    uiSum += abs( piOrg[24] - piCur[24] - iDeltaC );
+    uiSum += abs( piOrg[25] - piCur[25] - iDeltaC );
+    uiSum += abs( piOrg[26] - piCur[26] - iDeltaC );
+    uiSum += abs( piOrg[27] - piCur[27] - iDeltaC );
+    uiSum += abs( piOrg[28] - piCur[28] - iDeltaC );
+    uiSum += abs( piOrg[29] - piCur[29] - iDeltaC );
+    uiSum += abs( piOrg[30] - piCur[30] - iDeltaC );
+    uiSum += abs( piOrg[31] - piCur[31] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD24ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+    iOrigAvg += piOrg[8];
+    iOrigAvg += piOrg[9];
+    iOrigAvg += piOrg[10];
+    iOrigAvg += piOrg[11];
+    iOrigAvg += piOrg[12];
+    iOrigAvg += piOrg[13];
+    iOrigAvg += piOrg[14];
+    iOrigAvg += piOrg[15];
+    iOrigAvg += piOrg[16];
+    iOrigAvg += piOrg[17];
+    iOrigAvg += piOrg[18];
+    iOrigAvg += piOrg[19];
+    iOrigAvg += piOrg[20];
+    iOrigAvg += piOrg[21];
+    iOrigAvg += piOrg[22];
+    iOrigAvg += piOrg[23];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+    iCurAvg  += piCur[8];
+    iCurAvg  += piCur[9];
+    iCurAvg  += piCur[10];
+    iCurAvg  += piCur[11];
+    iCurAvg  += piCur[12];
+    iCurAvg  += piCur[13];
+    iCurAvg  += piCur[14];
+    iCurAvg  += piCur[15];
+    iCurAvg  += piCur[16];
+    iCurAvg  += piCur[17];
+    iCurAvg  += piCur[18];
+    iCurAvg  += piCur[19];
+    iCurAvg  += piCur[20];
+    iCurAvg  += piCur[21];
+    iCurAvg  += piCur[22];
+    iCurAvg  += piCur[23];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+  
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/24) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+    uiSum += abs( piOrg[16] - piCur[16] - iDeltaC );
+    uiSum += abs( piOrg[17] - piCur[17] - iDeltaC );
+    uiSum += abs( piOrg[18] - piCur[18] - iDeltaC );
+    uiSum += abs( piOrg[19] - piCur[19] - iDeltaC );
+    uiSum += abs( piOrg[20] - piCur[20] - iDeltaC );
+    uiSum += abs( piOrg[21] - piCur[21] - iDeltaC );
+    uiSum += abs( piOrg[22] - piCur[22] - iDeltaC );
+    uiSum += abs( piOrg[23] - piCur[23] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+UInt TComRdCost::xGetSAD64ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0] ;
+    iOrigAvg += piOrg[1] ;
+    iOrigAvg += piOrg[2] ;
+    iOrigAvg += piOrg[3] ;
+    iOrigAvg += piOrg[4] ;
+    iOrigAvg += piOrg[5] ;
+    iOrigAvg += piOrg[6] ;
+    iOrigAvg += piOrg[7] ;
+    iOrigAvg += piOrg[8] ;
+    iOrigAvg += piOrg[9] ;
+    iOrigAvg += piOrg[10] ;
+    iOrigAvg += piOrg[11] ;
+    iOrigAvg += piOrg[12] ;
+    iOrigAvg += piOrg[13] ;
+    iOrigAvg += piOrg[14] ;
+    iOrigAvg += piOrg[15] ;
+    iOrigAvg += piOrg[16] ;
+    iOrigAvg += piOrg[17] ;
+    iOrigAvg += piOrg[18] ;
+    iOrigAvg += piOrg[19] ;
+    iOrigAvg += piOrg[20] ;
+    iOrigAvg += piOrg[21] ;
+    iOrigAvg += piOrg[22] ;
+    iOrigAvg += piOrg[23] ;
+    iOrigAvg += piOrg[24] ;
+    iOrigAvg += piOrg[25] ;
+    iOrigAvg += piOrg[26] ;
+    iOrigAvg += piOrg[27] ;
+    iOrigAvg += piOrg[28] ;
+    iOrigAvg += piOrg[29] ;
+    iOrigAvg += piOrg[30] ;
+    iOrigAvg += piOrg[31] ;
+    iOrigAvg += piOrg[32] ;
+    iOrigAvg += piOrg[33] ;
+    iOrigAvg += piOrg[34] ;
+    iOrigAvg += piOrg[35] ;
+    iOrigAvg += piOrg[36] ;
+    iOrigAvg += piOrg[37] ;
+    iOrigAvg += piOrg[38] ;
+    iOrigAvg += piOrg[39] ;
+    iOrigAvg += piOrg[40] ;
+    iOrigAvg += piOrg[41] ;
+    iOrigAvg += piOrg[42] ;
+    iOrigAvg += piOrg[43] ;
+    iOrigAvg += piOrg[44] ;
+    iOrigAvg += piOrg[45] ;
+    iOrigAvg += piOrg[46] ;
+    iOrigAvg += piOrg[47] ;
+    iOrigAvg += piOrg[48] ;
+    iOrigAvg += piOrg[49] ;
+    iOrigAvg += piOrg[50] ;
+    iOrigAvg += piOrg[51] ;
+    iOrigAvg += piOrg[52] ;
+    iOrigAvg += piOrg[53] ;
+    iOrigAvg += piOrg[54] ;
+    iOrigAvg += piOrg[55] ;
+    iOrigAvg += piOrg[56] ;
+    iOrigAvg += piOrg[57] ;
+    iOrigAvg += piOrg[58] ;
+    iOrigAvg += piOrg[59] ;
+    iOrigAvg += piOrg[60] ;
+    iOrigAvg += piOrg[61] ;
+    iOrigAvg += piOrg[62] ;
+    iOrigAvg += piOrg[63] ;
+
+    iCurAvg += piCur[0] ;
+    iCurAvg += piCur[1] ;
+    iCurAvg += piCur[2] ;
+    iCurAvg += piCur[3] ;
+    iCurAvg += piCur[4] ;
+    iCurAvg += piCur[5] ;
+    iCurAvg += piCur[6] ;
+    iCurAvg += piCur[7] ;
+    iCurAvg += piCur[8] ;
+    iCurAvg += piCur[9] ;
+    iCurAvg += piCur[10] ;
+    iCurAvg += piCur[11] ;
+    iCurAvg += piCur[12] ;
+    iCurAvg += piCur[13] ;
+    iCurAvg += piCur[14] ;
+    iCurAvg += piCur[15] ;
+    iCurAvg += piCur[16] ;
+    iCurAvg += piCur[17] ;
+    iCurAvg += piCur[18] ;
+    iCurAvg += piCur[19] ;
+    iCurAvg += piCur[20] ;
+    iCurAvg += piCur[21] ;
+    iCurAvg += piCur[22] ;
+    iCurAvg += piCur[23] ;
+    iCurAvg += piCur[24] ;
+    iCurAvg += piCur[25] ;
+    iCurAvg += piCur[26] ;
+    iCurAvg += piCur[27] ;
+    iCurAvg += piCur[28] ;
+    iCurAvg += piCur[29] ;
+    iCurAvg += piCur[30] ;
+    iCurAvg += piCur[31] ;
+    iCurAvg += piCur[32] ;
+    iCurAvg += piCur[33] ;
+    iCurAvg += piCur[34] ;
+    iCurAvg += piCur[35] ;
+    iCurAvg += piCur[36] ;
+    iCurAvg += piCur[37] ;
+    iCurAvg += piCur[38] ;
+    iCurAvg += piCur[39] ;
+    iCurAvg += piCur[40] ;
+    iCurAvg += piCur[41] ;
+    iCurAvg += piCur[42] ;
+    iCurAvg += piCur[43] ;
+    iCurAvg += piCur[44] ;
+    iCurAvg += piCur[45] ;
+    iCurAvg += piCur[46] ;
+    iCurAvg += piCur[47] ;
+    iCurAvg += piCur[48] ;
+    iCurAvg += piCur[49] ;
+    iCurAvg += piCur[50] ;
+    iCurAvg += piCur[51] ;
+    iCurAvg += piCur[52] ;
+    iCurAvg += piCur[53] ;
+    iCurAvg += piCur[54] ;
+    iCurAvg += piCur[55] ;
+    iCurAvg += piCur[56] ;
+    iCurAvg += piCur[57] ;
+    iCurAvg += piCur[58] ;
+    iCurAvg += piCur[59] ;
+    iCurAvg += piCur[60] ;
+    iCurAvg += piCur[61] ;
+    iCurAvg += piCur[62] ;
+    iCurAvg += piCur[63] ;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/64) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+    uiSum += abs( piOrg[16] - piCur[16] - iDeltaC );
+    uiSum += abs( piOrg[17] - piCur[17] - iDeltaC );
+    uiSum += abs( piOrg[18] - piCur[18] - iDeltaC );
+    uiSum += abs( piOrg[19] - piCur[19] - iDeltaC );
+    uiSum += abs( piOrg[20] - piCur[20] - iDeltaC );
+    uiSum += abs( piOrg[21] - piCur[21] - iDeltaC );
+    uiSum += abs( piOrg[22] - piCur[22] - iDeltaC );
+    uiSum += abs( piOrg[23] - piCur[23] - iDeltaC );
+    uiSum += abs( piOrg[24] - piCur[24] - iDeltaC );
+    uiSum += abs( piOrg[25] - piCur[25] - iDeltaC );
+    uiSum += abs( piOrg[26] - piCur[26] - iDeltaC );
+    uiSum += abs( piOrg[27] - piCur[27] - iDeltaC );
+    uiSum += abs( piOrg[28] - piCur[28] - iDeltaC );
+    uiSum += abs( piOrg[29] - piCur[29] - iDeltaC );
+    uiSum += abs( piOrg[30] - piCur[30] - iDeltaC );
+    uiSum += abs( piOrg[31] - piCur[31] - iDeltaC );
+    uiSum += abs( piOrg[32] - piCur[32] - iDeltaC );
+    uiSum += abs( piOrg[33] - piCur[33] - iDeltaC );
+    uiSum += abs( piOrg[34] - piCur[34] - iDeltaC );
+    uiSum += abs( piOrg[35] - piCur[35] - iDeltaC );
+    uiSum += abs( piOrg[36] - piCur[36] - iDeltaC );
+    uiSum += abs( piOrg[37] - piCur[37] - iDeltaC );
+    uiSum += abs( piOrg[38] - piCur[38] - iDeltaC );
+    uiSum += abs( piOrg[39] - piCur[39] - iDeltaC );
+    uiSum += abs( piOrg[40] - piCur[40] - iDeltaC );
+    uiSum += abs( piOrg[41] - piCur[41] - iDeltaC );
+    uiSum += abs( piOrg[42] - piCur[42] - iDeltaC );
+    uiSum += abs( piOrg[43] - piCur[43] - iDeltaC );
+    uiSum += abs( piOrg[44] - piCur[44] - iDeltaC );
+    uiSum += abs( piOrg[45] - piCur[45] - iDeltaC );
+    uiSum += abs( piOrg[46] - piCur[46] - iDeltaC );
+    uiSum += abs( piOrg[47] - piCur[47] - iDeltaC );
+    uiSum += abs( piOrg[48] - piCur[48] - iDeltaC );
+    uiSum += abs( piOrg[49] - piCur[49] - iDeltaC );
+    uiSum += abs( piOrg[50] - piCur[50] - iDeltaC );
+    uiSum += abs( piOrg[51] - piCur[51] - iDeltaC );
+    uiSum += abs( piOrg[52] - piCur[52] - iDeltaC );
+    uiSum += abs( piOrg[53] - piCur[53] - iDeltaC );
+    uiSum += abs( piOrg[54] - piCur[54] - iDeltaC );
+    uiSum += abs( piOrg[55] - piCur[55] - iDeltaC );
+    uiSum += abs( piOrg[56] - piCur[56] - iDeltaC );
+    uiSum += abs( piOrg[57] - piCur[57] - iDeltaC );
+    uiSum += abs( piOrg[58] - piCur[58] - iDeltaC );
+    uiSum += abs( piOrg[59] - piCur[59] - iDeltaC );
+    uiSum += abs( piOrg[60] - piCur[60] - iDeltaC );
+    uiSum += abs( piOrg[61] - piCur[61] - iDeltaC );
+    uiSum += abs( piOrg[62] - piCur[62] - iDeltaC );
+    uiSum += abs( piOrg[63] - piCur[63] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD48ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0] ;
+    iOrigAvg += piOrg[1] ;
+    iOrigAvg += piOrg[2] ;
+    iOrigAvg += piOrg[3] ;
+    iOrigAvg += piOrg[4] ;
+    iOrigAvg += piOrg[5] ;
+    iOrigAvg += piOrg[6] ;
+    iOrigAvg += piOrg[7] ;
+    iOrigAvg += piOrg[8] ;
+    iOrigAvg += piOrg[9] ;
+    iOrigAvg += piOrg[10] ;
+    iOrigAvg += piOrg[11] ;
+    iOrigAvg += piOrg[12] ;
+    iOrigAvg += piOrg[13] ;
+    iOrigAvg += piOrg[14] ;
+    iOrigAvg += piOrg[15] ;
+    iOrigAvg += piOrg[16] ;
+    iOrigAvg += piOrg[17] ;
+    iOrigAvg += piOrg[18] ;
+    iOrigAvg += piOrg[19] ;
+    iOrigAvg += piOrg[20] ;
+    iOrigAvg += piOrg[21] ;
+    iOrigAvg += piOrg[22] ;
+    iOrigAvg += piOrg[23] ;
+    iOrigAvg += piOrg[24] ;
+    iOrigAvg += piOrg[25] ;
+    iOrigAvg += piOrg[26] ;
+    iOrigAvg += piOrg[27] ;
+    iOrigAvg += piOrg[28] ;
+    iOrigAvg += piOrg[29] ;
+    iOrigAvg += piOrg[30] ;
+    iOrigAvg += piOrg[31] ;
+    iOrigAvg += piOrg[32] ;
+    iOrigAvg += piOrg[33] ;
+    iOrigAvg += piOrg[34] ;
+    iOrigAvg += piOrg[35] ;
+    iOrigAvg += piOrg[36] ;
+    iOrigAvg += piOrg[37] ;
+    iOrigAvg += piOrg[38] ;
+    iOrigAvg += piOrg[39] ;
+    iOrigAvg += piOrg[40] ;
+    iOrigAvg += piOrg[41] ;
+    iOrigAvg += piOrg[42] ;
+    iOrigAvg += piOrg[43] ;
+    iOrigAvg += piOrg[44] ;
+    iOrigAvg += piOrg[45] ;
+    iOrigAvg += piOrg[46] ;
+    iOrigAvg += piOrg[47] ;
+
+    iCurAvg += piCur[0] ;
+    iCurAvg += piCur[1] ;
+    iCurAvg += piCur[2] ;
+    iCurAvg += piCur[3] ;
+    iCurAvg += piCur[4] ;
+    iCurAvg += piCur[5] ;
+    iCurAvg += piCur[6] ;
+    iCurAvg += piCur[7] ;
+    iCurAvg += piCur[8] ;
+    iCurAvg += piCur[9] ;
+    iCurAvg += piCur[10] ;
+    iCurAvg += piCur[11] ;
+    iCurAvg += piCur[12] ;
+    iCurAvg += piCur[13] ;
+    iCurAvg += piCur[14] ;
+    iCurAvg += piCur[15] ;
+    iCurAvg += piCur[16] ;
+    iCurAvg += piCur[17] ;
+    iCurAvg += piCur[18] ;
+    iCurAvg += piCur[19] ;
+    iCurAvg += piCur[20] ;
+    iCurAvg += piCur[21] ;
+    iCurAvg += piCur[22] ;
+    iCurAvg += piCur[23] ;
+    iCurAvg += piCur[24] ;
+    iCurAvg += piCur[25] ;
+    iCurAvg += piCur[26] ;
+    iCurAvg += piCur[27] ;
+    iCurAvg += piCur[28] ;
+    iCurAvg += piCur[29] ;
+    iCurAvg += piCur[30] ;
+    iCurAvg += piCur[31] ;
+    iCurAvg += piCur[32] ;
+    iCurAvg += piCur[33] ;
+    iCurAvg += piCur[34] ;
+    iCurAvg += piCur[35] ;
+    iCurAvg += piCur[36] ;
+    iCurAvg += piCur[37] ;
+    iCurAvg += piCur[38] ;
+    iCurAvg += piCur[39] ;
+    iCurAvg += piCur[40] ;
+    iCurAvg += piCur[41] ;
+    iCurAvg += piCur[42] ;
+    iCurAvg += piCur[43] ;
+    iCurAvg += piCur[44] ;
+    iCurAvg += piCur[45] ;
+    iCurAvg += piCur[46] ;
+    iCurAvg += piCur[47] ;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/48) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+    uiSum += abs( piOrg[16] - piCur[16] - iDeltaC );
+    uiSum += abs( piOrg[17] - piCur[17] - iDeltaC );
+    uiSum += abs( piOrg[18] - piCur[18] - iDeltaC );
+    uiSum += abs( piOrg[19] - piCur[19] - iDeltaC );
+    uiSum += abs( piOrg[20] - piCur[20] - iDeltaC );
+    uiSum += abs( piOrg[21] - piCur[21] - iDeltaC );
+    uiSum += abs( piOrg[22] - piCur[22] - iDeltaC );
+    uiSum += abs( piOrg[23] - piCur[23] - iDeltaC );
+    uiSum += abs( piOrg[24] - piCur[24] - iDeltaC );
+    uiSum += abs( piOrg[25] - piCur[25] - iDeltaC );
+    uiSum += abs( piOrg[26] - piCur[26] - iDeltaC );
+    uiSum += abs( piOrg[27] - piCur[27] - iDeltaC );
+    uiSum += abs( piOrg[28] - piCur[28] - iDeltaC );
+    uiSum += abs( piOrg[29] - piCur[29] - iDeltaC );
+    uiSum += abs( piOrg[30] - piCur[30] - iDeltaC );
+    uiSum += abs( piOrg[31] - piCur[31] - iDeltaC );
+    uiSum += abs( piOrg[32] - piCur[32] - iDeltaC );
+    uiSum += abs( piOrg[33] - piCur[33] - iDeltaC );
+    uiSum += abs( piOrg[34] - piCur[34] - iDeltaC );
+    uiSum += abs( piOrg[35] - piCur[35] - iDeltaC );
+    uiSum += abs( piOrg[36] - piCur[36] - iDeltaC );
+    uiSum += abs( piOrg[37] - piCur[37] - iDeltaC );
+    uiSum += abs( piOrg[38] - piCur[38] - iDeltaC );
+    uiSum += abs( piOrg[39] - piCur[39] - iDeltaC );
+    uiSum += abs( piOrg[40] - piCur[40] - iDeltaC );
+    uiSum += abs( piOrg[41] - piCur[41] - iDeltaC );
+    uiSum += abs( piOrg[42] - piCur[42] - iDeltaC );
+    uiSum += abs( piOrg[43] - piCur[43] - iDeltaC );
+    uiSum += abs( piOrg[44] - piCur[44] - iDeltaC );
+    uiSum += abs( piOrg[45] - piCur[45] - iDeltaC );
+    uiSum += abs( piOrg[46] - piCur[46] - iDeltaC );
+    uiSum += abs( piOrg[47] - piCur[47] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+
+#if IBDI_DISTORTION
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+
+  Int iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      iTemp = ((piOrg[n  ]+iOffset)>>iShift) - ((piCur[n  ]+iOffset)>>iShift);
+      uiSum += iTemp * iTemp;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE4( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((piCur[0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((piCur[1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((piCur[2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((piCur[3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE8( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((piCur[0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((piCur[1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((piCur[2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((piCur[3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[4]+iOffset)>>iShift) - ((piCur[4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[5]+iOffset)>>iShift) - ((piCur[5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[6]+iOffset)>>iShift) - ((piCur[6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[7]+iOffset)>>iShift) - ((piCur[7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = ((piOrg[ 0]+iOffset)>>iShift) - ((piCur[ 0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 1]+iOffset)>>iShift) - ((piCur[ 1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 2]+iOffset)>>iShift) - ((piCur[ 2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 3]+iOffset)>>iShift) - ((piCur[ 3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 4]+iOffset)>>iShift) - ((piCur[ 4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 5]+iOffset)>>iShift) - ((piCur[ 5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 6]+iOffset)>>iShift) - ((piCur[ 6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 7]+iOffset)>>iShift) - ((piCur[ 7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 8]+iOffset)>>iShift) - ((piCur[ 8]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 9]+iOffset)>>iShift) - ((piCur[ 9]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((piCur[10]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((piCur[11]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((piCur[12]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((piCur[13]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((piCur[14]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((piCur[15]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16N( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+
+      iTemp = ((piOrg[n+ 0]+iOffset)>>iShift) - ((piCur[n+ 0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 1]+iOffset)>>iShift) - ((piCur[n+ 1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 2]+iOffset)>>iShift) - ((piCur[n+ 2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 3]+iOffset)>>iShift) - ((piCur[n+ 3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 4]+iOffset)>>iShift) - ((piCur[n+ 4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 5]+iOffset)>>iShift) - ((piCur[n+ 5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 6]+iOffset)>>iShift) - ((piCur[n+ 6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 7]+iOffset)>>iShift) - ((piCur[n+ 7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 8]+iOffset)>>iShift) - ((piCur[n+ 8]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+ 9]+iOffset)>>iShift) - ((piCur[n+ 9]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+10]+iOffset)>>iShift) - ((piCur[n+10]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+11]+iOffset)>>iShift) - ((piCur[n+11]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+12]+iOffset)>>iShift) - ((piCur[n+12]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+13]+iOffset)>>iShift) - ((piCur[n+13]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+14]+iOffset)>>iShift) - ((piCur[n+14]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      iTemp = ((piOrg[n+15]+iOffset)>>iShift) - ((piCur[n+15]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE32( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = ((piOrg[ 0]+iOffset)>>iShift) - ((piCur[ 0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 1]+iOffset)>>iShift) - ((piCur[ 1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 2]+iOffset)>>iShift) - ((piCur[ 2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 3]+iOffset)>>iShift) - ((piCur[ 3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 4]+iOffset)>>iShift) - ((piCur[ 4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 5]+iOffset)>>iShift) - ((piCur[ 5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 6]+iOffset)>>iShift) - ((piCur[ 6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 7]+iOffset)>>iShift) - ((piCur[ 7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 8]+iOffset)>>iShift) - ((piCur[ 8]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 9]+iOffset)>>iShift) - ((piCur[ 9]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((piCur[10]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((piCur[11]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((piCur[12]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((piCur[13]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((piCur[14]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((piCur[15]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[16]+iOffset)>>iShift) - ((piCur[16]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[17]+iOffset)>>iShift) - ((piCur[17]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[18]+iOffset)>>iShift) - ((piCur[18]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[19]+iOffset)>>iShift) - ((piCur[19]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[20]+iOffset)>>iShift) - ((piCur[20]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[21]+iOffset)>>iShift) - ((piCur[21]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[22]+iOffset)>>iShift) - ((piCur[22]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[23]+iOffset)>>iShift) - ((piCur[23]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[24]+iOffset)>>iShift) - ((piCur[24]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[25]+iOffset)>>iShift) - ((piCur[25]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[26]+iOffset)>>iShift) - ((piCur[26]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[27]+iOffset)>>iShift) - ((piCur[27]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[28]+iOffset)>>iShift) - ((piCur[28]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[29]+iOffset)>>iShift) - ((piCur[29]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[30]+iOffset)>>iShift) - ((piCur[30]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[31]+iOffset)>>iShift) - ((piCur[31]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE64( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = ((piOrg[ 0]+iOffset)>>iShift) - ((piCur[ 0]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 1]+iOffset)>>iShift) - ((piCur[ 1]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 2]+iOffset)>>iShift) - ((piCur[ 2]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 3]+iOffset)>>iShift) - ((piCur[ 3]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 4]+iOffset)>>iShift) - ((piCur[ 4]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 5]+iOffset)>>iShift) - ((piCur[ 5]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 6]+iOffset)>>iShift) - ((piCur[ 6]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 7]+iOffset)>>iShift) - ((piCur[ 7]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 8]+iOffset)>>iShift) - ((piCur[ 8]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[ 9]+iOffset)>>iShift) - ((piCur[ 9]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((piCur[10]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((piCur[11]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((piCur[12]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((piCur[13]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((piCur[14]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((piCur[15]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[16]+iOffset)>>iShift) - ((piCur[16]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[17]+iOffset)>>iShift) - ((piCur[17]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[18]+iOffset)>>iShift) - ((piCur[18]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[19]+iOffset)>>iShift) - ((piCur[19]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[20]+iOffset)>>iShift) - ((piCur[20]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[21]+iOffset)>>iShift) - ((piCur[21]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[22]+iOffset)>>iShift) - ((piCur[22]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[23]+iOffset)>>iShift) - ((piCur[23]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[24]+iOffset)>>iShift) - ((piCur[24]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[25]+iOffset)>>iShift) - ((piCur[25]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[26]+iOffset)>>iShift) - ((piCur[26]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[27]+iOffset)>>iShift) - ((piCur[27]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[28]+iOffset)>>iShift) - ((piCur[28]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[29]+iOffset)>>iShift) - ((piCur[29]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[30]+iOffset)>>iShift) - ((piCur[30]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[31]+iOffset)>>iShift) - ((piCur[31]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[32]+iOffset)>>iShift) - ((piCur[32]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[33]+iOffset)>>iShift) - ((piCur[33]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[34]+iOffset)>>iShift) - ((piCur[34]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[35]+iOffset)>>iShift) - ((piCur[35]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[36]+iOffset)>>iShift) - ((piCur[36]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[37]+iOffset)>>iShift) - ((piCur[37]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[38]+iOffset)>>iShift) - ((piCur[38]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[39]+iOffset)>>iShift) - ((piCur[39]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[40]+iOffset)>>iShift) - ((piCur[40]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[41]+iOffset)>>iShift) - ((piCur[41]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[42]+iOffset)>>iShift) - ((piCur[42]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[43]+iOffset)>>iShift) - ((piCur[43]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[44]+iOffset)>>iShift) - ((piCur[44]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[45]+iOffset)>>iShift) - ((piCur[45]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[46]+iOffset)>>iShift) - ((piCur[46]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[47]+iOffset)>>iShift) - ((piCur[47]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[48]+iOffset)>>iShift) - ((piCur[48]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[49]+iOffset)>>iShift) - ((piCur[49]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[50]+iOffset)>>iShift) - ((piCur[50]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[51]+iOffset)>>iShift) - ((piCur[51]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[52]+iOffset)>>iShift) - ((piCur[52]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[53]+iOffset)>>iShift) - ((piCur[53]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[54]+iOffset)>>iShift) - ((piCur[54]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[55]+iOffset)>>iShift) - ((piCur[55]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[56]+iOffset)>>iShift) - ((piCur[56]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[57]+iOffset)>>iShift) - ((piCur[57]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[58]+iOffset)>>iShift) - ((piCur[58]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[59]+iOffset)>>iShift) - ((piCur[59]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[60]+iOffset)>>iShift) - ((piCur[60]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[61]+iOffset)>>iShift) - ((piCur[61]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[62]+iOffset)>>iShift) - ((piCur[62]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    iTemp = ((piOrg[63]+iOffset)>>iShift) - ((piCur[63]+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+#else
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  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 = g_uiBitIncrement<<1;
+  
+  Int iTemp;
+  
+#if HHI_INTERVIEW_SKIP
+  if( pcDtParam->pUsed )
+  {
+    Pel*  piUsed      = pcDtParam->pUsed;
+    Int   iStrideUsed = pcDtParam->iStrideUsed;
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+        if( piUsed[n] )
+    {
+      iTemp = piOrg[n  ] - piCur[n  ];
+      uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+      }
+      piOrg  += iStrideOrg;
+      piCur  += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+  }
+  else
+  {
+#endif
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      iTemp = piOrg[n  ] - piCur[n  ];
+      uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  #if HHI_INTERVIEW_SKIP
+  }
+#endif
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 4 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+#if HHI_INTERVIEW_SKIP
+  if( pcDtParam->pUsed )
+  {
+    Pel*  piUsed      = pcDtParam->pUsed;
+    Int   iStrideUsed = pcDtParam->iStrideUsed;
+    for( ; iRows != 0; iRows-- )
+    {
+      if( piUsed[0] ) { iTemp = piOrg[0] - piCur[0]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[1] ) { iTemp = piOrg[1] - piCur[1]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[2] ) { iTemp = piOrg[2] - piCur[2]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[3] ) { iTemp = piOrg[3] - piCur[3]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+
+      piOrg  += iStrideOrg;
+      piCur  += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+  }
+  else
+  {
+#endif
+  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;
+  }
+#if HHI_INTERVIEW_SKIP
+  }
+#endif
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 8 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+#if HHI_INTERVIEW_SKIP
+  if( pcDtParam->pUsed )
+  {
+    Pel*  piUsed      = pcDtParam->pUsed;
+    Int   iStrideUsed = pcDtParam->iStrideUsed;
+    for( ; iRows != 0; iRows-- )
+    {
+      if( piUsed[0] ) { iTemp = piOrg[0] - piCur[0]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[1] ) { iTemp = piOrg[1] - piCur[1]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[2] ) { iTemp = piOrg[2] - piCur[2]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[3] ) { iTemp = piOrg[3] - piCur[3]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[4] ) { iTemp = piOrg[4] - piCur[4]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[5] ) { iTemp = piOrg[5] - piCur[5]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[6] ) { iTemp = piOrg[6] - piCur[6]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[7] ) { iTemp = piOrg[7] - piCur[7]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+
+      piOrg  += iStrideOrg;
+      piCur  += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+  }
+  else
+  {
+#endif
+  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;
+  }
+#if HHI_INTERVIEW_SKIP
+  }
+#endif
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 16 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+#if HHI_INTERVIEW_SKIP
+  if( pcDtParam->pUsed )
+  {
+    Pel*  piUsed      = pcDtParam->pUsed;
+    Int   iStrideUsed = pcDtParam->iStrideUsed;
+    for( ; iRows != 0; iRows-- )
+    {
+      if( piUsed[ 0] ) { iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 1] ) { iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 2] ) { iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 3] ) { iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 4] ) { iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 5] ) { iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 6] ) { iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 7] ) { iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 8] ) { iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 9] ) { iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[10] ) { iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[11] ) { iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[12] ) { iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[13] ) { iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[14] ) { iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[15] ) { iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+
+      piOrg  += iStrideOrg;
+      piCur  += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+  }
+  else
+  {
+#endif
+  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;
+  }
+#if HHI_INTERVIEW_SKIP
+  }
+#endif
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16N( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  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 = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+#if HHI_INTERVIEW_SKIP
+  if( pcDtParam->pUsed )
+  {
+    Pel*  piUsed      = pcDtParam->pUsed;
+    Int   iStrideUsed = pcDtParam->iStrideUsed;
+    for( ; iRows != 0; iRows-- )
+    {
+      for (Int n = 0; n < iCols; n+=16 )
+      {
+        if( piUsed[n+ 0] ) { iTemp = piOrg[n+ 0] - piCur[n+ 0]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 1] ) { iTemp = piOrg[n+ 1] - piCur[n+ 1]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 2] ) { iTemp = piOrg[n+ 2] - piCur[n+ 2]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 3] ) { iTemp = piOrg[n+ 3] - piCur[n+ 3]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 4] ) { iTemp = piOrg[n+ 4] - piCur[n+ 4]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 5] ) { iTemp = piOrg[n+ 5] - piCur[n+ 5]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 6] ) { iTemp = piOrg[n+ 6] - piCur[n+ 6]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 7] ) { iTemp = piOrg[n+ 7] - piCur[n+ 7]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 8] ) { iTemp = piOrg[n+ 8] - piCur[n+ 8]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+ 9] ) { iTemp = piOrg[n+ 9] - piCur[n+ 9]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+10] ) { iTemp = piOrg[n+10] - piCur[n+10]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+11] ) { iTemp = piOrg[n+11] - piCur[n+11]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+12] ) { iTemp = piOrg[n+12] - piCur[n+12]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+13] ) { iTemp = piOrg[n+13] - piCur[n+13]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+14] ) { iTemp = piOrg[n+14] - piCur[n+14]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+        if( piUsed[n+15] ) { iTemp = piOrg[n+15] - piCur[n+15]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      }
+      piOrg  += iStrideOrg;
+      piCur  += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+  }
+  else
+  {
+#endif
+  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;
+  }
+#if HHI_INTERVIEW_SKIP
+  }
+#endif
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE32( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 32 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+#if HHI_INTERVIEW_SKIP
+  if( pcDtParam->pUsed )
+  {
+    Pel*  piUsed      = pcDtParam->pUsed;
+    Int   iStrideUsed = pcDtParam->iStrideUsed;
+    for( ; iRows != 0; iRows-- )
+    {
+      if( piUsed[ 0] ) { iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 1] ) { iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 2] ) { iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 3] ) { iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 4] ) { iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 5] ) { iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 6] ) { iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 7] ) { iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 8] ) { iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 9] ) { iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[10] ) { iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[11] ) { iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[12] ) { iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[13] ) { iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[14] ) { iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[15] ) { iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[16] ) { iTemp = piOrg[16] - piCur[16]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[17] ) { iTemp = piOrg[17] - piCur[17]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[18] ) { iTemp = piOrg[18] - piCur[18]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[19] ) { iTemp = piOrg[19] - piCur[19]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[20] ) { iTemp = piOrg[20] - piCur[20]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[21] ) { iTemp = piOrg[21] - piCur[21]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[22] ) { iTemp = piOrg[22] - piCur[22]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[23] ) { iTemp = piOrg[23] - piCur[23]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[24] ) { iTemp = piOrg[24] - piCur[24]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[25] ) { iTemp = piOrg[25] - piCur[25]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[26] ) { iTemp = piOrg[26] - piCur[26]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[27] ) { iTemp = piOrg[27] - piCur[27]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[28] ) { iTemp = piOrg[28] - piCur[28]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[29] ) { iTemp = piOrg[29] - piCur[29]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[30] ) { iTemp = piOrg[30] - piCur[30]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[31] ) { iTemp = piOrg[31] - piCur[31]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+
+      piOrg  += iStrideOrg;
+      piCur  += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+  }
+  else
+  {
+#endif
+  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;
+  }
+#if HHI_INTERVIEW_SKIP
+  }
+#endif
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE64( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 64 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+#if HHI_INTERVIEW_SKIP
+  if( pcDtParam->pUsed )
+  {
+    Pel*  piUsed      = pcDtParam->pUsed;
+    Int   iStrideUsed = pcDtParam->iStrideUsed;
+    for( ; iRows != 0; iRows-- )
+    {
+      if( piUsed[ 0] ) { iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 1] ) { iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 2] ) { iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 3] ) { iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 4] ) { iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 5] ) { iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 6] ) { iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 7] ) { iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 8] ) { iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[ 9] ) { iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[10] ) { iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[11] ) { iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[12] ) { iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[13] ) { iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[14] ) { iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[15] ) { iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[16] ) { iTemp = piOrg[16] - piCur[16]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[17] ) { iTemp = piOrg[17] - piCur[17]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[18] ) { iTemp = piOrg[18] - piCur[18]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[19] ) { iTemp = piOrg[19] - piCur[19]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[20] ) { iTemp = piOrg[20] - piCur[20]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[21] ) { iTemp = piOrg[21] - piCur[21]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[22] ) { iTemp = piOrg[22] - piCur[22]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[23] ) { iTemp = piOrg[23] - piCur[23]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[24] ) { iTemp = piOrg[24] - piCur[24]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[25] ) { iTemp = piOrg[25] - piCur[25]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[26] ) { iTemp = piOrg[26] - piCur[26]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[27] ) { iTemp = piOrg[27] - piCur[27]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[28] ) { iTemp = piOrg[28] - piCur[28]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[29] ) { iTemp = piOrg[29] - piCur[29]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[30] ) { iTemp = piOrg[30] - piCur[30]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[31] ) { iTemp = piOrg[31] - piCur[31]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[32] ) { iTemp = piOrg[32] - piCur[32]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[33] ) { iTemp = piOrg[33] - piCur[33]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[34] ) { iTemp = piOrg[34] - piCur[34]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[35] ) { iTemp = piOrg[35] - piCur[35]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[36] ) { iTemp = piOrg[36] - piCur[36]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[37] ) { iTemp = piOrg[37] - piCur[37]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[38] ) { iTemp = piOrg[38] - piCur[38]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[39] ) { iTemp = piOrg[39] - piCur[39]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[40] ) { iTemp = piOrg[40] - piCur[40]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[41] ) { iTemp = piOrg[41] - piCur[41]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[42] ) { iTemp = piOrg[42] - piCur[42]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[43] ) { iTemp = piOrg[43] - piCur[43]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[44] ) { iTemp = piOrg[44] - piCur[44]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[45] ) { iTemp = piOrg[45] - piCur[45]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[46] ) { iTemp = piOrg[46] - piCur[46]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[47] ) { iTemp = piOrg[47] - piCur[47]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[48] ) { iTemp = piOrg[48] - piCur[48]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[49] ) { iTemp = piOrg[49] - piCur[49]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[50] ) { iTemp = piOrg[50] - piCur[50]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[51] ) { iTemp = piOrg[51] - piCur[51]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[52] ) { iTemp = piOrg[52] - piCur[52]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[53] ) { iTemp = piOrg[53] - piCur[53]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[54] ) { iTemp = piOrg[54] - piCur[54]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[55] ) { iTemp = piOrg[55] - piCur[55]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[56] ) { iTemp = piOrg[56] - piCur[56]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[57] ) { iTemp = piOrg[57] - piCur[57]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[58] ) { iTemp = piOrg[58] - piCur[58]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[59] ) { iTemp = piOrg[59] - piCur[59]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[60] ) { iTemp = piOrg[60] - piCur[60]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[61] ) { iTemp = piOrg[61] - piCur[61]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[62] ) { iTemp = piOrg[62] - piCur[62]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+      if( piUsed[63] ) { iTemp = piOrg[63] - piCur[63]; uiSum += ( iTemp * iTemp ) >> uiShift; }
+
+      piOrg  += iStrideOrg;
+      piCur  += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+  }
+  else
+  {
+#endif
+  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;
+  }
+#if HHI_INTERVIEW_SKIP
+  }
+#endif
+  
+  return ( uiSum );
+}
+#endif
+
+
+#if 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;
+  Int iTemp;
+
+  dD = ( (Double) ( dDM >> g_uiBitIncrement ) ) * m_dDisparityCoeff;
+
+  iTemp = (Int) ROUND( 0.5 * fabs(dD) * ( abs( (Int) pVirRec[ x+y*iVirStride ] - (Int) pVirRec[ x-1+y*iVirStride ] ) + abs( (Int) pVirRec[ x+y*iVirStride ] - (Int) pVirRec[ x+1+y*iVirStride ] ) ) );
+
+  return (UInt) ( (iTemp*iTemp)>>1 );
+}
+
+UInt TComRdCost::xGetVSD( DistParam* pcDtParam )
+{
+  Pel* piOrg    = pcDtParam->pOrg;
+  Pel* piCur    = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows    = pcDtParam->iRows;
+  Int  iCols    = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < iCols; x++ )
+    {
+      dDM = (Int) ( piOrg[x  ] - piCur[x  ] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur; 
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD4( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    dDM = (Int) ( piOrg[0] - piCur[0] );  uiSum += ( getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, 0, y ) ) >> uiShift;
+    dDM = (Int) ( piOrg[1] - piCur[1] );  uiSum += ( getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, 1, y ) ) >> uiShift;
+    dDM = (Int) ( piOrg[2] - piCur[2] );  uiSum += ( getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, 2, y ) ) >> uiShift;
+    dDM = (Int) ( piOrg[3] - piCur[3] );  uiSum += ( getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, 3, y ) ) >> uiShift;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD8( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < 8; x++ )
+    {
+      dDM = (Int) ( piOrg[x] - piCur[x] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD16( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < 16; x++ )
+    {
+      dDM = (Int) ( piOrg[x] - piCur[x] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD16N( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < iCols; x+=16 )
+    {
+      for ( Int k = 0 ; k < 16 ; k++ )
+      {
+        dDM = (Int) ( piOrg[x+k] - piCur[x+k] );
+        uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x+k, y ) >> uiShift;
+      }
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD32( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < 32 ; x++ )
+    {
+      dDM = (Int) ( piOrg[x] - piCur[x] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD64( DistParam* pcDtParam )
+{
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Pel* piVirRec   = pcDtParam->pVirRec;
+  Pel* piVirOrg   = pcDtParam->pVirOrg;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < 64; x++ )
+    {
+      dDM = (Int) ( piOrg[x] - piCur[x] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------
+// HADAMARD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int satd = 0, diff[4], m[4];
+  assert( iStep == 1 );
+  diff[0] = piOrg[0             ] - piCur[0];
+  diff[1] = piOrg[1             ] - piCur[1];
+  diff[2] = piOrg[iStrideOrg    ] - piCur[0 + iStrideCur];
+  diff[3] = piOrg[iStrideOrg + 1] - piCur[1 + iStrideCur];
+  m[0] = diff[0] + diff[2];
+  m[1] = diff[1] + diff[3];
+  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];
+  
+  assert( iStep == 1 );
+  for( k = 0; k < 16; k+=4 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  /*===== hadamard transform =====*/
+  m[ 0] = diff[ 0] + diff[12];
+  m[ 1] = diff[ 1] + diff[13];
+  m[ 2] = diff[ 2] + diff[14];
+  m[ 3] = diff[ 3] + diff[15];
+  m[ 4] = diff[ 4] + diff[ 8];
+  m[ 5] = diff[ 5] + diff[ 9];
+  m[ 6] = diff[ 6] + diff[10];
+  m[ 7] = diff[ 7] + diff[11];
+  m[ 8] = diff[ 4] - diff[ 8];
+  m[ 9] = diff[ 5] - diff[ 9];
+  m[10] = diff[ 6] - diff[10];
+  m[11] = diff[ 7] - diff[11];
+  m[12] = diff[ 0] - diff[12];
+  m[13] = diff[ 1] - diff[13];
+  m[14] = diff[ 2] - diff[14];
+  m[15] = diff[ 3] - diff[15];
+  
+  d[ 0] = m[ 0] + m[ 4];
+  d[ 1] = m[ 1] + m[ 5];
+  d[ 2] = m[ 2] + m[ 6];
+  d[ 3] = m[ 3] + m[ 7];
+  d[ 4] = m[ 8] + m[12];
+  d[ 5] = m[ 9] + m[13];
+  d[ 6] = m[10] + m[14];
+  d[ 7] = m[11] + m[15];
+  d[ 8] = m[ 0] - m[ 4];
+  d[ 9] = m[ 1] - m[ 5];
+  d[10] = m[ 2] - m[ 6];
+  d[11] = m[ 3] - m[ 7];
+  d[12] = m[12] - m[ 8];
+  d[13] = m[13] - m[ 9];
+  d[14] = m[14] - m[10];
+  d[15] = m[15] - m[11];
+  
+  m[ 0] = d[ 0] + d[ 3];
+  m[ 1] = d[ 1] + d[ 2];
+  m[ 2] = d[ 1] - d[ 2];
+  m[ 3] = d[ 0] - d[ 3];
+  m[ 4] = d[ 4] + d[ 7];
+  m[ 5] = d[ 5] + d[ 6];
+  m[ 6] = d[ 5] - d[ 6];
+  m[ 7] = d[ 4] - d[ 7];
+  m[ 8] = d[ 8] + d[11];
+  m[ 9] = d[ 9] + d[10];
+  m[10] = d[ 9] - d[10];
+  m[11] = d[ 8] - d[11];
+  m[12] = d[12] + d[15];
+  m[13] = d[13] + d[14];
+  m[14] = d[13] - d[14];
+  m[15] = d[12] - d[15];
+  
+  d[ 0] = m[ 0] + m[ 1];
+  d[ 1] = m[ 0] - m[ 1];
+  d[ 2] = m[ 2] + m[ 3];
+  d[ 3] = m[ 3] - m[ 2];
+  d[ 4] = m[ 4] + m[ 5];
+  d[ 5] = m[ 4] - m[ 5];
+  d[ 6] = m[ 6] + m[ 7];
+  d[ 7] = m[ 7] - m[ 6];
+  d[ 8] = m[ 8] + m[ 9];
+  d[ 9] = m[ 8] - m[ 9];
+  d[10] = m[10] + m[11];
+  d[11] = m[11] - m[10];
+  d[12] = m[12] + m[13];
+  d[13] = m[12] - m[13];
+  d[14] = m[14] + m[15];
+  d[15] = m[15] - m[14];
+  
+  for (k=0; k<16; ++k)
+  {
+    satd += abs(d[k]);
+  }
+  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];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; k += 8 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+    diff[k+4] = piOrg[4] - piCur[4];
+    diff[k+5] = piOrg[5] - piCur[5];
+    diff[k+6] = piOrg[6] - piCur[6];
+    diff[k+7] = piOrg[7] - piCur[7];
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+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];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    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];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+  
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    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];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    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];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+  
+  for (i = 0; i < 8; i++)
+  {
+    for (j = 0; j < 8; j++)
+    {
+      sad += abs(m2[i][j]);
+    }
+  }
+  
+  sad=((sad+2)>>2);
+  
+  return sad;
+}
+
+#if NS_HAD
+UInt TComRdCost::xCalcHADs16x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[4][16], m2[4][16];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; k += 16 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+    diff[k+4] = piOrg[4] - piCur[4];
+    diff[k+5] = piOrg[5] - piCur[5];
+    diff[k+6] = piOrg[6] - piCur[6];
+    diff[k+7] = piOrg[7] - piCur[7];
+
+    diff[k+8]  = piOrg[8]  - piCur[8] ;
+    diff[k+9]  = piOrg[9]  - piCur[9] ;
+    diff[k+10] = piOrg[10] - piCur[10];
+    diff[k+11] = piOrg[11] - piCur[11];
+    diff[k+12] = piOrg[12] - piCur[12];
+    diff[k+13] = piOrg[13] - piCur[13];
+    diff[k+14] = piOrg[14] - piCur[14];
+    diff[k+15] = piOrg[15] - piCur[15];
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+
+  //horizontal
+  for (j=0; j < 4; j++)
+  {
+    jj = j << 4;
+
+    m2[j][0]  = diff[jj  ] + diff[jj+8];
+    m2[j][1]  = diff[jj+1] + diff[jj+9];
+    m2[j][2]  = diff[jj+2] + diff[jj+10];
+    m2[j][3]  = diff[jj+3] + diff[jj+11];
+    m2[j][4]  = diff[jj+4] + diff[jj+12];
+    m2[j][5]  = diff[jj+5] + diff[jj+13];
+    m2[j][6]  = diff[jj+6] + diff[jj+14];
+    m2[j][7]  = diff[jj+7] + diff[jj+15];
+    m2[j][8]  = diff[jj  ] - diff[jj+8];
+    m2[j][9]  = diff[jj+1] - diff[jj+9];
+    m2[j][10] = diff[jj+2] - diff[jj+10];
+    m2[j][11] = diff[jj+3] - diff[jj+11];
+    m2[j][12] = diff[jj+4] - diff[jj+12];
+    m2[j][13] = diff[jj+5] - diff[jj+13];
+    m2[j][14] = diff[jj+6] - diff[jj+14];
+    m2[j][15] = diff[jj+7] - diff[jj+15];
+
+    m1[j][0]  = m2[j][0]  + m2[j][4];
+    m1[j][1]  = m2[j][1]  + m2[j][5];
+    m1[j][2]  = m2[j][2]  + m2[j][6];
+    m1[j][3]  = m2[j][3]  + m2[j][7];
+    m1[j][4]  = m2[j][0]  - m2[j][4];
+    m1[j][5]  = m2[j][1]  - m2[j][5];
+    m1[j][6]  = m2[j][2]  - m2[j][6];
+    m1[j][7]  = m2[j][3]  - m2[j][7];
+    m1[j][8]  = m2[j][8]  + m2[j][12];
+    m1[j][9]  = m2[j][9]  + m2[j][13];
+    m1[j][10] = m2[j][10] + m2[j][14];
+    m1[j][11] = m2[j][11] + m2[j][15];
+    m1[j][12] = m2[j][8]  - m2[j][12];
+    m1[j][13] = m2[j][9]  - m2[j][13];
+    m1[j][14] = m2[j][10] - m2[j][14];
+    m1[j][15] = m2[j][11] - m2[j][15];
+
+    m2[j][0]  = m1[j][0]  + m1[j][2];
+    m2[j][1]  = m1[j][1]  + m1[j][3];
+    m2[j][2]  = m1[j][0]  - m1[j][2];
+    m2[j][3]  = m1[j][1]  - m1[j][3];
+    m2[j][4]  = m1[j][4]  + m1[j][6];
+    m2[j][5]  = m1[j][5]  + m1[j][7];
+    m2[j][6]  = m1[j][4]  - m1[j][6];
+    m2[j][7]  = m1[j][5]  - m1[j][7];
+    m2[j][8]  = m1[j][8]  + m1[j][10];
+    m2[j][9]  = m1[j][9]  + m1[j][11];
+    m2[j][10] = m1[j][8]  - m1[j][10];
+    m2[j][11] = m1[j][9]  - m1[j][11];
+    m2[j][12] = m1[j][12] + m1[j][14];
+    m2[j][13] = m1[j][13] + m1[j][15];
+    m2[j][14] = m1[j][12] - m1[j][14];
+    m2[j][15] = m1[j][13] - m1[j][15];
+
+    m1[j][0]  = m2[j][0]  + m2[j][1];
+    m1[j][1]  = m2[j][0]  - m2[j][1];
+    m1[j][2]  = m2[j][2]  + m2[j][3];
+    m1[j][3]  = m2[j][2]  - m2[j][3];
+    m1[j][4]  = m2[j][4]  + m2[j][5];
+    m1[j][5]  = m2[j][4]  - m2[j][5];
+    m1[j][6]  = m2[j][6]  + m2[j][7];
+    m1[j][7]  = m2[j][6]  - m2[j][7];
+    m1[j][8]  = m2[j][8]  + m2[j][9];
+    m1[j][9]  = m2[j][8]  - m2[j][9];
+    m1[j][10] = m2[j][10] + m2[j][11];
+    m1[j][11] = m2[j][10] - m2[j][11];
+    m1[j][12] = m2[j][12] + m2[j][13];
+    m1[j][13] = m2[j][12] - m2[j][13];
+    m1[j][14] = m2[j][14] + m2[j][15];
+    m1[j][15] = m2[j][14] - m2[j][15];
+  }
+
+  //vertical
+  for (i=0; i < 16; i++)
+  {    
+    m2[0][i] = m1[0][i] + m1[2][i];
+    m2[1][i] = m1[1][i] + m1[3][i];
+    m2[2][i] = m1[0][i] - m1[2][i];
+    m2[3][i] = m1[1][i] - m1[3][i];
+
+    m1[0][i] = m2[0][i] + m2[1][i];
+    m1[1][i] = m2[0][i] - m2[1][i];
+    m1[2][i] = m2[2][i] + m2[3][i];
+    m1[3][i] = m2[2][i] - m2[3][i];
+  }
+
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 16; j++)
+    {
+      sad += abs(m1[i][j]);
+    }
+  }
+
+  sad=((sad+2)>>2);
+
+  return sad;
+}
+
+UInt TComRdCost::xCalcHADs4x16( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[16][4], m2[16][4], m3[16][4];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; k += 4 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+
+  //horizontal
+  for (j=0; j < 16; j++)
+  {
+    jj = j << 2;
+    m2[j][0] = diff[jj  ] + diff[jj+2];
+    m2[j][1] = diff[jj+1] + diff[jj+3];
+    m2[j][2] = diff[jj  ] - diff[jj+2];
+    m2[j][3] = diff[jj+1] - diff[jj+3];
+
+    m1[j][0] = m2[j][0] + m2[j][1];
+    m1[j][1] = m2[j][0] - m2[j][1];
+    m1[j][2] = m2[j][2] + m2[j][3];
+    m1[j][3] = m2[j][2] - m2[j][3];
+  }
+
+  //vertical
+  for (i=0; i < 4; i++)
+  {
+    m2[0][i]  = m1[0][i] + m1[8][i];
+    m2[1][i]  = m1[1][i] + m1[9][i];
+    m2[2][i]  = m1[2][i] + m1[10][i];
+    m2[3][i]  = m1[3][i] + m1[11][i];
+    m2[4][i]  = m1[4][i] + m1[12][i];
+    m2[5][i]  = m1[5][i] + m1[13][i];
+    m2[6][i]  = m1[6][i] + m1[14][i];
+    m2[7][i]  = m1[7][i] + m1[15][i];
+    m2[8][i]  = m1[0][i] - m1[8][i];
+    m2[9][i]  = m1[1][i] - m1[9][i];
+    m2[10][i] = m1[2][i] - m1[10][i];
+    m2[11][i] = m1[3][i] - m1[11][i];
+    m2[12][i] = m1[4][i] - m1[12][i];
+    m2[13][i] = m1[5][i] - m1[13][i];
+    m2[14][i] = m1[6][i] - m1[14][i];
+    m2[15][i] = m1[7][i] - m1[15][i];
+
+    m3[0][i]  = m2[0][i]  + m2[4][i];
+    m3[1][i]  = m2[1][i]  + m2[5][i];
+    m3[2][i]  = m2[2][i]  + m2[6][i];
+    m3[3][i]  = m2[3][i]  + m2[7][i];
+    m3[4][i]  = m2[0][i]  - m2[4][i];
+    m3[5][i]  = m2[1][i]  - m2[5][i];
+    m3[6][i]  = m2[2][i]  - m2[6][i];
+    m3[7][i]  = m2[3][i]  - m2[7][i];
+    m3[8][i]  = m2[8][i]  + m2[12][i];
+    m3[9][i]  = m2[9][i]  + m2[13][i];
+    m3[10][i] = m2[10][i] + m2[14][i];
+    m3[11][i] = m2[11][i] + m2[15][i];
+    m3[12][i] = m2[8][i]  - m2[12][i];
+    m3[13][i] = m2[9][i]  - m2[13][i];
+    m3[14][i] = m2[10][i] - m2[14][i];
+    m3[15][i] = m2[11][i] - m2[15][i];
+
+    m1[0][i]  = m3[0][i]  + m3[2][i];
+    m1[1][i]  = m3[1][i]  + m3[3][i];
+    m1[2][i]  = m3[0][i]  - m3[2][i];
+    m1[3][i]  = m3[1][i]  - m3[3][i];
+    m1[4][i]  = m3[4][i]  + m3[6][i];
+    m1[5][i]  = m3[5][i]  + m3[7][i];
+    m1[6][i]  = m3[4][i]  - m3[6][i];
+    m1[7][i]  = m3[5][i]  - m3[7][i];
+    m1[8][i]  = m3[8][i]  + m3[10][i];
+    m1[9][i]  = m3[9][i]  + m3[11][i];
+    m1[10][i] = m3[8][i]  - m3[10][i];
+    m1[11][i] = m3[9][i]  - m3[11][i];
+    m1[12][i] = m3[12][i] + m3[14][i];
+    m1[13][i] = m3[13][i] + m3[15][i];
+    m1[14][i] = m3[12][i] - m3[14][i];
+    m1[15][i] = m3[13][i] - m3[15][i];
+
+    m2[0][i]  = m1[0][i]  + m1[1][i];
+    m2[1][i]  = m1[0][i]  - m1[1][i];
+    m2[2][i]  = m1[2][i]  + m1[3][i];
+    m2[3][i]  = m1[2][i]  - m1[3][i];
+    m2[4][i]  = m1[4][i]  + m1[5][i];
+    m2[5][i]  = m1[4][i]  - m1[5][i];
+    m2[6][i]  = m1[6][i]  + m1[7][i];
+    m2[7][i]  = m1[6][i]  - m1[7][i];
+    m2[8][i]  = m1[8][i]  + m1[9][i];
+    m2[9][i]  = m1[8][i]  - m1[9][i];
+    m2[10][i] = m1[10][i] + m1[11][i];
+    m2[11][i] = m1[10][i] - m1[11][i];
+    m2[12][i] = m1[12][i] + m1[13][i];
+    m2[13][i] = m1[12][i] - m1[13][i];
+    m2[14][i] = m1[14][i] + m1[15][i];
+    m2[15][i] = m1[14][i] - m1[15][i];
+  }
+
+  for (i = 0; i < 16; i++)
+  {
+    for (j = 0; j < 4; j++)
+    {
+      sad += abs(m2[i][j]);
+    }
+  }
+
+  sad=((sad+2)>>2);
+
+  return sad;
+}
+#endif
+
+UInt TComRdCost::xGetHADs4( 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 >> g_uiBitIncrement );
+}
+
+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 >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetHADs( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADsw( pcDtParam );
+  }
+#if LGE_ILLUCOMP_B0045
+  if(pcDtParam->bUseIC)
+  {
+    return xGetHADsic( pcDtParam );
+  }
+#endif
+  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 uiSum = 0;
+
+#if NS_HAD
+  if( ( ( iRows % 8 == 0) && (iCols % 8 == 0) && ( iRows == iCols ) ) || ( ( iRows % 8 == 0 ) && (iCols % 8 == 0) && !pcDtParam->bUseNSHAD ) )
+#else
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+#endif
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      for ( x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#if NS_HAD
+  else if ( ( iCols > 8 ) && ( iCols > iRows ) && pcDtParam->bUseNSHAD ) 
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 16 )
+      {
+        uiSum += xCalcHADs16x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if ( ( iRows > 8 ) && ( iCols < iRows ) && pcDtParam->bUseNSHAD ) 
+  {
+    Int  iOffsetOrg = iStrideOrg<<4;
+    Int  iOffsetCur = iStrideCur<<4;
+    for ( y=0; y<iRows; y+= 16 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x16( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#endif
+  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 )
+      {
+        uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<1;
+    Int  iOffsetCur = iStrideCur<<1;
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    assert(false);
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#if LGE_ILLUCOMP_B0045
+UInt TComRdCost::xGetHADsic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADsw( 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 uiSum = 0;
+  
+  Int  iOrigAvg = 0, iCurAvg = 0;
+  Int  iDeltaC;
+
+  for ( y=0; y<iRows; y++ )
+  {
+    for ( x=0; x<iCols; x++ )
+    {        
+      iOrigAvg += piOrg[x];
+      iCurAvg  += piCur[x];
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+
+  iDeltaC = (iOrigAvg - iCurAvg)/iRows/iCols;
+
+  for ( y=0; y<iRows; y++ )
+  {
+    for ( x=0; x<iCols; x++ )
+    {        
+      piOrg[x] -= iDeltaC;
+    }
+    piOrg += iStrideOrg;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+
+#if NS_HAD
+  if( ( ( iRows % 8 == 0) && (iCols % 8 == 0) && ( iRows == iCols ) ) || ( ( iRows % 8 == 0 ) && (iCols % 8 == 0) && !pcDtParam->bUseNSHAD ) )
+#else
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+#endif
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      for ( x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#if NS_HAD
+  else if ( ( iCols > 8 ) && ( iCols > iRows ) && pcDtParam->bUseNSHAD ) 
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 16 )
+      {
+        uiSum += xCalcHADs16x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if ( ( iRows > 8 ) && ( iCols < iRows ) && pcDtParam->bUseNSHAD ) 
+  {
+    Int  iOffsetOrg = iStrideOrg<<4;
+    Int  iOffsetCur = iStrideCur<<4;
+    for ( y=0; y<iRows; y+= 16 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x16( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#endif
+  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 )
+      {
+        uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<1;
+    Int  iOffsetCur = iStrideCur<<1;
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    assert(false);
+  }
+  
+  piOrg   = pcDtParam->pOrg;
+
+  for ( y=0; y<iRows; y++ )
+  {
+    for ( x=0; x<iCols; x++ )
+    {        
+      piOrg[x] += iDeltaC;
+    }
+    piOrg += iStrideOrg;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+#if HHI_VSO
+Void TComRdCost::setLambdaVSO( Double dLambdaVSO )
+{
+  m_dLambdaVSO           = dLambdaVSO;
+  m_dSqrtLambdaVSO       = sqrt(m_dLambdaVSO); 
+  m_uiLambdaMotionSADVSO = (UInt)floor(65536.0 *       m_dSqrtLambdaVSO);
+  m_uiLambdaMotionSSEVSO = (UInt)floor(65536.0 *       m_dLambdaVSO    );
+}
+
+Dist TComRdCost::xGetDistVSOMode4( Int iStartPosX, Int iStartPosY, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD )
+{ 
+  AOT(bSAD); 
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  RMDist iDist = m_pcRenModel->getDist( iStartPosX, iStartPosY, (Int) uiBlkWidth, (Int) uiBlkHeight, iCurStride, piCur, piOrg, iOrgStride);  
+#else
+  RMDist iDist = m_pcRenModel->getDist( iStartPosX, iStartPosY, (Int) uiBlkWidth, (Int) uiBlkHeight, iCurStride, piCur );  
+#endif
+
+  RMDist iDistMin = (RMDist) RDO_DIST_MIN; 
+#if HHI_VSO_DIST_INT
+  iDistMin = m_bAllowNegDist ? RDO_DIST_MIN : 0; 
+#endif
+  
+  iDist = Min( iDist, (RMDist) RDO_DIST_MAX);
+  iDist = Max( iDist, iDistMin);
+  return (Dist) iDist;
+}
+
+
+Dist TComRdCost::getDistVS( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD, UInt uiPlane )
+{ 
+  assert( m_bUseVSO );  
+  assert( this->m_fpDistortFuncVSO != 0 );
+
+  Int iPosX;
+  Int iPosY; 
+  
+  pcCU->getPosInPic( uiAbsPartIndex, iPosX, iPosY ); 
+  return (this->*m_fpDistortFuncVSO) ( iPosX, iPosY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight, bSAD );  
+}; 
+
+
+Void TComRdCost::setVSOMode( UInt uiIn )
+{
+  m_uiVSOMode = uiIn;
+  switch (m_uiVSOMode )
+  {
+  case   4:
+    m_fpDistortFuncVSO = &TComRdCost::xGetDistVSOMode4;
+    break;
+  default:
+    assert(0); 
+    break; 
+  }
+}
+
+
+Double TComRdCost::calcRdCostVSO( UInt uiBits, Dist uiDistortion, Bool bFlag, DFunc eDFunc )
+{
+  assert( m_bUseLambdaScaleVSO );   
+
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;   
+
+  switch ( eDFunc )
+  {
+  case DF_SSE:
+    assert(0);
+    break;
+  case DF_SAD:
+    dLambda = (Double)m_uiLambdaMotionSADVSO;
+    break;
+  case DF_DEFAULT:
+    dLambda =         m_dLambdaVSO;
+    break;
+  case DF_SSE_FRAME:
+    dLambda =         m_dFrameLambdaVSO;
+    break;
+  default:
+    assert (0);
+    break;
+  }
+
+  if (bFlag)
+  {
+    // Intra8x8, Intra4x4 Block only...
+    dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(Dist)floor(dRdCost);
+    }
+    else
+    {
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)));
+      dRdCost = (Double)(Dist)floor(dRdCost);
+    }
+  }
+
+  return dRdCost;
+}
+
+Void TComRdCost::setRenModelData( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piData, Int iStride, Int iBlkWidth, Int iBlkHeight )
+{
+  UInt iBlkX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIndex]];
+  UInt iBlkY = g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIndex]];
+
+  Int iStartPosX = iBlkX + pcCU->getCUPelX();
+  Int iStartPosY = iBlkY + pcCU->getCUPelY();
+
+  m_pcRenModel->setData( iStartPosX, iStartPosY, iBlkWidth, iBlkHeight, iStride, piData );
+}
+
+#if HHI_VSO_DIST_INT
+Void TComRdCost::setAllowNegDist( Bool bAllowNegDist )
+{
+  m_bAllowNegDist = bAllowNegDist;
+}
+#endif
+
+#endif 
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCost.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCost.h	(revision 341)
@@ -0,0 +1,468 @@
+/* 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-2012, 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     TComRdCost.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOST__
+#define __TCOMRDCOST__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+
+#include "TComRdCost.h"
+#include "TComSlice.h"
+#include "TComRdCostWeightPrediction.h"
+#include "../TLibRenderer/TRenModel.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#define FIX203 1
+
+class DistParam;
+class TComPattern;
+class TComRdCost; 
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+// for function pointer
+typedef UInt (*FpDistFunc) (DistParam*);
+
+#if HHI_VSO
+typedef Dist (TComRdCost::*FpDistFuncVSO) ( Int, Int, Pel*, Int, Pel*, Int, UInt, UInt, Bool );
+#endif
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// distortion parameter class
+class DistParam
+{
+public:
+  Pel*  pOrg;
+  Pel*  pCur;
+  Int   iStrideOrg;
+  Int   iStrideCur;
+#if SAIT_VSO_EST_A0033
+  Pel*  pVirRec;
+  Pel*  pVirOrg;
+  Int   iStrideVir;
+#endif
+  Int   iRows;
+  Int   iCols;
+  Int   iStep;
+#if LGE_ILLUCOMP_B0045
+  Bool  bUseIC;
+#endif
+  FpDistFunc DistFunc;
+
+#if HHI_INTERVIEW_SKIP
+  Pel*  pUsed;
+  Int   iStrideUsed;
+#endif
+  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)
+
+#if NS_HAD
+  Bool            bUseNSHAD;
+#endif
+
+  // (vertical) subsampling shift (for reducing complexity)
+  // - 0 = no subsampling, 1 = even rows, 2 = every 4th, etc.
+  Int   iSubShift;
+  
+  DistParam()
+  {
+    pOrg = NULL;
+    pCur = NULL;
+#if SAIT_VSO_EST_A0033
+    pVirRec = NULL;
+    pVirOrg = NULL;;
+    iStrideVir = 0;
+#endif
+    iStrideOrg = 0;
+    iStrideCur = 0;
+    iRows = 0;
+    iCols = 0;
+    iStep = 1;
+    DistFunc = NULL;
+    iSubShift = 0;
+#if HHI_INTERVIEW_SKIP
+    pUsed       = 0;
+    iStrideUsed = 0;
+#endif
+#if NS_HAD
+    bUseNSHAD = false;
+#endif
+  }
+};
+
+/// RD cost computation class
+class TComRdCost
+  : public TComRdCostWeightPrediction
+{
+private:
+  // for distortion
+  Int                     m_iBlkWidth;
+  Int                     m_iBlkHeight;
+  
+#if AMP_SAD
+  FpDistFunc              m_afpDistortFunc[64]; // [eDFunc]
+#else  
+  FpDistFunc              m_afpDistortFunc[33]; // [eDFunc]
+#endif  
+  
+#if WEIGHTED_CHROMA_DISTORTION
+  Double                  m_chromaDistortionWeight;   
+#endif
+  Double                  m_dLambda;
+  Double                  m_sqrtLambda;
+  UInt                    m_uiLambdaMotionSAD;
+  UInt                    m_uiLambdaMotionSSE;
+  Double                  m_dFrameLambda;
+#if SAIT_VSO_EST_A0033
+  static Double           m_dDisparityCoeff;
+#endif
+  
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  Double                  m_dLambdaScale ;
+#endif
+  // for motion cost
+#if FIX203
+  TComMv                  m_mvPredictor;
+#else
+  UInt*                   m_puiComponentCostOriginP;
+  UInt*                   m_puiComponentCost;
+  UInt*                   m_puiVerCost;
+  UInt*                   m_puiHorCost;
+#endif
+  UInt                    m_uiCost;
+  Int                     m_iCostScale;
+#if !FIX203
+  Int                     m_iSearchLimit;
+#endif
+  
+  Bool                    m_bUseMultiviewReg;
+  UInt                    m_uiLambdaMVReg;
+  UInt                    m_uiLambdaMVRegSAD;
+  UInt                    m_uiLambdaMVRegSSE;
+  UInt*                   m_puiMultiviewRegCostHorOrgP;
+  UInt*                   m_puiMultiviewRegCostVerOrgP;
+  UInt*                   m_puiMultiviewRegCostHor;
+  UInt*                   m_puiMultiviewRegCostVer;
+  UInt*                   m_puiHorRegCost;
+  UInt*                   m_puiVerRegCost;
+  TComMv                  m_cMultiviewOrgMvPred;
+  
+public:
+  TComRdCost();
+  virtual ~TComRdCost();
+  
+  Double  calcRdCost  ( UInt   uiBits, UInt   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  
+#if WEIGHTED_CHROMA_DISTORTION
+  Void    setChromaDistortionWeight      ( Double chromaDistortionWeight) { m_chromaDistortionWeight = chromaDistortionWeight; };
+#endif
+  Void    setLambda      ( Double dLambda );
+#if H3D_IVMP
+  Void    setLambdaMVReg ( Double dLambda );
+#endif
+  Void    setFrameLambda ( Double dLambda ) { m_dFrameLambda = dLambda; }
+  
+#if SAIT_VSO_EST_A0033
+  Void    setDisparityCoeff( Double dDisparityCoeff ) { m_dDisparityCoeff = dDisparityCoeff; }
+  Double  getDisparityCoeff()                         { return m_dDisparityCoeff; }
+#endif
+
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  Void   setLambdaScale  ( Double dLambdaScale) { m_dLambdaScale = dLambdaScale; }
+  Double   getLambdaScale  ( ) { return m_dLambdaScale ; }
+#endif
+  Double  getSqrtLambda ()   { return m_sqrtLambda; }
+  
+  // Distortion Functions
+  Void    init();
+  
+  Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+#if NS_HAD
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false, Bool bUseNSHAD=false );
+  Void    setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false, Bool bUseNSHAD=false );
+#else
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
+  Void    setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
+#endif
+  
+  UInt    calcHAD         ( Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
+  
+  // 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); 
+    m_uiLambdaMVReg = ( bSad ? m_uiLambdaMVRegSAD         : m_uiLambdaMVRegSSE         );
+
+   }
+  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 )
+  {
+#if FIX203
+    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 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
+  }
+
+  Void    setMultiviewReg( TComMv* pcMv )
+  {
+    if( pcMv )
+    {
+      m_bUseMultiviewReg    = true;
+      m_puiHorRegCost       = m_puiMultiviewRegCostHor - pcMv->getHor();
+      m_puiVerRegCost       = m_puiMultiviewRegCostVer - pcMv->getVer();
+      m_cMultiviewOrgMvPred = *pcMv;
+    }
+    else
+    {
+      m_bUseMultiviewReg    = false;
+      m_puiHorRegCost       = 0;
+      m_puiVerRegCost       = 0;
+      m_cMultiviewOrgMvPred.set( 0, 0 );
+    }
+  }
+  __inline Bool     useMultiviewReg      () { return m_bUseMultiviewReg; }
+  __inline TComMv&  getMultiviewOrgMvPred() { return m_cMultiviewOrgMvPred; }
+  __inline UInt     getMultiviewRegCost  ( Int x, Int y )
+  {
+#if FIX203
+    return m_uiLambdaMVReg * getBits(x, y) >> 16;
+#else
+    return ( ( m_uiLambdaMVReg * ( m_puiHorRegCost[ x * ( 1 << m_iCostScale ) ] + m_puiVerRegCost[ y * ( 1 << m_iCostScale ) ] ) ) >> 16 );
+#endif
+  }
+  
+private:
+  
+#if LGE_ILLUCOMP_B0045
+  static UInt xGetSADic         ( DistParam* pcDtParam );
+  static UInt xGetSAD4ic        ( DistParam* pcDtParam );
+  static UInt xGetSAD8ic        ( DistParam* pcDtParam );
+  static UInt xGetSAD16ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD32ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD64ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD16Nic      ( DistParam* pcDtParam );
+#endif
+  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 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 SAIT_VSO_EST_A0033
+  static UInt xGetVSD           ( DistParam* pcDtParam );
+  static UInt xGetVSD4          ( DistParam* pcDtParam );
+  static UInt xGetVSD8          ( DistParam* pcDtParam );
+  static UInt xGetVSD16         ( DistParam* pcDtParam );
+  static UInt xGetVSD32         ( DistParam* pcDtParam );
+  static UInt xGetVSD64         ( DistParam* pcDtParam );
+  static UInt xGetVSD16N        ( DistParam* pcDtParam );
+#endif
+
+#if AMP_SAD
+#if LGE_ILLUCOMP_B0045
+  static UInt xGetSAD12ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD24ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD48ic       ( DistParam* pcDtParam );
+#endif
+  static UInt xGetSAD12         ( DistParam* pcDtParam );
+  static UInt xGetSAD24         ( DistParam* pcDtParam );
+  static UInt xGetSAD48         ( DistParam* pcDtParam );
+#endif
+
+#if LGE_ILLUCOMP_B0045
+  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 );
+#if NS_HAD
+  static UInt xCalcHADs16x4     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs4x16     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+#endif
+  
+public:
+#if HHI_INTERVIEW_SKIP
+  UInt   getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, Pel* piUsed, Int iUsedStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc = DF_SSE );
+#endif
+#if WEIGHTED_CHROMA_DISTORTION
+  UInt   getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bWeighted = false, DFunc eDFunc = DF_SSE );
+#else
+  UInt   getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc = DF_SSE );
+#endif
+  
+#if SAIT_VSO_EST_A0033
+  UInt   getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, Pel* piVirRec, Pel* piVirOrg, Int iVirStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc = DF_VSD );
+  static UInt getVSDEstimate( Int dDM, Pel* pOrg, Int iOrgStride,  Pel* pVirRec, Pel* pVirOrg, Int iVirStride, Int x, Int y );
+#endif
+
+#if HHI_VSO
+private:
+  Double                  m_dLambdaVSO;
+  Double                  m_dSqrtLambdaVSO;
+  UInt                    m_uiLambdaMotionSADVSO;
+  UInt                    m_uiLambdaMotionSSEVSO;
+  Double                  m_dFrameLambdaVSO;
+
+#if HHI_VSO_DIST_INT
+  Bool                    m_bAllowNegDist;
+#endif
+#if SAIT_VSO_EST_A0033
+  TComPicYuv *            m_pcVideoRecPicYuv;
+  TComPicYuv *            m_pcDepthPicYuv;
+  Bool                    m_bUseEstimatedVSD; 
+#endif
+#if LGE_WVSO_A0119
+  Int                     m_iDWeight;
+  Int                     m_iVSOWeight;
+  Int                     m_iVSDWeight;
+  Bool                    m_bUseWVSO;
+#endif
+
+  Bool                    m_bUseVSO;
+  Bool                    m_bUseLambdaScaleVSO;
+  UInt                    m_uiVSOMode;
+
+  FpDistFuncVSO           m_fpDistortFuncVSO;
+  TRenModel*              m_pcRenModel;
+public:
+
+  Void    setRenModel       ( TRenModel* pcRenModel ) { m_pcRenModel = pcRenModel; }
+  Void    setRenModelData   ( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piData, Int iStride, Int iBlkWidth, Int iBlkHeight );
+  Void    setLambdaVSO      ( Double dLambda );
+  Void    setFrameLambdaVSO ( Double dLambda ) { m_dFrameLambdaVSO = dLambda; };
+
+
+  Void    setUseVSO ( Bool bIn )         { m_bUseVSO = bIn; };
+  Bool    getUseVSO ( )                  { return m_bUseVSO;};
+#if SAIT_VSO_EST_A0033
+  Bool    getUseEstimatedVSD( )           { return m_bUseEstimatedVSD; };
+  Void    setUseEstimatedVSD( Bool bIn )  { m_bUseEstimatedVSD = bIn; };
+
+  TComPicYuv* getVideoRecPicYuv ()                               { return m_pcVideoRecPicYuv; };
+  Void        setVideoRecPicYuv ( TComPicYuv* pcVideoRecPicYuv ) { m_pcVideoRecPicYuv = pcVideoRecPicYuv; };
+  TComPicYuv* getDepthPicYuv    ()                               { return m_pcDepthPicYuv; };
+  Void        setDepthPicYuv    ( TComPicYuv* pcDepthPicYuv )    { m_pcDepthPicYuv = pcDepthPicYuv; };
+#endif
+
+  Bool    getUseRenModel ( )             { return (m_bUseVSO && m_uiVSOMode == 4); };
+  Void    setUseLambdaScaleVSO(bool bIn) { m_bUseLambdaScaleVSO = bIn; };
+  Bool    getUseLambdaScaleVSO( )        { return m_bUseLambdaScaleVSO; };
+
+  Void    setVSOMode( UInt uiIn);
+  UInt    getVSOMode( )                  { return m_uiVSOMode; }
+#if LGE_WVSO_A0119
+  Void    setUseWVSO ( Bool bIn )         { m_bUseWVSO = bIn; }; 
+  Bool    getUseWVSO ( )                  { return m_bUseWVSO;};
+  Void    setDWeight   ( Int iDWeight   ) { m_iDWeight = iDWeight; };
+  Int     getDWeight   ()                 { return m_iDWeight; };
+  Void    setVSOWeight ( Int iVSOWeight ) { m_iVSOWeight = iVSOWeight; };
+  Int     getVSOWeight ()                 { return m_iVSOWeight; };
+  Void    setVSDWeight ( Int iVSDWeight ) { m_iVSDWeight = iVSDWeight; };
+  Int     getVSDWeight ()                 { return m_iVSDWeight; };
+#endif 
+#if HHI_VSO_DIST_INT
+  Void    setAllowNegDist ( Bool bAllowNegDist );
+#endif
+
+
+  Double  getSqrtLambdaVSO ()   { return m_dSqrtLambdaVSO; }
+  Double  getLambdaVSO ()       { return m_dLambdaVSO; }
+
+  Dist    getDistVS( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD, UInt uiPlane );
+  Double calcRdCostVSO( UInt   uiBits, Dist   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+
+private:
+  Dist xGetDistVSOMode4( Int iStartPosX, Int iStartPosY, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD );
+
+#endif // HHI_VSO
+
+};// END CLASS DEFINITION TComRdCost
+
+//! \}
+
+#endif // __TCOMRDCOST__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 341)
@@ -0,0 +1,590 @@
+/* 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-2012, 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     TComRdCostWeightPrediction.cpp
+    \brief    RD cost computation class with Weighted-Prediction
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRdCost.h"
+#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()
+{
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted SAD cost
+ * \param pcDtParam
+ * \returns UInt
+ */
+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;
+#if HHI_INTERVIEW_SKIP
+  if( pcDtParam->pUsed )
+  {
+    Pel*  piUsed      = pcDtParam->pUsed;
+    Int   iStrideUsed = pcDtParam->iStrideUsed;
+    for( ; iRows != 0; iRows-- )
+    {
+      for (Int n = 0; n < iCols; n++ )
+      {
+        if( piUsed[n])
+        {
+          pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+          uiSum += abs( piOrg[n] - pred );
+        }
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+#if FIX_LGE_WP_FOR_3D_C0223
+  }
+  else
+  {
+#endif
+#if FIX_LGE_WP_FOR_3D_C0223 //comment of #else
+    //#else
+#endif
+#endif
+    for( ; iRows != 0; iRows-- )
+    {
+      for (Int n = 0; n < iCols; n++ )
+      {
+        pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+        uiSum += abs( piOrg[n] - pred );
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+#if FIX_LGE_WP_FOR_3D_C0223 //comment of #endif
+    //#endif
+#endif
+#if HHI_INTERVIEW_SKIP
+  }
+#endif
+  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted SSD cost
+ * \param pcDtParam
+ * \returns UInt
+ */
+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 = g_uiBitIncrement<<1;
+  
+  Int iTemp;
+  
+  for( ; 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;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  return ( uiSum );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// 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 );
+  Pel   pred;
+
+  pred    = ( (m_w0*piCur[0*iStep             ] + m_round) >> m_shift ) + m_offset ;
+  diff[0] = piOrg[0             ] - pred;
+  pred    = ( (m_w0*piCur[1*iStep             ] + m_round) >> m_shift ) + m_offset ;
+  diff[1] = piOrg[1             ] - pred;
+  pred    = ( (m_w0*piCur[0*iStep + iStrideCur] + m_round) >> m_shift ) + m_offset ;
+  diff[2] = piOrg[iStrideOrg    ] - pred;
+  pred    = ( (m_w0*piCur[1*iStep + iStrideCur] + m_round) >> m_shift ) + m_offset ;
+  diff[3] = piOrg[iStrideOrg + 1] - pred;
+
+  m[0] = diff[0] + diff[2];
+  m[1] = diff[1] + diff[3];
+  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 ;
+    diff[k+0] = piOrg[0] - pred;
+    pred      = ( (m_w0*piCur[1*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+1] = piOrg[1] - pred;
+    pred      = ( (m_w0*piCur[2*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+2] = piOrg[2] - pred;
+    pred      = ( (m_w0*piCur[3*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+3] = piOrg[3] - pred;
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  /*===== hadamard transform =====*/
+  m[ 0] = diff[ 0] + diff[12];
+  m[ 1] = diff[ 1] + diff[13];
+  m[ 2] = diff[ 2] + diff[14];
+  m[ 3] = diff[ 3] + diff[15];
+  m[ 4] = diff[ 4] + diff[ 8];
+  m[ 5] = diff[ 5] + diff[ 9];
+  m[ 6] = diff[ 6] + diff[10];
+  m[ 7] = diff[ 7] + diff[11];
+  m[ 8] = diff[ 4] - diff[ 8];
+  m[ 9] = diff[ 5] - diff[ 9];
+  m[10] = diff[ 6] - diff[10];
+  m[11] = diff[ 7] - diff[11];
+  m[12] = diff[ 0] - diff[12];
+  m[13] = diff[ 1] - diff[13];
+  m[14] = diff[ 2] - diff[14];
+  m[15] = diff[ 3] - diff[15];
+  
+  d[ 0] = m[ 0] + m[ 4];
+  d[ 1] = m[ 1] + m[ 5];
+  d[ 2] = m[ 2] + m[ 6];
+  d[ 3] = m[ 3] + m[ 7];
+  d[ 4] = m[ 8] + m[12];
+  d[ 5] = m[ 9] + m[13];
+  d[ 6] = m[10] + m[14];
+  d[ 7] = m[11] + m[15];
+  d[ 8] = m[ 0] - m[ 4];
+  d[ 9] = m[ 1] - m[ 5];
+  d[10] = m[ 2] - m[ 6];
+  d[11] = m[ 3] - m[ 7];
+  d[12] = m[12] - m[ 8];
+  d[13] = m[13] - m[ 9];
+  d[14] = m[14] - m[10];
+  d[15] = m[15] - m[11];
+  
+  m[ 0] = d[ 0] + d[ 3];
+  m[ 1] = d[ 1] + d[ 2];
+  m[ 2] = d[ 1] - d[ 2];
+  m[ 3] = d[ 0] - d[ 3];
+  m[ 4] = d[ 4] + d[ 7];
+  m[ 5] = d[ 5] + d[ 6];
+  m[ 6] = d[ 5] - d[ 6];
+  m[ 7] = d[ 4] - d[ 7];
+  m[ 8] = d[ 8] + d[11];
+  m[ 9] = d[ 9] + d[10];
+  m[10] = d[ 9] - d[10];
+  m[11] = d[ 8] - d[11];
+  m[12] = d[12] + d[15];
+  m[13] = d[13] + d[14];
+  m[14] = d[13] - d[14];
+  m[15] = d[12] - d[15];
+  
+  d[ 0] = m[ 0] + m[ 1];
+  d[ 1] = m[ 0] - m[ 1];
+  d[ 2] = m[ 2] + m[ 3];
+  d[ 3] = m[ 3] - m[ 2];
+  d[ 4] = m[ 4] + m[ 5];
+  d[ 5] = m[ 4] - m[ 5];
+  d[ 6] = m[ 6] + m[ 7];
+  d[ 7] = m[ 7] - m[ 6];
+  d[ 8] = m[ 8] + m[ 9];
+  d[ 9] = m[ 8] - m[ 9];
+  d[10] = m[10] + m[11];
+  d[11] = m[11] - m[10];
+  d[12] = m[12] + m[13];
+  d[13] = m[12] - m[13];
+  d[14] = m[14] + m[15];
+  d[15] = m[15] - m[14];
+  
+  for (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];
+  Int iStep2 = iStep<<1;
+  Int iStep3 = iStep2 + iStep;
+  Int iStep4 = iStep3 + iStep;
+  Int iStep5 = iStep4 + iStep;
+  Int iStep6 = iStep5 + iStep;
+  Int iStep7 = iStep6 + iStep;
+  
+  assert( m_xSetDone );
+  Pel   pred;
+
+  for( k = 0; k < 64; k+=8 )
+  {
+    pred      = ( (m_w0*piCur[     0] + m_round) >> m_shift ) + m_offset ;
+    diff[k+0] = piOrg[0] - pred;
+    pred      = ( (m_w0*piCur[iStep ] + m_round) >> m_shift ) + m_offset ;
+    diff[k+1] = piOrg[1] - pred;
+    pred      = ( (m_w0*piCur[iStep2] + m_round) >> m_shift ) + m_offset ;
+    diff[k+2] = piOrg[2] - pred;
+    pred      = ( (m_w0*piCur[iStep3] + m_round) >> m_shift ) + m_offset ;
+    diff[k+3] = piOrg[3] - pred;
+    pred      = ( (m_w0*piCur[iStep4] + m_round) >> m_shift ) + m_offset ;
+    diff[k+4] = piOrg[4] - pred;
+    pred      = ( (m_w0*piCur[iStep5] + m_round) >> m_shift ) + m_offset ;
+    diff[k+5] = piOrg[5] - pred;
+    pred      = ( (m_w0*piCur[iStep6] + m_round) >> m_shift ) + m_offset ;
+    diff[k+6] = piOrg[6] - pred;
+    pred      = ( (m_w0*piCur[iStep7] + m_round) >> m_shift ) + m_offset ;
+    diff[k+7] = piOrg[7] - pred;
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+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];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    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];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+  
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    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];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    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];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+  
+  for (j=0; j < 8; j++)
+  {
+    for (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 >> g_uiBitIncrement );
+}
+
+/** 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 >> g_uiBitIncrement );
+}
+
+/** 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]);
+  Int   w0      = wpCur->w,
+        offset  = wpCur->offset,
+        shift   = wpCur->shift,
+        round   = wpCur->round; 
+  xSetWPscale(w0, 0, shift, offset, round);
+
+  UInt 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 )
+      {
+        uiSum += xCalcHADs8x8w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  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 )
+      {
+        uiSum += xCalcHADs4x4w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  
+  m_xSetDone  = false;
+
+  return ( uiSum >> g_uiBitIncrement );
+}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 341)
@@ -0,0 +1,96 @@
+/* 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-2012, 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     TComRdCostWeightPrediction.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOSTWEIGHTPREDICTION__
+#define __TCOMRDCOSTWEIGHTPREDICTION__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+#include "TComRdCost.h"
+#include "TComSlice.h"
+
+class DistParam;
+class TComPattern;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// RD cost computation class, with Weighted Prediction
+class 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;
+}
+
+#endif // __TCOMRDCOSTWEIGHTPREDICTION__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComResidualGenerator.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComResidualGenerator.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComResidualGenerator.cpp	(revision 341)
@@ -0,0 +1,662 @@
+/* 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-2011, 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 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     TComResidualGenerator.cpp
+    \brief    residual picture generator class
+*/
+
+
+
+#include "CommonDef.h"
+#include "TComResidualGenerator.h"
+
+
+#if H3D_IVRP
+
+
+TComResidualGenerator::TComResidualGenerator()
+{
+  m_bCreated            = false;
+  m_bInit               = false;
+  m_bDecoder            = false;
+  m_pcTrQuant           = 0;
+  m_pcDepthMapGenerator = 0;
+  m_pcSPSAccess         = 0;
+  m_pcAUPicAccess       = 0;
+  m_uiMaxDepth          = 0;
+  m_uiOrgDepthBitDepth  = 0;
+  m_ppcYuvTmp           = 0;
+  m_ppcYuv              = 0;
+  m_ppcCU               = 0;
+}
+
+TComResidualGenerator::~TComResidualGenerator()
+{
+  destroy ();
+  uninit  ();
+}
+
+Void
+TComResidualGenerator::create( Bool bDecoder, UInt uiPicWidth, UInt uiPicHeight, UInt uiMaxCUDepth, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiOrgBitDepth )
+{
+  destroy();
+  m_bDecoder            = bDecoder;
+  m_uiMaxDepth          = uiMaxCUDepth;
+  m_uiOrgDepthBitDepth  = uiOrgBitDepth;
+  m_ppcYuvTmp           = new TComYuv*    [ NUM_TMP_YUV_BUFFERS ];
+  m_ppcYuv              = new TComYuv*    [ m_uiMaxDepth ];
+  m_ppcCU               = new TComDataCU* [ m_uiMaxDepth ];
+  for( UInt uiIdx = 0; uiIdx < NUM_TMP_YUV_BUFFERS; uiIdx++ )
+  {
+    m_ppcYuvTmp[uiIdx]  = new TComYuv;    m_ppcYuvTmp[uiIdx]->create( uiMaxCUWidth, uiMaxCUHeight );
+  }
+  for( UInt uiDepth = 0; uiDepth < m_uiMaxDepth; uiDepth++ )
+  {
+    UInt  uiNumPart = 1 << ( ( m_uiMaxDepth - uiDepth ) << 1 );
+    UInt  uiWidth   = uiMaxCUWidth  >> uiDepth;
+    UInt  uiHeight  = uiMaxCUHeight >> uiDepth;
+
+    m_ppcYuv[ uiDepth ] = new TComYuv;    m_ppcYuv[ uiDepth ]->create(            uiWidth, uiHeight                                           );
+    m_ppcCU [ uiDepth ] = new TComDataCU; m_ppcCU [ uiDepth ]->create( uiNumPart, uiWidth, uiHeight, true, uiMaxCUWidth >> (uiMaxCUDepth - 1) );
+  }
+  m_cTmpPic.create( uiPicWidth, uiPicHeight, uiMaxCUWidth, uiMaxCUHeight, uiMaxCUDepth );
+  m_bCreated            = true;
+}
+
+Void
+TComResidualGenerator::destroy()
+{
+  if( m_bCreated )
+  {
+    m_bCreated            = false;
+    for( UInt uiIdx = 0; uiIdx < NUM_TMP_YUV_BUFFERS; uiIdx++ )
+    {
+      m_ppcYuvTmp[uiIdx]->destroy();  delete m_ppcYuvTmp[uiIdx]; m_ppcYuvTmp[uiIdx] = 0;
+    }
+    for( UInt uiDepth = 0; uiDepth < m_uiMaxDepth; uiDepth++ )
+    {
+      m_ppcYuv[ uiDepth ]->destroy(); delete m_ppcYuv[ uiDepth ]; m_ppcYuv[ uiDepth ] = 0;
+      m_ppcCU [ uiDepth ]->destroy(); delete m_ppcCU [ uiDepth ]; m_ppcCU [ uiDepth ] = 0;
+    }
+    delete [] m_ppcYuvTmp;  m_ppcYuvTmp = 0;
+    delete [] m_ppcYuv;     m_ppcYuv = 0;
+    delete [] m_ppcCU;      m_ppcCU  = 0;
+    m_cTmpPic.destroy();
+    m_uiMaxDepth          = 0;
+    m_uiOrgDepthBitDepth  = 0;
+    m_bDecoder            = false;
+  }
+}
+
+Void
+TComResidualGenerator::init( TComTrQuant* pcTrQuant, TComDepthMapGenerator* pcDepthMapGenerator )
+{
+  AOF( pcTrQuant           );
+  AOF( pcDepthMapGenerator );
+  AOF( pcDepthMapGenerator->getSPSAccess  () );
+  AOF( pcDepthMapGenerator->getAUPicAccess() );
+  uninit();
+  m_pcTrQuant           = pcTrQuant;
+  m_pcDepthMapGenerator = pcDepthMapGenerator;
+  m_pcSPSAccess         = pcDepthMapGenerator->getSPSAccess  ();
+  m_pcAUPicAccess       = pcDepthMapGenerator->getAUPicAccess();
+  m_bInit               = true;
+}
+
+Void
+TComResidualGenerator::uninit()
+{
+  if( m_bInit )
+  {
+    m_bInit               = false;
+    m_pcTrQuant           = 0;
+    m_pcDepthMapGenerator = 0;
+    m_pcSPSAccess         = 0;
+    m_pcAUPicAccess       = 0;
+  }
+}
+
+
+
+Void  
+TComResidualGenerator::initViewComponent( TComPic* pcPic )
+{
+  AOF  ( m_bCreated && m_bInit );
+  AOF  ( pcPic );
+
+  // set pointer in SPS
+  pcPic->getSPS()->setResidualGenerator( this );
+  ROFVS( pcPic->getSPS()->getMultiviewResPredMode() );
+
+#if OUTPUT_RESIDUAL_PICTURES
+  // dump reconstructed residual picture for first AU
+  if( pcPic->getPOC() == 0 )
+  {
+    AOF( pcPic->getSPS()->getViewId() );
+    UInt       uiBaseViewId = pcPic->getSPS()->getViewId() - 1;
+    TComPic*   pcBasePic    = m_pcAUPicAccess->getPic( uiBaseViewId );
+    AOF( pcBasePic );
+    Char       acFilenameBase[1024];
+    ::sprintf( acFilenameBase,  "RecResidual_%s", ( m_bDecoder ? "Dec" : "Enc" ) );
+    xDumpResidual( pcBasePic, acFilenameBase );
+  }
+#endif
+}
+
+
+
+Void
+TComResidualGenerator::setRecResidualPic( TComPic* pcPic )
+{
+  AOF  ( m_bCreated && m_bInit );
+  AOF  ( pcPic );
+
+#if H3D_IVRP
+  if (pcPic->getSPS()->getViewId() != 0)
+  {
+    return;
+  }
+#endif
+
+  if( pcPic->getPOC() == 0 )
+  {
+    if( pcPic->getSPS()->getViewId() == 0 || m_pcSPSAccess->getResPrd() != 0 )
+    {
+      // set residual picture
+      AOT( pcPic->getResidual() );
+      if( !pcPic->getResidual() )
+      {
+        pcPic->addResidualBuffer();
+      }
+      xSetRecResidualPic( pcPic );
+    }
+  }
+  else
+  {
+    if( m_pcSPSAccess->getResPrd() != 0 && pcPic->getSPS()->getViewId() < m_pcAUPicAccess->getMaxVId() )
+    {
+      // set residual picture
+      AOT( pcPic->getResidual() );
+      if( !pcPic->getResidual() )
+      {
+        pcPic->addResidualBuffer();
+      }
+      xSetRecResidualPic( pcPic );
+
+#if OUTPUT_RESIDUAL_PICTURES
+      // dump reconstructed residual picture
+      Char acFilenameBase[1024];
+      ::sprintf( acFilenameBase,  "RecResidual_%s", ( m_bDecoder ? "Dec" : "Enc" ) );
+      xDumpResidual( pcPic, acFilenameBase );
+#endif
+    }
+  }
+}
+
+#if H3D_NBDV
+Bool
+TComResidualGenerator::getResidualSamples( TComDataCU* pcCU, UInt uiPUIdx, TComYuv* pcYuv, TComMv iDisp, Bool bRecon  ) 
+#else
+Bool
+TComResidualGenerator::getResidualSamples( TComDataCU* pcCU, UInt uiPUIdx, TComYuv* pcYuv, Bool bRecon ) 
+#endif //H3D_NBDV
+{
+  AOF(  pcCU );
+  UInt  uiPartAddr;
+  Int   iBlkWidth, iBlkHeight, iXPos, iYPos;
+  AOT(  uiPUIdx );
+  uiPartAddr  = 0;
+  iBlkWidth   = pcCU->getWidth  ( 0 );
+  iBlkHeight  = pcCU->getHeight ( 0 );
+  pcCU->getPic()->getPicYuvRec()->getTopLeftSamplePos( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr, iXPos, iYPos );
+#if H3D_NBDV
+  return getResidualSamples( pcCU->getPic(), (UInt)iXPos, (UInt)iYPos, (UInt)iBlkWidth, (UInt)iBlkHeight, pcYuv, iDisp, bRecon); 
+#else
+  return getResidualSamples( pcCU->getPic(), (UInt)iXPos, (UInt)iYPos, (UInt)iBlkWidth, (UInt)iBlkHeight, pcYuv, bRecon); 
+#endif // H3D_NBDV
+}
+  
+#if H3D_NBDV
+Bool
+TComResidualGenerator::getResidualSamples( TComPic* pcPic, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv, TComMv iDisp, Bool bRecon)  
+#else
+Bool
+TComResidualGenerator::getResidualSamples( TComPic* pcPic, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv, Bool bRecon) 
+#endif
+{
+  UInt  uiBaseViewId  = 0;
+  if( !pcYuv )
+  {
+    pcYuv = m_ppcYuvTmp[1];
+  }
+  UInt uiXPosInRefView = uiXPos , uiYPosInRefView = uiYPos;
+#if H3D_NBDV
+  xSetPredResidualBlock( pcPic, uiBaseViewId, uiXPos, uiYPos, uiBlkWidth, uiBlkHeight, pcYuv, iDisp, &uiXPosInRefView , &uiYPosInRefView , bRecon  );
+#else
+  xSetPredResidualBlock( pcPic, uiBaseViewId, uiXPos, uiYPos, uiBlkWidth, uiBlkHeight, pcYuv, &uiXPosInRefView , &uiYPosInRefView , bRecon    );
+#endif
+  return true;
+}
+
+Bool TComResidualGenerator::xIsNonZeroByCBF( UInt uiBaseViewId , UInt uiXPos , UInt uiYPos, UInt uiBlkWidth , UInt uiBlkHeight )
+{
+  TComPic* pcBasePic   = m_pcAUPicAccess->getPic( uiBaseViewId );
+  const Int nMaxPicX = pcBasePic->getSPS()->getPicWidthInLumaSamples() - 1;
+  const Int nMaxPicY = pcBasePic->getSPS()->getPicHeightInLumaSamples() - 1;
+  for( UInt y = 0 ; y < uiBlkHeight ; y +=4 )
+  {
+    for( UInt x = 0 ; x <= uiBlkWidth ; x += 4 )
+    {      // to cover both the mapped CU and the 1-pixel-right-shifted mapped CU
+      Int iCuAddr = 0, iAbsZorderIdx = 0;
+      pcBasePic->getPicYuvRec()->getCUAddrAndPartIdx( Min( uiXPos + x , nMaxPicX ) , Min( uiYPos + y , nMaxPicY ) , iCuAddr , iAbsZorderIdx );
+      TComDataCU *pCUInRefView = pcBasePic->getCU( iCuAddr );
+      if( pCUInRefView->isIntra( iAbsZorderIdx ) )
+        // no inter-view residual pred from a intra CU
+        continue;
+      UInt uiTempTrDepth = pCUInRefView->getTransformIdx( iAbsZorderIdx );
+      if( pCUInRefView->getCbf( iAbsZorderIdx , TEXT_LUMA , uiTempTrDepth )
+        || pCUInRefView->getCbf( iAbsZorderIdx , TEXT_CHROMA_U , uiTempTrDepth )
+        || pCUInRefView->getCbf( iAbsZorderIdx , TEXT_CHROMA_V , uiTempTrDepth ) )
+        return( true );
+}
+  }
+
+  return( false );
+}
+
+
+
+Void
+TComResidualGenerator::xSetRecResidualPic( TComPic* pcPic )
+{
+  AOF( pcPic );
+  AOF( pcPic->getResidual() );
+  for( UInt uiCUAddr = 0; uiCUAddr < pcPic->getPicSym()->getNumberOfCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+    xSetRecResidualCU( pcCU, 0, 0 );
+  }
+  pcPic->getResidual()->setBorderExtension( false );
+  pcPic->getResidual()->extendPicBorder   ();
+}
+
+
+Void
+TComResidualGenerator::xSetRecResidualCU( TComDataCU* pcCU, UInt uiDepth, UInt uiAbsPartIdx )
+{
+  UInt  uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  UInt  uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  UInt  uiRPelX   = uiLPelX           + ( g_uiMaxCUWidth  >> uiDepth ) - 1;
+  UInt  uiBPelY   = uiTPelY           + ( g_uiMaxCUHeight >> uiDepth ) - 1;
+  Bool  bBoundary = ( uiRPelX >= pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() || uiBPelY >= pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() );
+  Bool  bSplit    = ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) && uiDepth < ( g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary );
+  if(   bSplit )
+  {
+    UInt uiQNumParts = ( pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 ) ) >> 2;
+    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  bInside = ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() && uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() );
+      if(   bInside )
+      {
+        xSetRecResidualCU( pcCU, uiDepth + 1, uiAbsPartIdx );
+      }
+    }
+    return;
+  }
+
+  //--- set sub-CU and sub-residual ---
+  TComDataCU* pcSubCU   = m_ppcCU [ uiDepth ];
+  TComYuv*    pcSubRes  = m_ppcYuv[ uiDepth ];
+  TComPicYuv* pcPicRes  = pcCU->getPic()->getResidual();
+  UInt        uiCUAddr  = pcCU->getAddr();
+  pcSubCU->copySubCU( pcCU, uiAbsPartIdx, uiDepth );
+
+  //--- set residual ---
+  switch( pcSubCU->getPredictionMode( 0 ) )
+  {
+  case MODE_INTRA:
+    xSetRecResidualIntraCU( pcSubCU, pcSubRes );
+    break;
+  case MODE_SKIP:
+  case MODE_INTER:
+    xSetRecResidualInterCU( pcSubCU, pcSubRes );
+    break;
+  default:
+    AOT( true );
+    break;
+  }
+
+  //--- copy sub-residual ---
+  pcSubRes->copyToPicYuv( pcPicRes, uiCUAddr, uiAbsPartIdx );
+}
+
+
+Void  
+TComResidualGenerator::xSetRecResidualIntraCU( TComDataCU* pcCU, TComYuv* pcCUResidual )
+{ 
+  //===== set residual to zero for entire CU =====
+  xClearResidual( pcCUResidual, 0, pcCU->getWidth( 0 ), pcCU->getHeight( 0 ) );
+}
+
+
+Void
+TComResidualGenerator::xSetRecResidualInterCU( TComDataCU* pcCU, TComYuv* pcCUResidual )
+{
+  //===== reconstruct residual from coded transform coefficient levels =====
+  xClearResidual( pcCUResidual, 0, pcCU->getWidth( 0 ), pcCU->getHeight( 0 ) );
+  // luma
+  UInt    uiWidth   = pcCU->getWidth  ( 0 );
+  UInt    uiHeight  = pcCU->getHeight ( 0 );
+  TCoeff* piCoeff   = pcCU->getCoeffY ();
+  Pel*    pRes      = pcCUResidual->getLumaAddr();
+  UInt    uiLumaTrMode, uiChromaTrMode;
+  pcCU->convertTransIdx             ( 0, pcCU->getTransformIdx( 0 ), uiLumaTrMode, uiChromaTrMode );
+    m_pcTrQuant->setQPforQuant      ( pcCU->getQP( 0 ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_LUMA, pRes, 0, pcCUResidual->getStride(), uiWidth, uiHeight, uiLumaTrMode, 0, piCoeff );
+  // chroma Cb
+  uiWidth   >>= 1;
+  uiHeight  >>= 1;
+  piCoeff     = pcCU->getCoeffCb();
+  pRes        = pcCUResidual->getCbAddr();
+    m_pcTrQuant->setQPforQuant      ( pcCU->getQP( 0 ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset() );
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_U, pRes, 0, pcCUResidual->getCStride(), uiWidth, uiHeight, uiChromaTrMode, 0, piCoeff );
+  // chroma Cr
+  piCoeff     = pcCU->getCoeffCr();
+  pRes        = pcCUResidual->getCrAddr();
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_V, pRes, 0, pcCUResidual->getCStride(), uiWidth, uiHeight, uiChromaTrMode, 0, piCoeff );
+
+  //===== clear inter-view predicted parts =====
+  for( UInt uiPartIdx = 0; uiPartIdx < pcCU->getNumPartInter(); uiPartIdx++ )
+  {
+    xClearIntViewResidual( pcCU, pcCUResidual, uiPartIdx );
+  }
+}
+
+
+Void
+TComResidualGenerator::xClearIntViewResidual( TComDataCU* pcCU, TComYuv* pcCUResidual, UInt uiPartIdx )
+{
+  UInt uiCurrViewId = pcCU->getSlice()->getSPS()->getViewId();
+  if(  uiCurrViewId )
+  {
+    Int             iWidth;
+    Int             iHeight;
+    UInt            uiAbsPartIdx;
+    pcCU->getPartIndexAndSize( uiPartIdx, uiAbsPartIdx, iWidth, iHeight );
+    TComCUMvField*  aiCurrMvField[2]  = { pcCU->getCUMvField( REF_PIC_LIST_0 ),        pcCU->getCUMvField( REF_PIC_LIST_1 )        };
+    Int             aiCurrRefIdx [2]  = { aiCurrMvField[0]->getRefIdx( uiAbsPartIdx ), aiCurrMvField[1]->getRefIdx( uiAbsPartIdx ) };
+    Bool            abCurrIntView[2]  = { aiCurrRefIdx[0] >= 0 && pcCU->getSlice()->getRefPic( REF_PIC_LIST_0, aiCurrRefIdx[0] )->getSPS()->getViewId() != uiCurrViewId,
+                                          aiCurrRefIdx[1] >= 0 && pcCU->getSlice()->getRefPic( REF_PIC_LIST_1, aiCurrRefIdx[1] )->getSPS()->getViewId() != uiCurrViewId };
+    Bool            bUsesInterViewPrd = ( abCurrIntView[0] || abCurrIntView[1] );
+    if( bUsesInterViewPrd )
+    { //===== set resiudal to zero =====
+      xClearResidual( pcCUResidual, uiAbsPartIdx, (UInt)iWidth, (UInt)iHeight );
+    }
+  }
+}
+
+
+Void  
+TComResidualGenerator::xClearResidual( TComYuv* pcCUResidual, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight ) 
+{
+  // luma
+  Pel* pSamplesY = pcCUResidual->getLumaAddr( uiAbsPartIdx );
+  Int  iStrideY  = pcCUResidual->getStride  ();
+  for( UInt  uiY = 0; uiY < uiHeight; uiY++, pSamplesY += iStrideY )
+  {
+    ::memset( pSamplesY, 0x00, uiWidth * sizeof( Pel ) );
+  }
+  // chroma
+  uiWidth      >>= 1;
+  uiHeight     >>= 1;
+  Pel* pSamplesU = pcCUResidual->getCbAddr ( uiAbsPartIdx );
+  Pel* pSamplesV = pcCUResidual->getCrAddr ( uiAbsPartIdx );
+  Int  iStrideC  = pcCUResidual->getCStride();
+  for( UInt  uiY = 0; uiY < uiHeight; uiY++, pSamplesU += iStrideC, pSamplesV += iStrideC )
+  {
+    ::memset( pSamplesU, 0x00, uiWidth * sizeof( Pel ) );
+    ::memset( pSamplesV, 0x00, uiWidth * sizeof( Pel ) );
+  }
+}
+
+
+#if H3D_NBDV
+Void  
+TComResidualGenerator::xSetPredResidualBlock( TComPic* pcPic, UInt uiBaseViewId, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv, TComMv iDisp
+                                             ,UInt * puiXPosInRefView , UInt * puiYPosInRefView , Bool bRecon )
+#else // H3D_NBDV
+Void  
+TComResidualGenerator::xSetPredResidualBlock( TComPic* pcPic, UInt uiBaseViewId, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv 
+                                             , UInt * puiXPosInRefView , UInt * puiYPosInRefView , Bool bRecon  )
+#endif // H3D_NBDV
+{
+  //===== set and check some basic variables =====
+  AOF(          pcYuv     );
+  TComPic*      pcBasePic   = m_pcAUPicAccess->getPic( uiBaseViewId );
+  AOF(          pcPic     );
+  AOF(          pcBasePic );
+  TComPicYuv*   pcBaseRes   = pcBasePic->getResidual    ();
+  TComPicYuv*   pcPdmMap    = pcPic    ->getPredDepthMap();
+  AOF(          pcBaseRes );
+  AOF(          pcPdmMap  );
+  UInt          uiPicWidth  = pcBaseRes->getWidth ();
+  UInt          uiPicHeight = pcBaseRes->getHeight();
+  AOT( uiXPos + uiBlkWidth  > uiPicWidth  );
+  AOT( uiYPos + uiBlkHeight > uiPicHeight );
+
+  //===== get disparity =====
+#if H3D_NBDV
+  Int iDisparity_y = iDisp.getVer();
+  Int iDisparity   = iDisp.getHor();
+#else //H3D_NBDV
+  Int           iMidPosX    = Int( uiXPos + ( ( uiBlkWidth  - 1 ) >> 1 ) ) >> m_pcDepthMapGenerator->getSubSampExpX();
+  Int           iMidPosY    = Int( uiYPos + ( ( uiBlkHeight - 1 ) >> 1 ) ) >> m_pcDepthMapGenerator->getSubSampExpY();
+  Int           iDisparity  = m_pcDepthMapGenerator->getDisparity( pcPic, iMidPosX, iMidPosY, uiBaseViewId );
+#endif //H3D_NBDV
+  //===== compensate luma =====
+  Int           iYWidth     = Int( uiBlkWidth  );
+  Int           iYHeight    = Int( uiBlkHeight );
+  Int           iYWeight1   = ( iDisparity & 3 );
+  Int           iYWeight0   = 4 - iYWeight1;
+  Int           iYRefPosX0  = Int( uiXPos )     + ( iDisparity >> 2 );
+  Int           iYRefPosX1  = iYRefPosX0        + 1;
+  Int           iYMaxPosY   = Int( uiPicHeight ) - 1;
+  Int           iYWeight3   = ( iDisparity_y & 3 );
+  Int           iYWeight2   = 4 - iYWeight3;
+  Int           iYRefPosY0  = Max( 0, Min( iYMaxPosY, Int( uiYPos )     + ( iDisparity_y >> 2 )) );
+  Int           iYRefPosY1  = Max( 0, Min( iYMaxPosY, iYRefPosY0 + 1 ));
+  Int           iYMaxPosX   = Int( uiPicWidth ) - 1;
+  Int           iSrcStrideY = pcBaseRes->getStride   ();
+  Int           iDesStrideY = pcYuv    ->getStride   ();
+  Pel*          pSrcSamplesY0= pcBaseRes->getLumaAddr ( 0 ) + iYRefPosY0 * iSrcStrideY;
+  Pel*          pSrcSamplesY1= pcBaseRes->getLumaAddr ( 0 ) + iYRefPosY1 * iSrcStrideY;
+  Pel*          pDesSamplesY= pcYuv    ->getLumaAddr ();
+
+
+  if( puiXPosInRefView != NULL )
+    *puiXPosInRefView = Max( 0, Min( iYMaxPosX, iYRefPosX0 ) );
+  if( puiYPosInRefView != NULL )
+    *puiYPosInRefView = uiYPos;
+  if( bRecon == false )
+    return;
+
+  for(   Int iY = 0; iY < iYHeight; iY++, pSrcSamplesY0 += iSrcStrideY, pSrcSamplesY1 += iSrcStrideY, pDesSamplesY += iDesStrideY )
+  {
+    for( Int iX = 0; iX < iYWidth; iX++ )
+    {
+      Int iXPic0        = Max( 0, Min( iYMaxPosX, iYRefPosX0 + iX ) );
+      Int iXPic1        = Max( 0, Min( iYMaxPosX, iYRefPosX1 + iX ) );
+      Pel Temp1,Temp2;
+      Temp1 =( iYWeight0 * pSrcSamplesY0[iXPic0] + iYWeight1 * pSrcSamplesY0[iXPic1] + 2 ) >> 2;
+      Temp2 =( iYWeight0 * pSrcSamplesY1[iXPic0] + iYWeight1 * pSrcSamplesY1[iXPic1] + 2 ) >> 2;
+      pDesSamplesY[iX]  = ( iYWeight2 * Temp1 + iYWeight3 * Temp2 + 2 ) >> 2;
+    }
+  }
+
+  //===== compensate chroma =====
+  Int           iCWidth     = Int( uiBlkWidth  >> 1 );
+  Int           iCHeight    = Int( uiBlkHeight >> 1 );
+  Int           iCWeight1   = ( iDisparity & 7 );
+  Int           iCWeight0   = 8 - iCWeight1;
+  Int           iCRefPosX0  = Int( uiXPos     >> 1 ) + ( iDisparity >> 3 );
+  Int           iCRefPosX1  = iCRefPosX0             + 1;
+  Int           iCMaxPosY   = Int( uiPicHeight >> 1 ) - 1;
+  Int           iCWeight3   = ( iDisparity_y & 7 );
+  Int           iCWeight2   = 8 - iCWeight3;
+  Int           iCRefPosY0  = Max( 0, Min( iCMaxPosY, Int( uiYPos >> 1 )     + ( iDisparity_y >> 3 )) );
+  Int           iCRefPosY1  = Max( 0, Min( iCMaxPosY, iCRefPosY0 + 1 ));
+  Int           iCMaxPosX   = Int( uiPicWidth >> 1 ) - 1;
+  Int           iSrcStrideC = pcBaseRes->getCStride();
+  Int           iDesStrideC = pcYuv    ->getCStride();
+
+  Pel*          pSrcSamplesU0= pcBaseRes->getCbAddr ( 0 ) + iCRefPosY0 * iSrcStrideC;
+  Pel*          pSrcSamplesU1= pcBaseRes->getCbAddr ( 0 ) + iCRefPosY1 * iSrcStrideC;
+  Pel*          pSrcSamplesV0= pcBaseRes->getCrAddr ( 0 ) + iCRefPosY0 * iSrcStrideC;
+  Pel*          pSrcSamplesV1= pcBaseRes->getCrAddr ( 0 ) + iCRefPosY1 * iSrcStrideC;
+  Pel*          pDesSamplesU= pcYuv    ->getCbAddr ();
+  Pel*          pDesSamplesV= pcYuv    ->getCrAddr ();
+  for(   Int iY = 0; iY < iCHeight; iY++, pSrcSamplesU0 += iSrcStrideC, pSrcSamplesU1 += iSrcStrideC, pDesSamplesU += iDesStrideC,
+                                          pSrcSamplesV0 += iSrcStrideC, pSrcSamplesV1 += iSrcStrideC, pDesSamplesV += iDesStrideC )
+  {
+    for( Int iX = 0; iX < iCWidth; iX++ )
+    {
+      Int iXPic0        = Max( 0, Min( iCMaxPosX, iCRefPosX0 + iX ) );
+      Int iXPic1        = Max( 0, Min( iCMaxPosX, iCRefPosX1 + iX ) );
+      Pel Temp1,Temp2;
+      Temp1 =( iCWeight0 * pSrcSamplesU0[iXPic0] + iCWeight1 * pSrcSamplesU0[iXPic1] + 4 ) >> 3;
+      Temp2 =( iCWeight0 * pSrcSamplesU1[iXPic0] + iCWeight1 * pSrcSamplesU1[iXPic1] + 4 ) >> 3;
+      pDesSamplesU[iX]  = ( iCWeight2 * Temp1 + iCWeight3 * Temp2 + 4 ) >> 3;
+      Temp1 =( iCWeight0 * pSrcSamplesV0[iXPic0] + iCWeight1 * pSrcSamplesV0[iXPic1] + 4 ) >> 3;
+      Temp2 =( iCWeight0 * pSrcSamplesV1[iXPic0] + iCWeight1 * pSrcSamplesV1[iXPic1] + 4 ) >> 3;
+      pDesSamplesV[iX]  = ( iCWeight2 * Temp1 + iCWeight3 * Temp2 + 4 ) >> 3;
+    }
+  }
+}
+
+
+Bool
+TComResidualGenerator::xIsNonZero( TComYuv* pcYuv, UInt uiBlkWidth, UInt uiBlkHeight )
+{
+  AOF( pcYuv );
+  //===== check luma =====
+  Int   iYWidth   = Int( uiBlkWidth  );
+  Int   iYHeight  = Int( uiBlkHeight );
+  Int   iStrideY  = pcYuv->getStride   ();
+  Pel*  pSamplesY = pcYuv->getLumaAddr ();
+  for(   Int iY = 0; iY < iYHeight; iY++, pSamplesY += iStrideY )
+  {
+    for( Int iX = 0; iX < iYWidth; iX++ )
+    {
+      ROTRS( pSamplesY[iX], true );
+    }
+  }
+  //===== compensate chroma =====
+  Int   iCWidth   = Int( uiBlkWidth  >> 1 );
+  Int   iCHeight  = Int( uiBlkHeight >> 1 );
+  Int   iStrideC  = pcYuv->getCStride();
+  Pel*  pSamplesU = pcYuv->getCbAddr ();
+  Pel*  pSamplesV = pcYuv->getCrAddr ();
+  for(   Int iY = 0; iY < iCHeight; iY++, pSamplesU += iStrideC, pSamplesV += iStrideC )
+  {
+    for( Int iX = 0; iX < iCWidth; iX++ )
+    {
+      ROTRS( pSamplesU[iX], true );
+      ROTRS( pSamplesV[iX], true );
+    }
+  }
+  return false;
+}
+
+
+
+Void
+TComResidualGenerator::xDumpResidual( TComPic* pcPic, char* pFilenameBase )
+{
+  AOF( m_bCreated && m_bInit );
+  AOF( pcPic );
+  AOF( pFilenameBase );
+  AOF( m_uiOrgDepthBitDepth == 8 + g_uiBitIncrement );
+
+  // convert to output format (just clip high absolute values, since they are very unlikely)
+  Int         iMin        = 0;
+  Int         iMax        = ( 1 << m_uiOrgDepthBitDepth )  - 1;
+  Int         iMid        = ( 1 << m_uiOrgDepthBitDepth ) >> 1;
+  UInt        uiViewId    = pcPic   ->getSPS      ()->getViewId();
+  TComPicYuv* pcPicYuv    = pcPic   ->getResidual ();
+  // luma
+  Int         iWidth      = pcPicYuv->getWidth    ();
+  Int         iHeight     = pcPicYuv->getHeight   ();
+  Int         iSrcStride  = pcPicYuv->getStride   ();
+  Int         iDstStride  = m_cTmpPic.getStride   ();
+  Pel*        pSrcSamples = pcPicYuv->getLumaAddr ( 0 );
+  Pel*        pDstSamples = m_cTmpPic.getLumaAddr ( 0 );
+  AOF( m_cTmpPic.getWidth () == iWidth  );
+  AOF( m_cTmpPic.getHeight() == iHeight );
+  for( Int iY = 0; iY < iHeight; iY++, pSrcSamples += iSrcStride, pDstSamples += iDstStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pDstSamples[ iX ] = Max( iMin, Min( iMax, iMid + pSrcSamples[ iX ] ) );
+    }
+  }
+  // chroma
+  iWidth    >>= 1;
+  iHeight   >>= 1;
+  iSrcStride  = pcPicYuv->getCStride();
+  iDstStride  = m_cTmpPic.getCStride();
+  Pel* pSrcCb = pcPicYuv->getCbAddr ( 0 );
+  Pel* pSrcCr = pcPicYuv->getCrAddr ( 0 );
+  Pel* pDstCb = m_cTmpPic.getCbAddr ( 0 );
+  Pel* pDstCr = m_cTmpPic.getCrAddr ( 0 );
+  for( Int iY = 0; iY < iHeight; iY++, pSrcCb += iSrcStride, pSrcCr += iSrcStride, pDstCb += iDstStride, pDstCr += iDstStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pDstCb[ iX ] = Max( iMin, Min( iMax, iMid + pSrcCb[ iX ] ) );
+      pDstCr[ iX ] = Max( iMin, Min( iMax, iMid + pSrcCr[ iX ] ) );
+    }
+  }
+
+  // output
+  Char  acFilename[1024];
+  ::sprintf     ( acFilename, "%s_V%d.yuv", pFilenameBase, uiViewId );
+  m_cTmpPic.dump( acFilename, ( pcPic->getPOC() != 0 )  );
+}
+
+
+#endif // H3D_IVRP
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComResidualGenerator.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComResidualGenerator.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComResidualGenerator.h	(revision 341)
@@ -0,0 +1,118 @@
+/* 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-2011, 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 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     TComResidualGenerator.h
+    \brief    residual picture generator class (header)
+*/
+
+
+#ifndef __TCOM_RESIDUAL_GENERATOR__
+#define __TCOM_RESIDUAL_GENERATOR__
+
+
+#include "CommonDef.h"
+#include "TComPic.h"
+#include "TComSlice.h"
+#include "TComDepthMapGenerator.h"
+#include "TComTrQuant.h"
+
+
+#if H3D_IVRP
+
+class TComResidualGenerator
+{
+  enum { NUM_TMP_YUV_BUFFERS = 3 };
+
+public:
+  TComResidualGenerator ();
+  ~TComResidualGenerator();
+
+  Void  create                ( Bool bDecoder, UInt uiPicWidth, UInt uiPicHeight, UInt uiMaxCUDepth, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiOrgBitDepth );
+  Void  destroy               ();
+
+  Void  init                  ( TComTrQuant*  pcTrQuant, TComDepthMapGenerator* pcDepthMapGenerator );
+  Void  uninit                ();
+
+  Void  initViewComponent     ( TComPic*      pcPic );
+  Void  setRecResidualPic     ( TComPic*      pcPic );
+
+#if H3D_NBDV
+  Bool  getResidualSamples    ( TComDataCU*   pcCU,  UInt uiPUIdx, TComYuv* pcYuv, TComMv iDisp_x, Bool bRecon );
+  Bool  getResidualSamples    ( TComPic* pcPic, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv , TComMv iDisp_x, Bool bRecon );
+#else // H3D_NBDV
+  Bool  getResidualSamples    ( TComDataCU*   pcCU,  UInt uiPUIdx, TComYuv* pcYuv, Bool bRecon ); 
+  Bool  getResidualSamples    ( TComPic* pcPic, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv, Bool bRecon ); 
+#endif // H3D_NBDV
+
+private:
+  Void  xSetRecResidualPic    ( TComPic*      pcPic );
+  Void  xSetRecResidualCU     ( TComDataCU*   pcCU,  UInt     uiDepth,      UInt uiAbsPartIdx );
+  Void  xSetRecResidualIntraCU( TComDataCU*   pcCU,  TComYuv* pcCUResidual );
+  Void  xSetRecResidualInterCU( TComDataCU*   pcCU,  TComYuv* pcCUResidual );
+  Void  xClearIntViewResidual ( TComDataCU*   pcCU,  TComYuv* pcCUResidual, UInt uiPartIdx    );
+  Void  xClearResidual        (                      TComYuv* pcCUResidual, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight );
+#if H3D_NBDV
+  Void  xSetPredResidualBlock ( TComPic*      pcPic, UInt uiBaseViewId, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv, TComMv iDisp, UInt * puiXPosInRefView , UInt * puiYPosInRefView , Bool bRecon  );    
+#else
+  Void  xSetPredResidualBlock ( TComPic*      pcPic, UInt uiBaseViewId, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv, UInt * puiXPosInRefView , UInt * puiYPosInRefView , Bool bRecon  ); 
+#endif
+  Bool  xIsNonZero            ( TComYuv*      pcYuv, UInt uiBlkWidth, UInt uiBlkHeight );
+  Bool  xIsNonZeroByCBF       ( UInt uiBaseViewId , UInt uiXPos , UInt uiYPos, UInt uiBlkWidth , UInt uiBlkHeight );
+  Void  xDumpResidual         ( TComPic*      pcPic, char* pFilenameBase );
+private:
+  // general parameters
+  Bool                    m_bCreated;
+  Bool                    m_bInit;
+  Bool                    m_bDecoder;
+  TComTrQuant*            m_pcTrQuant;
+  TComDepthMapGenerator*  m_pcDepthMapGenerator;
+  TComSPSAccess*          m_pcSPSAccess;
+  TComAUPicAccess*        m_pcAUPicAccess;
+  UInt                    m_uiMaxDepth;
+  UInt                    m_uiOrgDepthBitDepth;
+  TComYuv**               m_ppcYuvTmp;
+  TComYuv**               m_ppcYuv;
+  TComDataCU**            m_ppcCU;
+  TComPicYuv              m_cTmpPic;
+};
+
+
+#endif // __TCOM_RESIDUAL_GENERATOR__
+
+#endif // H3D_IVRP
+
+
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRom.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRom.cpp	(revision 341)
@@ -0,0 +1,1035 @@
+/* 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-2012, 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     TComRom.cpp
+    \brief    global variables & functions
+*/
+
+#include "TComRom.h"
+#include <memory.h>
+#include <stdlib.h>
+#include <stdio.h>
+// ====================================================================================================================
+// Initialize / destroy functions
+// ====================================================================================================================
+
+//! \ingroup TLibCommon
+//! \{
+
+// 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 ) );
+  c=0;
+  for ( i=4; i<MAX_CU_SIZE; i*=2 )
+  {
+    g_aucConvertToBit[ i ] = c;
+    c++;
+  }
+  g_aucConvertToBit[ i ] = c;
+  
+  // g_auiFrameScanXY[ g_aucConvertToBit[ transformSize ] ]: zigzag scan array for transformSize
+  c=2;
+  for ( i=0; i<MAX_CU_DEPTH; i++ )
+  {
+    g_auiFrameScanXY[ i ] = new UInt[ c*c ];
+    g_auiFrameScanX [ i ] = new UInt[ c*c ];
+    g_auiFrameScanY [ i ] = new UInt[ c*c ];
+    initFrameScanXY( g_auiFrameScanXY[i], g_auiFrameScanX[i], g_auiFrameScanY[i], c, c );
+    g_auiSigLastScan[0][i] = new UInt[ c*c ];
+    g_auiSigLastScan[1][i] = new UInt[ c*c ];
+    g_auiSigLastScan[2][i] = new UInt[ c*c ];
+    g_auiSigLastScan[3][i] = new UInt[ c*c ];
+    initSigLastScan( g_auiSigLastScan[0][i], g_auiSigLastScan[1][i], g_auiSigLastScan[2][i], g_auiSigLastScan[3][i], c, c, i);
+
+    c <<= 1;
+  }  
+
+  g_sigScanNSQT[0] = new UInt[ 64 ];  // 4x16
+  g_sigScanNSQT[1] = new UInt[ 256 ]; // 8x32
+  g_sigScanNSQT[2] = new UInt[ 64 ];  // 16x4
+  g_sigScanNSQT[3] = new UInt[ 256 ]; // 32x8
+  
+  static int diagScanX[ 16 ] =
+  {
+    0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 1, 2, 3, 2, 3, 3
+  };
+  static int diagScanY[ 16 ] =
+  {
+    0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 3, 2, 3
+  };
+  
+  Int j;
+  // 4x16 scan
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 16; j++)
+    {
+      g_sigScanNSQT[ 0 ][ 16 * i + j ] = 16 * i + 4 * diagScanY[ j ] + diagScanX[ j ];
+    }
+  }
+  
+  // 8x32 scan
+  for (i = 0; i < 16; i++)
+  {
+    Int x = g_sigCGScanNSQT[ 1 ][ i ] & 1;
+    Int y = g_sigCGScanNSQT[ 1 ][ i ] >> 1;
+    
+    for (j = 0; j < 16; j++)
+    {
+      g_sigScanNSQT[ 1 ][ 16 * i + j ] = 32 * y + 4 * x + 8 * diagScanY[ j ] + diagScanX[ j ];
+    }
+  }
+  
+  // 16x4 scan
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 16; j++)
+    {
+      g_sigScanNSQT[ 2 ][ 16 * i + j ] = 4 * i + 16 * diagScanY[ j ] + diagScanX[ j ];
+    }
+  }
+  
+  // 32x8 scan
+  for (i = 0; i < 16; i++)
+  {
+    Int x = g_sigCGScanNSQT[ 3 ][ i ] & 7;
+    Int y = g_sigCGScanNSQT[ 3 ][ i ] >> 3;
+    
+    for (j = 0; j < 16; j++)
+    {
+      g_sigScanNSQT[ 3 ][ 16 * i + j ] = 128 * y + 4 * x + 32 * diagScanY[ j ] + diagScanX[ j ];
+    }
+  }
+}
+
+Void destroyROM()
+{
+  Int i;
+  
+  for ( i=0; i<MAX_CU_DEPTH; i++ )
+  {
+    delete[] g_auiFrameScanXY[i];
+    delete[] g_auiFrameScanX [i];
+    delete[] g_auiFrameScanY [i];
+    delete[] g_auiSigLastScan[0][i];
+    delete[] g_auiSigLastScan[1][i];
+    delete[] g_auiSigLastScan[2][i];
+    delete[] g_auiSigLastScan[3][i];
+  }
+  for (i = 0; i < 4; i++)
+  {
+    delete[] g_sigScanNSQT[ i ];    
+  }
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if ( !g_aacWedgeLists.empty() )
+  {
+    for ( UInt ui = 0; ui < g_aacWedgeLists.size(); ui++ )
+    {
+      g_aacWedgeLists[ui].clear();
+    }
+    g_aacWedgeLists.clear();
+  }
+
+  if ( !g_aacWedgeRefLists.empty() )
+  {
+    for ( UInt ui = 0; ui < g_aacWedgeRefLists.size(); ui++ )
+    {
+      g_aacWedgeRefLists[ui].clear();
+    }
+    g_aacWedgeRefLists.clear();
+  }
+
+  if ( !g_aacWedgeNodeLists.empty() )
+  {
+    for ( UInt ui = 0; ui < g_aacWedgeNodeLists.size(); ui++ )
+    {
+      g_aacWedgeNodeLists[ui].clear();
+    }
+    g_aacWedgeNodeLists.clear();
+  }
+
+#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_motionRefer   [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, }; 
+
+UInt g_auiPUOffset[8] = { 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 )
+  {
+    rpuiCurrIdx[0] = uiStartVal;
+    rpuiCurrIdx++;
+  }
+  else
+  {
+    Int iStep = iStride >> iDepth;
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal,                     rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep,               rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep*iStride,       rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep*iStride+iStep, rpuiCurrIdx );
+  }
+}
+
+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++ )
+  {
+    g_auiRasterToZscan[ g_auiZscanToRaster[i] ] = i;
+  }
+}
+
+/** generate motion data compression mapping table
+* \param uiMaxCUWidth, width of LCU
+* \param uiMaxCUHeight, hight of LCU
+* \param uiMaxDepth, max depth of LCU
+* \returns Void
+*/
+Void initMotionReferIdx ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth )
+{
+  Int  minCUWidth  = (Int)uiMaxCUWidth  >> ( (Int)uiMaxDepth - 1 );
+  Int  minCUHeight = (Int)uiMaxCUHeight >> ( (Int)uiMaxDepth - 1 );
+
+  Int  numPartInWidth  = (Int)uiMaxCUWidth  / (Int)minCUWidth;
+  Int  numPartInHeight = (Int)uiMaxCUHeight / (Int)minCUHeight;
+
+  for ( Int i = 0; i < numPartInWidth*numPartInHeight; i++ )
+  {
+    g_motionRefer[i] = i;
+  }
+
+  Int compressionNum = 2;
+
+  for ( Int i = numPartInWidth*(numPartInHeight-1); i < numPartInWidth*numPartInHeight; i += compressionNum*2)
+  {
+    for ( Int j = 1; j < compressionNum; j++ )
+    {
+      g_motionRefer[g_auiRasterToZscan[i+j]] = g_auiRasterToZscan[i];
+    }
+  }
+
+  for ( Int i = numPartInWidth*(numPartInHeight-1)+compressionNum*2-1; i < numPartInWidth*numPartInHeight; i += compressionNum*2)
+  {
+    for ( Int j = 1; j < compressionNum; j++ )
+    {
+      g_motionRefer[g_auiRasterToZscan[i-j]] = g_auiRasterToZscan[i];
+    }
+  }
+}
+
+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++ )
+  {
+    uiTempX[0] = uiTempX[-1] + uiMinCUWidth; uiTempX++;
+  }
+  for ( i = 1; i < uiNumPartInHeight; i++ )
+  {
+    memcpy(uiTempX, uiTempX-uiNumPartInWidth, sizeof(UInt)*uiNumPartInWidth);
+    uiTempX += uiNumPartInWidth;
+  }
+  
+  for ( i = 1; i < uiNumPartInWidth*uiNumPartInHeight; i++ )
+  {
+    uiTempY[i] = ( i / uiNumPartInWidth ) * uiMinCUWidth;
+  }
+};
+
+#if RWTH_SDC_DLT_B0036
+UInt g_auiSDCPredModes[RWTH_SDC_NUM_PRED_MODES] = { DC_IDX, DMM_WEDGE_FULL_IDX, PLANAR_IDX };
+#endif
+
+Int g_quantScales[6] =
+{
+  26214,23302,20560,18396,16384,14564
+};    
+
+Int g_invQuantScales[6] =
+{
+  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[52]=
+{
+  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,32,33,34,34,35,35,36,36,37,37,
+  37,38,38,38,39,39,39,39
+};
+
+
+// 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[7] =
+{
+  3,  //   2x2
+  8,  //   4x4
+  8,  //   8x8
+  3,  //  16x16   
+  3,  //  32x32   
+  3,  //  64x64   
+  3   // 128x128  
+};
+#else // FAST_UDI_USE_MPM
+const UChar g_aucIntraModeNumFast[7] =
+{
+  3,  //   2x2
+  9,  //   4x4
+  9,  //   8x8
+  4,  //  16x16   33
+  4,  //  32x32   33
+  5,  //  64x64   33
+  4   // 128x128  33
+};
+#endif // FAST_UDI_USE_MPM
+
+// chroma
+
+const UChar g_aucConvertTxtTypeToIdx[4] = { 0, 1, 1, 2 };
+
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+UInt g_uiBitDepth     = 8;    // base bit-depth
+UInt g_uiBitIncrement = 0;    // increments
+UInt g_uiIBDI_MAX     = 255;  // max. value after  IBDI
+UInt g_uiBASE_MAX     = 255;  // max. value before IBDI
+
+UInt g_uiPCMBitDepthLuma     = 8;    // PCM bit-depth
+UInt g_uiPCMBitDepthChroma   = 8;    // PCM bit-depth
+
+// ====================================================================================================================
+// Depth model modes
+// ====================================================================================================================
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+Int g_iDeltaDCsQuantOffset = 0;
+
+const WedgeResolution g_aeWedgeResolutionList[5] = 
+{
+  HALF_PEL,    //  4x4
+  HALF_PEL,    //  8x8
+  FULL_PEL,    // 16x16
+  DOUBLE_PEL,  // 32x32
+  DOUBLE_PEL   // 64x64
+};
+
+const UChar g_aucWedgeFullBitsListIdx[7] =
+{
+  0,   //   2x2
+  7,   //   4x4    WedgeListSize[  HALF_PEL]   86
+  10,  //   8x8    WedgeListSize[  HALF_PEL]  782
+  11,  //  16x16   WedgeListSize[  FULL_PEL] 1394
+  11,  //  32x32   WedgeListSize[DOUBLE_PEL] 1503
+  13,  //  64x64   WedgeListSize[DOUBLE_PEL] 6079
+  0    // 128x128  
+};
+
+#if LGE_DMM3_SIMP_C0044
+const UChar g_aucWedgeTexPredBitsListIdx[7] =
+{
+  0,   //   2x2
+  6,   //   4x4    
+  9,  //   8x8    
+  9,  //  16x16   
+  9,  //  32x32   
+  0,  //  64x64   
+  0    // 128x128  
+};
+#endif
+
+const UChar g_aucIntraSizeIdxToWedgeSize[7] =
+{
+  2,
+  4,
+  8,
+  16,
+  32,
+  64,
+  128
+};
+#endif
+
+// ====================================================================================================================
+// Misc.
+// ====================================================================================================================
+
+Char  g_aucConvertToBit  [ MAX_CU_SIZE+1 ];
+
+#if ENC_DEC_TRACE
+FILE*  g_hTrace = NULL;
+const Bool g_bEncDecTraceEnable  = true;
+const Bool g_bEncDecTraceDisable = false;
+Bool   g_bJustDoIt = false;
+UInt64 g_nSymbolCounter = 0;
+#endif
+// ====================================================================================================================
+// Scanning order & context model mapping
+// ====================================================================================================================
+
+// scanning order table
+UInt* g_auiFrameScanXY[ MAX_CU_DEPTH  ];
+UInt* g_auiFrameScanX [ MAX_CU_DEPTH  ];
+UInt* g_auiFrameScanY [ MAX_CU_DEPTH  ];
+UInt* g_auiSigLastScan[4][ MAX_CU_DEPTH ];
+UInt *g_sigScanNSQT[ 4 ]; // scan for non-square partitions
+UInt g_sigCGScanNSQT[ 4 ][ 16 ] =
+{
+  { 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
+  { 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 15 },
+  { 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
+  { 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 }
+};
+
+const UInt g_sigLastScan8x8[ 4 ][ 4 ] =
+{
+  {0, 1, 2, 3},
+  {0, 1, 2, 3},
+  {0, 1, 2, 3},
+  {0, 2, 1, 3}
+};
+UInt g_sigLastScanCG32x32[ 64 ];
+
+UInt* g_auiNonSquareSigLastScan[ 4 ];
+
+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};
+const UInt g_uiLastCtx[ 28 ]    = 
+{
+  0,   1,  2,  2,                         // 4x4    4
+  3,   4,  5,  5, 2,  2,                  // 8x8    6  
+  6,   7,  8,  8, 9,  9, 2, 2,            // 16x16  8
+  10, 11, 12, 12, 13, 13, 14, 14, 2, 2    // 32x32  10
+};
+
+// Rice parameters for absolute transform levels
+const UInt g_auiGoRiceRange[5] =
+{
+  7, 14, 26, 46, 78
+};
+
+const UInt g_auiGoRicePrefixLen[5] =
+{
+  8, 7, 6, 5, 4
+};
+
+const UInt g_aauiGoRiceUpdate[5][24] =
+{
+  {
+    0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4
+  },
+  {
+    1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4
+  },
+  {
+    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4
+  },
+  {
+    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4
+  },
+  {
+    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
+  }
+};
+
+// initialize g_auiFrameScanXY
+Void initFrameScanXY( UInt* pBuff, UInt* pBuffX, UInt* pBuffY, Int iWidth, Int iHeight )
+{
+  Int x, y, c = 0;
+  
+  // starting point
+  pBuffX[ c ] = 0;
+  pBuffY[ c ] = 0;
+  pBuff[ c++ ] = 0;
+  
+  // loop
+  x=1; y=0;
+  while (1)
+  {
+    // decrease loop
+    while ( x>=0 )
+    {
+      if ( x >= 0 && x < iWidth && y >= 0 && y < iHeight )
+      {
+        pBuffX[ c ] = x;
+        pBuffY[ c ] = y;
+        pBuff[ c++ ] = x+y*iWidth;
+      }
+      x--; y++;
+    }
+    x=0;
+    
+    // increase loop
+    while ( y>=0 )
+    {
+      if ( x >= 0 && x < iWidth && y >= 0 && y < iHeight )
+      {
+        pBuffX[ c ] = x;
+        pBuffY[ c ] = y;
+        pBuff[ c++ ] = x+y*iWidth;
+      }
+      x++; y--;
+    }
+    y=0;
+    
+    // termination condition
+    if ( c >= iWidth*iHeight ) break;
+  }  
+}
+
+Void initSigLastScan(UInt* pBuffZ, UInt* pBuffH, UInt* pBuffV, UInt* pBuffD, Int iWidth, Int iHeight, Int iDepth)
+{
+  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--;
+        }
+      }
+    }
+  }
+  
+  memcpy(pBuffZ, g_auiFrameScanXY[iDepth], sizeof(UInt)*iWidth*iHeight);
+
+  UInt uiCnt = 0;
+  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 ++;
+    }
+  }    
+}
+
+Void initNonSquareSigLastScan(UInt* pBuffZ, UInt uiWidth, UInt uiHeight)
+{
+
+  Int x, y, c = 0;
+
+  // starting point
+  pBuffZ[ c++ ] = 0;
+
+  // loop
+  if ( uiWidth > uiHeight )
+  {
+    x=0; y=1;
+    while (1)
+    {
+      // increase loop
+      while ( y>=0 )
+      {
+        if ( x >= 0 && x < uiWidth && y >= 0 && y < uiHeight )
+        {
+          pBuffZ[ c++ ] = x + y * uiWidth;
+        }
+        x++;
+        y--;
+      }
+      y=0;
+
+      // decrease loop
+      while ( x>=0 )
+      {
+        if ( x >= 0 && x < uiWidth && y >= 0 && y < uiHeight )
+        {
+          pBuffZ[ c++ ] = x + y * uiWidth;
+        }
+        x--;
+        y++;
+      }
+      x=0;
+
+      // termination condition
+      if ( c >= uiWidth * uiHeight ) 
+        break;
+    }
+  }
+  else
+  {
+    x=1; y=0;
+    while (1)
+    {
+      // increase loop
+      while ( x>=0 )
+      {
+        if ( x >= 0 && x < uiWidth && y >= 0 && y < uiHeight )
+        {
+          pBuffZ[ c++ ] = x + y * uiWidth;
+        }
+        x--;
+        y++;
+      }
+      x=0;
+
+      // decrease loop
+      while ( y>=0 )
+      {
+        if ( x >= 0 && x < uiWidth && y >= 0 && y < uiHeight )
+        {
+          pBuffZ[ c++ ] = x + y * uiWidth;
+        }
+        x++;
+        y--;
+      }
+      y=0;
+
+      // termination condition
+      if ( c >= uiWidth * uiHeight ) 
+        break;
+    }
+  }
+}
+
+Int g_quantIntraDefault4x4[16] =
+{
+  16,16,17,21,
+  16,17,20,25,
+  17,20,30,41,
+  21,25,41,70
+};
+Int g_quantInterDefault4x4[16] =
+{
+  16,16,17,21,
+  16,17,21,24,
+  17,21,24,36,
+  21,24,36,57
+};
+
+Int g_quantIntraDefault8x8[64] =
+{
+  16,16,16,16,17,18,21,24,
+  16,16,16,16,17,19,22,25,
+  16,16,17,18,20,22,25,29,
+  16,16,18,21,24,27,31,36,
+  17,17,20,24,30,35,41,47,
+  18,19,22,27,35,44,54,65,
+  21,22,25,31,41,54,70,88,
+  24,25,29,36,47,65,88,115
+};
+
+Int g_quantInterDefault8x8[64] =
+{
+  16,16,16,16,17,18,20,24,
+  16,16,16,17,18,20,24,25,
+  16,16,17,18,20,24,25,28,
+  16,17,18,20,24,25,28,33,
+  17,18,20,24,25,28,33,41,
+  18,20,24,25,28,33,41,54,
+  20,24,25,28,33,41,54,71,
+  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};
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+std::vector< std::vector<TComWedgelet> > g_aacWedgeLists;
+std::vector< std::vector<TComWedgeRef> > g_aacWedgeRefLists;
+
+std::vector< std::vector< std::vector<UInt> > > g_aauiWdgLstM3;
+std::vector< std::vector< TComWedgeNode> >      g_aacWedgeNodeLists;
+
+Void initWedgeLists()
+{
+  for( UInt ui = g_aucConvertToBit[DMM_WEDGEMODEL_MIN_SIZE]; ui < (g_aucConvertToBit[DMM_WEDGEMODEL_MAX_SIZE]+1); ui++ )
+  {
+    UInt uiWedgeBlockSize = ((UInt)DMM_WEDGEMODEL_MIN_SIZE)<<ui;
+    std::vector<TComWedgelet> acWedgeList;
+    std::vector<TComWedgeRef> acWedgeRefList;
+    createWedgeList( uiWedgeBlockSize, uiWedgeBlockSize, acWedgeList, acWedgeRefList, g_aeWedgeResolutionList[ui] );
+    g_aacWedgeLists.push_back( acWedgeList );
+    g_aacWedgeRefLists.push_back( acWedgeRefList );
+
+    // create WedgeNodeList
+    std::vector<TComWedgeNode> acWedgeNodeList;
+    for( UInt uiPos = 0; uiPos < acWedgeList.size(); uiPos++ )
+    {
+      if( acWedgeList[uiPos].getIsCoarse() )
+      {
+        TComWedgeNode cWedgeNode;
+        cWedgeNode.setPatternIdx( uiPos );
+
+        // set refinement idxs
+        UInt uiRefPos = 0;
+        for( Int iOffS = -1; iOffS <= 1; iOffS++ )
+        {
+          for( Int iOffE = -1; iOffE <= 1; iOffE++ )
+          {
+            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() )
+            {
+            case( 0 ): { iSx += iOffS; iEy += iOffE; } break;
+            case( 1 ): { iSy += iOffS; iEx -= iOffE; } break;
+            case( 2 ): { iSx -= iOffS; iEy -= iOffE; } break;
+            case( 3 ): { iSy -= iOffS; iEx += iOffE; } break;
+            case( 4 ): { iSx += iOffS; iEx += iOffE; } break;
+            case( 5 ): { iSy += iOffS; iEy += iOffE; } break;
+            default: assert( 0 );
+            }
+
+            for( UInt k = 0; k < acWedgeRefList.size(); k++ )
+            {
+              if( iSx == (Int)acWedgeRefList[k].getStartX() && 
+                iSy == (Int)acWedgeRefList[k].getStartY() && 
+                iEx == (Int)acWedgeRefList[k].getEndX() && 
+                iEy == (Int)acWedgeRefList[k].getEndY()    )
+              {
+                if( acWedgeRefList[k].getRefIdx() != cWedgeNode.getPatternIdx() )
+                {
+                  Bool bNew = true;
+                  for( UInt m = 0; m < uiRefPos; m++ ) { if( acWedgeRefList[k].getRefIdx() == cWedgeNode.getRefineIdx( m ) ) { bNew = false; break; } }
+
+                  if( bNew ) 
+                  {
+                    cWedgeNode.setRefineIdx( acWedgeRefList[k].getRefIdx(), uiRefPos );
+                    uiRefPos++;
+                    break;
+                  }
+                }
+              }
+            }
+          }
+        }
+        acWedgeNodeList.push_back( cWedgeNode );
+      }
+    }
+    g_aacWedgeNodeLists.push_back( acWedgeNodeList );
+
+  }
+  return;
+}
+
+Void createWedgeList( UInt uiWidth, UInt uiHeight, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList, WedgeResolution eWedgeRes )
+{
+  assert( uiWidth == uiHeight );
+
+  UChar    uhStartX = 0,    uhStartY = 0,    uhEndX = 0,    uhEndY = 0;
+  Int   iStepStartX = 0, iStepStartY = 0, iStepEndX = 0, iStepEndY = 0;
+
+  UInt uiBlockSize = 0;
+  switch( eWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiBlockSize = (uiWidth>>1); break; }
+  case(   FULL_PEL ): { uiBlockSize =  uiWidth;     break; }
+  case(   HALF_PEL ): { uiBlockSize = (uiWidth<<1); break; }
+  }
+
+  TComWedgelet cTempWedgelet( uiWidth, uiHeight );
+  for( UInt uiOri = 0; uiOri < 6; uiOri++ )
+  {
+    // init the edge line parameters for each of the 6 wedgelet types
+    switch( uiOri )
+    {
+    case( 0 ): {  uhStartX = 0;               uhStartY = 0;               uhEndX = 0;               uhEndY = 0;               iStepStartX = +1; iStepStartY =  0; iStepEndX =  0; iStepEndY = +1; break; }
+    case( 1 ): {  uhStartX = (uiBlockSize-1); uhStartY = 0;               uhEndX = (uiBlockSize-1); uhEndY = 0;               iStepStartX =  0; iStepStartY = +1; iStepEndX = -1; iStepEndY =  0; break; }
+    case( 2 ): {  uhStartX = (uiBlockSize-1); uhStartY = (uiBlockSize-1); uhEndX = (uiBlockSize-1); uhEndY = (uiBlockSize-1); iStepStartX = -1; iStepStartY =  0; iStepEndX =  0; iStepEndY = -1; break; }
+    case( 3 ): {  uhStartX = 0;               uhStartY = (uiBlockSize-1); uhEndX = 0;               uhEndY = (uiBlockSize-1); iStepStartX =  0; iStepStartY = -1; iStepEndX = +1; iStepEndY =  0; break; }
+    case( 4 ): {  uhStartX = 0;               uhStartY = 0;               uhEndX = 0;               uhEndY = (uiBlockSize-1); iStepStartX = +1; iStepStartY =  0; iStepEndX = +1; iStepEndY =  0; break; }
+    case( 5 ): {  uhStartX = (uiBlockSize-1); uhStartY = 0;               uhEndX = 0;               uhEndY = 0;               iStepStartX =  0; iStepStartY = +1; iStepEndX =  0; iStepEndY = +1; break; }
+    }
+
+    for( Int iK = 0; iK < uiBlockSize; iK++ )
+    {
+      for( Int iL = 0; iL < uiBlockSize; iL++ )
+      {
+        cTempWedgelet.setWedgelet( uhStartX + (iK*iStepStartX) , uhStartY + (iK*iStepStartY), uhEndX + (iL*iStepEndX), uhEndY + (iL*iStepEndY), (UChar)uiOri, eWedgeRes, ((iL%2)==0 && (iK%2)==0) );
+        addWedgeletToList( cTempWedgelet, racWedgeList, racWedgeRefList );
+      }
+    }
+  }
+  UInt uiThrSz = DMM3_SIMPLIFY_TR;
+
+  std::vector< std::vector<UInt> > auiWdgListSz;
+  for( Int idxM=2; idxM<=34 ; idxM++)
+  {
+    std::vector<UInt> auiWdgList;
+    for( Int idxW=0; idxW<racWedgeList.size(); idxW++)
+    {
+      UInt uiAbsDiff = abs(idxM-(Int)racWedgeList[idxW].getAng());
+      if( uiAbsDiff <= uiThrSz )
+      {
+        auiWdgList.push_back(idxW);
+      }
+    }
+    auiWdgListSz.push_back(auiWdgList);
+  }
+  g_aauiWdgLstM3.push_back(auiWdgListSz);
+}
+
+Void addWedgeletToList( TComWedgelet cWedgelet, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList )
+{
+  Bool bValid = cWedgelet.checkNotPlain();
+  if( bValid )
+  {
+    for( UInt uiPos = 0; uiPos < racWedgeList.size(); uiPos++ )
+    {
+      if( cWedgelet.checkIdentical( racWedgeList[uiPos].getPattern() ) )
+      {
+        TComWedgeRef cWedgeRef;
+        cWedgeRef.setWedgeRef( cWedgelet.getStartX(), cWedgelet.getStartY(), cWedgelet.getEndX(), cWedgelet.getEndY(), uiPos );
+        racWedgeRefList.push_back( cWedgeRef );
+        bValid = false;
+        return;
+      }
+    }
+  }
+  if( bValid )
+  {
+    for( UInt uiPos = 0; uiPos < racWedgeList.size(); uiPos++ )
+    {
+      if( cWedgelet.checkInvIdentical( racWedgeList[uiPos].getPattern() ) )
+      {
+        TComWedgeRef cWedgeRef;
+        cWedgeRef.setWedgeRef( cWedgelet.getStartX(), cWedgelet.getStartY(), cWedgelet.getEndX(), cWedgelet.getEndY(), uiPos );
+        racWedgeRefList.push_back( cWedgeRef );
+        bValid = false;
+        return;
+      }
+    }
+  }
+  if( bValid )
+  {
+    cWedgelet.findClosetAngle();
+    racWedgeList.push_back( cWedgelet );
+    TComWedgeRef cWedgeRef;
+    cWedgeRef.setWedgeRef( cWedgelet.getStartX(), cWedgelet.getStartY(), cWedgelet.getEndX(), cWedgelet.getEndY(), (UInt)(racWedgeList.size()-1) );
+    racWedgeRefList.push_back( cWedgeRef );
+  }
+}
+#endif //HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRom.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRom.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComRom.h	(revision 341)
@@ -0,0 +1,353 @@
+/* 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-2012, 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     TComRom.h
+    \brief    global variables & functions (header)
+*/
+
+#ifndef __TCOMROM__
+#define __TCOMROM__
+
+#include "CommonDef.h"
+
+#include<stdio.h>
+#include<iostream>
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#include "TComWedgelet.h"
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Macros
+// ====================================================================================================================
+
+#define     MAX_CU_DEPTH            7                           // 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         initFrameScanXY( UInt* pBuff, UInt* pBuffX, UInt* pBuffY, Int iWidth, Int iHeight );
+Void         initSigLastScan(UInt* pBuffZ, UInt* pBuffH, UInt* pBuffV, UInt* pBuffD, Int iWidth, Int iHeight, Int iDepth);
+Void         initNonSquareSigLastScan(UInt* pBuffZ, UInt uiWidth, UInt uiHeight);
+// ====================================================================================================================
+// 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_motionRefer[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+
+Void         initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx );
+Void         initRasterToZscan ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth         );
+
+Void          initMotionReferIdx ( 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 ];
+
+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;
+
+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];
+
+// ====================================================================================================================
+// Luma QP to Chroma QP mapping
+// ====================================================================================================================
+
+extern const UChar  g_aucChromaScale      [52];
+
+// ====================================================================================================================
+// Scanning order & context mapping table
+// ====================================================================================================================
+
+extern       UInt*  g_auiFrameScanXY[ MAX_CU_DEPTH  ];    // raster index     from scanning index
+extern       UInt*  g_auiFrameScanX [ MAX_CU_DEPTH  ];    // raster index (x) from scanning index
+extern       UInt*  g_auiFrameScanY [ MAX_CU_DEPTH  ];    // raster index (y) from scanning index
+extern       UInt*  g_auiSigLastScan[4][ MAX_CU_DEPTH ];  // raster index from scanning index (zigzag, hor, ver, diag)
+extern UInt *g_sigScanNSQT[ 4 ]; // scan for non-square partitions
+extern UInt g_sigCGScanNSQT[ 4 ][ 16 ]; // coarse-grain scan for non-square partitions
+
+extern       UInt*  g_auiNonSquareSigLastScan[ 4 ];      // raster index from scanning index (zigzag)
+
+extern const UInt   g_uiGroupIdx[ 32 ];
+extern const UInt   g_uiMinInGroup[ 10 ];
+extern const UInt   g_uiLastCtx[ 28 ];
+
+extern const UInt   g_auiGoRiceRange[5];                  //!< maximum value coded with Rice codes
+extern const UInt   g_auiGoRicePrefixLen[5];              //!< prefix length for each maximum value
+extern const UInt   g_aauiGoRiceUpdate[5][24];            //!< parameter update rules for Rice codes
+  
+extern const UInt   g_sigLastScan8x8[ 4 ][ 4 ];           //!< coefficient group scan order for 8x8 TUs
+extern       UInt   g_sigLastScanCG32x32[ 64 ];
+
+// ====================================================================================================================
+// ADI table
+// ====================================================================================================================
+
+extern const UChar  g_aucIntraModeNumFast[7];
+
+// ====================================================================================================================
+// Angular Intra table
+// ====================================================================================================================
+
+extern const UChar g_aucIntraModeNumAng[7];
+extern const UChar g_aucIntraModeBitsAng[7];
+extern const UChar g_aucAngIntraModeOrder[NUM_INTRA_MODE];
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+extern       UInt g_uiBitDepth;
+extern       UInt g_uiBitIncrement;
+extern       UInt g_uiIBDI_MAX;
+extern       UInt g_uiBASE_MAX;
+extern       UInt g_uiPCMBitDepthLuma;
+extern       UInt g_uiPCMBitDepthChroma;
+
+// ====================================================================================================================
+// Texture type to integer mapping
+// ====================================================================================================================
+
+extern const UChar g_aucConvertTxtTypeToIdx[4];
+
+// ====================================================================================================================
+// Depth model modes
+// ====================================================================================================================
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+extern       Int             g_iDeltaDCsQuantOffset;
+extern const WedgeResolution g_aeWedgeResolutionList[5];
+extern const UChar           g_aucWedgeFullBitsListIdx[7];
+#if LGE_DMM3_SIMP_C0044
+extern const UChar           g_aucWedgeTexPredBitsListIdx[7];
+#endif
+extern const UChar           g_aucIntraSizeIdxToWedgeSize[7];
+
+extern       std::vector< std::vector<TComWedgelet> >  g_aacWedgeLists;
+extern       std::vector< std::vector<TComWedgeRef> >  g_aacWedgeRefLists;
+
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+extern       std::vector< std::vector< std::vector<UInt> > > g_aauiWdgLstM3;
+extern       std::vector< std::vector<TComWedgeNode> >       g_aacWedgeNodeLists;
+#endif
+
+#if RWTH_SDC_DLT_B0036
+#define RWTH_SDC_NUM_PRED_MODES 3
+extern      UInt g_auiSDCPredModes[RWTH_SDC_NUM_PRED_MODES];
+#endif
+
+Void initWedgeLists();
+Void createWedgeList( UInt uiWidth, UInt uiHeight, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList, WedgeResolution eWedgeRes );
+Void addWedgeletToList( TComWedgelet cWedgelet, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList );
+
+__inline Void mapDMMtoIntraMode(  UInt& dirMode ) { dirMode = (dirMode >= NUM_INTRA_MODE) ? DC_IDX : dirMode; }
+__inline Void mapDMMtoIntraMode(   Int& dirMode ) { dirMode = (dirMode >= NUM_INTRA_MODE) ? DC_IDX : dirMode; }
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+__inline Void mapEdgeIntratoDC( UChar& curDir ) { curDir = (curDir >= EDGE_INTRA_IDX) ? DC_IDX : curDir; }
+__inline Void mapEdgeIntratoDC(  UInt& curDir ) { curDir = (curDir >= EDGE_INTRA_IDX) ? DC_IDX : curDir; }
+__inline Void mapEdgeIntratoDC(   Int& curDir ) { curDir = (curDir >= EDGE_INTRA_IDX) ? DC_IDX : curDir; }
+#endif
+
+// ==========================================
+// Mode-Dependent DST Matrices
+extern const short g_as_DST_MAT_4 [4][4];
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+extern const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE+NUM_DMM_MODE];
+extern const UChar g_aucDCTDSTMode_Hor [NUM_INTRA_MODE+NUM_DMM_MODE];
+#else
+extern const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE];
+extern const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE];
+#endif
+// ==========================================
+
+// ====================================================================================================================
+// Misc.
+// ====================================================================================================================
+
+extern       Char   g_aucConvertToBit  [ MAX_CU_SIZE+1 ];   // from width to log2(width)-2
+
+#define ENC_DEC_TRACE 0
+
+
+#if ENC_DEC_TRACE
+extern FILE*  g_hTrace;
+extern Bool   g_bJustDoIt;
+extern const Bool g_bEncDecTraceEnable;
+extern const Bool g_bEncDecTraceDisable;
+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 );
+#define DTRACE_CABAC_VL(x)    if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%lld", x );
+#define DTRACE_CABAC_T(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%s", x );
+#define DTRACE_CABAC_X(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%x", x );
+#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"    );
+
+#else
+
+#define DTRACE_CABAC_F(x)
+#define DTRACE_CABAC_V(x)
+#define DTRACE_CABAC_VL(x)
+#define DTRACE_CABAC_T(x)
+#define DTRACE_CABAC_X(x)
+#define DTRACE_CABAC_R( x,y )
+#define DTRACE_CABAC_N
+
+#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 ScalingListDIR
+{
+  SCALING_LIST_SQT = 0,
+  SCALING_LIST_VER,
+  SCALING_LIST_HOR,
+  SCALING_LIST_DIR_NUM
+};
+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_quantIntraDefault4x4[16];
+extern Int g_quantIntraDefault8x8[64];
+extern Int g_quantIntraDefault16x16[256];
+extern Int g_quantIntraDefault32x32[1024];
+extern Int g_quantInterDefault4x4[16];
+extern Int g_quantInterDefault8x8[64];
+extern Int g_quantInterDefault16x16[256];
+extern Int g_quantInterDefault32x32[1024];
+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  //__TCOMROM__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 341)
@@ -0,0 +1,1379 @@
+/* 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-2012, 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     TComSampleAdaptiveOffset.cpp
+    \brief    sample adaptive offset class
+*/
+
+#include "TComSampleAdaptiveOffset.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibCommon
+//! \{
+
+SAOParam::~SAOParam()
+{
+  for (Int i = 0 ; i<3; i++)
+  {
+    if (psSaoPart[i])
+    {
+      delete [] psSaoPart[i];
+    }
+  }
+}
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+TComSampleAdaptiveOffset::TComSampleAdaptiveOffset()
+{
+  m_pcPic = NULL;
+  m_iOffsetBo = NULL;
+  m_pClipTable = NULL;
+  m_pClipTableBase = NULL;
+  m_lumaTableBo = NULL;
+  m_iUpBuff1 = NULL;
+  m_iUpBuff2 = NULL;
+  m_iUpBufft = NULL;
+  ipSwap = NULL;
+  m_pcYuvTmp = NULL;
+
+  m_pTmpU1 = NULL;
+  m_pTmpU2 = NULL;
+  m_pTmpL1 = NULL;
+  m_pTmpL2 = NULL;
+  m_iLcuPartIdx = NULL;
+}
+
+TComSampleAdaptiveOffset::~TComSampleAdaptiveOffset()
+{
+
+}
+
+const Int TComSampleAdaptiveOffset::m_aiNumPartsInRow[5] =
+{
+  1,   //level 0
+  2,   //level 1
+  4,   //level 2
+  8,   //level 3
+  16   //level 4
+};
+
+const Int TComSampleAdaptiveOffset::m_aiNumPartsLevel[5] =
+{
+  1,   //level 0
+  4,   //level 1
+  16,  //level 2
+  64,  //level 3
+  256  //level 4
+};
+
+const Int TComSampleAdaptiveOffset::m_aiNumCulPartsLevel[5] =
+{
+  1,   //level 0
+  5,   //level 1
+  21,  //level 2
+  85,  //level 3
+  341, //level 4
+};
+
+const UInt TComSampleAdaptiveOffset::m_auiEoTable[9] =
+{
+  1, //0    
+  2, //1   
+  0, //2
+  3, //3
+  4, //4
+  0, //5  
+  0, //6  
+  0, //7 
+  0
+};
+
+const UInt TComSampleAdaptiveOffset::m_iWeightSao[MAX_NUM_SAO_TYPE] =
+{
+  2,
+  2,
+  2,
+  2,
+  1
+};
+
+const UInt TComSampleAdaptiveOffset::m_auiEoTable2D[9] =
+{
+  1, //0    
+  2, //1   
+  3, //2
+  0, //3
+  0, //4
+  0, //5  
+  4, //6  
+  5, //7 
+  6
+};
+
+Int TComSampleAdaptiveOffset::m_iNumClass[MAX_NUM_SAO_TYPE] =
+{
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_BO_LEN
+};
+
+UInt TComSampleAdaptiveOffset::m_uiMaxDepth = SAO_MAX_DEPTH;
+
+
+/** convert Level Row Col to Idx
+ * \param   level,  row,  col
+ */
+Int  TComSampleAdaptiveOffset::convertLevelRowCol2Idx(int level, int row, int col)
+{
+  Int idx;
+  if (level == 0)
+  {
+    idx = 0;
+  }
+  else if (level == 1)
+  {
+    idx = 1 + row*2 + col;
+  }
+  else if (level == 2)
+  {
+    idx = 5 + row*4 + col;
+  }
+  else if (level == 3)
+  {
+    idx = 21 + row*8 + col;
+  }
+  else // (level == 4)
+  {
+    idx = 85 + row*16 + col;
+  }
+  return idx;
+}
+/** convert quadtree Idx to Level, Row, and Col
+ * \param  idx,  *level,  *row,  *col
+ */
+void TComSampleAdaptiveOffset::convertIdx2LevelRowCol(int idx, int *level, int *row, int *col)
+{
+  if (idx == 0)
+  {
+    *level = 0;
+    *row = 0;
+    *col = 0;
+  }
+  else if (idx>=1 && idx<=4)
+  {
+    *level = 1;
+    *row = (idx-1) / 2;
+    *col = (idx-1) % 2;
+  }
+  else if (idx>=5 && idx<=20)
+  {
+    *level = 2;
+    *row = (idx-5) / 4;
+    *col = (idx-5) % 4;
+  }
+  else if (idx>=21 && idx<=84)
+  {
+    *level = 3;
+    *row = (idx-21) / 8;
+    *col = (idx-21) % 8;
+  }
+  else // (idx>=85 && idx<=340)
+  {
+    *level = 4;
+    *row = (idx-85) / 16;
+    *col = (idx-85) % 16;
+  }
+}
+/** create SampleAdaptiveOffset memory.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth)
+{
+  m_iPicWidth  = uiSourceWidth;
+  m_iPicHeight = uiSourceHeight;
+
+  m_uiMaxCUWidth  = uiMaxCUWidth;
+  m_uiMaxCUHeight = uiMaxCUHeight;
+
+  m_iNumCuInWidth  = m_iPicWidth / m_uiMaxCUWidth;
+  m_iNumCuInWidth += ( m_iPicWidth % m_uiMaxCUWidth ) ? 1 : 0;
+
+  m_iNumCuInHeight  = m_iPicHeight / m_uiMaxCUHeight;
+  m_iNumCuInHeight += ( m_iPicHeight % m_uiMaxCUHeight ) ? 1 : 0;
+
+  Int iMaxSplitLevelHeight = (Int)(logf((float)m_iNumCuInHeight)/logf(2.0));
+  Int iMaxSplitLevelWidth  = (Int)(logf((float)m_iNumCuInWidth )/logf(2.0));
+
+  m_uiMaxSplitLevel = (iMaxSplitLevelHeight < iMaxSplitLevelWidth)?(iMaxSplitLevelHeight):(iMaxSplitLevelWidth);
+  m_uiMaxSplitLevel = (m_uiMaxSplitLevel< m_uiMaxDepth)?(m_uiMaxSplitLevel):(m_uiMaxDepth);
+  /* various structures are overloaded to store per component data.
+   * m_iNumTotalParts must allow for sufficient storage in any allocated arrays */
+  m_iNumTotalParts  = max(3,m_aiNumCulPartsLevel[m_uiMaxSplitLevel]);
+
+  UInt uiInternalBitDepth = g_uiBitDepth+g_uiBitIncrement;
+  UInt uiPixelRange = 1<<uiInternalBitDepth;
+  UInt uiBoRangeShift = uiInternalBitDepth - SAO_BO_BITS;
+
+  m_lumaTableBo = new Pel [uiPixelRange];
+  for (Int k2=0; k2<uiPixelRange; k2++)
+  {
+    m_lumaTableBo[k2] = 1 + (k2>>uiBoRangeShift);
+  }
+  m_iUpBuff1 = new Int[m_iPicWidth+2];
+  m_iUpBuff2 = new Int[m_iPicWidth+2];
+  m_iUpBufft = new Int[m_iPicWidth+2];
+
+  m_iUpBuff1++;
+  m_iUpBuff2++;
+  m_iUpBufft++;
+  Pel i;
+
+  UInt uiMaxY  = g_uiIBDI_MAX;
+  UInt uiMinY  = 0;
+
+  Int iCRangeExt = uiMaxY>>1;
+
+  m_pClipTableBase = new Pel[uiMaxY+2*iCRangeExt];
+  m_iOffsetBo      = new Int[uiMaxY+2*iCRangeExt];
+
+  for(i=0;i<(uiMinY+iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = uiMinY;
+  }
+
+  for(i=uiMinY+iCRangeExt;i<(uiMaxY+  iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = i-iCRangeExt;
+  }
+
+  for(i=uiMaxY+iCRangeExt;i<(uiMaxY+2*iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = uiMaxY;
+  }
+
+  m_pClipTable = &(m_pClipTableBase[iCRangeExt]);
+
+  m_iLcuPartIdx = new Int [m_iNumCuInHeight*m_iNumCuInWidth];
+  m_pTmpL1 = new Pel [m_uiMaxCUHeight+1];
+  m_pTmpL2 = new Pel [m_uiMaxCUHeight+1];
+  m_pTmpU1 = new Pel [m_iPicWidth];
+  m_pTmpU2 = new Pel [m_iPicWidth];
+}
+
+/** destroy SampleAdaptiveOffset memory.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::destroy()
+{
+  if (m_pClipTableBase)
+  {
+    delete [] m_pClipTableBase; m_pClipTableBase = NULL;
+  }
+  if (m_iOffsetBo)
+  {
+    delete [] m_iOffsetBo; m_iOffsetBo = NULL;
+  }
+  if (m_lumaTableBo)
+  {
+    delete[] m_lumaTableBo; m_lumaTableBo = NULL;
+  }
+
+
+  m_iUpBuff1--;
+  m_iUpBuff2--;
+  m_iUpBufft--;
+
+  if (m_iUpBuff1)
+  {
+    delete [] m_iUpBuff1; m_iUpBuff1 = NULL;
+  }
+  if (m_iUpBuff2)
+  {
+    delete [] m_iUpBuff2; m_iUpBuff2 = NULL;
+  }
+  if (m_iUpBufft)
+  {
+    delete [] m_iUpBufft; m_iUpBufft = NULL;
+  }
+  if (m_pTmpL1)
+  {
+    delete [] m_pTmpL1; m_pTmpL1 = NULL;
+  }
+  if (m_pTmpL2)
+  {
+    delete [] m_pTmpL2; m_pTmpL2 = NULL;
+  }
+  if (m_pTmpU1)
+  {
+    delete [] m_pTmpU1; m_pTmpU1 = NULL;
+  }
+  if (m_pTmpU2)
+  {
+    delete [] m_pTmpU2; m_pTmpU2 = NULL;
+  }
+  if(m_iLcuPartIdx)
+  {
+    delete []m_iLcuPartIdx; m_iLcuPartIdx = NULL;
+  }
+}
+
+/** allocate memory for SAO parameters
+ * \param    *pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::allocSaoParam(SAOParam *pcSaoParam)
+{
+  pcSaoParam->iMaxSplitLevel = m_uiMaxSplitLevel;
+  pcSaoParam->psSaoPart[0] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,0);
+  pcSaoParam->psSaoPart[1] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  pcSaoParam->psSaoPart[2] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,1);
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,2);
+  for(Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+  {
+    pcSaoParam->iNumClass[j] = m_iNumClass[j];
+  }
+  pcSaoParam->numCuInWidth  = m_iNumCuInWidth;
+  pcSaoParam->numCuInHeight = m_iNumCuInHeight;
+  pcSaoParam->saoLcuParam[0] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+  pcSaoParam->saoLcuParam[1] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+  pcSaoParam->saoLcuParam[2] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+}
+
+/** initialize SAO parameters
+ * \param    *pcSaoParam,  iPartLevel,  iPartRow,  iPartCol,  iParentPartIdx,  StartCUX,  EndCUX,  StartCUY,  EndCUY,  iYCbCr
+ */
+Void TComSampleAdaptiveOffset::initSAOParam(SAOParam *pcSaoParam, Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY, Int iYCbCr)
+{
+  Int j;
+  Int iPartIdx = convertLevelRowCol2Idx(iPartLevel, iPartRow, iPartCol);
+
+  SAOQTPart* pSaoPart;
+
+  pSaoPart = &(pcSaoParam->psSaoPart[iYCbCr][iPartIdx]);
+
+  pSaoPart->PartIdx   = iPartIdx;
+  pSaoPart->PartLevel = iPartLevel;
+  pSaoPart->PartRow   = iPartRow;
+  pSaoPart->PartCol   = iPartCol;
+
+  pSaoPart->StartCUX  = StartCUX;
+  pSaoPart->EndCUX    = EndCUX;
+  pSaoPart->StartCUY  = StartCUY;
+  pSaoPart->EndCUY    = EndCUY;
+
+  pSaoPart->UpPartIdx = iParentPartIdx;
+  pSaoPart->iBestType   = -1;
+  pSaoPart->iLength     =  0;
+
+  pSaoPart->bandPosition = 0;
+
+  for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+  {
+    pSaoPart->iOffset[j] = 0;
+  }
+
+  if(pSaoPart->PartLevel != m_uiMaxSplitLevel)
+  {
+    Int DownLevel    = (iPartLevel+1 );
+    Int DownRowStart = (iPartRow << 1);
+    Int DownColStart = (iPartCol << 1);
+
+    Int iDownRowIdx, iDownColIdx;
+    Int NumCUWidth,  NumCUHeight;
+    Int NumCULeft;
+    Int NumCUTop;
+
+    Int DownStartCUX, DownStartCUY;
+    Int DownEndCUX, DownEndCUY;
+
+    NumCUWidth  = EndCUX - StartCUX +1;
+    NumCUHeight = EndCUY - StartCUY +1;
+    NumCULeft   = (NumCUWidth  >> 1);
+    NumCUTop    = (NumCUHeight >> 1);
+
+    DownStartCUX= StartCUX;
+    DownEndCUX  = DownStartCUX + NumCULeft - 1;
+    DownStartCUY= StartCUY;
+    DownEndCUY  = DownStartCUY + NumCUTop  - 1;
+    iDownRowIdx = DownRowStart + 0;
+    iDownColIdx = DownColStart + 0;
+
+    pSaoPart->DownPartsIdx[0]= convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx, DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX + NumCULeft;
+    DownEndCUX   = EndCUX;
+    DownStartCUY = StartCUY;
+    DownEndCUY   = DownStartCUY + NumCUTop -1;
+    iDownRowIdx  = DownRowStart + 0;
+    iDownColIdx  = DownColStart + 1;
+
+    pSaoPart->DownPartsIdx[1] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx,  DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX;
+    DownEndCUX   = DownStartCUX + NumCULeft -1;
+    DownStartCUY = StartCUY + NumCUTop;
+    DownEndCUY   = EndCUY;
+    iDownRowIdx  = DownRowStart + 1;
+    iDownColIdx  = DownColStart + 0;
+
+    pSaoPart->DownPartsIdx[2] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx, DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX+ NumCULeft;
+    DownEndCUX   = EndCUX;
+    DownStartCUY = StartCUY + NumCUTop;
+    DownEndCUY   = EndCUY;
+    iDownRowIdx  = DownRowStart + 1;
+    iDownColIdx  = DownColStart + 1;
+
+    pSaoPart->DownPartsIdx[3] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx,DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+  }
+  else
+  {
+    pSaoPart->DownPartsIdx[0]=pSaoPart->DownPartsIdx[1]= pSaoPart->DownPartsIdx[2]= pSaoPart->DownPartsIdx[3]= -1; 
+  }
+}
+
+/** free memory of SAO parameters
+ * \param   pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::freeSaoParam(SAOParam *pcSaoParam)
+{
+  delete [] pcSaoParam->psSaoPart[0];
+  delete [] pcSaoParam->psSaoPart[1];
+  delete [] pcSaoParam->psSaoPart[2];
+  pcSaoParam->psSaoPart[0] = 0;
+  pcSaoParam->psSaoPart[1] = 0;
+  pcSaoParam->psSaoPart[2] = 0;
+  if( pcSaoParam->saoLcuParam[0]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[0]; pcSaoParam->saoLcuParam[0] = NULL;
+  }
+  if( pcSaoParam->saoLcuParam[1]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[1]; pcSaoParam->saoLcuParam[1] = NULL;
+  }
+  if( pcSaoParam->saoLcuParam[2]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[2]; pcSaoParam->saoLcuParam[2] = NULL;
+  }
+} 
+
+/** reset SAO parameters
+ * \param   pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::resetSAOParam(SAOParam *pcSaoParam)
+{
+  Int iNumComponet = 3;
+  for(Int c=0; c<iNumComponet; c++)
+  {
+    pcSaoParam->bSaoFlag[c] = 0;
+    for(Int i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
+    {
+      pcSaoParam->psSaoPart[c][i].iBestType     = -1;
+      pcSaoParam->psSaoPart[c][i].iLength       =  0;
+      pcSaoParam->psSaoPart[c][i].bSplit        = false; 
+      pcSaoParam->psSaoPart[c][i].bProcessed    = false;
+      pcSaoParam->psSaoPart[c][i].dMinCost      = MAX_DOUBLE;
+      pcSaoParam->psSaoPart[c][i].iMinDist      = MAX_INT;
+      pcSaoParam->psSaoPart[c][i].iMinRate      = MAX_INT;
+      pcSaoParam->psSaoPart[c][i].bandPosition = 0;
+      for (Int j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+      {
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+      }
+    }
+    pcSaoParam->oneUnitFlag[0]   = 0;
+    pcSaoParam->oneUnitFlag[1]   = 0;
+    pcSaoParam->oneUnitFlag[2]   = 0;
+    resetLcuPart(pcSaoParam->saoLcuParam[0]);
+    resetLcuPart(pcSaoParam->saoLcuParam[1]);
+    resetLcuPart(pcSaoParam->saoLcuParam[2]);
+  }
+}
+
+/** get the sign of input variable
+ * \param   x
+ */
+inline int xSign(int x)
+{
+  return ((x >> 31) | ((int)( (((unsigned int) -x)) >> 31)));
+}
+
+/** initialize variables for SAO process
+ * \param  pcPic picture data pointer
+ * \param  numSlicesInPic number of slices in picture
+ */
+Void TComSampleAdaptiveOffset::createPicSaoInfo(TComPic* pcPic, Int numSlicesInPic)
+{
+  m_pcPic   = pcPic;
+  m_uiNumSlicesInPic = numSlicesInPic;
+  m_iSGDepth         = pcPic->getSliceGranularityForNDBFilter();
+  m_bUseNIF = ( pcPic->getIndependentSliceBoundaryForNDBFilter() || pcPic->getIndependentTileBoundaryForNDBFilter() );
+  if(m_bUseNIF)
+  {
+    m_pcYuvTmp = pcPic->getYuvPicBufferForIndependentBoundaryProcessing();
+  }
+}
+
+Void TComSampleAdaptiveOffset::destroyPicSaoInfo()
+{
+
+}
+
+/** sample adaptive offset process for one LCU
+ * \param   iAddr, iSaoType, iYCbCr
+ */
+Void TComSampleAdaptiveOffset::processSaoCu(Int iAddr, Int iSaoType, Int iYCbCr)
+{
+  if(!m_bUseNIF)
+  {
+    processSaoCuOrg( iAddr, iSaoType, iYCbCr);
+  }
+  else
+  {  
+    Int  isChroma = (iYCbCr != 0)? 1:0;
+    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
+    Pel* pPicRest = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr);
+    Pel* pPicDec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
+
+    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
+
+    //variables
+    UInt  xPos, yPos, width, height;
+    Bool* pbBorderAvail;
+    UInt  posOffset;
+
+    for(Int i=0; i< vFilterBlocks.size(); i++)
+    {
+      xPos        = vFilterBlocks[i].posX   >> isChroma;
+      yPos        = vFilterBlocks[i].posY   >> isChroma;
+      width       = vFilterBlocks[i].width  >> isChroma;
+      height      = vFilterBlocks[i].height >> isChroma;
+      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
+
+      posOffset = (yPos* stride) + xPos;
+
+      processSaoBlock(pPicDec+ posOffset, pPicRest+ posOffset, stride, iSaoType, xPos, yPos, width, height, pbBorderAvail);
+    }
+  }
+}
+
+/** Perform SAO for non-cross-slice or non-cross-tile process
+ * \param  pDec to-be-filtered block buffer pointer
+ * \param  pRest filtered block buffer pointer
+ * \param  stride picture buffer stride
+ * \param  saoType SAO offset type
+ * \param  xPos x coordinate
+ * \param  yPos y coordinate
+ * \param  width block width
+ * \param  height block height
+ * \param  pbBorderAvail availabilities of block border pixels
+ */
+Void TComSampleAdaptiveOffset::processSaoBlock(Pel* pDec, Pel* pRest, Int stride, Int saoType, UInt xPos, UInt yPos, UInt width, UInt height, Bool* pbBorderAvail)
+{
+  //variables
+  Int startX, startY, endX, endY, x, y;
+  Int signLeft,signRight,signDown,signDown1;
+  UInt edgeType;
+
+  switch (saoType)
+  {
+  case SAO_EO_0: // dir: -
+    {
+
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+      for (y=0; y< height; y++)
+      {
+        signLeft = xSign(pDec[startX] - pDec[startX-1]);
+        for (x=startX; x< endX; x++)
+        {
+          signRight =  xSign(pDec[x] - pDec[x+1]); 
+          edgeType =  signRight + signLeft + 2;
+          signLeft  = -signRight;
+
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+        pDec  += stride;
+        pRest += stride;
+      }
+      break;
+    }
+  case SAO_EO_1: // dir: |
+    {
+      startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
+      endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
+      if (!pbBorderAvail[SGU_T])
+      {
+        pDec  += stride;
+        pRest += stride;
+      }
+      for (x=0; x< width; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x-stride]);
+      }
+      for (y=startY; y<endY; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          signDown  = xSign(pDec[x] - pDec[x+stride]); 
+          edgeType = signDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x]= -signDown;
+
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+        pDec  += stride;
+        pRest += stride;
+      }
+      break;
+    }
+  case SAO_EO_2: // dir: 135
+    {
+      Int posShift= stride + 1;
+
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
+
+      //prepare 2nd line upper sign
+      pDec += stride;
+      for (x=startX; x< endX+1; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x- posShift]);
+      }
+
+      //1st line
+      pDec -= stride;
+      if(pbBorderAvail[SGU_TL])
+      {
+        x= 0;
+        edgeType      =  xSign(pDec[x] - pDec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+        pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+
+      }
+      if(pbBorderAvail[SGU_T])
+      {
+        for(x= 1; x< endX; x++)
+        {
+          edgeType      =  xSign(pDec[x] - pDec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      pDec   += stride;
+      pRest  += stride;
+
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        for (x=startX; x<endX; x++)
+        {
+          signDown1      =  xSign(pDec[x] - pDec[x+ posShift]) ;
+          edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+
+          m_iUpBufft[x+1] = -signDown1; 
+        }
+        m_iUpBufft[startX] = xSign(pDec[stride+startX] - pDec[startX-1]);
+
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pDec  += stride;
+        pRest += stride;
+      }
+
+      //last line
+      if(pbBorderAvail[SGU_B])
+      {
+        for(x= startX; x< width-1; x++)
+        {
+          edgeType =  xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      if(pbBorderAvail[SGU_BR])
+      {
+        x= width -1;
+        edgeType =  xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+        pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+      }
+      break;
+    } 
+  case SAO_EO_3: // dir: 45
+    {
+      Int  posShift     = stride - 1;
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+
+      //prepare 2nd line upper sign
+      pDec += stride;
+      for (x=startX-1; x< endX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x- posShift]);
+      }
+
+
+      //first line
+      pDec -= stride;
+      if(pbBorderAvail[SGU_T])
+      {
+        for(x= startX; x< width -1; x++)
+        {
+          edgeType = xSign(pDec[x] - pDec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      if(pbBorderAvail[SGU_TR])
+      {
+        x= width-1;
+        edgeType = xSign(pDec[x] - pDec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+        pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+      }
+      pDec  += stride;
+      pRest += stride;
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        for(x= startX; x< endX; x++)
+        {
+          signDown1      =  xSign(pDec[x] - pDec[x+ posShift]) ;
+          edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+          m_iUpBuff1[x-1] = -signDown1; 
+        }
+        m_iUpBuff1[endX-1] = xSign(pDec[endX-1 + stride] - pDec[endX]);
+
+        pDec  += stride;
+        pRest += stride;
+      }
+
+      //last line
+      if(pbBorderAvail[SGU_BL])
+      {
+        x= 0;
+        edgeType = xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+        pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+
+      }
+      if(pbBorderAvail[SGU_B])
+      {
+        for(x= 1; x< endX; x++)
+        {
+          edgeType = xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+          pRest[x] = m_pClipTable[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      break;
+    }   
+  case SAO_BO:
+    {
+      for (y=0; y< height; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          pRest[x] = m_iOffsetBo[pDec[x]];
+        }
+        pRest += stride;
+        pDec  += stride;
+      }
+      break;
+    }
+  default: break;
+  }
+
+}
+
+/** sample adaptive offset process for one LCU crossing LCU boundary
+ * \param   iAddr, iSaoType, iYCbCr
+ */
+Void TComSampleAdaptiveOffset::processSaoCuOrg(Int iAddr, Int iSaoType, Int iYCbCr)
+{
+  Int x,y;
+  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
+  Pel* pRec;
+  Int  iStride;
+  Int  iLcuWidth  = m_uiMaxCUWidth;
+  Int  iLcuHeight = m_uiMaxCUHeight;
+  UInt uiLPelX    = pTmpCu->getCUPelX();
+  UInt uiTPelY    = pTmpCu->getCUPelY();
+  UInt uiRPelX;
+  UInt uiBPelY;
+  Int  iSignLeft;
+  Int  iSignRight;
+  Int  iSignDown;
+  Int  iSignDown1;
+  Int  iSignDown2;
+  UInt uiEdgeType;
+  Int iPicWidthTmp;
+  Int iPicHeightTmp;
+  Int iStartX;
+  Int iStartY;
+  Int iEndX;
+  Int iEndY;
+  Int iIsChroma = (iYCbCr!=0)? 1:0;
+  Int iShift;
+  Int iCuHeightTmp;
+  Pel *pTmpLSwap;
+  Pel *pTmpL;
+  Pel *pTmpU;
+
+  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
+  iPicHeightTmp = m_iPicHeight >> iIsChroma;
+  iLcuWidth     = iLcuWidth    >> iIsChroma;
+  iLcuHeight    = iLcuHeight   >> iIsChroma;
+  uiLPelX       = uiLPelX      >> iIsChroma;
+  uiTPelY       = uiTPelY      >> iIsChroma;
+  uiRPelX       = uiLPelX + iLcuWidth  ;
+  uiBPelY       = uiTPelY + iLcuHeight ;
+  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
+  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
+  iLcuWidth     = uiRPelX - uiLPelX;
+  iLcuHeight    = uiBPelY - uiTPelY;
+
+  if(pTmpCu->getPic()==0)
+  {
+    return;
+  }
+  if (iYCbCr == 0)
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+    iStride    = m_pcPic->getStride();
+  } 
+  else if (iYCbCr == 1)
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getCbAddr(iAddr);
+    iStride    = m_pcPic->getCStride();
+  }
+  else 
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getCrAddr(iAddr);
+    iStride    = m_pcPic->getCStride();
+  }
+
+//   if (iSaoType!=SAO_BO_0 || iSaoType!=SAO_BO_1)
+  {
+    iCuHeightTmp = (m_uiMaxCUHeight >> iIsChroma);
+    iShift = (m_uiMaxCUWidth>> iIsChroma)-1;
+    for (Int i=0;i<iCuHeightTmp+1;i++)
+    {
+      m_pTmpL2[i] = pRec[iShift];
+      pRec += iStride;
+    }
+    pRec -= (iStride*(iCuHeightTmp+1));
+
+    pTmpL = m_pTmpL1; 
+    pTmpU = &(m_pTmpU1[uiLPelX]); 
+  }
+
+  switch (iSaoType)
+  {
+  case SAO_EO_0: // dir: -
+    {
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+      for (y=0; y<iLcuHeight; y++)
+      {
+        iSignLeft = xSign(pRec[iStartX] - pTmpL[y]);
+        for (x=iStartX; x< iEndX; x++)
+        {
+          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
+          uiEdgeType =  iSignRight + iSignLeft + 2;
+          iSignLeft  = -iSignRight;
+
+          pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  case SAO_EO_1: // dir: |
+    {
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+      if (uiTPelY == 0)
+      {
+        pRec += iStride;
+      }
+      for (x=0; x< iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        for (x=0; x<iLcuWidth; x++)
+        {
+          iSignDown  = xSign(pRec[x] - pRec[x+iStride]); 
+          uiEdgeType = iSignDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x]= -iSignDown;
+
+          pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  case SAO_EO_2: // dir: 135
+    {
+      iStartX = (uiLPelX == 0)            ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+
+      iStartY = (uiTPelY == 0) ?             1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+
+      if (uiTPelY == 0)
+      {
+        pRec += iStride;
+      }
+
+      for (x=iStartX; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x-1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        iSignDown2 = xSign(pRec[iStride+iStartX] - pTmpL[y]);
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBufft[x+1] = -iSignDown1; 
+          pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        m_iUpBufft[iStartX] = iSignDown2;
+
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pRec += iStride;
+      }
+      break;
+    } 
+  case SAO_EO_3: // dir: 45
+    {
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+
+      if (iStartY == 1)
+      {
+        pRec += iStride;
+      }
+
+      for (x=iStartX-1; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x+1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        x=iStartX;
+        iSignDown1      =  xSign(pRec[x] - pTmpL[y+1]) ;
+        uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+        m_iUpBuff1[x-1] = -iSignDown1; 
+        pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        for (x=iStartX+1; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x-1] = -iSignDown1; 
+          pRec[x] = m_pClipTable[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
+
+        pRec += iStride;
+      } 
+      break;
+    }   
+  case SAO_BO:
+    {
+      for (y=0; y<iLcuHeight; y++)
+      {
+        for (x=0; x<iLcuWidth; x++)
+        {
+          pRec[x] = m_iOffsetBo[pRec[x]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  default: break;
+  }
+//   if (iSaoType!=SAO_BO_0 || iSaoType!=SAO_BO_1)
+  {
+    pTmpLSwap = m_pTmpL1;
+    m_pTmpL1  = m_pTmpL2;
+    m_pTmpL2  = pTmpLSwap;
+  }
+}
+/** Sample adaptive offset process
+ * \param pcPic, pcSaoParam  
+ */
+Void TComSampleAdaptiveOffset::SAOProcess(TComPic* pcPic, SAOParam* pcSaoParam)
+{
+  if (pcSaoParam->bSaoFlag[0])
+  {
+#if FULL_NBIT
+    m_uiSaoBitIncrease = g_uiBitDepth + (g_uiBitDepth-8) - min((Int)(g_uiBitDepth + (g_uiBitDepth-8)), 10);
+#else
+    m_uiSaoBitIncrease = g_uiBitDepth + g_uiBitIncrement - min((Int)(g_uiBitDepth + g_uiBitIncrement), 10);
+#endif
+
+    if(m_bUseNIF)
+    {
+      m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
+    }
+
+    if (m_saoInterleavingFlag)
+    {
+      pcSaoParam->oneUnitFlag[0] = 0;  
+      pcSaoParam->oneUnitFlag[1] = 0;  
+      pcSaoParam->oneUnitFlag[2] = 0;  
+    }
+    Int iY  = 0;
+    processSaoUnitAll( pcSaoParam->saoLcuParam[iY], pcSaoParam->oneUnitFlag[iY], iY);
+
+    Int iCb = 1;
+    Int iCr = 2;
+    if (pcSaoParam->bSaoFlag[iCb])
+    {
+      processSaoUnitAll( pcSaoParam->saoLcuParam[iCb], pcSaoParam->oneUnitFlag[iCb], iCb);
+    }
+    if (pcSaoParam->bSaoFlag[iCr])
+    {
+      processSaoUnitAll( pcSaoParam->saoLcuParam[iCr], pcSaoParam->oneUnitFlag[iCr], iCr);
+    }
+
+
+    m_pcPic = NULL;
+  }
+}
+
+Pel* TComSampleAdaptiveOffset::getPicYuvAddr(TComPicYuv* pcPicYuv, Int iYCbCr, Int iAddr)
+{
+  switch (iYCbCr)
+  {
+  case 0:
+    return pcPicYuv->getLumaAddr(iAddr);
+    break;
+  case 1:
+    return pcPicYuv->getCbAddr(iAddr);
+    break;
+  case 2:
+    return pcPicYuv->getCrAddr(iAddr);
+    break;
+  default:
+    return NULL;
+    break;
+  }
+}
+/** Process SAO all units 
+ * \param saoLcuParam SAO LCU parameters
+ * \param oneUnitFlag one unit flag
+ * \param yCbCr color componet index
+ */
+Void TComSampleAdaptiveOffset::processSaoUnitAll(SaoLcuParam* saoLcuParam, Bool oneUnitFlag, Int yCbCr)
+{
+  Pel *pRec;
+  Int picWidthTmp;
+
+  if (yCbCr == 0)
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getLumaAddr();
+    picWidthTmp = m_iPicWidth;
+  } 
+  else if (yCbCr == 1)
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getCbAddr();
+    picWidthTmp = m_iPicWidth>>1;
+  }
+  else 
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getCrAddr();
+    picWidthTmp = m_iPicWidth>>1;
+  }
+
+  memcpy(m_pTmpU1, pRec, sizeof(Pel)*picWidthTmp);
+
+  int  i;
+  UInt edgeType;
+  Pel* ppLumaTable = NULL;
+  Int  typeIdx;
+
+  static Int offset[LUMA_GROUP_NUM+1];
+  Int idxX;
+  Int idxY;
+  Int addr;
+  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
+  Int frameHeightInCU = m_pcPic->getFrameHeightInCU();
+  Int stride;
+  Pel *tmpUSwap;
+  Int isChroma = (yCbCr == 0) ? 0:1;
+  Bool mergeLeftFlag;
+
+
+  for (idxY = 0; idxY< frameHeightInCU; idxY++)
+  { 
+    addr = idxY * frameWidthInCU;
+    if (yCbCr == 0)
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getLumaAddr(addr);
+      stride = m_pcPic->getStride();
+      picWidthTmp = m_iPicWidth;
+    }
+    else if (yCbCr == 1)
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getCbAddr(addr);
+      stride = m_pcPic->getCStride();
+      picWidthTmp = m_iPicWidth>>1;
+    }
+    else
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getCrAddr(addr);
+      stride = m_pcPic->getCStride();
+      picWidthTmp = m_iPicWidth>>1;
+    }
+
+    //     pRec += iStride*(m_uiMaxCUHeight-1);
+    for (i=0;i<(m_uiMaxCUHeight>>isChroma)+1;i++)
+    {
+      m_pTmpL1[i] = pRec[0];
+      pRec+=stride;
+    }
+    pRec-=(stride<<1);
+
+    memcpy(m_pTmpU2, pRec, sizeof(Pel)*picWidthTmp);
+
+    for (idxX = 0; idxX < frameWidthInCU; idxX++)
+    {
+      addr = idxY * frameWidthInCU + idxX;
+
+      if (oneUnitFlag)
+      {
+        typeIdx = saoLcuParam[0].typeIdx;
+        mergeLeftFlag = (addr == 0)? 0:1;
+      }
+      else
+      {
+        typeIdx = saoLcuParam[addr].typeIdx;
+        mergeLeftFlag = saoLcuParam[addr].mergeLeftFlag;
+      }
+      if (typeIdx>=0)
+      {
+        if (!mergeLeftFlag)
+        {
+
+          if (typeIdx == SAO_BO)
+          {
+            for (i=0; i<SAO_MAX_BO_CLASSES+1;i++)
+            {
+              offset[i] = 0;
+            }
+            for (i=0; i<saoLcuParam[addr].length; i++)
+            {
+              offset[ (saoLcuParam[addr].bandPosition +i)%SAO_MAX_BO_CLASSES  +1] = saoLcuParam[addr].offset[i] << m_uiSaoBitIncrease;
+            }
+
+            ppLumaTable = m_lumaTableBo;
+
+#if FULL_NBIT
+            for (i=0;i<(1<<(g_uiBitDepth));i++)
+#else
+            for (i=0;i<(1<<(g_uiBitIncrement+8));i++)
+#endif
+            {
+              m_iOffsetBo[i] = m_pClipTable[i + offset[ppLumaTable[i]]];
+            }
+
+          }
+          if (typeIdx == SAO_EO_0 || typeIdx == SAO_EO_1 || typeIdx == SAO_EO_2 || typeIdx == SAO_EO_3)
+          {
+            for (i=0;i<saoLcuParam[addr].length;i++)
+            {
+              offset[i+1] = saoLcuParam[addr].offset[i] << m_uiSaoBitIncrease;
+            }
+            for (edgeType=0;edgeType<6;edgeType++)
+            {
+              m_iOffsetEo[edgeType]= offset[m_auiEoTable[edgeType]];
+            }
+          }
+        }
+        processSaoCu(addr, typeIdx, yCbCr);
+      }
+      else
+      {
+        if (idxX != (frameWidthInCU-1))
+        {
+          if (yCbCr == 0)
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getLumaAddr(addr);
+            stride = m_pcPic->getStride();
+          }
+          else if (yCbCr == 1)
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getCbAddr(addr);
+            stride = m_pcPic->getCStride();
+          }
+          else
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getCrAddr(addr);
+            stride = m_pcPic->getCStride();
+          }
+          Int widthShift = m_uiMaxCUWidth>>isChroma;
+          for (i=0;i<(m_uiMaxCUHeight>>isChroma)+1;i++)
+          {
+            m_pTmpL1[i] = pRec[widthShift-1];
+            pRec+=stride;
+          }
+        }
+      }
+    }
+    tmpUSwap = m_pTmpU1;
+    m_pTmpU1 = m_pTmpU2;
+    m_pTmpU2 = tmpUSwap;
+  }
+
+}
+/** Reset SAO LCU part 
+ * \param saoLcuParam
+ */
+Void TComSampleAdaptiveOffset::resetLcuPart(SaoLcuParam* saoLcuParam)
+{
+  Int i,j;
+  for (i=0;i<m_iNumCuInWidth*m_iNumCuInHeight;i++)
+  {
+    saoLcuParam[i].mergeUpFlag     =  1;
+    saoLcuParam[i].mergeLeftFlag =  0;
+    saoLcuParam[i].partIdx   =  0;
+    saoLcuParam[i].typeIdx      = -1;
+    for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+    {
+      saoLcuParam[i].offset[j] = 0;
+    }
+    saoLcuParam[i].bandPosition = 0;
+  }
+}
+
+/** convert QP part to SAO unit 
+* \param saoParam SAO parameter 
+* \param partIdx SAO part index
+* \param yCbCr color component index
+ */
+Void TComSampleAdaptiveOffset::convertQT2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr)
+{
+
+  SAOQTPart*  saoPart= &(saoParam->psSaoPart[yCbCr][partIdx]);
+  if (!saoPart->bSplit)
+  {
+    convertOnePart2SaoUnit(saoParam, partIdx, yCbCr);
+    return;
+  }
+
+  if (saoPart->PartLevel < m_uiMaxSplitLevel)
+  {
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[0], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[1], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[2], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[3], yCbCr);
+  }
+}
+/** convert one SAO part to SAO unit 
+* \param saoParam SAO parameter 
+* \param partIdx SAO part index
+* \param yCbCr color component index
+ */
+Void TComSampleAdaptiveOffset::convertOnePart2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr)
+{
+  Int j;
+  Int idxX;
+  Int idxY;
+  Int addr;
+  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
+  SAOQTPart* saoQTPart = saoParam->psSaoPart[yCbCr];
+  SaoLcuParam* saoLcuParam = saoParam->saoLcuParam[yCbCr];
+
+  for (idxY = saoQTPart[partIdx].StartCUY; idxY<= saoQTPart[partIdx].EndCUY; idxY++)
+  {
+    for (idxX = saoQTPart[partIdx].StartCUX; idxX<= saoQTPart[partIdx].EndCUX; idxX++)
+    {
+      addr = idxY * frameWidthInCU + idxX;
+      saoLcuParam[addr].partIdxTmp = (Int)partIdx; 
+      saoLcuParam[addr].typeIdx    = saoQTPart[partIdx].iBestType;
+      saoLcuParam[addr].bandPosition = saoQTPart[partIdx].bandPosition;
+      if (saoLcuParam[addr].typeIdx!=-1)
+      {
+        saoLcuParam[addr].length    = saoQTPart[partIdx].iLength;
+        for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+        {
+          saoLcuParam[addr].offset[j] = saoQTPart[partIdx].iOffset[j];
+        }
+      }
+      else
+      {
+        saoLcuParam[addr].length    = 0;
+        saoLcuParam[addr].bandPosition = saoQTPart[partIdx].bandPosition;
+        for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+        {
+          saoLcuParam[addr].offset[j] = 0;
+        }
+      }
+    }
+  }
+}
+
+
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 341)
@@ -0,0 +1,146 @@
+/* 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-2012, 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     TComSampleAdaptiveOffset.h
+    \brief    sample adaptive offset class (header)
+*/
+
+#ifndef __TCOMSAMPLEADAPTIVEOFFSET__
+#define __TCOMSAMPLEADAPTIVEOFFSET__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define SAO_MAX_DEPTH                 4
+#define SAO_BO_BITS                   5
+#define LUMA_GROUP_NUM                (1<<SAO_BO_BITS)
+#define MAX_NUM_SAO_OFFSETS           4
+#define MAX_NUM_SAO_CLASS             33
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Sample Adaptive Offset class
+class TComSampleAdaptiveOffset
+{
+protected:
+  TComPic*          m_pcPic;
+
+  static UInt m_uiMaxDepth;
+  static const Int m_aiNumPartsInRow[5];
+  static const Int m_aiNumPartsLevel[5];
+  static const Int m_aiNumCulPartsLevel[5];
+  static const UInt m_auiEoTable[9];
+  static const UInt m_auiEoTable2D[9];
+  static const UInt m_iWeightSao[MAX_NUM_SAO_TYPE];
+  Int *m_iOffsetBo;
+  Int m_iOffsetEo[LUMA_GROUP_NUM];
+
+  Int  m_iPicWidth;
+  Int  m_iPicHeight;
+  UInt m_uiMaxSplitLevel;
+  UInt m_uiMaxCUWidth;
+  UInt m_uiMaxCUHeight;
+  Int  m_iNumCuInWidth;
+  Int  m_iNumCuInHeight;
+  Int  m_iNumTotalParts;
+  static Int m_iNumClass[MAX_NUM_SAO_TYPE];
+  SliceType  m_eSliceType;
+  Int        m_iPicNalReferenceIdc;
+
+  UInt m_uiSaoBitIncrease;
+  UInt m_uiQP;
+
+  Pel   *m_pClipTable;
+  Pel   *m_pClipTableBase;
+  Pel   *m_lumaTableBo;
+  Int   *m_iUpBuff1;
+  Int   *m_iUpBuff2;
+  Int   *m_iUpBufft;
+  Int   *ipSwap;
+  Bool  m_bUseNIF;       //!< true for performing non-cross slice boundary ALF
+  UInt  m_uiNumSlicesInPic;      //!< number of slices in picture
+  Int   m_iSGDepth;              //!< slice granularity depth
+  TComPicYuv* m_pcYuvTmp;    //!< temporary picture buffer pointer when non-across slice/tile boundary SAO is enabled
+
+  Pel* m_pTmpU1;
+  Pel* m_pTmpU2;
+  Pel* m_pTmpL1;
+  Pel* m_pTmpL2;
+  Int* m_iLcuPartIdx;
+  Int     m_maxNumOffsetsPerPic;
+  Bool    m_saoInterleavingFlag;
+public:
+  TComSampleAdaptiveOffset         ();
+  virtual ~TComSampleAdaptiveOffset();
+
+  Void create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
+  Void destroy ();
+
+  Int  convertLevelRowCol2Idx(int level, int row, int col);
+  void convertIdx2LevelRowCol(int idx, int *level, int *row, int *col);
+
+  Void initSAOParam   (SAOParam *pcSaoParam, Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY, Int iYCbCr);
+  Void allocSaoParam  (SAOParam* pcSaoParam);
+  Void resetSAOParam  (SAOParam *pcSaoParam);
+  Void freeSaoParam   (SAOParam *pcSaoParam);
+
+  Void SAOProcess(TComPic* pcPic, SAOParam* pcSaoParam);
+  Void processSaoCu(Int iAddr, Int iSaoType, Int iYCbCr);
+  Void processSaoOnePart(SAOQTPart *psQTPart, UInt uiPartIdx, Int iYCbCr);
+  Void processSaoQuadTree(SAOQTPart *psQTPart, UInt uiPartIdx, Int iYCbCr);
+  Pel* getPicYuvAddr(TComPicYuv* pcPicYuv, Int iYCbCr,Int iAddr = 0);
+
+  Void processSaoCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);  //!< LCU-basd SAO process without slice granularity 
+  Void createPicSaoInfo(TComPic* pcPic, Int numSlicesInPic = 1);
+  Void destroyPicSaoInfo();
+  Void processSaoBlock(Pel* pDec, Pel* pRest, Int stride, Int iSaoType, UInt xPos, UInt yPos, UInt width, UInt height, Bool* pbBorderAvail);
+
+  Void resetLcuPart(SaoLcuParam* saoLcuParam);
+  Void convertQT2SaoUnit(SAOParam* saoParam, UInt partIdx, Int yCbCr);
+  Void convertOnePart2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr);
+  Void processSaoUnitAll(SaoLcuParam* saoLcuParam, Bool oneUnitFlag, Int yCbCr);
+  Void setSaoInterleavingFlag (Bool bVal)  {m_saoInterleavingFlag = bVal;}
+  Bool getSaoInterleavingFlag ()           {return m_saoInterleavingFlag;}
+};
+
+//! \}
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSlice.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSlice.cpp	(revision 341)
@@ -0,0 +1,2312 @@
+/* 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-2012, 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     TComSlice.cpp
+    \brief    slice header and SPS class
+*/
+
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComSlice::TComSlice()
+#if QC_MVHEVC_B0046
+: m_iPPSId                        ( 0  )
+#else
+: m_iPPSId                        ( -1 )
+#endif
+, m_iPOC                          ( 0 )
+, m_iLastIDR                      ( 0 )
+, m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR )
+, m_eNalUnitTypeBaseViewMvc       ( NAL_UNIT_INVALID )
+, m_eSliceType                    ( I_SLICE )
+, m_iSliceQp                      ( 0 )
+#if ADAPTIVE_QP_SELECTION
+, m_iSliceQpBase                  ( 0 )
+#endif
+, m_bLoopFilterDisable            ( false )
+, m_inheritDblParamFromAPS       ( true )
+, m_loopFilterBetaOffsetDiv2    ( 0 )
+, m_loopFilterTcOffsetDiv2      ( 0 )
+, m_bRefPicListModificationFlagLC ( false )
+, m_bRefPicListCombinationFlag    ( false )
+, m_bCheckLDC                     ( false )
+, m_iSliceQpDelta                 ( 0 )
+, m_pcTexturePic                  ( NULL )
+, m_iDepth                        ( 0 )
+, m_bRefenced                     ( false )
+, m_pcSPS                         ( NULL )
+, m_pcPPS                         ( NULL )
+, m_pcPic                         ( NULL )
+, m_uiColDir                      ( 0 )
+#if COLLOCATED_REF_IDX
+, m_colRefIdx                     ( 0 )
+#endif
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+, m_dLambdaLuma( 0.0 )
+, m_dLambdaChroma( 0.0 )
+#else
+, m_dLambda                       ( 0.0 )
+#endif
+, m_bNoBackPredFlag               ( false )
+, m_bRefIdxCombineCoding          ( false )
+, m_uiTLayer                      ( 0 )
+, m_bTLayerSwitchingFlag          ( false )
+, m_uiSliceMode                   ( 0 )
+, m_uiSliceArgument               ( 0 )
+, m_uiSliceCurStartCUAddr         ( 0 )
+, m_uiSliceCurEndCUAddr           ( 0 )
+, m_uiSliceIdx                    ( 0 )
+, m_uiEntropySliceMode            ( 0 )
+, m_uiEntropySliceArgument        ( 0 )
+, m_uiEntropySliceCurStartCUAddr  ( 0 )
+, m_uiEntropySliceCurEndCUAddr    ( 0 )
+, m_bNextSlice                    ( false )
+, m_bNextEntropySlice             ( false )
+, m_uiSliceBits                   ( 0 )
+, m_uiEntropySliceCounter         ( 0 )
+, m_bFinalized                    ( false )
+, m_uiTileByteLocation            ( NULL )
+, m_uiTileCount                   ( 0 )
+, m_iTileMarkerFlag               ( 0 )
+, m_uiTileOffstForMultES          ( 0 )
+, m_puiSubstreamSizes             ( NULL )
+#if CABAC_INIT_FLAG
+, m_cabacInitFlag                 ( false )
+#else
+, m_cabacInitIdc                 ( -1 )
+#endif
+, m_numEntryPointOffsets          ( 0 )
+#if LGE_ILLUCOMP_B0045
+, m_bApplyIC                      ( false )
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+, m_bIVScalingFlag                (false)
+, m_iViewOrderIdx                 ( 0 )        // will be changed to view_id
+#endif
+{
+  m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = m_aiNumRefIdx[2] = 0;
+
+  initEqualRef();
+  
+  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF_LC; iNumCount++)
+  {
+    m_iRefIdxOfLC[REF_PIC_LIST_0][iNumCount]=-1;
+    m_iRefIdxOfLC[REF_PIC_LIST_1][iNumCount]=-1;
+    m_eListIdFromIdxOfLC[iNumCount]=0;
+    m_iRefIdxFromIdxOfLC[iNumCount]=0;
+    m_iRefIdxOfL0FromRefIdxOfL1[iNumCount] = -1;
+    m_iRefIdxOfL1FromRefIdxOfL0[iNumCount] = -1;
+  }    
+  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF+1; iNumCount++)
+  {
+    m_apcRefPicList  [0][iNumCount] = NULL;
+    m_apcRefPicList  [1][iNumCount] = NULL;
+    m_aiRefPOCList   [0][iNumCount] = 0;
+    m_aiRefPOCList   [1][iNumCount] = 0;
+    m_aiRefViewIdList[0][iNumCount] = 0;
+    m_aiRefViewIdList[1][iNumCount] = 0;
+  }
+  m_bCombineWithReferenceFlag = 0;
+  resetWpScaling(m_weightPredTable);
+  resetWpScalingLC(m_weightPredTableLC);
+  initWpAcDcParam();
+#if QC_IV_AS_LT_B0046
+  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF+1; iNumCount++)
+  {
+     m_bWasLongTerm[0][iNumCount] = false;
+     m_bWasLongTerm[1][iNumCount] = false;
+  }
+#endif
+}
+
+TComSlice::~TComSlice()
+{
+  if (m_uiTileByteLocation) 
+  {
+    delete [] m_uiTileByteLocation;
+    m_uiTileByteLocation = NULL;
+  }
+  delete[] m_puiSubstreamSizes;
+  m_puiSubstreamSizes = NULL;
+}
+
+
+Void TComSlice::initSlice()
+{
+  m_aiNumRefIdx[0]      = 0;
+  m_aiNumRefIdx[1]      = 0;
+  
+  m_uiColDir = 0;
+  
+#if COLLOCATED_REF_IDX
+  m_colRefIdx = 0;
+#endif
+  m_pcTexturePic = NULL;
+
+  initEqualRef();
+  m_bNoBackPredFlag = false;
+  m_bRefIdxCombineCoding = false;
+  m_bRefPicListCombinationFlag = false;
+  m_bRefPicListModificationFlagLC = false;
+  m_bCheckLDC = false;
+
+  m_aiNumRefIdx[REF_PIC_LIST_C]      = 0;
+
+  m_uiMaxNumMergeCand = MRG_MAX_NUM_CANDS_SIGNALED;
+
+  m_bFinalized=false;
+
+  m_uiTileCount          = 0;
+#if CABAC_INIT_FLAG
+  m_cabacInitFlag        = false;
+#endif
+  m_numEntryPointOffsets = 0;
+#if QC_TMVP_MRG_REFIDX_C0047
+  m_aiNewRefIdx[0]                  = -1;
+  m_aiNewRefIdx[1]                  = -1;
+#endif
+}
+
+Void TComSlice::initTiles()
+{
+  Int iWidth             = m_pcSPS->getPicWidthInLumaSamples();
+  Int iHeight            = m_pcSPS->getPicHeightInLumaSamples();
+  UInt uiWidthInCU       = ( iWidth %g_uiMaxCUWidth  ) ? iWidth /g_uiMaxCUWidth  + 1 : iWidth /g_uiMaxCUWidth;
+  UInt uiHeightInCU      = ( iHeight%g_uiMaxCUHeight ) ? iHeight/g_uiMaxCUHeight + 1 : iHeight/g_uiMaxCUHeight;
+  UInt uiNumCUsInFrame   = uiWidthInCU * uiHeightInCU;
+
+  if (m_uiTileByteLocation==NULL) m_uiTileByteLocation   = new UInt[uiNumCUsInFrame];
+}
+
+
+/**
+ - 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)
+{
+  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++;
+    pcPicExtract = *(iterPicExtract);
+    pcPicExtract->setCurrSliceIdx(0);
+    
+    iterPicInsert = rcListPic.begin();
+    while (iterPicInsert != iterPicExtract)
+    {
+      pcPicInsert = *(iterPicInsert);
+      pcPicInsert->setCurrSliceIdx(0);
+      if (pcPicInsert->getPOC() >= pcPicExtract->getPOC())
+      {
+        break;
+      }
+      
+      iterPicInsert++;
+    }
+    
+    iterPicExtract_1 = iterPicExtract;    iterPicExtract_1++;
+    
+    //  swap iterPicExtract and iterPicInsert, iterPicExtract = curr. / iterPicInsert = insertion position
+    rcListPic.insert (iterPicInsert, iterPicExtract, iterPicExtract_1);
+    rcListPic.erase  (iterPicExtract);
+  }
+}
+
+TComPic* TComSlice::xGetRefPic( TComList<TComPic*>& rcListPic, UInt uiPOC )
+{
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+  TComPic*                      pcPic = *(iterPic);
+  while ( iterPic != rcListPic.end() )
+  {
+    if(pcPic->getPOC() == uiPOC)
+    {
+      break;
+    }
+    iterPic++;
+    pcPic = *(iterPic);
+  }
+  return  pcPic;
+}
+
+
+TComPic* TComSlice::xGetLongTermRefPic( TComList<TComPic*>& rcListPic, UInt uiPOC )
+{
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+  TComPic*                      pcPic = *(iterPic);
+  TComPic*                      pcStPic = pcPic;
+  while ( iterPic != rcListPic.end() )
+  {
+    pcPic = *(iterPic);
+    if(pcPic && (pcPic->getPOC()%(1<<getSPS()->getBitsForPOC())) == (uiPOC%(1<<getSPS()->getBitsForPOC())))
+    {
+      if(pcPic->getIsLongTerm())
+        return pcPic;
+      else
+        pcStPic = pcPic;
+      break;
+    }
+
+    iterPic++;
+  }
+  return  pcStPic;
+}
+
+TComPic* TComSlice::xGetInterViewRefPic( std::vector<TComPic*>& rcListIvPic, UInt uiViewId )
+{
+  TComPic* pcPic = NULL;
+  for( Int k = 0; k < rcListIvPic.size(); k++ )
+  {
+    if( rcListIvPic[k]->getViewId() == uiViewId )
+    {
+      pcPic = rcListIvPic[k];
+      break;
+    }
+  }
+
+  assert( pcPic != NULL );
+  return pcPic;
+}
+
+Int TComSlice::getNumPocTotalCurr()
+{
+  if( m_eSliceType == I_SLICE ) 
+  {
+    return 0;
+  }
+
+  Int numPocTotalCurr = 0;
+  for( UInt i = 0; i < m_pcRPS->getNumberOfNegativePictures()+ m_pcRPS->getNumberOfPositivePictures() + m_pcRPS->getNumberOfLongtermPictures(); i++ )
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      numPocTotalCurr++;
+    }
+  }
+
+  return numPocTotalCurr;
+}
+
+Int TComSlice::getNumPocTotalCurrMvc()
+{
+  if( m_eSliceType == I_SLICE ) 
+  {
+    return 0;
+  }
+  return getNumPocTotalCurr() + m_pcSPS->getNumberOfUsableInterViewRefs();
+}
+
+Void TComSlice::setRefPOCnViewListsMvc()
+{
+  for(Int iDir = 0; iDir < 2; iDir++)
+  {
+    for(Int iNumRefIdx = 0; iNumRefIdx < m_aiNumRefIdx[iDir]; iNumRefIdx++)
+    {
+      m_aiRefPOCList   [iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getPOC();
+      m_aiRefViewIdList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getViewId();
+    }
+  }
+}
+
+Void TComSlice::generateCombinedList()
+{
+  if(m_aiNumRefIdx[REF_PIC_LIST_C] > 0)
+  {
+    m_aiNumRefIdx[REF_PIC_LIST_C]=0;
+    for(Int iNumCount = 0; iNumCount < MAX_NUM_REF_LC; iNumCount++)
+    {
+      m_iRefIdxOfLC[REF_PIC_LIST_0][iNumCount]=-1;
+      m_iRefIdxOfLC[REF_PIC_LIST_1][iNumCount]=-1;
+      m_eListIdFromIdxOfLC[iNumCount]=0;
+      m_iRefIdxFromIdxOfLC[iNumCount]=0;
+      m_iRefIdxOfL0FromRefIdxOfL1[iNumCount] = -1;
+      m_iRefIdxOfL1FromRefIdxOfL0[iNumCount] = -1;
+    }
+
+    for (Int iNumRefIdx = 0; iNumRefIdx < MAX_NUM_REF; iNumRefIdx++)
+    {
+      if(iNumRefIdx < m_aiNumRefIdx[REF_PIC_LIST_0])
+      {
+        Bool bTempRefIdxInL2 = true;
+        for ( Int iRefIdxLC = 0; iRefIdxLC < m_aiNumRefIdx[REF_PIC_LIST_C]; iRefIdxLC++ )
+        {
+          if( (m_apcRefPicList[REF_PIC_LIST_0][iNumRefIdx]->getPOC()    == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getPOC()   ) &&
+              (m_apcRefPicList[REF_PIC_LIST_0][iNumRefIdx]->getViewId() == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getViewId())    )
+          {
+            m_iRefIdxOfL1FromRefIdxOfL0[iNumRefIdx] = m_iRefIdxFromIdxOfLC[iRefIdxLC];
+            m_iRefIdxOfL0FromRefIdxOfL1[m_iRefIdxFromIdxOfLC[iRefIdxLC]] = iNumRefIdx;
+            bTempRefIdxInL2 = false;
+            break;
+          }
+        }
+
+        if(bTempRefIdxInL2 == true)
+        { 
+          m_eListIdFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = REF_PIC_LIST_0;
+          m_iRefIdxFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = iNumRefIdx;
+          m_iRefIdxOfLC[REF_PIC_LIST_0][iNumRefIdx] = m_aiNumRefIdx[REF_PIC_LIST_C]++;
+        }
+      }
+
+      if(iNumRefIdx < m_aiNumRefIdx[REF_PIC_LIST_1])
+      {
+        Bool bTempRefIdxInL2 = true;
+        for ( Int iRefIdxLC = 0; iRefIdxLC < m_aiNumRefIdx[REF_PIC_LIST_C]; iRefIdxLC++ )
+        {
+          if( (m_apcRefPicList[REF_PIC_LIST_1][iNumRefIdx]->getPOC()    == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getPOC()   ) &&
+              (m_apcRefPicList[REF_PIC_LIST_1][iNumRefIdx]->getViewId() == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getViewId())    )
+          {
+            m_iRefIdxOfL0FromRefIdxOfL1[iNumRefIdx] = m_iRefIdxFromIdxOfLC[iRefIdxLC];
+            m_iRefIdxOfL1FromRefIdxOfL0[m_iRefIdxFromIdxOfLC[iRefIdxLC]] = iNumRefIdx;
+            bTempRefIdxInL2 = false;
+            break;
+          }
+        }
+        if(bTempRefIdxInL2 == true)
+        {
+          m_eListIdFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = REF_PIC_LIST_1;
+          m_iRefIdxFromIdxOfLC[m_aiNumRefIdx[REF_PIC_LIST_C]] = iNumRefIdx;
+          m_iRefIdxOfLC[REF_PIC_LIST_1][iNumRefIdx] = m_aiNumRefIdx[REF_PIC_LIST_C]++;
+        }
+      }
+    }
+  }
+#if QC_TMVP_MRG_REFIDX_C0047
+  Int  iCurrPOC = this->getPOC();
+  for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )//just to get one updated ref idx for merge in each L0/L1 direction, if it is not avaialbe, it is still -1 
+  {        
+    if ( this->getNumRefIdx( RefPicList( uiRefListIdx ) ) == 0)
+        continue;
+
+    Bool bZeroIdxInterViewFlag =  ( this->getRefPic(RefPicList(uiRefListIdx), 0)->getPOC() == iCurrPOC ) ? true : false;
+    for(Int i = 1; i < this->getNumRefIdx(RefPicList(uiRefListIdx)); i++ )
+    {
+      if ( (bZeroIdxInterViewFlag && this->getRefPic(RefPicList(uiRefListIdx), i)->getPOC() != iCurrPOC ) ||
+           (!bZeroIdxInterViewFlag && this->getRefPic(RefPicList(uiRefListIdx), i)->getPOC() == iCurrPOC ) )
+      {
+        this->setNewRefIdx(RefPicList(uiRefListIdx),i);
+        break;
+      }
+    }
+  }
+
+#endif
+}
+
+Void TComSlice::setRefPicListMvc( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& rapcInterViewRefPics )
+{
+  if( m_eSliceType == I_SLICE )
+  {
+    ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList) );
+    ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ) );
+
+    return;
+  }
+
+  TComPic*  pcRefPic;
+  TComPic*  RefPicSetStCurr0[16];
+  TComPic*  RefPicSetStCurr1[16];
+  TComPic*  RefPicSetLtCurr [16];
+  TComPic*  RefPicSetIvCurr [16];
+
+  UInt NumPocStCurr0 = 0;
+  UInt NumPocStCurr1 = 0;
+  UInt NumPocLtCurr  = 0;
+  UInt NumPocIvCurr  = 0;
+
+  Int i;
+  // short term negative
+  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++;
+    }
+  }
+  // short term positive
+  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++;
+    }
+  }
+  // long term
+  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) );
+      pcRefPic->setIsLongTerm( 1 );
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
+      NumPocLtCurr++;
+    }
+  }
+  // inter-view
+  for( i = 0; i < m_pcSPS->getNumberOfUsableInterViewRefs(); i++ )
+  {
+    pcRefPic = xGetInterViewRefPic( rapcInterViewRefPics, getViewId() + m_pcSPS->getUsableInterViewRef(i) );
+#if QC_IV_AS_LT_B0046
+    pcRefPic->setIsLongTerm( 1 );
+#else
+    pcRefPic->setIsLongTerm( 0 );
+#endif
+    pcRefPic->getPicYuvRec()->extendPicBorder();
+    RefPicSetIvCurr[NumPocIvCurr] = pcRefPic;
+    NumPocIvCurr++;
+  }
+
+  // ref_pic_list_init
+  UInt cIdx = 0;
+  UInt num_ref_idx_l0_active_minus1 = m_aiNumRefIdx[0] - 1;
+  UInt num_ref_idx_l1_active_minus1 = m_aiNumRefIdx[1] - 1;
+
+  assert( (NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr + NumPocIvCurr) == getNumPocTotalCurrMvc() );
+  Int numRpsCurrTempList0 = max( (num_ref_idx_l0_active_minus1 + 1), (NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr + NumPocIvCurr) );
+  Int numRpsCurrTempList1 = max( (num_ref_idx_l1_active_minus1 + 1), (NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr + NumPocIvCurr) );
+
+  assert( numRpsCurrTempList0 <= 16 );
+  TComPic* refPicListTemp0[16];
+  assert( numRpsCurrTempList1 <= 16 );
+  TComPic* refPicListTemp1[16];
+
+  cIdx = 0;
+  while( cIdx < numRpsCurrTempList0 )
+  {
+    for( i = 0; i < NumPocStCurr0 && cIdx < numRpsCurrTempList0; cIdx++, i++ ) { refPicListTemp0[cIdx] = RefPicSetStCurr0[i]; }
+    for( i = 0; i < NumPocStCurr1 && cIdx < numRpsCurrTempList0; cIdx++, i++ ) { refPicListTemp0[cIdx] = RefPicSetStCurr1[i]; }
+    for( i = 0; i < NumPocLtCurr  && cIdx < numRpsCurrTempList0; cIdx++, i++ ) { refPicListTemp0[cIdx] = RefPicSetLtCurr [i]; }
+    for( i = 0; i < NumPocIvCurr  && cIdx < numRpsCurrTempList0; cIdx++, i++ ) { refPicListTemp0[cIdx] = RefPicSetIvCurr [i]; }
+  }
+
+  cIdx = 0;
+  while( cIdx < numRpsCurrTempList1 && m_eSliceType == B_SLICE )
+  {
+    for( i = 0; i < NumPocStCurr1 && cIdx < numRpsCurrTempList1; cIdx++, i++ ) { refPicListTemp1[cIdx] = RefPicSetStCurr1[i]; }
+    for( i = 0; i < NumPocStCurr0 && cIdx < numRpsCurrTempList1; cIdx++, i++ ) { refPicListTemp1[cIdx] = RefPicSetStCurr0[i]; }
+    for( i = 0; i < NumPocLtCurr  && cIdx < numRpsCurrTempList1; cIdx++, i++ ) { refPicListTemp1[cIdx] = RefPicSetLtCurr [i]; }
+    for( i = 0; i < NumPocIvCurr  && cIdx < numRpsCurrTempList1; cIdx++, i++ ) { refPicListTemp1[cIdx] = RefPicSetIvCurr [i]; }
+  }
+
+  for( cIdx = 0; cIdx <= num_ref_idx_l0_active_minus1; cIdx ++ )
+  {
+    m_apcRefPicList[0][cIdx] = m_RefPicListModification.getRefPicListModificationFlagL0() ? refPicListTemp0[ m_RefPicListModification.getRefPicSetIdxL0(cIdx) ] : refPicListTemp0[cIdx];
+#if QC_IV_AS_LT_B0046
+    setWasLongTerm(m_apcRefPicList[0][cIdx]->getIsLongTerm(), REF_PIC_LIST_0, cIdx);
+#endif
+  }
+  if( m_eSliceType == P_SLICE )
+  {
+    m_aiNumRefIdx[1] = 0;
+    ::memset( m_apcRefPicList[1], 0, sizeof(m_apcRefPicList[1]) );
+  }
+  else
+  {
+    for( cIdx = 0; cIdx <= num_ref_idx_l1_active_minus1; cIdx ++ )
+    {
+      m_apcRefPicList[1][cIdx] = m_RefPicListModification.getRefPicListModificationFlagL1() ? refPicListTemp1[ m_RefPicListModification.getRefPicSetIdxL1(cIdx) ] : refPicListTemp1[cIdx];
+#if QC_IV_AS_LT_B0046
+      setWasLongTerm(m_apcRefPicList[1][cIdx]->getIsLongTerm(), REF_PIC_LIST_1, cIdx);
+#endif
+    }
+  }
+}
+
+Void TComSlice::initEqualRef()
+{
+  for (Int iDir = 0; iDir < 2; iDir++)
+  {
+    for (Int iRefIdx1 = 0; iRefIdx1 < MAX_NUM_REF; iRefIdx1++)
+    {
+      for (Int iRefIdx2 = iRefIdx1; iRefIdx2 < MAX_NUM_REF; iRefIdx2++)
+      {
+        m_abEqualRef[iDir][iRefIdx1][iRefIdx2] = m_abEqualRef[iDir][iRefIdx2][iRefIdx1] = (iRefIdx1 == iRefIdx2? true : false);
+      }
+    }
+  }
+}
+
+Void TComSlice::initMultiviewSlice( Int** aaiScale, Int** aaiOffset )
+{
+  if( m_pcSPS->hasCamParInSliceHeader() )
+  {
+    UInt uiViewId = m_pcSPS->getViewId();
+    for( UInt uiBaseViewId = 0; uiBaseViewId < uiViewId; uiBaseViewId++ )
+    {
+      m_aaiCodedScale [ 0 ][ uiBaseViewId ] = aaiScale [ uiBaseViewId ][     uiViewId ];
+      m_aaiCodedScale [ 1 ][ uiBaseViewId ] = aaiScale [     uiViewId ][ uiBaseViewId ];
+      m_aaiCodedOffset[ 0 ][ uiBaseViewId ] = aaiOffset[ uiBaseViewId ][     uiViewId ];
+      m_aaiCodedOffset[ 1 ][ uiBaseViewId ] = aaiOffset[     uiViewId ][ uiBaseViewId ];
+    }
+  }
+}
+
+#if COLLOCATED_REF_IDX
+Void TComSlice::checkColRefIdx(UInt curSliceIdx, TComPic* pic)
+{
+  Int i;
+  TComSlice* curSlice = pic->getSlice(curSliceIdx);
+  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(curSlice->getColDir()), curSlice->getColRefIdx());
+  TComSlice* preSlice;
+  Int preColRefPOC;
+  for(i=curSliceIdx-1; i>=0; i--)
+  {
+    preSlice = pic->getSlice(i);
+    if(preSlice->getSliceType() != I_SLICE)
+    {
+      preColRefPOC  = preSlice->getRefPOC( RefPicList(preSlice->getColDir()), preSlice->getColRefIdx());
+      if(currColRefPOC != preColRefPOC)
+      {
+        printf("Collocated_ref_idx shall always be the same for all slices of a coded picture!\n");
+        exit(EXIT_FAILURE);
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+}
+#endif
+Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, TComList<TComPic*>& rcListPic)
+{
+  for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
+  {
+    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
+    {
+      assert(getPOC()+pReferencePictureSet->getDeltaPOC(i) >= pocCRA);
+    }
+  }
+  for(Int i = pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i < pReferencePictureSet->getNumberOfPictures(); i++)
+  {
+    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
+    {
+      assert(pReferencePictureSet->getPOC(i) >= pocCRA);
+    }
+  }
+  if( getNalUnitTypeBaseViewMvc() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+  {
+    pocCRA = getPOC();
+  }
+}
+
+/** Function for marking the reference pictures when an IDR and CRA is encountered.
+ * \param pocCRA POC of the CRA picture
+ * \param bRefreshPending flag indicating if a deferred decoding refresh is pending
+ * \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 all pictures in the reference picture list  
+ * is marked as "unused for reference" 
+ * Otherwise do for the CRA case (non CRA case has no effect since both if conditions below will not be true)
+ *    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 picture (pocCRA), 
+ *    mark all reference pictures except the latest CRA picture as "unused for reference" and set 
+ *    the bRefreshPending flag to false.
+ *    If the nal_unit_type is CRA, 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;
+  UInt uiPOCCurr = getPOC(); 
+
+  if( getNalUnitTypeBaseViewMvc() == NAL_UNIT_CODED_SLICE_IDR )  // IDR
+  {
+    // mark all pictures as not used for reference
+    TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+    while (iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic);
+      rpcPic->setCurrSliceIdx(0);
+      if (rpcPic->getPOC() != uiPOCCurr) rpcPic->getSlice(0)->setReferenced(false);
+      iterPic++;
+    }
+  }
+  else // CRA or No DR
+  {
+    if (bRefreshPending==true && uiPOCCurr > pocCRA) // CRA reference marking pending 
+    {
+      TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+      while (iterPic != rcListPic.end())
+      {
+        rpcPic = *(iterPic);
+        if (rpcPic->getPOC() != uiPOCCurr && rpcPic->getPOC() != pocCRA) rpcPic->getSlice(0)->setReferenced(false);
+        iterPic++;
+      }
+      bRefreshPending = false; 
+    }
+    if( getNalUnitTypeBaseViewMvc() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+    {
+      bRefreshPending = true; 
+      pocCRA = uiPOCCurr;
+    }
+  }
+}
+
+Void TComSlice::copySliceInfo(TComSlice *pSrc)
+{
+  assert( pSrc != NULL );
+
+  Int i, j, k;
+
+  m_iPOC                 = pSrc->m_iPOC;
+  m_viewId               = pSrc->m_viewId;
+#if INTER_VIEW_VECTOR_SCALING_C0115    
+  m_iViewOrderIdx        = pSrc->m_iViewOrderIdx;// will be changed to view_id
+  m_bIVScalingFlag       = pSrc->m_bIVScalingFlag;
+#endif
+  m_eNalUnitType         = pSrc->m_eNalUnitType;
+  m_eNalUnitTypeBaseViewMvc = pSrc->m_eNalUnitTypeBaseViewMvc;
+  m_eSliceType           = pSrc->m_eSliceType;
+  m_iSliceQp             = pSrc->m_iSliceQp;
+#if ADAPTIVE_QP_SELECTION
+  m_iSliceQpBase         = pSrc->m_iSliceQpBase;
+#endif
+  m_bLoopFilterDisable   = pSrc->m_bLoopFilterDisable;
+  m_inheritDblParamFromAPS = pSrc->m_inheritDblParamFromAPS;
+  m_loopFilterBetaOffsetDiv2 = pSrc->m_loopFilterBetaOffsetDiv2;
+  m_loopFilterTcOffsetDiv2 = pSrc->m_loopFilterTcOffsetDiv2;
+  
+  for (i = 0; i < 3; i++)
+  {
+    m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
+  }
+
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF_LC; j++)
+    {
+       m_iRefIdxOfLC[i][j]  = pSrc->m_iRefIdxOfLC[i][j];
+    }
+  }
+  for (i = 0; i < MAX_NUM_REF_LC; i++)
+  {
+    m_eListIdFromIdxOfLC[i] = pSrc->m_eListIdFromIdxOfLC[i];
+    m_iRefIdxFromIdxOfLC[i] = pSrc->m_iRefIdxFromIdxOfLC[i];
+    m_iRefIdxOfL1FromRefIdxOfL0[i] = pSrc->m_iRefIdxOfL1FromRefIdxOfL0[i];
+    m_iRefIdxOfL0FromRefIdxOfL1[i] = pSrc->m_iRefIdxOfL0FromRefIdxOfL1[i];
+  }
+  m_bRefPicListModificationFlagLC = pSrc->m_bRefPicListModificationFlagLC;
+  m_bRefPicListCombinationFlag    = pSrc->m_bRefPicListCombinationFlag;
+  m_bCheckLDC             = pSrc->m_bCheckLDC;
+  m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF; j++)
+    {
+      m_apcRefPicList  [i][j] = pSrc->m_apcRefPicList  [i][j];
+      m_aiRefPOCList   [i][j] = pSrc->m_aiRefPOCList   [i][j];
+      m_aiRefViewIdList[i][j] = pSrc->m_aiRefViewIdList[i][j];
+    }
+  }  
+  m_iDepth               = pSrc->m_iDepth;
+
+  // referenced slice
+  m_bRefenced            = pSrc->m_bRefenced;
+
+  // access channel
+  m_pcSPS                = pSrc->m_pcSPS;
+  m_pcPPS                = pSrc->m_pcPPS;
+  m_pcRPS                = pSrc->m_pcRPS;
+  m_iLastIDR             = pSrc->m_iLastIDR;
+
+  m_pcPic                = pSrc->m_pcPic;
+  m_pcAPS                = pSrc->m_pcAPS;
+  m_iAPSId               = pSrc->m_iAPSId;
+
+  m_uiColDir             = pSrc->m_uiColDir;
+#if COLLOCATED_REF_IDX
+  m_colRefIdx            = pSrc->m_colRefIdx;
+#endif
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA 
+  m_dLambdaLuma          = pSrc->m_dLambdaLuma;
+  m_dLambdaChroma        = pSrc->m_dLambdaChroma;
+#else
+  m_dLambda              = pSrc->m_dLambda;
+#endif
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF; j++)
+    {
+      for (k =0; k < MAX_NUM_REF; k++)
+      {
+        m_abEqualRef[i][j][k] = pSrc->m_abEqualRef[i][j][k];
+      }
+    }
+  }
+
+  m_bNoBackPredFlag      = pSrc->m_bNoBackPredFlag;
+  m_bRefIdxCombineCoding = pSrc->m_bRefIdxCombineCoding;
+
+  m_uiTLayer                      = pSrc->m_uiTLayer;
+  m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
+
+  m_uiSliceMode                   = pSrc->m_uiSliceMode;
+  m_uiSliceArgument               = pSrc->m_uiSliceArgument;
+  m_uiSliceCurStartCUAddr         = pSrc->m_uiSliceCurStartCUAddr;
+  m_uiSliceCurEndCUAddr           = pSrc->m_uiSliceCurEndCUAddr;
+  m_uiSliceIdx                    = pSrc->m_uiSliceIdx;
+  m_uiEntropySliceMode            = pSrc->m_uiEntropySliceMode;
+  m_uiEntropySliceArgument        = pSrc->m_uiEntropySliceArgument; 
+  m_uiEntropySliceCurStartCUAddr  = pSrc->m_uiEntropySliceCurStartCUAddr;
+  m_uiEntropySliceCurEndCUAddr    = pSrc->m_uiEntropySliceCurEndCUAddr;
+  m_bNextSlice                    = pSrc->m_bNextSlice;
+  m_bNextEntropySlice             = pSrc->m_bNextEntropySlice;
+  m_iTileMarkerFlag             = pSrc->m_iTileMarkerFlag;
+  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_saoInterleavingFlag = pSrc->m_saoInterleavingFlag;
+  m_saoEnabledFlagCb = pSrc->m_saoEnabledFlagCb;
+  m_saoEnabledFlagCr = pSrc->m_saoEnabledFlagCr; 
+#if CABAC_INIT_FLAG
+  m_cabacInitFlag                = pSrc->m_cabacInitFlag;
+#endif
+  m_numEntryPointOffsets  = pSrc->m_numEntryPointOffsets;
+
+  m_bLMvdL1Zero = pSrc->m_bLMvdL1Zero;
+}
+
+int TComSlice::m_prevPOC = 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 
+ * temporal_layer_switching_point_flag is set accordingly.
+ */
+Void TComSlice::setTLayerInfo( UInt uiTLayer )
+{
+
+  m_uiTLayer = uiTLayer;
+}
+
+#if H0566_TLA_SET_FOR_SWITCHING_POINTS
+/** Function for checking if this is a switching-point
+*/
+Bool TComSlice::isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+  TComPic* rpcPic;
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if(rpcPic->getSlice(0)->isReferenced() && rpcPic->getPOC() != getPOC())
+    {
+      if(rpcPic->getTLayer() >= getTLayer())
+      {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+#endif
+
+/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
+*/
+Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+  TComPic* rpcPic;
+  Int i, isReference;
+
+  Int j = 0;
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    j++;
+    rpcPic = *(iterPic++);
+
+    isReference = 0;
+    // loop through all pictures in the Reference Picture Set to see if the picture should be kept as reference picture
+    for(i=0;i<pReferencePictureSet->getNumberOfPositivePictures()+pReferencePictureSet->getNumberOfNegativePictures();i++)
+    {
+#if QC_IV_AS_LT_B0046
+       if( rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i))
+#else
+      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i))
+#endif
+      {
+        isReference = 1;
+        rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        rpcPic->setIsLongTerm(0);
+      }
+    }
+    // long term pictures
+    for(;i<pReferencePictureSet->getNumberOfPictures();i++)
+    {
+#if QC_IV_AS_LT_B0046
+     if( (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()))
+#else
+      if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()))
+#endif
+      {
+        isReference = 1;
+        rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+      }
+    }
+    // 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 );   
+      rpcPic->setIsLongTerm(0);
+    }
+  }  
+}
+
+/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
+*/
+Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool outputFlag, Int pocRandomAccess)
+{
+  TComPic* rpcPic;
+  Int i, isAvailable, j;
+  Int atLeastOneLost = 0;
+  Int atLeastOneRemoved = 0;
+  Int iPocLost = 0;
+
+  // loop through all long-term pictures in the Reference Picture Set
+  // to see if the picture should be kept as reference picture
+  for(i=pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i<pReferencePictureSet->getNumberOfPictures();i++)
+  {
+    j = 0;
+    isAvailable = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      j++;
+      rpcPic = *(iterPic++);
+      if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()) && rpcPic->getSlice(0)->isReferenced())
+      {
+        isAvailable = 1;
+      }
+    }
+    // if there was no such long-term check the short terms
+    if(!isAvailable)
+    {
+      iterPic = rcListPic.begin();
+      while ( iterPic != rcListPic.end())
+      {
+        j++;
+        rpcPic = *(iterPic++);
+
+        if((rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == (this->getPOC() + pReferencePictureSet->getDeltaPOC(i))%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()) && rpcPic->getSlice(0)->isReferenced())
+        {
+          isAvailable = 1;
+          rpcPic->setIsLongTerm(1);
+          break;
+        }
+      }
+    }
+    // report that a picture is lost if it is in the Reference Picture Set
+    // but not available as reference picture
+    if(isAvailable == 0)    
+    {            
+      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
+      {
+        if(!pReferencePictureSet->getUsed(i) )
+        {
+          if(outputFlag)
+            printf("\nLong-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          atLeastOneRemoved = 1;
+        }
+        else
+        {
+          if(outputFlag)
+            printf("\nLong-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          atLeastOneLost = 1;
+          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
+        }
+      }
+    }
+  }  
+  // loop through all short-term pictures in the Reference Picture Set
+  // to see if the picture should be kept as reference picture
+  for(i=0;i<pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i++)
+  {
+    j = 0;
+    isAvailable = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      j++;
+      rpcPic = *(iterPic++);
+
+      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
+      {
+        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 (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
+      {
+        if(!pReferencePictureSet->getUsed(i) )
+        {
+          if(outputFlag)
+            printf("\nShort-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          atLeastOneRemoved = 1;
+        }
+        else
+        {
+          if(outputFlag)
+            printf("\nShort-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          atLeastOneLost = 1;
+          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
+        }
+      }
+    }
+  }    
+  if(atLeastOneLost)
+  {
+    return iPocLost+1;
+  }
+  if(atLeastOneRemoved)
+  {
+    return -2;
+  }
+  else
+    return 0;
+}
+
+/** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
+*/
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+  TComPic* rpcPic;
+  Int i, j;
+  Int k = 0;
+  Int nrOfNegativePictures = 0;
+  Int nrOfPositivePictures = 0;
+  TComReferencePictureSet* pcRPS = this->getLocalRPS();
+
+  // loop through all pictures in the Reference Picture Set
+  for(i=0;i<pReferencePictureSet->getNumberOfPictures();i++)
+  {
+    j = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      j++;
+      rpcPic = *(iterPic++);
+
+      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
+      {
+        // This picture exists as a reference picture
+        // and should be added to the explicit Reference Picture Set
+        pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
+        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i));
+        if(pcRPS->getDeltaPOC(k) < 0)
+          nrOfNegativePictures++;
+        else
+          nrOfPositivePictures++;
+        k++;
+      }
+    }
+  }
+  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 
+  // 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())
+  {
+    pcRPS->setInterRPSPrediction(false);
+    pcRPS->setNumRefIdc(0);
+  }
+  else
+  {
+    Int rIdx =  this->getRPSidx() - pReferencePictureSet->getDeltaRIdxMinus1() - 1;
+    Int deltaRPS = pReferencePictureSet->getDeltaRPS();
+    TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
+    Int iRefPics = pcRefRPS->getNumberOfPictures();
+    Int iNewIdc=0;
+    for(i=0; i<= iRefPics; i++) 
+    {
+      Int deltaPOC = ((i != iRefPics)? pcRefRPS->getDeltaPOC(i) : 0);  // check if the reference abs POC is >= 0
+      Int iRefIdc = 0;
+      for (j=0; j < pcRPS->getNumberOfPictures(); j++) // loop through the  pictures in the new RPS
+      {
+        if ( (deltaPOC + deltaRPS) == pcRPS->getDeltaPOC(j))
+        {
+          if (pcRPS->getUsed(j))
+          {
+            iRefIdc = 1;
+          }
+          else
+          {
+            iRefIdc = 2;
+          }
+        }
+      }
+      pcRPS->setRefIdc(i, iRefIdc);
+      iNewIdc++;
+    }
+    pcRPS->setInterRPSPrediction(true);
+    pcRPS->setNumRefIdc(iNewIdc);
+    pcRPS->setDeltaRPS(deltaRPS); 
+    pcRPS->setDeltaRIdxMinus1(pReferencePictureSet->getDeltaRIdxMinus1() + this->getSPS()->getRPSList()->getNumberOfReferencePictureSets() - this->getRPSidx());
+  }
+
+  this->setRPS(pcRPS);
+  this->setRPSidx(-1);
+}
+
+Void TComSlice::decodingMarkingForNoTMVP( TComList<TComPic*>& rcListPic, Int currentPOC )
+{
+  TComList<TComPic*>::iterator it;
+  for ( it = rcListPic.begin(); it != rcListPic.end(); it++ )
+  {
+    if ( (*it)->getSlice(0)->getPOC() != currentPOC )
+    {
+      (*it)->setUsedForTMVP( false );
+    }
+  }
+}
+
+/** get AC and DC values for weighted pred
+ * \param *wp
+ * \returns Void
+ */
+Void  TComSlice::getWpAcDcParam(wpACDCParam *&wp)
+{
+  wp = m_weightACDCParam;
+}
+
+/** init AC and DC values for weighted pred
+ * \returns Void
+ */
+Void  TComSlice::initWpAcDcParam()
+{
+  for(Int iComp = 0; iComp < 3; iComp++ )
+  {
+    m_weightACDCParam[iComp].iAC = 0;
+    m_weightACDCParam[iComp].iDC = 0;
+  }
+}
+
+/** get WP tables for weighted pred
+ * \param RefPicList
+ * \param iRefIdx
+ * \param *&wpScalingParam
+ * \returns Void
+ */
+Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, wpScalingParam *&wp )
+{
+  wp = m_weightPredTable[e][iRefIdx];
+}
+
+/** reset Default WP tables settings : no weight. 
+ * \param wpScalingParam
+ * \returns Void
+ */
+Void  TComSlice::resetWpScaling(wpScalingParam  wp[2][MAX_NUM_REF][3])
+{
+  for ( int e=0 ; e<2 ; e++ ) 
+  {
+    for ( int i=0 ; i<MAX_NUM_REF ; i++ )
+    {
+      for ( int yuv=0 ; yuv<3 ; yuv++ ) 
+      {
+        wpScalingParam  *pwp = &(wp[e][i][yuv]);
+        pwp->bPresentFlag      = false;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->iWeight           = 1;
+        pwp->iOffset           = 0;
+      }
+    }
+  }
+}
+
+/** init WP table
+ * \returns Void
+ */
+Void  TComSlice::initWpScaling()
+{
+  initWpScaling(m_weightPredTable);
+}
+
+/** set WP tables 
+ * \param wpScalingParam
+ * \returns Void
+ */
+Void  TComSlice::initWpScaling(wpScalingParam  wp[2][MAX_NUM_REF][3])
+{
+  for ( int e=0 ; e<2 ; e++ ) 
+  {
+    for ( int i=0 ; i<MAX_NUM_REF ; i++ )
+    {
+      for ( int yuv=0 ; yuv<3 ; yuv++ ) 
+      {
+        wpScalingParam  *pwp = &(wp[e][i][yuv]);
+        if ( !pwp->bPresentFlag ) {
+          // Inferring values not present :
+          pwp->iWeight = (1 << pwp->uiLog2WeightDenom);
+          pwp->iOffset = 0;
+        }
+
+        pwp->w      = pwp->iWeight;
+        pwp->o      = pwp->iOffset * (1 << (g_uiBitDepth-8));
+        pwp->shift  = pwp->uiLog2WeightDenom;
+        pwp->round  = (pwp->uiLog2WeightDenom>=1) ? (1 << (pwp->uiLog2WeightDenom-1)) : (0);
+      }
+    }
+  }
+}
+
+/** get WP tables for weighted pred of LC
+ * \param iRefIdxLC
+ * \param *&wpScalingParam
+ * \returns Void
+ */
+Void TComSlice::getWpScalingLC( Int iRefIdx, wpScalingParam *&wp )
+{
+  wp = m_weightPredTableLC[iRefIdx];
+}
+/** reset Default WP tables settings for LC : no weight. 
+ * \param wpScalingParam
+ * \returns Void
+ */
+Void TComSlice::resetWpScalingLC(wpScalingParam  wp[2*MAX_NUM_REF][3])
+{
+  for ( int i=0 ; i<2*MAX_NUM_REF ; i++ )
+  {
+    for ( int yuv=0 ; yuv<3 ; yuv++ ) 
+    {
+      wpScalingParam  *pwp = &(wp[i][yuv]);
+      pwp->bPresentFlag      = false;
+      pwp->uiLog2WeightDenom = 0;
+      pwp->uiLog2WeightDenom = 0;
+      pwp->iWeight           = 1;
+      pwp->iOffset           = 0;
+    }
+  }
+}
+/** set current WP tables settings for LC
+ * \returns Void
+ */
+Void TComSlice::setWpParamforLC()
+{
+  for ( Int iRefIdx=0 ; iRefIdx<getNumRefIdx(REF_PIC_LIST_C) ; iRefIdx++ )
+  {
+    RefPicList eRefPicList = (RefPicList)getListIdFromIdxOfLC(iRefIdx);
+    Int iCombRefIdx = getRefIdxFromIdxOfLC(iRefIdx);
+
+    wpScalingParam  *wp_src, *wp_dst;
+    getWpScalingLC(iRefIdx, wp_src);
+    getWpScaling(eRefPicList, iCombRefIdx, wp_dst);
+    copyWPtable(wp_src, wp_dst);
+
+    if(eRefPicList == REF_PIC_LIST_0)
+    {
+      Int iRefIdxL1 = getRefIdxOfL1FromRefIdxOfL0(iCombRefIdx);
+      if(iRefIdxL1 >= 0)
+      {
+        getWpScaling(REF_PIC_LIST_1, iRefIdxL1, wp_dst);
+        copyWPtable(wp_src, wp_dst);
+      }
+    }
+    if(eRefPicList == REF_PIC_LIST_1)
+    {
+      Int iRefIdxL0 = getRefIdxOfL0FromRefIdxOfL1(iCombRefIdx);
+      if(iRefIdxL0 >= 0)
+      {
+        getWpScaling(REF_PIC_LIST_0, iRefIdxL0, wp_dst);
+        copyWPtable(wp_src, wp_dst);
+      }
+    }
+  }
+  initWpScaling();
+}
+/** copy source WP tables to destination table for LC
+ * \param wpScalingParam *&wp_src : source
+ * \param wpScalingParam *&wp_dst : destination
+ * \returns Void
+ */
+Void TComSlice::copyWPtable(wpScalingParam *&wp_src, wpScalingParam *&wp_dst)
+{
+  for ( Int iComp = 0; iComp < 3; iComp++ )
+  {
+    wp_dst[iComp].uiLog2WeightDenom = (iComp==0) ? wp_src[0].uiLog2WeightDenom : wp_src[1].uiLog2WeightDenom;
+    wp_dst[iComp].bPresentFlag = wp_src[iComp].bPresentFlag;
+    wp_dst[iComp].iWeight = wp_src[iComp].iWeight;
+    wp_dst[iComp].iOffset = wp_src[iComp].iOffset;
+  }
+}
+
+#if LGE_ILLUCOMP_B0045
+Void TComSlice::xSetApplyIC()
+{
+  Int iMaxPelValue = (1<<g_uiBitDepth); 
+  Int *aiRefOrgHist;
+  Int *aiCurrHist;
+  aiRefOrgHist = new Int;
+  aiCurrHist   = new Int;
+  aiRefOrgHist = (Int *)xMalloc(Int,iMaxPelValue);
+  aiCurrHist   = (Int *)xMalloc(Int,iMaxPelValue);
+  memset(aiRefOrgHist, 0, iMaxPelValue*sizeof(Int) );
+  memset(aiCurrHist, 0, iMaxPelValue*sizeof(Int) );
+  // Reference Idx Number
+  Int iNumRefIdx = getNumRefIdx( REF_PIC_LIST_0 );
+  TComPic* pcCurrPic = NULL;
+  TComPic* pcRefPic = NULL;
+  TComPicYuv* pcCurrPicYuv = NULL;
+  TComPicYuv* pcRefPicYuvOrg = NULL;
+  pcCurrPic = getPic();
+  pcCurrPicYuv = pcCurrPic->getPicYuvOrg();
+  Int iWidth = pcCurrPicYuv->getWidth();
+  Int iHeight = pcCurrPicYuv->getHeight();
+
+
+  // Get InterView Reference picture
+  // !!!!! Assume only one Interview Reference Picture in L0
+  for (Int i = 0; i < iNumRefIdx; i++)
+  {
+    pcRefPic = getRefPic( REF_PIC_LIST_0, i);
+    if (pcRefPic != NULL)
+    {
+      // Current Picture 
+      if (pcCurrPic->getViewId() != pcRefPic->getViewId())
+      {
+        pcRefPicYuvOrg = pcRefPic->getPicYuvOrg();
+      }
+    }
+  }
+  if (pcRefPicYuvOrg != NULL)
+  {
+    Pel* pCurrY = pcCurrPicYuv ->getLumaAddr();
+    Pel* pRefOrgY = pcRefPicYuvOrg  ->getLumaAddr();
+    Int iCurrStride = pcCurrPicYuv->getStride();
+    Int iRefStride = pcRefPicYuvOrg->getStride();
+    Int iSumOrgSAD = 0;
+#if LGE_ILLUCOMP_DEPTH_C0046
+    Double dThresholdOrgSAD = getIsDepth() ? 0.1 : 0.05;
+#else
+    double dThresholdOrgSAD = 0.05;
+#endif
+    // Histogram building - luminance
+    for ( Int y = 0; y < iHeight; y++)
+    {
+      for ( Int x = 0; x < iWidth; x++)
+      {
+        aiCurrHist[pCurrY[x]]++;
+        aiRefOrgHist[pRefOrgY[x]]++;
+      }
+      pCurrY += iCurrStride;
+      pRefOrgY += iRefStride;
+    }
+    // Calc SAD
+    for (Int i = 0; i < iMaxPelValue; i++)
+    {
+      iSumOrgSAD += abs(aiCurrHist[i] - aiRefOrgHist[i]);
+    }
+    // Setting
+    if ( iSumOrgSAD > Int(dThresholdOrgSAD * iWidth * iHeight) )
+    {
+      m_bApplyIC = true;
+    }
+    else
+    {
+      m_bApplyIC = false;
+    }
+  }
+  xFree(aiCurrHist);
+  xFree(aiRefOrgHist);
+  aiCurrHist = NULL;
+  aiRefOrgHist = NULL;
+}
+#endif
+
+// ------------------------------------------------------------------------------------------------
+// Video parameter set (VPS)
+// ------------------------------------------------------------------------------------------------
+#if QC_MVHEVC_B0046
+TComVPS::TComVPS()
+: m_VPSId                     (  0)
+, m_uiMaxTLayers              (  1)
+, m_uiMaxLayers               (  1)
+, m_bTemporalIdNestingFlag    (false)
+, m_uiNumHRDParameter         (  0)
+, m_numAddiLayerOperationPoints (2)
+, m_numAddiProLevelSets       (  1)
+{
+  for( Int i = 0; i < MAX_LAYER_NUM; i++)
+  {
+  m_numOpLayerIdMinus1[i] = 0;
+  if(i)
+      m_numDirectRefLayer[i] = 1;
+  else
+    m_numDirectRefLayer[i] = 0;
+  for( Int j = 0; j < MAX_LAYER_NUM; j++)
+  {
+    m_numDirectRefID[i][j] = 0;
+    m_numOpLayerId[i][j]   = 0;
+  }
+    m_uiViewId[i] = 0;
+    m_iViewOrderIdx[i] = 0;
+  }
+  
+  for( Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_numReorderPics[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 0; 
+    m_uiMaxLatencyIncrease[i] = 0;
+  }
+}
+
+TComVPS::~TComVPS()
+{
+}
+#else
+#if VIDYO_VPS_INTEGRATION
+TComVPS::TComVPS()
+: m_VPSId                     (  0)
+, m_uiMaxTLayers              (  1)
+, m_uiMaxLayers               (  1)
+, m_bTemporalIdNestingFlag    (false)
+, m_uiExtensionType           (  0)
+{
+  for( Int i = 0; i < MAX_LAYER_NUM; i++)
+  {
+    m_uiDependentLayer[i] = i? i-1: 0;
+    m_bDependentFlag[i] = false;
+    m_uiViewId[i] = 0;
+    m_bDepthFlag[i] = 0;
+    m_iViewOrderIdx[i] = 0;
+  }
+  
+  for( Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_numReorderPics[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 0; 
+    m_uiMaxLatencyIncrease[i] = 0;
+  }
+}
+
+TComVPS::~TComVPS()
+{
+  
+  
+}
+
+#endif
+#endif
+
+// ------------------------------------------------------------------------------------------------
+// Sequence parameter set (SPS)
+// ------------------------------------------------------------------------------------------------
+
+TComSPS::TComSPS()
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+: m_VPSId                     (  0)
+, m_SPSId                     (  0)
+#else
+: m_SPSId                     (  0)
+#endif
+, m_ProfileIdc                (  0)
+, m_LevelIdc                  (  0)
+, m_chromaFormatIdc           (CHROMA_420)
+, m_uiMaxTLayers              (  1)
+// Structure
+, m_picWidthInLumaSamples     (352)
+, m_picHeightInLumaSamples    (288)
+, m_picCroppingFlag           (false)
+, m_picCropLeftOffset         (  0)
+, m_picCropRightOffset        (  0)
+, m_picCropTopOffset          (  0)
+, m_picCropBottomOffset       (  0) 
+, m_uiMaxCUWidth              ( 32)
+, m_uiMaxCUHeight             ( 32)
+, m_uiMaxCUDepth              (  3)
+, m_uiMinTrDepth              (  0)
+, m_uiMaxTrDepth              (  1)
+, m_bLongTermRefsPresent      (false)
+, m_iNumberOfUsableInterViewRefs( 0 )
+, m_uiQuadtreeTULog2MaxSize   (  0)
+, m_uiQuadtreeTULog2MinSize   (  0)
+, m_uiQuadtreeTUMaxDepthInter (  0)
+, m_uiQuadtreeTUMaxDepthIntra (  0)
+// Tool list
+, m_usePCM                   (false)
+, m_pcmLog2MaxSize            (  5)
+, m_uiPCMLog2MinSize          (  7)
+, m_bDisInter4x4              (  1)
+, m_bUseALF                   (false)
+, m_bALFCoefInSlice           (false)
+, m_bUseLMChroma              (false)
+, m_bUseLComb                 (false)
+, m_bLCMod                    (false)
+#if QC_MVHEVC_B0046
+, m_restrictedRefPicListsFlag   (  0)
+#else
+, m_restrictedRefPicListsFlag   (  1)
+#endif
+, m_listsModificationPresentFlag(  0)
+, m_uiBitDepth                (  8)
+, m_uiBitIncrement            (  0)
+, m_qpBDOffsetY               (  0)
+, m_qpBDOffsetC               (  0)
+#if LOSSLESS_CODING
+, m_useLossless               (false)
+#endif
+, m_uiPCMBitDepthLuma         (  8)
+, m_uiPCMBitDepthChroma       (  8)
+, m_bPCMFilterDisableFlag     (false)
+, m_uiBitsForPOC              (  8)
+, m_uiMaxTrSize               ( 32)
+, m_bLFCrossSliceBoundaryFlag (false)
+, m_bUseSAO                   (false) 
+#if HHI_MPI
+, m_bUseMVI                   (false)
+#endif
+, m_bLFCrossTileBoundaryFlag  (false) 
+, m_iUniformSpacingIdr        (  0 )
+, m_iTileBoundaryIndependenceIdr (  0 )
+, m_iNumColumnsMinus1         (  0 )
+, m_puiColumnWidth            ( NULL )
+, m_iNumRowsMinus1            (  0 )
+, m_puiRowHeight              ( NULL )
+, m_bTemporalIdNestingFlag    (false)
+, m_scalingListEnabledFlag    (false)
+,  m_tilesOrEntropyCodingSyncIdc( 0 )
+,  m_numSubstreams              ( 0 )
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+, m_bUseDMM                   (false)
+#endif
+#if FLEX_CODING_ORDER_M23723 && HHI_DMM_PRED_TEX
+, m_bUseDMM34                   (false)
+#endif
+#if H3D_QTL
+, m_bUseQTLPC                 (false)
+#endif
+{
+  // AMVP parameter
+  ::memset( m_aeAMVPMode, 0, sizeof( m_aeAMVPMode ) );
+  for ( Int i = 0; i < MAX_TLAYER; i++ )
+  {
+    m_uiMaxLatencyIncrease[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 0;
+    m_numReorderPics[i]       = 0;
+  }
+
+  m_uiViewId              = 0;
+  m_iViewOrderIdx         = 0;
+  m_bDepth                = false;
+  m_uiCamParPrecision     = 0;
+  m_bCamParInSliceHeader  = false;
+  ::memset( m_aaiCodedScale,  0x00, sizeof( m_aaiCodedScale  ) );
+  ::memset( m_aaiCodedOffset, 0x00, sizeof( m_aaiCodedOffset ) );
+
+#if DEPTH_MAP_GENERATION
+  m_uiPredDepthMapGeneration = 0;
+  m_uiPdmPrecision           = 0;
+  ::memset( m_aiPdmScaleNomDelta, 0x00, sizeof( m_aiPdmScaleNomDelta  ) );
+  ::memset( m_aiPdmOffset,        0x00, sizeof( m_aiPdmOffset         ) );
+#endif
+#if H3D_IVMP
+  m_uiMultiviewMvPredMode    = 0;
+#endif
+
+  ::memset( m_aiUsableInterViewRefs, 0, sizeof( m_aiUsableInterViewRefs ) );
+  
+#if RWTH_SDC_DLT_B0036
+  m_bUseDLT = false;
+  
+  m_uiBitsPerDepthValue = g_uiBitDepth;
+  m_uiNumDepthmapValues = 0;
+  m_uiDepthValue2Idx    = NULL;
+  m_uiIdx2DepthValue    = NULL;
+#endif
+}
+
+TComSPS::~TComSPS()
+{
+  if( m_iNumColumnsMinus1 > 0 && m_iUniformSpacingIdr == 0 )
+  {
+    delete [] m_puiColumnWidth; 
+    m_puiColumnWidth = NULL;
+  }
+  if( m_iNumRowsMinus1 > 0 && m_iUniformSpacingIdr == 0 )
+  {
+    delete [] m_puiRowHeight;
+    m_puiRowHeight = NULL;
+  }
+}
+
+#if RWTH_SDC_DLT_B0036
+Void TComSPS::setDepthLUTs(UInt* uidx2DepthValue, UInt uiNumDepthValues)
+{
+  UInt uiMaxDepthValue = g_uiIBDI_MAX;
+  
+  // allocate some memory
+  if( m_uiNumDepthmapValues == 0 )
+  {
+    m_uiNumDepthmapValues = uiMaxDepthValue+1;
+    m_uiBitsPerDepthValue = (UInt)ceil(Log2(m_uiNumDepthmapValues));
+    
+    m_uiDepthValue2Idx    = (UInt*) xMalloc(UInt, m_uiNumDepthmapValues);
+    m_uiIdx2DepthValue    = (UInt*) xMalloc(UInt, m_uiNumDepthmapValues);
+    
+    //default mapping
+    for (Int i=0; i<m_uiNumDepthmapValues; i++)
+    {
+      m_uiDepthValue2Idx[i] = i;
+      m_uiIdx2DepthValue[i] = i;
+    }
+  }
+  
+  if( uidx2DepthValue == NULL || uiNumDepthValues == 0 ) // default mapping only
+    return;
+  
+  // copy idx2DepthValue to internal array
+  memcpy(m_uiIdx2DepthValue, uidx2DepthValue, uiNumDepthValues*sizeof(UInt));
+  
+  for(Int p=0; p<=uiMaxDepthValue; p++)
+  {
+    Int iIdxDown    = 0;
+    Int iIdxUp      = uiNumDepthValues-1;
+    Bool bFound     = false;
+    
+    // iterate over indices to find lower closest depth
+    Int i = 1;
+    while(!bFound && i<uiNumDepthValues)
+    {
+      if( m_uiIdx2DepthValue[i] > p )
+      {
+        iIdxDown  = i-1;
+        bFound    = true;
+      }
+      
+      i++;
+    }
+    // iterate over indices to find upper closest depth
+    i = uiNumDepthValues-2;
+    bFound = false;
+    while(!bFound && i>=0)
+    {
+      if( m_uiIdx2DepthValue[i] < p )
+      {
+        iIdxUp  = i+1;
+        bFound    = true;
+      }
+      
+      i--;
+    }
+    
+    // assert monotony
+    assert(iIdxDown<=iIdxUp);
+    
+    // assign closer depth value/idx
+    if( abs(p-(Int)m_uiIdx2DepthValue[iIdxDown]) < abs(p-(Int)m_uiIdx2DepthValue[iIdxUp]) )
+    {
+      m_uiDepthValue2Idx[p] = iIdxDown;
+    }
+    else
+    {
+      m_uiDepthValue2Idx[p] = iIdxUp;
+    }
+    
+  }
+  
+  // update globals
+  m_uiNumDepthmapValues = uiNumDepthValues;
+  m_uiBitsPerDepthValue = (UInt)ceil(Log2(m_uiNumDepthmapValues));
+}
+#endif
+
+TComPPS::TComPPS()
+: m_PPSId                       (0)
+, m_SPSId                       (0)
+, m_picInitQPMinus26            (0)
+, m_useDQP                      (false)
+, m_bConstrainedIntraPred       (false)
+, m_pcSPS                       (NULL)
+, m_uiMaxCuDQPDepth             (0)
+, m_uiMinCuDQPSize              (0)
+, m_iChromaQpOffset             (0)
+, m_iChromaQpOffset2nd          (0)
+, m_iSliceGranularity           (0)
+, m_iTileBehaviorControlPresentFlag (0)
+, m_bLFCrossTileBoundaryFlag     (true)
+, m_iColumnRowInfoPresent        (0)
+, m_iUniformSpacingIdr           (0)
+, m_iNumColumnsMinus1            (0)
+, m_puiColumnWidth               (NULL)
+, m_iNumRowsMinus1               (0)
+, m_puiRowHeight                 (NULL)
+,  m_iNumSubstreams             (1)
+, m_signHideFlag(0)
+, m_signHidingThreshold(0)
+#if CABAC_INIT_FLAG
+, m_cabacInitPresentFlag        (false)
+, m_encCABACTableIdx            (0)
+#if FIX_POZNAN_CABAC_INIT_FLAG
+, m_encPrevPOC            (0)
+#endif
+#endif
+{
+}
+
+TComPPS::~TComPPS()
+{
+  if( m_iNumColumnsMinus1 > 0 && m_iUniformSpacingIdr == 0 )
+  {
+    if (m_puiColumnWidth) delete [] m_puiColumnWidth; 
+    m_puiColumnWidth = NULL;
+  }
+  if( m_iNumRowsMinus1 > 0 && m_iUniformSpacingIdr == 0 )
+  {
+    if (m_puiRowHeight) delete [] m_puiRowHeight;
+    m_puiRowHeight = NULL;
+  }
+}
+
+Void
+TComSPS::initMultiviewSPS( UInt uiViewId, Int iViewOrderIdx, UInt uiCamParPrecision, Bool bCamParSlice, Int** aaiScale, Int** aaiOffset )
+{
+#if !QC_MVHEVC_B0046
+  AOT( uiViewId == 0 && iViewOrderIdx != 0 );
+  AOT( uiViewId != 0 && iViewOrderIdx == 0 );
+  AOT( uiViewId != 0 && !bCamParSlice && ( aaiScale == 0 || aaiOffset == 0 ) );
+#endif
+  m_uiViewId              = uiViewId;
+  m_iViewOrderIdx         = iViewOrderIdx;
+  m_bDepth                = false;
+  m_uiCamParPrecision     = ( m_uiViewId ? uiCamParPrecision : 0 );
+  m_bCamParInSliceHeader  = ( m_uiViewId ? bCamParSlice  : false );
+  ::memset( m_aaiCodedScale,  0x00, sizeof( m_aaiCodedScale  ) );
+  ::memset( m_aaiCodedOffset, 0x00, sizeof( m_aaiCodedOffset ) );
+#if !QC_MVHEVC_B0046
+  if( !m_bCamParInSliceHeader )
+  {
+    for( UInt uiBaseViewId = 0; uiBaseViewId < m_uiViewId; uiBaseViewId++ )
+    {
+      m_aaiCodedScale [ 0 ][ uiBaseViewId ] = aaiScale [ uiBaseViewId ][   m_uiViewId ];
+      m_aaiCodedScale [ 1 ][ uiBaseViewId ] = aaiScale [   m_uiViewId ][ uiBaseViewId ];
+      m_aaiCodedOffset[ 0 ][ uiBaseViewId ] = aaiOffset[ uiBaseViewId ][   m_uiViewId ];
+      m_aaiCodedOffset[ 1 ][ uiBaseViewId ] = aaiOffset[   m_uiViewId ][ uiBaseViewId ];
+    }
+  }
+#endif
+}
+
+Void
+#if FCO_FIX_SPS_CHANGE
+TComSPS::initMultiviewSPSDepth( UInt uiViewId, Int iViewOrderIdx, UInt uiCamParPrecision, Bool bCamParSlice, Int** aaiScale, Int** aaiOffset )
+#else
+TComSPS::initMultiviewSPSDepth( UInt uiViewId, Int iViewOrderIdx )
+#endif
+{
+  AOT( uiViewId == 0 && iViewOrderIdx != 0 );
+  AOT( uiViewId != 0 && iViewOrderIdx == 0 );
+
+  m_uiViewId              = uiViewId;
+  m_iViewOrderIdx         = iViewOrderIdx;
+  m_bDepth                = true;
+#if FCO_FIX_SPS_CHANGE
+  m_uiCamParPrecision     = ( m_uiViewId ? uiCamParPrecision : 0 );
+  m_bCamParInSliceHeader  = ( m_uiViewId ? bCamParSlice  : false );
+#else
+  m_uiCamParPrecision     = 0;
+  m_bCamParInSliceHeader  = false;
+#endif
+  ::memset( m_aaiCodedScale,  0x00, sizeof( m_aaiCodedScale  ) );
+  ::memset( m_aaiCodedOffset, 0x00, sizeof( m_aaiCodedOffset ) );
+#if FCO_FIX_SPS_CHANGE
+#if !QC_MVHEVC_B0046
+  if( !m_bCamParInSliceHeader )
+  {
+    for( UInt uiBaseViewId = 0; uiBaseViewId < m_uiViewId; uiBaseViewId++ )
+    {
+      m_aaiCodedScale [ 0 ][ uiBaseViewId ] = aaiScale [ uiBaseViewId ][   m_uiViewId ];
+      m_aaiCodedScale [ 1 ][ uiBaseViewId ] = aaiScale [   m_uiViewId ][ uiBaseViewId ];
+      m_aaiCodedOffset[ 0 ][ uiBaseViewId ] = aaiOffset[ uiBaseViewId ][   m_uiViewId ];
+      m_aaiCodedOffset[ 1 ][ uiBaseViewId ] = aaiOffset[   m_uiViewId ][ uiBaseViewId ];
+    }
+  }
+#endif
+#endif
+
+}
+
+#if DEPTH_MAP_GENERATION
+Void
+TComSPS::setPredDepthMapGeneration( UInt uiViewId, Bool bIsDepth, UInt uiPdmGenMode, UInt uiPdmMvPredMode, UInt uiPdmPrec, Int** aaiPdmScaleNomDelta, Int** aaiPdmOffset )
+{ 
+  AOF( m_uiViewId == uiViewId );
+  AOF( m_bDepth   == bIsDepth );
+  AOT( ( uiViewId == 0 || bIsDepth ) && uiPdmGenMode );
+  AOT( uiPdmGenMode && ( aaiPdmScaleNomDelta == 0 || aaiPdmOffset == 0 ) );
+  AOT( uiPdmMvPredMode && uiPdmGenMode == 0 );
+
+  m_uiPredDepthMapGeneration = uiPdmGenMode;
+#if H3D_IVMP
+  m_uiMultiviewMvPredMode    = uiPdmMvPredMode;
+#endif
+
+  m_uiPdmPrecision           = ( m_uiPredDepthMapGeneration ? uiPdmPrec : 0 );
+  ::memset( m_aiPdmScaleNomDelta, 0x00, sizeof( m_aiPdmScaleNomDelta  ) );
+  ::memset( m_aiPdmOffset,        0x00, sizeof( m_aiPdmOffset         ) );
+  if( m_uiPredDepthMapGeneration )
+  {
+    for( UInt uiBaseId = 0; uiBaseId < m_uiViewId; uiBaseId++ )
+    {
+      m_aiPdmScaleNomDelta[ uiBaseId ]  = aaiPdmScaleNomDelta[ m_uiViewId ][ uiBaseId ];
+      m_aiPdmOffset       [ uiBaseId ]  = aaiPdmOffset       [ m_uiViewId ][ uiBaseId ];
+    }
+  }
+}
+#endif
+
+TComReferencePictureSet::TComReferencePictureSet()
+: m_numberOfPictures (0)
+, m_numberOfNegativePictures (0)
+, m_numberOfPositivePictures (0)
+, m_numberOfLongtermPictures (0)
+, m_interRPSPrediction (0) 
+, m_deltaRIdxMinus1 (0)   
+, m_deltaRPS (0) 
+, m_numRefIdc (0) 
+{
+  ::memset( m_deltaPOC, 0, sizeof(m_deltaPOC) );
+  ::memset( m_POC, 0, sizeof(m_POC) );
+  ::memset( m_used, 0, sizeof(m_used) );
+  ::memset( m_refIdc, 0, sizeof(m_refIdc) );
+}
+
+TComReferencePictureSet::~TComReferencePictureSet()
+{
+}
+
+Void TComReferencePictureSet::setUsed(Int bufferNum, Bool used)
+{
+  m_used[bufferNum] = used;
+}
+
+Void TComReferencePictureSet::setDeltaPOC(Int bufferNum, Int deltaPOC)
+{
+  m_deltaPOC[bufferNum] = deltaPOC;
+}
+
+Void TComReferencePictureSet::setNumberOfPictures(Int numberOfPictures)
+{
+  m_numberOfPictures = numberOfPictures;
+}
+
+Int TComReferencePictureSet::getUsed(Int bufferNum)
+{
+  return m_used[bufferNum];
+}
+
+Int TComReferencePictureSet::getDeltaPOC(Int bufferNum)
+{
+  return m_deltaPOC[bufferNum];
+}
+
+Int TComReferencePictureSet::getNumberOfPictures()
+{
+  return m_numberOfPictures;
+}
+
+Int TComReferencePictureSet::getPOC(Int bufferNum)
+{
+  return m_POC[bufferNum];
+}
+Void TComReferencePictureSet::setPOC(Int bufferNum, Int POC)
+{
+  m_POC[bufferNum] = POC;
+}
+
+/** set the reference idc value at uiBufferNum entry to the value of iRefIdc
+ * \param uiBufferNum
+ * \param iRefIdc
+ * \returns Void
+ */
+Void TComReferencePictureSet::setRefIdc(Int bufferNum, Int refIdc)
+{
+  m_refIdc[bufferNum] = refIdc;
+}
+
+/** get the reference idc value at uiBufferNum
+ * \param uiBufferNum
+ * \returns Int
+ */
+Int  TComReferencePictureSet::getRefIdc(Int bufferNum)
+{
+  return m_refIdc[bufferNum];
+}
+
+/** Sorts the deltaPOC and Used by current values in the RPS based on the deltaPOC values.
+ *  deltaPOC values are sorted with -ve values before the +ve values.  -ve values are in decreasing order.
+ *  +ve values are in increasing order.
+ * \returns Void
+ */
+Void TComReferencePictureSet::sortDeltaPOC()
+{
+  // sort in increasing order (smallest first)
+  for(Int j=1; j < getNumberOfPictures(); j++)
+  { 
+    Int deltaPOC = getDeltaPOC(j);
+    Bool used = getUsed(j);
+    for (Int k=j-1; k >= 0; k--)
+    {
+      Int temp = getDeltaPOC(k);
+      if (deltaPOC < temp)
+      {
+        setDeltaPOC(k+1, temp);
+        setUsed(k+1, getUsed(k));
+        setDeltaPOC(k, deltaPOC);
+        setUsed(k, used);
+      }
+    }
+  }
+  // flip the negative values to largest first
+  Int numNegPics = getNumberOfNegativePictures();
+  for(Int j=0, k=numNegPics-1; j < numNegPics>>1; j++, k--)
+  { 
+    Int deltaPOC = getDeltaPOC(j);
+    Bool used = getUsed(j);
+    setDeltaPOC(j, getDeltaPOC(k));
+    setUsed(j, getUsed(k));
+    setDeltaPOC(k, deltaPOC);
+    setUsed(k, used);
+  }
+}
+
+/** Prints the deltaPOC and RefIdc (if available) values in the RPS.
+ *  A "*" is added to the deltaPOC value if it is Used bu current.
+ * \returns Void
+ */
+Void TComReferencePictureSet::printDeltaPOC()
+{
+  printf("DeltaPOC = { ");
+  for(Int j=0; j < getNumberOfPictures(); j++)
+  {
+    printf("%d%s ", getDeltaPOC(j), (getUsed(j)==1)?"*":"");
+  } 
+  if (getInterRPSPrediction()) 
+  {
+    printf("}, RefIdc = { ");
+    for(Int j=0; j < getNumRefIdc(); j++)
+    {
+      printf("%d ", getRefIdc(j));
+    } 
+  }
+  printf("}\n");
+}
+
+TComRPSList::TComRPSList()
+{
+}
+
+TComRPSList::~TComRPSList()
+{
+}
+
+Void TComRPSList::create( Int numberOfReferencePictureSets)
+{
+  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
+  m_referencePictureSets = new TComReferencePictureSet[numberOfReferencePictureSets];
+}
+
+Void TComRPSList::destroy()
+{
+  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)
+{
+  ::memset( m_RefPicSetIdxL0, 0, sizeof(m_RefPicSetIdxL0) );
+  ::memset( m_RefPicSetIdxL1, 0, sizeof(m_RefPicSetIdxL1) );
+}
+
+TComRefPicListModification::~TComRefPicListModification()
+{
+}
+
+TComAPS::TComAPS()
+{
+  m_apsID = 0;
+  m_bAlfEnabled = false;
+  m_bSaoEnabled = false;
+  m_pSaoParam = NULL;
+  m_alfParamSet = NULL;
+  m_scalingList = NULL;
+  m_scalingListEnabled = false;
+}
+
+TComAPS::~TComAPS()
+{
+
+}
+
+TComAPS& TComAPS::operator= (const TComAPS& src)
+{
+  m_apsID       = src.m_apsID;
+  m_loopFilterOffsetInAPS = src.m_loopFilterOffsetInAPS;
+  m_loopFilterDisable = src.m_loopFilterDisable;
+  m_loopFilterBetaOffsetDiv2 = src.m_loopFilterBetaOffsetDiv2;
+  m_loopFilterTcOffsetDiv2 = src.m_loopFilterTcOffsetDiv2;
+  m_bAlfEnabled = src.m_bAlfEnabled;
+  m_bSaoEnabled = src.m_bSaoEnabled;
+  m_pSaoParam   = src.m_pSaoParam; 
+  m_alfParamSet    = src.m_alfParamSet;
+  m_scalingList = src.m_scalingList;
+  m_scalingListEnabled = src.m_scalingListEnabled;
+  m_saoInterleavingFlag = src.m_saoInterleavingFlag;
+
+  return *this;
+}
+
+Void TComAPS::createSaoParam()
+{
+  m_pSaoParam = new SAOParam;
+}
+
+Void TComAPS::destroySaoParam()
+{
+  if(m_pSaoParam != NULL)
+  {
+    delete m_pSaoParam;
+    m_pSaoParam = NULL;
+  }
+}
+
+Void TComAPS::createAlfParam()
+{
+  m_alfParamSet = new AlfParamSet;
+}
+Void TComAPS::destroyAlfParam()
+{
+  if(m_alfParamSet != NULL)
+  {
+    delete m_alfParamSet;
+    m_alfParamSet = NULL;
+  }
+}
+
+Void TComAPS::createScalingList()
+{
+  m_scalingList = new TComScalingList;
+}
+Void TComAPS::destroyScalingList()
+{
+  delete m_scalingList;
+}
+
+TComScalingList::TComScalingList()
+{
+  init();
+}
+TComScalingList::~TComScalingList()
+{
+  destroy();
+}
+
+/** set default quantization matrix to array
+*/
+Void TComSlice::setDefaultScalingList()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
+    {
+      getScalingList()->processDefaultMarix(sizeId, listId);
+    }
+  }
+}
+/** check if use default quantization matrix
+ * \returns true if use default quantization matrix in all size
+*/
+Bool TComSlice::checkDefaultScalingList()
+{
+  UInt defaultCounter=0;
+
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
+    {
+      if(getScalingList()->getUseDefaultScalingMatrixFlag(sizeId,listId))
+      {
+        defaultCounter++;
+      }
+    }
+  }
+  return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM - 4)) ? true : false; // -4 for 32x32
+}
+/** get scaling matrix from RefMatrixID
+ * \param sizeId size index
+ * \param Index of input matrix
+ * \param Index of reference matrix
+ */
+Void TComScalingList::processRefMatrix( UInt sizeId, UInt listId , UInt refListId )
+{
+  ::memcpy(getScalingListAddress(sizeId, listId),getScalingListAddress(sizeId, refListId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+}
+/** parse syntax infomation 
+ *  \param pchFile syntax infomation
+ *  \returns false if successful
+ */
+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);
+    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)))
+          {
+            printf("Error: can't read DC :: set Default Matrix\n");
+            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);
+      }
+    }
+  }
+  fclose(fp);
+  return false;
+}
+
+/** 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 
+ * \param sizeId size index
+ * \param listId list index
+ * \returns pointer of quantization matrix
+ */
+Int* TComScalingList::getScalingListDefaultAddress(UInt sizeId, UInt listId)
+{
+  Int *src = 0;
+  switch(sizeId)
+  {
+    case SCALING_LIST_4x4:
+      src = (listId<3) ? g_quantIntraDefault4x4 : g_quantInterDefault4x4;
+      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;
+      break;
+    default:
+      assert(0);
+      src = NULL;
+      break;
+  }
+  return src;
+}
+/** process of default matrix
+ * \param sizeId size index
+ * \param Index of input matrix
+ */
+Void TComScalingList::processDefaultMarix(UInt sizeId, UInt listId)
+{
+  ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+  setUseDefaultScalingMatrixFlag(sizeId,listId,true);
+  setScalingListDC(sizeId,listId,SCALING_LIST_DC);
+}
+/** check DC value of matrix for default matrix signaling
+ */
+Void TComScalingList::checkDcOfMatrix()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      setUseDefaultScalingMatrixFlag(sizeId,listId,false);
+      //check default matrix?
+      if(getScalingListDC(sizeId,listId) == 0)
+      {
+        processDefaultMarix(sizeId, listId);
+      }
+    }
+  }
+}
+
+ParameterSetManager::ParameterSetManager()
+: m_spsMap(MAX_NUM_SPS)
+, m_ppsMap(MAX_NUM_PPS)
+, m_apsMap(MAX_NUM_APS)
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+, m_vpsMap(MAX_NUM_VPS)
+#endif
+{
+}
+
+
+ParameterSetManager::~ParameterSetManager()
+{
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSlice.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComSlice.h	(revision 341)
@@ -0,0 +1,1533 @@
+/* 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-2012, 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     TComSlice.h
+    \brief    slice header and SPS class (header)
+*/
+
+#ifndef __TCOMSLICE__
+#define __TCOMSLICE__
+
+#include <cstring>
+#include <map>
+#include <vector>
+#include "CommonDef.h"
+#include "TComRom.h"
+#include "TComList.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+class TComPic;
+class TComTrQuant;
+#if DEPTH_MAP_GENERATION
+class TComDepthMapGenerator;
+#endif
+#if H3D_IVRP
+class TComResidualGenerator;
+#endif
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+/// max number of supported APS in software
+#define MAX_NUM_SUPPORTED_APS 1
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Reference Picture Set class
+class TComReferencePictureSet
+{
+private:
+  Int  m_numberOfPictures;
+  Int  m_numberOfNegativePictures;
+  Int  m_numberOfPositivePictures;
+  Int  m_numberOfLongtermPictures;
+  Int  m_deltaPOC[MAX_NUM_REF_PICS];
+  Int  m_POC[MAX_NUM_REF_PICS];
+  Bool m_used[MAX_NUM_REF_PICS];
+  Bool m_interRPSPrediction;
+  Int  m_deltaRIdxMinus1;   
+  Int  m_deltaRPS; 
+  Int  m_numRefIdc; 
+  Int  m_refIdc[MAX_NUM_REF_PICS+1];
+
+public:
+  TComReferencePictureSet();
+  virtual ~TComReferencePictureSet();
+
+  Void setNumberOfPictures(Int numberOfPictures);
+  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 setDeltaPOC(Int bufferNum, Int deltaPOC);
+  Int  getDeltaPOC(Int bufferNum);
+  Void setPOC(Int bufferNum, Int deltaPOC);
+  Int  getPOC(Int bufferNum);
+
+  Void setUsed(Int bufferNum, Bool used);
+  Int  getUsed(Int bufferNum);
+
+  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();
+};
+
+/// Reference Picture Set set class
+class TComRPSList
+{
+private:
+  Int  m_numberOfReferencePictureSets;
+  TComReferencePictureSet* m_referencePictureSets;
+  
+public:
+  TComRPSList();
+  virtual ~TComRPSList();
+  
+  Void  create  (Int numberOfEntries);
+  Void  destroy ();
+
+
+  TComReferencePictureSet* getReferencePictureSet(Int referencePictureSetNum);
+  Int getNumberOfReferencePictureSets();
+  Void setNumberOfReferencePictureSets(Int numberOfReferencePictureSets);
+};
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+/// VPS class
+
+class TComVPS
+{
+private:
+  Int         m_VPSId;
+  UInt        m_uiMaxTLayers;
+  UInt        m_uiMaxLayers;
+  Bool        m_bTemporalIdNestingFlag;
+
+  UInt        m_uiExtensionType;
+#if !QC_MVHEVC_B0046  
+  Bool        m_bDependentFlag[MAX_LAYER_NUM];
+#else
+  UInt        m_uiNumHRDParameter;
+  UInt        m_numAddiLayerOperationPoints;
+  UInt        m_numAddiProLevelSets;
+  UInt        m_numDirectRefLayer[MAX_LAYER_NUM];
+  UInt        m_numDirectRefID[MAX_LAYER_NUM][MAX_LAYER_NUM];
+  UInt        m_numOpLayerIdMinus1[MAX_LAYER_NUM];
+  UInt        m_numOpLayerId[MAX_LAYER_NUM][MAX_LAYER_NUM];
+#endif
+  UInt        m_uiViewId[MAX_LAYER_NUM];
+#if !QC_MVHEVC_B0046  
+  Bool        m_bDepthFlag[MAX_LAYER_NUM];
+#endif
+  Int         m_iViewOrderIdx[MAX_LAYER_NUM];
+#if !QC_MVHEVC_B0046  
+  UInt        m_uiDependentLayer[MAX_LAYER_NUM];
+#endif
+
+  UInt        m_numReorderPics[MAX_TLAYER];
+  UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
+  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Bool          m_bIVScalingFlag;
+#endif
+public:
+  TComVPS();
+  virtual ~TComVPS();
+  
+  Int     getVPSId       ()                   { return m_VPSId;          }
+  Void    setVPSId       (Int i)              { m_VPSId = i;             }
+  
+  UInt    getMaxTLayers  ()                   { return m_uiMaxTLayers;   }
+  Void    setMaxTLayers  (UInt t)             { m_uiMaxTLayers = t; }
+    
+  UInt    getMaxLayers   ()                   { return m_uiMaxLayers;   }
+  Void    setMaxLayers   (UInt l)             { m_uiMaxLayers = l; }
+  
+  Bool    getTemporalNestingFlag   ()         { return m_uiMaxLayers;   }
+  Void    setTemporalNestingFlag   (UInt t)   { m_bTemporalIdNestingFlag = t; }
+#if !QC_MVHEVC_B0046
+  Void    setExtensionType(UInt v)                     { m_uiExtensionType = v;    }
+  UInt    getExtensionType()                             { return m_uiExtensionType; }
+  
+  Void    setDependentFlag(Bool d, UInt layer)              { m_bDependentFlag[layer] = d;    }
+  Bool    getDependentFlag(UInt layer)                      { return m_bDependentFlag[layer]; }
+#endif
+  Void    setViewId(UInt v, UInt layer)                     { m_uiViewId[layer] = v;    }
+  UInt    getViewId(UInt layer)                             { return m_uiViewId[layer]; }
+#if !QC_MVHEVC_B0046 
+  Void    setDepthFlag(Bool d, UInt layer)                  { m_bDepthFlag[layer] = d;    }
+  Bool    getDepthFlag(UInt layer)                          { return m_bDepthFlag[layer]; }
+#endif
+  Void    setViewOrderIdx(Int v, UInt layer)                { m_iViewOrderIdx[layer] = v;    }
+  Int     getViewOrderIdx(UInt layer)                       { return m_iViewOrderIdx[layer]; }
+#if !QC_MVHEVC_B0046   
+  Void    setDependentLayer(UInt v, UInt layer)                     { m_uiDependentLayer[layer] = v;    }
+  UInt    getDependentLayer(UInt layer)                             { return m_uiDependentLayer[layer]; }
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Bool getIVScalingFlag( )                                   { return m_bIVScalingFlag; }
+  Void setIVScalingFlag(Bool b)                              { m_bIVScalingFlag = b;    }
+#endif
+  Void    setNumReorderPics(UInt v, UInt tLayer)                { m_numReorderPics[tLayer] = v;    }
+  UInt    getNumReorderPics(UInt tLayer)                        { return m_numReorderPics[tLayer]; }
+  
+  Void    setMaxDecPicBuffering(UInt v, UInt 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]; }
+#if QC_MVHEVC_B0046
+  Void    setNumHRDParameters(UInt n)                                { m_uiNumHRDParameter = n;    }
+  UInt    getNumHRDParameters()                                      { return m_uiNumHRDParameter; }
+  Void    setNumDirectRefLayer(UInt n, UInt layer)                   { m_numDirectRefLayer[layer] = n;        };
+  UInt    getNumDirectRefLayer(UInt layer)                           { return m_numDirectRefLayer[layer];     };
+  Void    setDirectRefLayerId (UInt n, UInt layer, UInt refId)       { m_numDirectRefID[layer][refId] = n;   assert(refId < MAX_NUM_REF ); };
+  UInt    getDirectRefLayerId (        UInt layer, UInt refId)       { return m_numDirectRefID[layer][refId]; };
+  UInt    getNumAddiLayerOperationPoints(      )               { return m_numAddiLayerOperationPoints;  };
+  Void    setNumAddiLayerOperationPoints(UInt n)                {  m_numAddiLayerOperationPoints = n;  };
+  Void    setNumAddiProLevelSets        (UInt n)                     {  m_numAddiProLevelSets = n;}
+  UInt    getNumAddiProLevelSets        (      )                     { return m_numAddiProLevelSets;}
+
+  Void    setNumOpLayerIdMinus1         (UInt n, UInt layer)                     {  m_numOpLayerIdMinus1[layer] = n;}
+  UInt    getNumOpLayerIdMinus1         (UInt layer      )                       { return m_numOpLayerIdMinus1[layer];}
+
+  Void    setNumOpLayerId               (UInt n, UInt layer, UInt OpId)                     {  m_numOpLayerId[layer][OpId] = n;}
+  UInt    getNumOpLayerId               (UInt layer, UInt OpId        )                     { return m_numOpLayerId[layer][OpId];}
+  
+#endif 
+};
+
+#endif
+
+/// SPS class
+class TComSPS
+{
+private:
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Int          m_VPSId;
+#endif
+  Int         m_SPSId;
+  Int         m_ProfileIdc;
+  Int         m_LevelIdc;
+  Int         m_chromaFormatIdc;
+
+  UInt        m_uiMaxTLayers;           // maximum number of temporal layers
+
+  UInt        m_uiViewId;
+  Int         m_iViewOrderIdx;
+  Bool        m_bDepth;
+  UInt        m_uiCamParPrecision;
+  Bool        m_bCamParInSliceHeader;
+  Int         m_aaiCodedScale [2][MAX_VIEW_NUM];
+  Int         m_aaiCodedOffset[2][MAX_VIEW_NUM];
+
+  // Structure
+  UInt        m_picWidthInLumaSamples;
+  UInt        m_picHeightInLumaSamples;
+  Bool        m_picCroppingFlag;
+  Int         m_picCropLeftOffset;
+  Int         m_picCropRightOffset;
+  Int         m_picCropTopOffset;
+  Int         m_picCropBottomOffset;
+  UInt        m_uiMaxCUWidth;
+  UInt        m_uiMaxCUHeight;
+  UInt        m_uiMaxCUDepth;
+  UInt        m_uiMinTrDepth;
+  UInt        m_uiMaxTrDepth;
+  TComRPSList* m_RPSList;
+  Bool        m_bLongTermRefsPresent;
+  Int         m_numReorderPics[MAX_TLAYER];
+  
+  Int         m_iNumberOfUsableInterViewRefs;
+  Int         m_aiUsableInterViewRefs[MAX_VIEW_NUM];
+
+  // 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_bDisInter4x4;
+  Bool        m_useAMP;
+  Bool        m_bUseALF;
+  Bool        m_bALFCoefInSlice;
+  Bool        m_bUseLMChroma; // JL:
+
+  Bool        m_bUseLComb;
+  Bool        m_bLCMod;
+  Bool        m_useNSQT;
+  
+  Bool        m_restrictedRefPicListsFlag;
+  Bool        m_listsModificationPresentFlag;
+
+  // Parameter
+  AMVP_MODE   m_aeAMVPMode[MAX_CU_DEPTH];
+  UInt        m_uiBitDepth;
+  UInt        m_uiBitIncrement;
+  Int         m_qpBDOffsetY;
+  Int         m_qpBDOffsetC;
+
+#if LOSSLESS_CODING
+  Bool        m_useLossless;
+#endif
+
+  UInt        m_uiPCMBitDepthLuma;
+  UInt        m_uiPCMBitDepthChroma;
+  Bool        m_bPCMFilterDisableFlag;
+
+  UInt        m_uiBitsForPOC;
+  // Max physical transform size
+  UInt        m_uiMaxTrSize;
+  
+  Int m_iAMPAcc[MAX_CU_DEPTH];
+
+  Bool        m_bLFCrossSliceBoundaryFlag;
+  Bool        m_bUseSAO; 
+#if HHI_MPI
+  Bool        m_bUseMVI;
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  Bool        m_bUseDLT;
+  
+  UInt        m_uiBitsPerDepthValue;
+  UInt        m_uiNumDepthmapValues;
+  UInt*       m_uiDepthValue2Idx;
+  UInt*       m_uiIdx2DepthValue;
+#endif
+
+  Bool     m_bLFCrossTileBoundaryFlag;
+  Int      m_iUniformSpacingIdr;
+  Int      m_iTileBoundaryIndependenceIdr;
+  Int      m_iNumColumnsMinus1;
+  UInt*    m_puiColumnWidth;
+  Int      m_iNumRowsMinus1;
+  UInt*    m_puiRowHeight;
+  
+  Bool        m_bTemporalIdNestingFlag; // temporal_id_nesting_flag
+
+  Bool        m_scalingListEnabledFlag;
+  UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
+  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];
+
+  Bool        m_useDF;
+
+  UInt        m_tilesOrEntropyCodingSyncIdc;
+  Int         m_numSubstreams;
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool  m_bUseDMM;
+#endif
+
+#if HHI_DMM_PRED_TEX && FLEX_CODING_ORDER_M23723
+  Bool  m_bUseDMM34;
+#endif
+
+#if H3D_QTL
+  Bool m_bUseQTLPC;
+#endif
+
+#if DEPTH_MAP_GENERATION
+  UInt  m_uiPredDepthMapGeneration;
+  UInt  m_uiPdmPrecision;
+  Int   m_aiPdmScaleNomDelta[MAX_VIEW_NUM];
+  Int   m_aiPdmOffset       [MAX_VIEW_NUM];
+#endif
+
+#if H3D_IVMP
+  UInt  m_uiMultiviewMvPredMode;
+#endif
+#if H3D_IVRP
+  UInt  m_uiMultiviewResPredMode;
+#endif
+
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator* m_pcDepthMapGenerator;
+#endif
+#if H3D_IVRP
+  TComResidualGenerator* m_pcResidualGenerator;
+#endif
+
+public:
+  TComSPS();
+  virtual ~TComSPS();
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Int  getVPSId       ()         { return m_VPSId;          }
+  Void setVPSId       (Int i)    { m_VPSId = i;             }
+#endif
+  Int  getSPSId       ()         { return m_SPSId;          }
+  Void setSPSId       (Int i)    { m_SPSId = i;             }
+  Int  getProfileIdc  ()         { return m_ProfileIdc;     }
+  Void setProfileIdc  (Int i)    { m_ProfileIdc = i;        }
+  Int  getLevelIdc    ()         { return m_LevelIdc;       }
+  Void setLevelIdc    (Int i)    { m_LevelIdc = i;          }
+
+  Int  getChromaFormatIdc ()         { return m_chromaFormatIdc;       }
+  Void setChromaFormatIdc (Int i)    { m_chromaFormatIdc = i;          }
+  
+  // 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;   }
+
+  Bool getPicCroppingFlag() const          { return m_picCroppingFlag; }
+  Void setPicCroppingFlag(Bool val)        { m_picCroppingFlag = val; }
+  Int  getPicCropLeftOffset() const        { return m_picCropLeftOffset; }
+  Void setPicCropLeftOffset(Int val)       { m_picCropLeftOffset = val; }
+  Int  getPicCropRightOffset() const       { return m_picCropRightOffset; }
+  Void setPicCropRightOffset(Int val)      { m_picCropRightOffset = val; }
+  Int  getPicCropTopOffset() const         { return m_picCropTopOffset; }
+  Void setPicCropTopOffset(Int val)        { m_picCropTopOffset = val; }
+  Int  getPicCropBottomOffset() const      { return m_picCropBottomOffset; }
+  Void setPicCropBottomOffset(Int val)     { m_picCropBottomOffset = 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 getDisInter4x4()         { return m_bDisInter4x4;        }
+  Void setDisInter4x4      ( Bool b ) { m_bDisInter4x4  = b;          }
+  Bool getUseAMP() { return m_useAMP; }
+  Void setUseAMP( Bool b ) { m_useAMP = b; }
+  Void setMinTrDepth  ( UInt u ) { m_uiMinTrDepth = u;      }
+  UInt getMinTrDepth  ()         { return  m_uiMinTrDepth;  }
+  Void setMaxTrDepth  ( UInt u ) { m_uiMaxTrDepth = u;      }
+  UInt getMaxTrDepth  ()         { return  m_uiMaxTrDepth;  }
+  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      setRPSList( TComRPSList* RPSList )   { m_RPSList = RPSList;       }
+  TComRPSList* getRPSList()                      { return m_RPSList;          }
+  Bool      getLongTermRefsPresent()         { return m_bLongTermRefsPresent; }
+  Void      setLongTermRefsPresent(Bool b)   { m_bLongTermRefsPresent=b;      }
+
+  Void setNumberOfUsableInterViewRefs( Int number )      { m_iNumberOfUsableInterViewRefs = number;    }
+  Int  getNumberOfUsableInterViewRefs()                  { return m_iNumberOfUsableInterViewRefs;      }
+  Void setUsableInterViewRef( Int pos, Int deltaViewId ) { m_aiUsableInterViewRefs[pos] = deltaViewId; }
+  Int  getUsableInterViewRef( Int pos )                  { return m_aiUsableInterViewRefs[pos];        }
+
+  
+  // physical transform
+  Void setMaxTrSize   ( UInt u ) { m_uiMaxTrSize = u;       }
+  UInt getMaxTrSize   ()         { return  m_uiMaxTrSize;   }
+  
+  // Tool list
+  Bool getUseALF      ()         { return m_bUseALF;        }
+  Void setUseALFCoefInSlice(Bool b) {m_bALFCoefInSlice = b;}
+  Bool getUseALFCoefInSlice()    {return m_bALFCoefInSlice;}
+
+  Void setUseALF      ( Bool b ) { m_bUseALF  = b;          }
+  Void setUseLComb    (Bool b)   { m_bUseLComb = b;         }
+  Bool getUseLComb    ()         { return m_bUseLComb;      }
+  Void setLCMod       (Bool b)   { m_bLCMod = b;     }
+  Bool getLCMod       ()         { return m_bLCMod;  }
+
+  Bool getUseLMChroma ()         { return m_bUseLMChroma;        }
+  Void setUseLMChroma ( Bool b ) { m_bUseLMChroma  = b;          }
+
+#if LOSSLESS_CODING
+  Bool getUseLossless ()         { return m_useLossless; }
+  Void setUseLossless ( Bool b ) { m_useLossless  = b; }
+#endif
+  Bool getUseNSQT() { return m_useNSQT; }
+  Void setUseNSQT( Bool b ) { m_useNSQT = b; }
+  
+  Bool getRestrictedRefPicListsFlag    ()          { return m_restrictedRefPicListsFlag;   }
+  Void setRestrictedRefPicListsFlag    ( Bool b )  { m_restrictedRefPicListsFlag = b;      }
+  Bool getListsModificationPresentFlag ()          { return m_listsModificationPresentFlag; }
+  Void setListsModificationPresentFlag ( Bool b )  { m_listsModificationPresentFlag = b;    }
+
+  // AMVP mode (for each depth)
+  AMVP_MODE getAMVPMode ( UInt uiDepth ) { assert(uiDepth < g_uiMaxCUDepth);  return m_aeAMVPMode[uiDepth]; }
+  Void      setAMVPMode ( UInt uiDepth, AMVP_MODE eMode) { assert(uiDepth < g_uiMaxCUDepth);  m_aeAMVPMode[uiDepth] = eMode; }
+  
+  // 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
+  UInt      getBitDepth     ()         { return m_uiBitDepth;     }
+  Void      setBitDepth     ( UInt u ) { m_uiBitDepth = u;        }
+  UInt      getBitIncrement ()         { return m_uiBitIncrement; }
+  Void      setBitIncrement ( UInt u ) { m_uiBitIncrement = 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      setLFCrossSliceBoundaryFlag     ( Bool   bValue  )    { m_bLFCrossSliceBoundaryFlag = bValue; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                    { return m_bLFCrossSliceBoundaryFlag;   } 
+
+  Void setUseDF                   ( Bool b ) { m_useDF = b; }
+  Bool getUseDF                   ()         { return m_useDF; }
+
+  Void setUseSAO                  (Bool bVal)  {m_bUseSAO = bVal;}
+  Bool getUseSAO                  ()           {return m_bUseSAO;}
+
+#if HHI_MPI
+  Void setUseMVI                  (Bool bVal)  {m_bUseMVI = bVal;}
+  Bool getUseMVI                  ()           {return m_bUseMVI;}
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  Bool getUseDLT      ()          { return m_bUseDLT; }
+  Void setUseDLT      ( Bool b ) { m_bUseDLT  = b;          }
+  
+  UInt getBitsPerDepthValue()       { return m_bUseDLT?m_uiBitsPerDepthValue:g_uiBitDepth; }
+  UInt getNumDepthValues()          { return m_bUseDLT?m_uiNumDepthmapValues:g_uiIBDI_MAX; }
+  UInt depthValue2idx(Pel uiValue)  { return m_bUseDLT?m_uiDepthValue2Idx[uiValue]:uiValue; }
+  Pel  idx2DepthValue(UInt uiIdx)   { return m_bUseDLT?m_uiIdx2DepthValue[uiIdx]:uiIdx; }
+  Void setDepthLUTs   (UInt* uidx2DepthValue = NULL, UInt uiNumDepthValues = 0);
+#endif
+
+  UInt      getMaxTLayers()                           { return m_uiMaxTLayers; }
+  Void      setMaxTLayers( UInt uiMaxTLayers )        { assert( uiMaxTLayers <= MAX_TLAYER ); m_uiMaxTLayers = uiMaxTLayers; }
+
+  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;   } 
+
+  Void    setLFCrossTileBoundaryFlag               ( Bool   bValue  )    { m_bLFCrossTileBoundaryFlag = bValue; }
+  Bool    getLFCrossTileBoundaryFlag               ()                    { return m_bLFCrossTileBoundaryFlag;   }
+  Void     setUniformSpacingIdr             ( Int i )           { m_iUniformSpacingIdr = i; }
+  Int      getUniformSpacingIdr             ()                  { return m_iUniformSpacingIdr; }
+  Void     setNumColumnsMinus1              ( Int i )           { m_iNumColumnsMinus1 = i; }
+  Int      getNumColumnsMinus1              ()                  { return m_iNumColumnsMinus1; }
+  Void     setColumnWidth ( UInt* columnWidth )
+  {
+    if( m_iUniformSpacingIdr == 0 && m_iNumColumnsMinus1 > 0 )
+    {
+      m_puiColumnWidth = new UInt[ m_iNumColumnsMinus1 ];
+
+      for(Int i=0; i<m_iNumColumnsMinus1; i++)
+      {
+        m_puiColumnWidth[i] = columnWidth[i];
+     }
+    }
+  }
+  UInt     getColumnWidth  (UInt columnIdx) { return *( m_puiColumnWidth + columnIdx ); }
+  Void     setNumRowsMinus1( Int i )        { m_iNumRowsMinus1 = i; }
+  Int      getNumRowsMinus1()               { return m_iNumRowsMinus1; }
+  Void     setRowHeight    ( UInt* rowHeight )
+  {
+    if( m_iUniformSpacingIdr == 0 && m_iNumRowsMinus1 > 0 )
+    {
+      m_puiRowHeight = new UInt[ m_iNumRowsMinus1 ];
+
+      for(Int i=0; i<m_iNumRowsMinus1; i++)
+      {
+        m_puiRowHeight[i] = rowHeight[i];
+      }
+    }
+  }
+  UInt     getRowHeight           (UInt rowIdx)    { return *( m_puiRowHeight + rowIdx ); }
+  Bool getScalingListFlag       ()         { return m_scalingListEnabledFlag;     }
+  Void setScalingListFlag       ( Bool b ) { m_scalingListEnabledFlag  = b;       }
+  UInt getMaxDecPicBuffering  (UInt tlayer)            { return m_uiMaxDecPicBuffering[tlayer]; }
+  Void setMaxDecPicBuffering  ( UInt ui, UInt tlayer ) { m_uiMaxDecPicBuffering[tlayer] = ui;   }
+  UInt getMaxLatencyIncrease  (UInt tlayer)            { return m_uiMaxLatencyIncrease[tlayer];   }
+  Void setMaxLatencyIncrease  ( UInt ui , UInt tlayer) { m_uiMaxLatencyIncrease[tlayer] = ui;      }
+  UInt getTilesOrEntropyCodingSyncIdc ()                    { return m_tilesOrEntropyCodingSyncIdc;   }
+  Void setTilesOrEntropyCodingSyncIdc ( UInt val )          { m_tilesOrEntropyCodingSyncIdc = val;    }
+  Int  getNumSubstreams               ()                    { return m_numSubstreams;                 }
+  Void setNumSubstreams               ( Int numSubstreams ) { m_numSubstreams = numSubstreams;        }
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool getUseDMM()         { return m_bUseDMM; }
+  Void setUseDMM( Bool b ) { m_bUseDMM = b;    }
+#endif
+
+#if HHI_DMM_PRED_TEX && FLEX_CODING_ORDER_M23723
+  Bool getUseDMM34()         { return m_bUseDMM34; }
+  Void setUseDMM34( Bool b ) { m_bUseDMM34 = b;    }
+#endif
+
+#if H3D_QTL
+  Void setUseQTLPC( Bool b ) { m_bUseQTLPC = b;    }
+  Bool getUseQTLPC()         { return m_bUseQTLPC; }
+#endif
+
+  Void initMultiviewSPS      ( UInt uiViewId, Int iViewOrderIdx = 0, UInt uiCamParPrecision = 0, Bool bCamParSlice = false, Int** aaiScale = 0, Int** aaiOffset = 0 );
+#if FCO_FIX_SPS_CHANGE
+  Void initMultiviewSPSDepth ( UInt uiViewId, Int iViewOrderIdx, UInt uiCamParPrecision = 0, Bool bCamParSlice = false, Int** aaiScale = 0, Int** aaiOffset = 0 );
+#else
+  Void initMultiviewSPSDepth ( UInt uiViewId, Int iViewOrderIdx );
+#endif
+
+  UInt getViewId             ()  { return m_uiViewId; }
+  Int  getViewOrderIdx       ()  { return m_iViewOrderIdx; }
+  Bool isDepth               ()  { return m_bDepth; }
+  UInt getCamParPrecision    ()  { return m_uiCamParPrecision; }
+  Bool hasCamParInSliceHeader()  { return m_bCamParInSliceHeader; }
+  Int* getCodedScale         ()  { return m_aaiCodedScale [0]; }
+  Int* getCodedOffset        ()  { return m_aaiCodedOffset[0]; }
+  Int* getInvCodedScale      ()  { return m_aaiCodedScale [1]; }
+  Int* getInvCodedOffset     ()  { return m_aaiCodedOffset[1]; }
+
+
+#if DEPTH_MAP_GENERATION
+  Void setPredDepthMapGeneration( UInt uiViewId, Bool bIsDepth, UInt uiPdmGenMode = 0, UInt uiPdmMvPredMode = 0, UInt uiPdmPrec = 0, Int** aaiPdmScaleNomDelta = 0, Int** aaiPdmOffset = 0 );
+#endif
+#if H3D_IVRP
+  Void  setMultiviewResPredMode  ( UInt uiResPrdMode ) { m_uiMultiviewResPredMode = uiResPrdMode; }
+#endif
+
+#if DEPTH_MAP_GENERATION
+  UInt getPredDepthMapGeneration()          { return m_uiPredDepthMapGeneration; }
+  UInt getPdmPrecision          ()          { return m_uiPdmPrecision;           }
+  Int* getPdmScaleNomDelta      ()          { return m_aiPdmScaleNomDelta;       }
+  Int* getPdmOffset             ()          { return m_aiPdmOffset;              }
+#endif
+
+#if H3D_IVMP
+  UInt  getMultiviewMvPredMode   ()          { return m_uiMultiviewMvPredMode;    }
+#endif
+#if H3D_IVRP
+  UInt  getMultiviewResPredMode  ()          { return m_uiMultiviewResPredMode;   }
+#endif
+
+#if DEPTH_MAP_GENERATION
+  Void                    setDepthMapGenerator( TComDepthMapGenerator* pcDepthMapGenerator )  { m_pcDepthMapGenerator = pcDepthMapGenerator; }
+  TComDepthMapGenerator*  getDepthMapGenerator()                                              { return m_pcDepthMapGenerator; }
+#endif
+#if H3D_IVRP
+  Void                    setResidualGenerator( TComResidualGenerator* pcResidualGenerator )  { m_pcResidualGenerator = pcResidualGenerator; }
+  TComResidualGenerator*  getResidualGenerator()                                              { return m_pcResidualGenerator; }
+#endif
+};
+
+
+/// Reference Picture Lists class
+class TComRefPicListModification
+{
+private:
+  UInt      m_bRefPicListModificationFlagL0;  
+  UInt      m_bRefPicListModificationFlagL1;  
+  UInt      m_RefPicSetIdxL0[32];
+  UInt      m_RefPicSetIdxL1[32];
+    
+public:
+  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]; }
+};
+
+/// PPS class
+class TComPPS
+{
+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
+ 
+  // access channel
+  TComSPS*    m_pcSPS;
+  UInt        m_uiMaxCuDQPDepth;
+  UInt        m_uiMinCuDQPSize;
+
+  Int        m_iChromaQpOffset;
+  Int        m_iChromaQpOffset2nd;
+
+
+
+  Int         m_iSliceGranularity;
+
+  Bool        m_bUseWeightPred;           // Use of Weighting Prediction (P_SLICE)
+  UInt        m_uiBiPredIdc;              // Use of Weighting Bi-Prediction (B_SLICE)
+
+  Bool        m_OutputFlagPresentFlag;   // Indicates the presence of output_flag in slice header
+
+  Int      m_iTileBehaviorControlPresentFlag;
+  Bool     m_bLFCrossTileBoundaryFlag;
+  Int      m_iColumnRowInfoPresent;
+  Int      m_iUniformSpacingIdr;
+  Int      m_iNumColumnsMinus1;
+  UInt*    m_puiColumnWidth;
+  Int      m_iNumRowsMinus1;
+  UInt*    m_puiRowHeight;
+  
+  Int      m_iEntropyCodingMode; // !!! in PPS now, but also remains in slice header!
+  Int      m_iNumSubstreams;
+
+  Bool     m_enableTMVPFlag;
+
+  Int      m_signHideFlag;
+  Int      m_signHidingThreshold;
+
+#if CABAC_INIT_FLAG
+  Bool     m_cabacInitPresentFlag;
+  UInt     m_encCABACTableIdx;           // Used to transmit table selection across slices
+#if FIX_POZNAN_CABAC_INIT_FLAG
+  UInt     m_encPrevPOC;
+#endif
+#endif
+  Bool     m_DeblockingFilterControlPresent;
+  UInt m_log2ParallelMergeLevelMinus2;
+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       getSliceGranularity()        { return m_iSliceGranularity; }
+  Void      setSliceGranularity( Int i ) { m_iSliceGranularity = 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;     }
+
+
+  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; }
+
+  Void      setChromaQpOffset   ( Int i ) { m_iChromaQpOffset = i; }
+  Int       getChromaQpOffset   () { return m_iChromaQpOffset;}
+  Void      setChromaQpOffset2nd( Int i ) { m_iChromaQpOffset2nd = i; }
+  Int       getChromaQpOffset2nd() { return m_iChromaQpOffset2nd;}
+
+  Bool getUseWP                     ()          { return m_bUseWeightPred;  }
+  UInt getWPBiPredIdc               ()          { return m_uiBiPredIdc;     }
+
+  Void setUseWP                     ( Bool b )  { m_bUseWeightPred = b;     }
+  Void setWPBiPredIdc               ( UInt u )  { m_uiBiPredIdc = u;        }
+
+  Void      setOutputFlagPresentFlag( Bool b )  { m_OutputFlagPresentFlag = b;    }
+  Bool      getOutputFlagPresentFlag()          { return m_OutputFlagPresentFlag; }
+
+  Void    setTileBehaviorControlPresentFlag        ( Int i )             { m_iTileBehaviorControlPresentFlag = i;    }
+  Int     getTileBehaviorControlPresentFlag        ()                    { return m_iTileBehaviorControlPresentFlag; }
+  Void    setLFCrossTileBoundaryFlag               ( Bool   bValue  )    { m_bLFCrossTileBoundaryFlag = bValue; }
+  Bool    getLFCrossTileBoundaryFlag               ()                    { return m_bLFCrossTileBoundaryFlag;   }
+  Void     setColumnRowInfoPresent          ( Int i )           { m_iColumnRowInfoPresent = i; }
+  Int      getColumnRowInfoPresent          ()                  { return m_iColumnRowInfoPresent; }
+  Void     setUniformSpacingIdr             ( Int i )           { m_iUniformSpacingIdr = i; }
+  Int      getUniformSpacingIdr             ()                  { return m_iUniformSpacingIdr; }
+  Void     setNumColumnsMinus1              ( Int i )           { m_iNumColumnsMinus1 = i; }
+  Int      getNumColumnsMinus1              ()                  { return m_iNumColumnsMinus1; }
+  Void     setColumnWidth ( UInt* columnWidth )
+  {
+    if( m_iUniformSpacingIdr == 0 && m_iNumColumnsMinus1 > 0 )
+    {
+      m_puiColumnWidth = new UInt[ m_iNumColumnsMinus1 ];
+
+      for(Int i=0; i<m_iNumColumnsMinus1; i++)
+      {
+        m_puiColumnWidth[i] = columnWidth[i];
+      }
+    }
+  }
+  UInt     getColumnWidth  (UInt columnIdx) { return *( m_puiColumnWidth + columnIdx ); }
+  Void     setNumRowsMinus1( Int i )        { m_iNumRowsMinus1 = i; }
+  Int      getNumRowsMinus1()               { return m_iNumRowsMinus1; }
+  Void     setRowHeight    ( UInt* rowHeight )
+  {
+    if( m_iUniformSpacingIdr == 0 && m_iNumRowsMinus1 > 0 )
+    {
+      m_puiRowHeight = new UInt[ m_iNumRowsMinus1 ];
+
+      for(Int i=0; i<m_iNumRowsMinus1; i++)
+      {
+        m_puiRowHeight[i] = rowHeight[i];
+      }
+    }
+  }
+  UInt     getRowHeight           (UInt rowIdx)    { return *( m_puiRowHeight + rowIdx ); }
+  Void     setEntropyCodingMode(Int iEntropyCodingMode)       { m_iEntropyCodingMode = iEntropyCodingMode; }
+  Int      getEntropyCodingMode()                             { return m_iEntropyCodingMode; }
+  Void     setNumSubstreams(Int iNumSubstreams)               { m_iNumSubstreams = iNumSubstreams; }
+  Int      getNumSubstreams()                                 { return m_iNumSubstreams; }
+
+  Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
+  Void      setTSIG( Int tsig )                 { m_signHidingThreshold = tsig; }
+  Int       getSignHideFlag()                    { return m_signHideFlag; }
+  Int       getTSIG()                            { return m_signHidingThreshold; }
+
+  Void     setEnableTMVPFlag( Bool b )  { m_enableTMVPFlag = b;    }
+  Bool     getEnableTMVPFlag()          { return m_enableTMVPFlag; }
+
+#if CABAC_INIT_FLAG
+  Void     setCabacInitPresentFlag( Bool flag )     { m_cabacInitPresentFlag = flag;    }
+  Void     setEncCABACTableIdx( Int idx )           { m_encCABACTableIdx = idx;         }
+  Bool     getCabacInitPresentFlag()                { return m_cabacInitPresentFlag;    }
+  UInt     getEncCABACTableIdx()                    { return m_encCABACTableIdx;        }
+#if FIX_POZNAN_CABAC_INIT_FLAG
+  Void     setEncPrevPOC(UInt uiPOC)                { m_encPrevPOC = uiPOC;             }
+  UInt     getEncPrevPOC()                          { return m_encPrevPOC;              }
+#endif
+#endif
+  Void setDeblockingFilterControlPresent    ( Bool bValue )       { m_DeblockingFilterControlPresent = bValue; }
+  Bool getDeblockingFilterControlPresent    ()                    { return m_DeblockingFilterControlPresent; }
+  UInt getLog2ParallelMergeLevelMinus2      ()                    { return m_log2ParallelMergeLevelMinus2; }
+  Void setLog2ParallelMergeLevelMinus2      (UInt mrgLevel)       { m_log2ParallelMergeLevelMinus2 = mrgLevel; }
+};
+
+/// SCALING_LIST class
+class TComScalingList
+{
+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     processDefaultMarix            (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     setUseDefaultScalingMatrixFlag (UInt sizeId, UInt listId, Bool b)   { m_useDefaultScalingMatrixFlag[sizeId][listId] = b;    } //!< set default matrix enabled/disabled in each matrix
+  Bool     getUseDefaultScalingMatrixFlag (UInt sizeId, UInt listId)           { return m_useDefaultScalingMatrixFlag[sizeId][listId]; } //!< get default matrix enabled/disabled in each matrix
+  Void     processRefMatrix               (UInt sizeId, UInt listId , UInt refListId );
+  Bool     xParseScalingList              (char* pchFile);
+
+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
+};
+
+/// APS class
+class TComAPS
+{
+public:
+  TComAPS();
+  virtual ~TComAPS();
+
+  Void      setAPSID      (Int iID)   {m_apsID = iID;            }  //!< set APS ID 
+  Int       getAPSID      ()          {return m_apsID;           }  //!< get APS ID
+  Void      setSaoEnabled (Bool bVal) {m_bSaoEnabled = bVal;     }  //!< set SAO enabled/disabled in APS
+  Bool      getSaoEnabled ()          {return m_bSaoEnabled;     }  //!< get SAO enabled/disabled in APS
+  Void      setAlfEnabled (Bool bVal) {m_bAlfEnabled = bVal;     }  //!< set ALF enabled/disabled in APS
+  Bool      getAlfEnabled ()          {return m_bAlfEnabled;     }  //!< get ALF enabled/disabled in APS
+
+  AlfParamSet* getAlfParam   ()          {return m_alfParamSet;}
+  SAOParam* getSaoParam   ()          {return m_pSaoParam;       }  //!< get SAO parameters in APS
+
+  Void      createSaoParam();   //!< create SAO parameter object
+  Void      destroySaoParam();  //!< destroy SAO parameter object
+
+  Void      createAlfParam();   //!< create ALF parameter object
+  Void      destroyAlfParam();  //!< destroy ALF parameter object
+
+  Void      setLoopFilterOffsetInAPS(Bool val)  {m_loopFilterOffsetInAPS = val; }      //!< set offset for deblocking filter enabled/disabled in APS
+  Bool      getLoopFilterOffsetInAPS()          {return m_loopFilterOffsetInAPS; }     //!< get offset for deblocking filter enabled/disabled in APS
+  Void      setLoopFilterDisable(Bool val)      {m_loopFilterDisable = val; }          //!< set offset for deblocking filter disabled
+  Bool      getLoopFilterDisable()              {return m_loopFilterDisable; }         //!< get offset for deblocking filter disabled
+  Void      setLoopFilterBetaOffset(Int val)    {m_loopFilterBetaOffsetDiv2 = val; }    //!< set beta offset for deblocking filter
+  Int       getLoopFilterBetaOffset()           {return m_loopFilterBetaOffsetDiv2; }   //!< get beta offset for deblocking filter
+  Void      setLoopFilterTcOffset(Int val)      {m_loopFilterTcOffsetDiv2 = val; }      //!< set tc offset for deblocking filter
+  Int       getLoopFilterTcOffset()             {return m_loopFilterTcOffsetDiv2; }     //!< get tc offset for deblocking filter
+
+  Void      createScalingList();
+  Void      destroyScalingList();
+  Void      setScalingListEnabled (Bool bVal) { m_scalingListEnabled = bVal; }  //!< set ScalingList enabled/disabled in APS
+  Bool      getScalingListEnabled ()          { return m_scalingListEnabled; }  //!< get ScalingList enabled/disabled in APS
+  TComScalingList* getScalingList ()          { return m_scalingList; }         //!< get ScalingList class pointer in APS
+  Bool     getSaoInterleavingFlag() {return m_saoInterleavingFlag;}             //!< get SAO interleaving flag in APS
+  Void     setSaoInterleavingFlag(Bool bVal) {m_saoInterleavingFlag = bVal;}    //!< set SAO interleaving flag in APS
+
+private:
+  Int         m_apsID;        //!< APS ID
+  Bool        m_bSaoEnabled;  //!< SAO enabled/disabled in APS (true for enabled)
+  Bool        m_bAlfEnabled;  //!< ALF enabled/disabled in APS (true for enabled)
+  SAOParam*   m_pSaoParam;    //!< SAO parameter object pointer 
+  AlfParamSet*   m_alfParamSet;
+  Bool        m_loopFilterOffsetInAPS;       //< offset for deblocking filter in 0 = slice header, 1 = APS
+  Bool        m_loopFilterDisable;           //< Deblocking filter enabled/disabled in APS
+  Int         m_loopFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int         m_loopFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  Bool        m_scalingListEnabled;     //!< ScalingList enabled/disabled in APS (true for enabled)
+  TComScalingList*     m_scalingList;   //!< ScalingList class pointer
+  Bool        m_saoInterleavingFlag;    //!< SAO interleaving flag
+
+public:
+  TComAPS& operator= (const TComAPS& src);  //!< "=" operator for APS object
+};
+
+typedef struct {
+  // 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;
+
+  // Weighted prediction scaling values built from above parameters (bitdepth scaled):
+  Int         w, o, offset, shift, round;
+} wpScalingParam;
+
+typedef struct {
+  Int64 iAC;
+  Int64 iDC;
+} wpACDCParam;
+
+/// slice header class
+class TComSlice
+{
+  
+private:
+  //  Bitstream writing
+  Int         m_iAPSId; //!< APS ID in slice header
+  bool       m_alfEnabledFlag;
+  bool       m_saoEnabledFlag;
+  bool       m_saoInterleavingFlag;   ///< SAO interleaving flag
+  bool       m_saoEnabledFlagCb;      ///< SAO Cb enabled flag
+  bool       m_saoEnabledFlagCr;      ///< SAO Cr enabled flag
+  Int         m_iPPSId;               ///< picture parameter set ID
+  Bool        m_PicOutputFlag;        ///< pic_output_flag 
+  Int         m_iPOC;
+  Int         m_iLastIDR;
+  static Int  m_prevPOC;
+  TComReferencePictureSet *m_pcRPS;
+  TComReferencePictureSet m_LocalRPS;
+  Int         m_iBDidx; 
+  Int         m_iCombinationBDidx;
+  Bool        m_bCombineWithReferenceFlag;
+  TComRefPicListModification m_RefPicListModification;
+  NalUnitType m_eNalUnitType;            ///< Nal unit type for the slice
+  NalUnitType m_eNalUnitTypeBaseViewMvc; ///< Nal unit type of the base view slice for multiview coding
+  SliceType   m_eSliceType;
+  Int         m_iSliceQp;
+#if ADAPTIVE_QP_SELECTION
+  Int         m_iSliceQpBase;
+#endif
+  Bool        m_bLoopFilterDisable;
+  Bool        m_loopFilterOffsetInAPS;
+  Bool        m_inheritDblParamFromAPS;      //< offsets for deblocking filter inherit from APS
+  Int         m_loopFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int         m_loopFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  
+  Int         m_aiNumRefIdx   [3];    //  for multiple reference of current slice
+
+  Int         m_iRefIdxOfLC[2][MAX_NUM_REF_LC];
+  Int         m_eListIdFromIdxOfLC[MAX_NUM_REF_LC];
+  Int         m_iRefIdxFromIdxOfLC[MAX_NUM_REF_LC];
+  Int         m_iRefIdxOfL1FromRefIdxOfL0[MAX_NUM_REF_LC];
+  Int         m_iRefIdxOfL0FromRefIdxOfL1[MAX_NUM_REF_LC];
+  Bool        m_bRefPicListModificationFlagLC;
+  Bool        m_bRefPicListCombinationFlag;
+
+  Bool        m_bCheckLDC;
+#if QC_TMVP_MRG_REFIDX_C0047
+  Int         m_aiNewRefIdx    [2]; 
+#endif
+
+  //  Data
+  Int         m_iSliceQpDelta;
+  TComPic*    m_apcRefPicList  [2][MAX_NUM_REF+1];
+  Int         m_aiRefPOCList   [2][MAX_NUM_REF+1];
+  Int         m_aiRefViewIdList[2][MAX_NUM_REF+1];
+  TComPic*    m_pcTexturePic;
+  Int         m_iDepth;
+  
+  // referenced slice?
+  Bool        m_bRefenced;
+  
+  // access channel
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  TComVPS*    m_pcVPS;
+#endif
+#if QC_IV_AS_LT_B0046
+  Bool        m_bWasLongTerm[2][MAX_NUM_REF+1]; //was long-term picture
+#endif
+  TComSPS*    m_pcSPS;
+  TComPPS*    m_pcPPS;
+  TComPic*    m_pcPic;
+#if ADAPTIVE_QP_SELECTION
+  TComTrQuant* m_pcTrQuant;
+#endif  
+  TComAPS*    m_pcAPS;  //!< pointer to APS parameter object
+
+  UInt        m_uiColDir;  // direction to get colocated CUs
+  
+#if COLLOCATED_REF_IDX
+  UInt        m_colRefIdx;
+#endif
+
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+  Double      m_dLambdaLuma;
+  Double      m_dLambdaChroma;
+#else
+  Double      m_dLambda;
+#endif
+
+  Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
+  
+  Bool        m_bNoBackPredFlag;
+  Bool        m_bRefIdxCombineCoding;
+
+  UInt        m_uiTLayer;
+  Bool        m_bTLayerSwitchingFlag;
+
+  UInt        m_uiSliceMode;
+  UInt        m_uiSliceArgument;
+  UInt        m_uiSliceCurStartCUAddr;
+  UInt        m_uiSliceCurEndCUAddr;
+  UInt        m_uiSliceIdx;
+  UInt        m_uiEntropySliceMode;
+  UInt        m_uiEntropySliceArgument;
+  UInt        m_uiEntropySliceCurStartCUAddr;
+  UInt        m_uiEntropySliceCurEndCUAddr;
+  Bool        m_bNextSlice;
+  Bool        m_bNextEntropySlice;
+  UInt        m_uiSliceBits;
+  UInt        m_uiEntropySliceCounter;
+  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]
+  wpScalingParam  m_weightPredTableLC[2*MAX_NUM_REF][3]; // [refIdxLC][0:Y, 1:U, 2:V]
+
+  UInt        *m_uiTileByteLocation;
+  UInt        m_uiTileCount;
+  Int         m_iTileMarkerFlag;
+  UInt        m_uiTileOffstForMultES;
+
+  UInt*       m_puiSubstreamSizes;
+  TComScalingList*     m_scalingList;                 //!< pointer of quantization matrix
+#if CABAC_INIT_FLAG
+  Bool        m_cabacInitFlag; 
+#else
+  Int         m_cabacInitIdc; 
+#endif
+
+  Bool       m_bLMvdL1Zero;
+  Int         m_numEntryPointOffsets;
+
+  Int        m_viewId;
+  Bool       m_isDepth;
+  Int        m_aaiCodedScale [2][MAX_VIEW_NUM];
+  Int        m_aaiCodedOffset[2][MAX_VIEW_NUM];
+
+#if LGE_ILLUCOMP_B0045
+  Bool        m_bApplyIC;
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115|QC_MVHEVC_B0046
+  Bool       m_bIVScalingFlag;
+  Int        m_iViewOrderIdx;    // will be changed to view_id
+#endif
+
+#if MERL_VSP_C0152
+  TComPic*     m_apcRefPicBaseTxt;
+  TComPic*     m_apcRefPicBaseDepth;
+  Int*         m_aiShiftLUT;
+  Int          m_iShiftPrec;
+#endif
+
+public:
+  TComSlice();
+  virtual ~TComSlice();
+  
+  Void      initSlice       ();
+  Void      initTiles();
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void      setVPS          ( TComVPS* pcVPS ) { m_pcVPS = pcVPS; }
+  TComVPS*  getVPS          () { return m_pcVPS; }
+#endif
+#if QC_IV_AS_LT_B0046
+  Void          setWasLongTerm( Bool lt,  RefPicList e, Int iRefIdx ) { m_bWasLongTerm[e][iRefIdx] = lt; }
+  Bool          getWasLongTerm( RefPicList e, Int iRefIdx           ) { return m_bWasLongTerm[e][iRefIdx] ; }
+#endif
+
+  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; }
+
+#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      setAPS          ( TComAPS* pcAPS ) { m_pcAPS = pcAPS; } //!< set APS pointer
+  TComAPS*  getAPS          ()                 { return m_pcAPS;  } //!< get APS pointer
+  Void      setAPSId        ( Int Id)          { m_iAPSId =Id;    } //!< set APS ID
+  Int       getAPSId        ()                 { return m_iAPSId; } //!< get APS ID
+  Void      setPicOutputFlag( Bool b )         { m_PicOutputFlag = b;    }
+  Bool      getPicOutputFlag()                 { return m_PicOutputFlag; }
+  Void      setAlfEnabledFlag(Bool s) {m_alfEnabledFlag =s; }
+  Bool      getAlfEnabledFlag() { return m_alfEnabledFlag; }
+  Void      setSaoEnabledFlag(Bool s) {m_saoEnabledFlag =s; }
+  Bool      getSaoEnabledFlag() { return m_saoEnabledFlag; }
+  Void      setSaoInterleavingFlag(Bool s) {m_saoInterleavingFlag =s; } //!< set SAO interleaving flag
+  Bool      getSaoInterleavingFlag() { return m_saoInterleavingFlag;  } //!< get SAO interleaving flag
+  Void      setSaoEnabledFlagCb(Bool s) {m_saoEnabledFlagCb =s; }       //!< set SAO Cb enabled flag
+  Bool      getSaoEnabledFlagCb() { return m_saoEnabledFlagCb; }        //!< get SAO Cb enabled flag
+  Void      setSaoEnabledFlagCr(Bool s) {m_saoEnabledFlagCr =s; }       //!< set SAO Cr enabled flag
+  Bool      getSaoEnabledFlagCr() { return m_saoEnabledFlagCr; }        //!< get SAO 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; }
+  Void      setCombinationBDidx          ( Int iCombinationBDidx ) { m_iCombinationBDidx = iCombinationBDidx; }
+  Int       getCombinationBDidx          () { return m_iCombinationBDidx; }
+  Void      setCombineWithReferenceFlag          ( Bool bCombineWithReferenceFlag ) { m_bCombineWithReferenceFlag = bCombineWithReferenceFlag; }
+  Bool      getCombineWithReferenceFlag          () { return m_bCombineWithReferenceFlag; }
+  Int       getPrevPOC      ()                          { return  m_prevPOC;       }
+
+  TComRefPicListModification* getRefPicListModification() { return &m_RefPicListModification; }
+  Void      setLastIDR(Int iIDRPOC)                       { m_iLastIDR = iIDRPOC; }
+  Int       getLastIDR()                                  { return m_iLastIDR; }
+  SliceType getSliceType    ()                          { return  m_eSliceType;         }
+  Int       getPOC          ()                          { return  m_iPOC;           }
+  Int       getSliceQp      ()                          { return  m_iSliceQp;           }
+#if ADAPTIVE_QP_SELECTION
+  Int       getSliceQpBase  ()                          { return  m_iSliceQpBase;       }
+#endif
+  Int       getSliceQpDelta ()                          { return  m_iSliceQpDelta;      }
+  Bool      getLoopFilterDisable()                      { return  m_bLoopFilterDisable; }
+  Bool      getLoopFilterOffsetInAPS()                  { return  m_loopFilterOffsetInAPS;}
+  Bool      getInheritDblParamFromAPS()                 { return  m_inheritDblParamFromAPS; }
+  Int       getLoopFilterBetaOffset()                   { return  m_loopFilterBetaOffsetDiv2; }
+  Int       getLoopFilterTcOffset()                     { return  m_loopFilterTcOffsetDiv2; }
+
+  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];   }
+  Int       getRefViewId        ( RefPicList e, Int iRefIdx)    { return  m_aiRefViewIdList[e][iRefIdx]; }
+  TComPic*  getTexturePic       () const                        { return  m_pcTexturePic; }
+  Int       getDepth            ()                              { return  m_iDepth;                     }
+  UInt      getColDir           ()                              { return  m_uiColDir;                   }
+#if COLLOCATED_REF_IDX
+  Bool      getColRefIdx        ()                              { return  m_colRefIdx;                  }
+  Void      checkColRefIdx      (UInt curSliceIdx, TComPic* pic);
+#endif
+  Bool      getCheckLDC     ()                                  { return m_bCheckLDC; }
+  Bool      getMvdL1ZeroFlag ()                                  { return m_bLMvdL1Zero;    }
+  Int       getRefIdxOfLC       (RefPicList e, Int iRefIdx)     { return m_iRefIdxOfLC[e][iRefIdx];           }
+  Int       getListIdFromIdxOfLC(Int iRefIdx)                   { return m_eListIdFromIdxOfLC[iRefIdx];       }
+  Int       getRefIdxFromIdxOfLC(Int iRefIdx)                   { return m_iRefIdxFromIdxOfLC[iRefIdx];       }
+  Int       getRefIdxOfL0FromRefIdxOfL1(Int iRefIdx)            { return m_iRefIdxOfL0FromRefIdxOfL1[iRefIdx];}
+  Int       getRefIdxOfL1FromRefIdxOfL0(Int iRefIdx)            { return m_iRefIdxOfL1FromRefIdxOfL0[iRefIdx];}
+  Bool      getRefPicListModificationFlagLC()                   {return m_bRefPicListModificationFlagLC;}
+  Void      setRefPicListModificationFlagLC(Bool bflag)         {m_bRefPicListModificationFlagLC=bflag;}     
+  Bool      getRefPicListCombinationFlag()                      {return m_bRefPicListCombinationFlag;}
+  Void      setRefPicListCombinationFlag(Bool bflag)            {m_bRefPicListCombinationFlag=bflag;}     
+  Void      setListIdFromIdxOfLC(Int  iRefIdx, UInt uiVal)      { m_eListIdFromIdxOfLC[iRefIdx]=uiVal; }
+  Void      setRefIdxFromIdxOfLC(Int  iRefIdx, UInt uiVal)      { m_iRefIdxFromIdxOfLC[iRefIdx]=uiVal; }
+  Void      setRefIdxOfLC       (RefPicList e, Int iRefIdx, Int RefIdxLC)     { m_iRefIdxOfLC[e][iRefIdx]=RefIdxLC;}
+
+  Void      setReferenced(Bool b)                               { m_bRefenced = b; }
+  Bool      isReferenced()                                      { return m_bRefenced; }
+  
+  Void      setPOC              ( Int i )                       { m_iPOC              = i; if(getTLayer()==0) m_prevPOC=i; }
+  Void      setNalUnitType      ( NalUnitType e )               { m_eNalUnitType      = e;      }
+  NalUnitType getNalUnitType    ()                              { return m_eNalUnitType;        }
+  Void      setNalUnitTypeBaseViewMvc  ( NalUnitType e )        { m_eNalUnitTypeBaseViewMvc = e;    }
+  NalUnitType getNalUnitTypeBaseViewMvc()                       { return m_eNalUnitTypeBaseViewMvc; }
+  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, 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      setLoopFilterDisable( Bool b )                      { m_bLoopFilterDisable= b;      }
+  Void      setLoopFilterOffsetInAPS( Bool b )                  { m_loopFilterOffsetInAPS = b;}
+  Void      setInheritDblParamFromAPS( Bool b )                 { m_inheritDblParamFromAPS = b; }
+  Void      setLoopFilterBetaOffset( Int i )                    { m_loopFilterBetaOffsetDiv2 = i; }
+  Void      setLoopFilterTcOffset( Int i )                      { m_loopFilterTcOffsetDiv2 = 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      setRefViewId        ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefViewIdList[e][iRefIdx] = i; }
+  Void      setTexturePic       ( TComPic *pcTexturePic )       { m_pcTexturePic = pcTexturePic; }
+  Void      setNumRefIdx        ( RefPicList e, Int i )         { m_aiNumRefIdx[e]    = i;      }
+  Void      setPic              ( TComPic* p )                  { m_pcPic             = p;      }
+  Void      setDepth            ( Int iDepth )                  { m_iDepth            = iDepth; }
+  
+  Int       getNumPocTotalCurr();
+  Int       getNumPocTotalCurrMvc();
+  Void      setRefPicListMvc    ( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& rapcInterViewRefPics );
+  Void      setRefPOCnViewListsMvc();
+
+  Void      setColDir           ( UInt uiDir ) { m_uiColDir = uiDir; }
+#if COLLOCATED_REF_IDX
+  Void      setColRefIdx        ( UInt refIdx) { m_colRefIdx = refIdx; }
+#endif
+  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;  }
+  
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA  
+  Void      setLambda( Double d, Double e ) { m_dLambdaLuma = d; m_dLambdaChroma = e;}
+  Double    getLambdaLuma() { return m_dLambdaLuma;        }
+  Double    getLambdaChroma() { return m_dLambdaChroma;        }
+#else
+  Void      setLambda( Double d ) { m_dLambda = d; }
+  Double    getLambda() { return m_dLambda;        }
+#endif
+  
+  Void      initEqualRef();
+  Bool      isEqualRef  ( RefPicList e, Int iRefIdx1, Int iRefIdx2 )
+  {
+    if (iRefIdx1 < 0 || iRefIdx2 < 0) return false;
+    return m_abEqualRef[e][iRefIdx1][iRefIdx2];
+  }
+  
+  Void setEqualRef( RefPicList e, Int iRefIdx1, Int iRefIdx2, Bool b)
+  {
+    m_abEqualRef[e][iRefIdx1][iRefIdx2] = m_abEqualRef[e][iRefIdx2][iRefIdx1] = b;
+  }
+  
+  static Void      sortPicList         ( TComList<TComPic*>& rcListPic );
+  
+  Bool getNoBackPredFlag() { return m_bNoBackPredFlag; }
+  Void setNoBackPredFlag( Bool b ) { m_bNoBackPredFlag = b; }
+  Bool getRefIdxCombineCoding() { return m_bRefIdxCombineCoding; }
+  Void setRefIdxCombineCoding( Bool b ) { m_bRefIdxCombineCoding = b; }
+  Void generateCombinedList       ();
+
+  UInt getTLayer             ()                            { return m_uiTLayer;                      }
+  Void setTLayer             ( UInt uiTLayer )             { m_uiTLayer = uiTLayer;                  }
+
+
+  Void setTLayerInfo( UInt uiTLayer );
+  Void decodingMarking( TComList<TComPic*>& rcListPic, Int iGOPSIze, Int& iMaxRefPicNum ); 
+  Void applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
+#if H0566_TLA_SET_FOR_SWITCHING_POINTS
+  Bool isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
+#endif
+  Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool outputFlag, Int pocRandomAccess = 0);
+  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet);
+
+  Void decodingMarkingForNoTMVP( TComList<TComPic*>& rcListPic, Int currentPOC );
+
+  UInt m_uiMaxNumMergeCand;
+  Void setMaxNumMergeCand               (UInt maxNumMergeCand ) { m_uiMaxNumMergeCand = maxNumMergeCand;  }
+  UInt getMaxNumMergeCand               ()                  {return m_uiMaxNumMergeCand;                  }
+
+  Void setSliceMode                     ( UInt uiMode )     { m_uiSliceMode = uiMode;                     }
+  UInt getSliceMode                     ()                  { return m_uiSliceMode;                       }
+  Void setSliceArgument                 ( UInt uiArgument ) { m_uiSliceArgument = uiArgument;             }
+  UInt getSliceArgument                 ()                  { return m_uiSliceArgument;                   }
+  Void setSliceCurStartCUAddr           ( UInt uiAddr )     { m_uiSliceCurStartCUAddr = uiAddr;           }
+  UInt getSliceCurStartCUAddr           ()                  { return m_uiSliceCurStartCUAddr;             }
+  Void setSliceCurEndCUAddr             ( UInt uiAddr )     { m_uiSliceCurEndCUAddr = uiAddr;             }
+  UInt getSliceCurEndCUAddr             ()                  { return m_uiSliceCurEndCUAddr;               }
+  Void setSliceIdx                      ( UInt i)           { m_uiSliceIdx = i;                           }
+  UInt getSliceIdx                      ()                  { return  m_uiSliceIdx;                       }
+  Void copySliceInfo                    (TComSlice *pcSliceSrc);
+  Void setEntropySliceMode              ( UInt uiMode )     { m_uiEntropySliceMode = uiMode;              }
+  UInt getEntropySliceMode              ()                  { return m_uiEntropySliceMode;                }
+  Void setEntropySliceArgument          ( UInt uiArgument ) { m_uiEntropySliceArgument = uiArgument;      }
+  UInt getEntropySliceArgument          ()                  { return m_uiEntropySliceArgument;            }
+  Void setEntropySliceCurStartCUAddr    ( UInt uiAddr )     { m_uiEntropySliceCurStartCUAddr = uiAddr;    }
+  UInt getEntropySliceCurStartCUAddr    ()                  { return m_uiEntropySliceCurStartCUAddr;      }
+  Void setEntropySliceCurEndCUAddr      ( UInt uiAddr )     { m_uiEntropySliceCurEndCUAddr = uiAddr;      }
+  UInt getEntropySliceCurEndCUAddr      ()                  { return m_uiEntropySliceCurEndCUAddr;        }
+  Void setNextSlice                     ( Bool b )          { m_bNextSlice = b;                           }
+  Bool isNextSlice                      ()                  { return m_bNextSlice;                        }
+  Void setNextEntropySlice              ( Bool b )          { m_bNextEntropySlice = b;                    }
+  Bool isNextEntropySlice               ()                  { return m_bNextEntropySlice;                 }
+  Void setSliceBits                     ( UInt uiVal )      { m_uiSliceBits = uiVal;                      }
+  UInt getSliceBits                     ()                  { return m_uiSliceBits;                       }  
+  Void setEntropySliceCounter           ( UInt uiVal )      { m_uiEntropySliceCounter = uiVal;            }
+  UInt getEntropySliceCounter           ()                  { return m_uiEntropySliceCounter;             }
+  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  (wpScalingParam  wp[2][MAX_NUM_REF][3]);
+  Void  initWpScaling    (wpScalingParam  wp[2][MAX_NUM_REF][3]);
+  Void  initWpScaling   ();
+  inline Bool applyWP   () { return( (m_eSliceType==P_SLICE && m_pcPPS->getUseWP()) || (m_eSliceType==B_SLICE && m_pcPPS->getWPBiPredIdc()) ); }
+  
+  Void  setWpAcDcParam  ( wpACDCParam wp[3] ) { memcpy(m_weightACDCParam, wp, sizeof(wpACDCParam)*3); }
+  Void  getWpAcDcParam  ( wpACDCParam *&wp );
+  Void  initWpAcDcParam ();
+  Void  copyWPtable     (wpScalingParam *&wp_src, wpScalingParam *&wp_dst);
+  Void  getWpScalingLC  ( Int iRefIdx, wpScalingParam *&wp);
+  Void  resetWpScalingLC(wpScalingParam  wp[2*MAX_NUM_REF][3]);
+  Void  setWpParamforLC();
+  Void setTileLocationCount             ( UInt uiCount )      { m_uiTileCount = uiCount;                  }
+  UInt getTileLocationCount             ()                    { return m_uiTileCount;                     }
+  Void setTileLocation                  ( Int i, UInt uiLOC ) { m_uiTileByteLocation[i] = uiLOC;          }
+  UInt getTileLocation                  ( Int i )             { return m_uiTileByteLocation[i];           }
+  Void setTileMarkerFlag                ( Int iFlag )         { m_iTileMarkerFlag = iFlag;                }
+  Int  getTileMarkerFlag                ()                    { return m_iTileMarkerFlag;                 }
+  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     ();
+#if CABAC_INIT_FLAG
+  Void      setCabacInitFlag  ( Bool val ) { m_cabacInitFlag = val;      }  //!< set CABAC initial flag 
+  Bool      getCabacInitFlag  ()           { return m_cabacInitFlag;     }  //!< get CABAC initial flag 
+#else
+  Void      setCABACinitIDC(Int iVal) {m_cabacInitIdc = iVal;    }  //!< set CABAC initial IDC number 
+  Int       getCABACinitIDC()         {return m_cabacInitIdc;    }  //!< get CABAC initial IDC number 
+#endif
+  Void      setNumEntryPointOffsets(Int val)  { m_numEntryPointOffsets = val;     }
+  Int       getNumEntryPointOffsets()         { return m_numEntryPointOffsets;    }
+
+  Void setViewId( Int viewId )       { m_viewId = viewId;   }
+  Int  getViewId()                   { return m_viewId;     }
+#if QC_MVHEVC_B0046
+  Void    setViewOrderIdx(Int v, UInt layer)                { m_iViewOrderIdx = v;    }
+  Int     getViewOrderIdx()                                 { return m_iViewOrderIdx; }
+#endif
+  Void setIsDepth( Bool isDepth )    { m_isDepth = isDepth; }
+  Bool getIsDepth()                  { return m_isDepth;    }
+ 
+  Void      initMultiviewSlice    ( 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]; }
+
+#if LGE_ILLUCOMP_B0045
+  Void      setApplyIC            ( Bool b ) { m_bApplyIC = b; }
+  Bool      getApplyIC            ()  { return m_bApplyIC; }
+  Void      xSetApplyIC           ();
+#endif
+#if QC_TMVP_MRG_REFIDX_C0047
+  Int       getNewRefIdx        ( RefPicList e )                { return  m_aiNewRefIdx[e];     }
+  Void      setNewRefIdx        ( RefPicList e, Int i )         { m_aiNewRefIdx[e]    = i;      }
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Void setIVScalingFlag( Bool val )         { m_bIVScalingFlag = val;     }
+  Bool getIVScalingFlag()                   { return m_bIVScalingFlag;    }
+  Void setViewOrderIdx     ( Int i )        { m_iViewOrderIdx     = i;    }   // will be changed to view_id
+  Int  getViewOrderIdx     ()               { return  m_iViewOrderIdx;    }   // will be changed to view_id
+#endif
+
+#if MERL_VSP_C0152
+  TComPic*     getRefPicBaseTxt          ()                        { return  m_apcRefPicBaseTxt; }
+  Void         setRefPicBaseTxt          ( TComPic* RefPic)        { m_apcRefPicBaseTxt = RefPic; }
+  TComPic*     getRefPicBaseDepth        ()                        { return  m_apcRefPicBaseDepth; }
+  Void         setRefPicBaseDepth        ( TComPic* RefPic)        { m_apcRefPicBaseDepth = RefPic; }
+
+  Void setBWVSPLUTParam( Int *pShiftLUT, Int iLoG2LUTPrec) { m_aiShiftLUT = pShiftLUT; m_iShiftPrec = iLoG2LUTPrec; }
+  Void getBWVSPLUTParam( Int*&pShiftLUT, Int&iLoG2LUTPrec) { pShiftLUT = m_aiShiftLUT; iLoG2LUTPrec = m_iShiftPrec; }
+#endif
+
+protected:
+  TComPic*  xGetRefPic        (TComList<TComPic*>& rcListPic, UInt uiPOC);
+  TComPic*  xGetLongTermRefPic(TComList<TComPic*>& rcListPic, UInt uiPOC);
+  TComPic*  xGetInterViewRefPic( std::vector<TComPic*>& rcListIvPic, UInt uiViewId );
+};// END CLASS DEFINITION TComSlice
+
+
+template <class T> class ParameterSetMap
+{
+public:
+  ParameterSetMap(Int maxId)
+  :m_maxId (maxId)
+  {}
+
+  ~ParameterSetMap()
+  {
+    for (typename std::map<Int,T *>::iterator i = m_paramsetMap.begin(); i!= m_paramsetMap.end(); i++)
+    {
+      delete (*i).second;
+    }
+  }
+
+  Void storePS(Int psId, T *ps)
+  {
+    assert ( psId < m_maxId );
+    if ( m_paramsetMap.find(psId) != m_paramsetMap.end() )
+    {
+      delete m_paramsetMap[psId];
+    }
+    m_paramsetMap[psId] = ps; 
+  }
+
+  Void mergePSList(ParameterSetMap<T> &rPsList)
+  {
+    for (typename std::map<Int,T *>::iterator i = rPsList.m_paramsetMap.begin(); i!= rPsList.m_paramsetMap.end(); i++)
+    {
+      storePS(i->first, i->second);
+    }
+    rPsList.m_paramsetMap.clear();
+  }
+
+
+  T* getPS(Int psId)
+  {
+    return ( m_paramsetMap.find(psId) == m_paramsetMap.end() ) ? NULL : m_paramsetMap[psId];
+  }
+
+  T* getFirstPS()
+  {
+    return (m_paramsetMap.begin() == m_paramsetMap.end() ) ? NULL : m_paramsetMap.begin()->second;
+  }
+
+#if QC_MVHEVC_B0046
+  Void clearPSList()
+  {
+    m_paramsetMap.clear();
+  }
+#endif
+private:
+  std::map<Int,T *> m_paramsetMap;
+  Int               m_maxId;
+};
+
+class ParameterSetManager
+{
+public:
+  ParameterSetManager();
+  virtual ~ParameterSetManager();
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  //! store video 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(); };
+#if QC_MVHEVC_B0046
+  Void     clearVPS()         { m_vpsMap.clearPSList(); };
+  Void     clearSPS()         { m_spsMap.clearPSList(); };
+  Void     clearPPS()         { m_ppsMap.clearPSList(); };
+#endif
+#endif
+  //! 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(); };
+
+  //! store adaptation parameter set and take ownership of it 
+  Void storeAPS(TComAPS *aps) { m_apsMap.storePS( aps->getAPSID(), aps); };
+  //! getPointer to existing adaptation parameter set  
+  TComAPS* getAPS(Int apsId)  { return m_apsMap.getPS(apsId); };
+
+protected:
+  ParameterSetMap<TComSPS> m_spsMap; 
+  ParameterSetMap<TComPPS> m_ppsMap; 
+  ParameterSetMap<TComAPS> m_apsMap; 
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  ParameterSetMap<TComVPS> m_vpsMap; 
+#endif
+};
+
+//! \}
+
+#endif // __TCOMSLICE__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 341)
@@ -0,0 +1,2833 @@
+/* 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-2012, 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     TComTrQuant.cpp
+    \brief    transform and quantization class
+*/
+
+#include <stdlib.h>
+#include <math.h>
+#include <memory.h>
+#include "TComTrQuant.h"
+#include "TComPic.h"
+#include "ContextTables.h"
+
+typedef struct
+{
+  Int    iNNZbeforePos0;
+  Double d64CodedLevelandDist; // distortion and level cost only
+  Double d64UncodedDist;    // all zero coded block distortion
+  Double d64SigCost;
+  Double d64SigCost_0;
+} coeffGroupRDStats;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define RDOQ_CHROMA                 1           ///< use of RDOQ in chroma
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// RDOQ parameter
+
+// ====================================================================================================================
+// Qp class member functions
+// ====================================================================================================================
+
+QpParam::QpParam()
+{
+}
+
+// ====================================================================================================================
+// TComTrQuant class member functions
+// ====================================================================================================================
+
+TComTrQuant::TComTrQuant()
+{
+  m_cQP.clear();
+  
+  // allocate temporary buffers
+  m_plTempCoeff  = new Int[ MAX_CU_SIZE*MAX_CU_SIZE ];
+  
+  // allocate bit estimation class  (for RDOQ)
+  m_pcEstBitsSbac = new estBitsSbacStruct;
+  initScalingList();
+}
+
+TComTrQuant::~TComTrQuant()
+{
+  // delete temporary buffers
+  if ( m_plTempCoeff )
+  {
+    delete [] m_plTempCoeff;
+    m_plTempCoeff = NULL;
+  }
+  
+  // delete bit estimation class
+  if ( m_pcEstBitsSbac )
+  {
+    delete m_pcEstBitsSbac;
+  }
+  destroyScalingList();
+}
+
+#if ADAPTIVE_QP_SELECTION
+Void TComTrQuant::storeSliceQpNext(TComSlice* pcSlice)
+{
+  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] ;
+  }
+
+  if( !m_bUseRDOQ )
+  {
+    sliceQpused = qpBase;
+    alpha = 0.5;
+  }
+
+  if( cnt > 120 )
+  {
+    Double sum = 0;
+    Int k = 0;
+    for(Int u=1; u<LEVEL_RANGE; u++)
+    {
+      sum += u*m_sliceSumC[u];
+      k += u*u*m_sliceNsamples[u];
+    }
+
+    Int v;
+    Double q[MAX_QP+1] ;
+    for(v=0; v<=MAX_QP; v++)
+    {
+      q[v] = (Double)(g_invQuantScales[v%6] * (1<<(v/6)))/64 ;
+    }
+
+    Double qnext = sum/k * q[sliceQpused] / (1<<ARL_C_PRECISION);
+
+    for(v=0; v<MAX_QP; v++)
+    {
+      if(qnext < alpha * q[v] + (1 - alpha) * q[v+1] )
+      {
+        break;
+      }
+    }
+    sliceQpnext = Clip3(sliceQpused - 3, sliceQpused + 3, v);
+  }
+  else
+  {
+    sliceQpnext = sliceQpused;
+  }
+
+  m_qpDelta[qpBase] = sliceQpnext - qpBase; 
+}
+
+Void TComTrQuant::initSliceQpDelta()
+{
+  for(Int qp=0; qp<=MAX_QP; qp++)
+  {
+    m_qpDelta[qp] = qp < 17 ? 0 : 1;
+  }
+}
+
+Void TComTrQuant::clearSliceARLCnt()
+{ 
+  memset(m_sliceSumC, 0, sizeof(Double)*(LEVEL_RANGE+1));
+  memset(m_sliceNsamples, 0, sizeof(Int)*(LEVEL_RANGE+1));
+}
+#endif
+
+
+/** Set qP for Quantization.
+ * \param qpy QPy
+ * \param bLowpass
+ * \param eSliceType
+ * \param eTxtType
+ * \param qpBdOffset
+ * \param chromaQPOffset
+ *
+ * return void  
+ */
+Void TComTrQuant::setQPforQuant( Int qpy, Bool bLowpass, SliceType eSliceType, TextType eTxtType, Int qpBdOffset, Int chromaQPOffset)
+{
+  Int qpScaled;
+
+  if(eTxtType == TEXT_LUMA)
+  {
+    qpScaled = qpy + qpBdOffset;
+  }
+  else
+  {
+    qpScaled = Clip3( -qpBdOffset, 51, qpy + chromaQPOffset );
+
+    if(qpScaled < 0)
+    {
+      qpScaled = qpScaled + qpBdOffset;
+    }
+    else
+    {
+      qpScaled = g_aucChromaScale[ Clip3(0, 51, qpScaled) ] + qpBdOffset;
+    }
+  }
+  m_cQP.setQpParam( qpScaled, bLowpass, eSliceType );
+}
+
+#if MATRIX_MULT
+/** NxN forward transform (2D) using brute force matrix multiplication (3 nested loops)
+ *  \param block pointer to input data (residual)
+ *  \param coeff pointer to output data (transform coefficients)
+ *  \param uiStride stride of input data
+ *  \param uiTrSize transform size (uiTrSize x uiTrSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+void xTr(Pel *block, Int *coeff, UInt uiStride, UInt uiTrSize, UInt uiMode)
+{
+  Int i,j,k,iSum;
+  Int tmp[32*32];
+  const short *iT;
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiTrSize ] + 2;
+
+  if (uiTrSize==4)
+  {
+    iT  = g_aiT4[0];
+  }
+  else if (uiTrSize==8)
+  {
+    iT = g_aiT8[0];
+  }
+  else if (uiTrSize==16)
+  {
+    iT = g_aiT16[0];
+  }
+  else if (uiTrSize==32)
+  {
+    iT = g_aiT32[0];
+  }
+  else
+  {
+    assert(0);
+  }
+
+#if FULL_NBIT
+  int shift_1st = uiLog2TrSize - 1 + g_uiBitDepth - 8; // log2(N) - 1 + g_uiBitDepth - 8
+#else
+  int shift_1st = uiLog2TrSize - 1 + g_uiBitIncrement; // log2(N) - 1 + g_uiBitIncrement
+#endif
+
+  int add_1st = 1<<(shift_1st-1);
+  int shift_2nd = uiLog2TrSize + 6;
+  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++)
+  {
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {
+        iSum += iT[i*uiTrSize+k]*block[j*uiStride+k];
+      }
+      tmp[i*uiTrSize+j] = (iSum + add_1st)>>shift_1st;
+    }
+  }
+  
+  /* 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++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {
+        iSum += iT[i*uiTrSize+k]*tmp[j*uiTrSize+k];        
+      }
+      coeff[i*uiTrSize+j] = (iSum + add_2nd)>>shift_2nd; 
+    }
+  }
+}
+
+/** NxN inverse transform (2D) using brute force matrix multiplication (3 nested loops)
+ *  \param coeff pointer to input data (transform coefficients)
+ *  \param block pointer to output data (residual)
+ *  \param uiStride stride of output data
+ *  \param uiTrSize transform size (uiTrSize x uiTrSize)
+ *  \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;
+  
+  if (uiTrSize==4)
+  {
+    iT  = g_aiT4[0];
+  }
+  else if (uiTrSize==8)
+  {
+    iT = g_aiT8[0];
+  }
+  else if (uiTrSize==16)
+  {
+    iT = g_aiT16[0];
+  }
+  else if (uiTrSize==32)
+  {
+    iT = g_aiT32[0];
+  }
+  else
+  {
+    assert(0);
+  }
+  
+  int shift_1st = SHIFT_INV_1ST;
+  int add_1st = 1<<(shift_1st-1);  
+#if FULL_NBIT
+  int shift_2nd = SHIFT_INV_2ND - ((short)g_uiBitDepth - 8);
+#else
+  int shift_2nd = SHIFT_INV_2ND - g_uiBitIncrement;
+#endif
+  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];
+    }
+  }
+  
+  /* 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];
+    }
+  }
+  
+  /* 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
+
+/** 4x4 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
+ */
+
+void partialButterfly4(short *src,short *dst,int shift, int line)
+{
+  int j;  
+  int E[2],O[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* E and O */
+    E[0] = src[0] + src[3];
+    O[0] = src[0] - src[3];
+    E[1] = src[1] + src[2];
+    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;
+
+    src += 4;
+    dst ++;
+  }
+}
+
+// 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);
+  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);
+  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)
+{
+  int j;    
+  int E[2],O[2];
+  int add = 1<<(shift-1);
+
+  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];
+
+    /* 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 );
+            
+    src   ++;
+    dst += 4;
+  }
+}
+
+
+void partialButterfly8(short *src,short *dst,int shift, int line)
+{
+  int j,k;  
+  int E[4],O[4];
+  int EE[2],EO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {  
+    /* E and O*/
+    for (k=0;k<4;k++)
+    {
+      E[k] = src[k] + src[7-k];
+      O[k] = src[k] - src[7-k];
+    }    
+    /* EE and EO */
+    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;
+
+    src += 8;
+    dst ++;
+  }
+}
+
+
+void partialButterflyInverse8(short *src,short *dst,int shift, int line)
+{
+  int j,k;    
+  int E[4],O[4];
+  int EE[2],EO[2];
+  int add = 1<<(shift-1);
+
+  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 */ 
+    E[0] = EE[0] + EO[0];
+    E[3] = EE[0] - EO[0];
+    E[1] = EE[1] + EO[1];
+    E[2] = EE[1] - EO[1];
+    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 );
+    }   
+    src ++;
+    dst += 8;
+  }
+}
+
+
+void partialButterfly16(short *src,short *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++) 
+  {    
+    /* E and O*/
+    for (k=0;k<8;k++)
+    {
+      E[k] = src[k] + src[15-k];
+      O[k] = src[k] - src[15-k];
+    } 
+    /* EE and EO */
+    for (k=0;k<4;k++)
+    {
+      EE[k] = E[k] + E[7-k];
+      EO[k] = E[k] - E[7-k];
+    }
+    /* EEE and EEO */
+    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;
+
+    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;      
+    }
+
+    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;
+    }
+
+    src += 16;
+    dst ++; 
+
+  }
+}
+
+
+void partialButterflyInverse16(short *src,short *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++)
+  {    
+    /* 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];
+    }
+    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 */ 
+    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 += 16;
+  }
+}
+
+
+void partialButterfly32(short *src,short *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);
+
+  for (j=0; j<line; j++)
+  {    
+    /* E and O*/
+    for (k=0;k<16;k++)
+    {
+      E[k] = src[k] + src[31-k];
+      O[k] = src[k] - src[31-k];
+    } 
+    /* EE and EO */
+    for (k=0;k<8;k++)
+    {
+      EE[k] = E[k] + E[15-k];
+      EO[k] = E[k] - E[15-k];
+    }
+    /* EEE and EEO */
+    for (k=0;k<4;k++)
+    {
+      EEE[k] = EE[k] + EE[7-k];
+      EEO[k] = EE[k] - EE[7-k];
+    }
+    /* EEEE and EEEO */
+    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;
+    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;
+    }       
+    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;
+    }       
+    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;
+    }
+    src += 32;
+    dst ++;
+  }
+}
+
+
+void partialButterflyInverse32(short *src,short *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);
+
+  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 ];
+    }
+    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 ];
+    }
+    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 ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
+    EEE[0] = EEEE[0] + EEEO[0];
+    EEE[3] = EEEE[0] - EEEO[0];
+    EEE[1] = 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 );
+    }
+    src ++;
+    dst += 32;
+  }
+}
+
+
+/** 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)
+*/
+void xTrMxN(short *block,short *coeff, int iWidth, int iHeight, UInt uiMode)
+{
+#if FULL_NBIT
+  int shift_1st = g_aucConvertToBit[iWidth]  + 1 + g_uiBitDepth - 8; // log2(iWidth) - 1 + g_uiBitDepth - 8
+#else
+  int shift_1st = g_aucConvertToBit[iWidth]  + 1 + g_uiBitIncrement; // log2(iWidth) - 1 + g_uiBitIncrement
+#endif
+  int shift_2nd = g_aucConvertToBit[iHeight]  + 8;                   // log2(iHeight) + 6
+
+  short tmp[ 64 * 64 ];
+
+  if( iWidth == 16 && iHeight == 4)
+  {
+    partialButterfly16( block, tmp, shift_1st, iHeight );
+    partialButterfly4( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 32 && iHeight == 8 )
+  {
+    partialButterfly32( block, tmp, shift_1st, iHeight );
+    partialButterfly8( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 4 && iHeight == 16)
+  {
+    partialButterfly4( block, tmp, shift_1st, iHeight );
+    partialButterfly16( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 8 && iHeight == 32 )
+  {
+    partialButterfly8( block, tmp, shift_1st, iHeight );
+    partialButterfly32( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 4 && iHeight == 4)
+  {
+    if (uiMode != REG_DCT && (!uiMode || (uiMode>=2 && uiMode <= 25)))    // Check for DCT or DST
+    {
+      fastForwardDst(block,tmp,shift_1st); // Forward DST BY FAST ALGORITHM, block input, tmp output
+    }
+    else  
+    {
+      partialButterfly4(block, tmp, shift_1st, iHeight);
+    }
+    if (uiMode != REG_DCT && (!uiMode || (uiMode>=11 && uiMode <= 34)))    // Check for DCT or DST
+    {
+      fastForwardDst(tmp,coeff,shift_2nd); // Forward DST BY FAST ALGORITHM, tmp input, coeff output
+    }
+    else  
+    {
+      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 );
+  }
+}
+/** 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)
+*/
+void xITrMxN(short *coeff,short *block, int iWidth, int iHeight, UInt uiMode)
+{
+  int shift_1st = SHIFT_INV_1ST;
+#if FULL_NBIT
+  int shift_2nd = SHIFT_INV_2ND - ((short)g_uiBitDepth - 8);
+#else
+  int shift_2nd = SHIFT_INV_2ND - g_uiBitIncrement;
+#endif
+
+  short tmp[ 64*64];
+  if( iWidth == 16 && iHeight == 4)
+  {
+    partialButterflyInverse4(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse16(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 32 && iHeight == 8)
+  {
+    partialButterflyInverse8(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse32(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 4 && iHeight == 16)
+  {
+    partialButterflyInverse16(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse4(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 8 && iHeight == 32)
+  {
+    partialButterflyInverse32(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse8(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 4 && iHeight == 4)
+  {
+    if (uiMode != REG_DCT && (!uiMode || (uiMode>=11 && uiMode <= 34)))    // Check for DCT or DST
+    {
+      fastInverseDst(coeff,tmp,shift_1st);    // Inverse DST by FAST Algorithm, coeff input, tmp output
+    }
+    else
+    {
+      partialButterflyInverse4(coeff,tmp,shift_1st,iWidth);    
+    } 
+    if (uiMode != REG_DCT && (!uiMode || (uiMode>=2 && uiMode <= 25)))    // Check for DCT or DST
+    {
+      fastInverseDst(tmp,block,shift_2nd); // Inverse DST by FAST Algorithm, tmp input, coeff output
+    }
+    else
+    {
+      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( TComDataCU* pcCU, TCoeff* pQCoef, TCoeff* pCoef, UInt const *scan, Int* deltaU, Int width, Int height )
+{
+  Int tsig = pcCU->getSlice()->getPPS()->getTSIG() ;
+  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 ;
+    absSum = 0 ;
+
+    for(n = SCAN_SET_SIZE-1; n >= 0; --n )
+    {
+      if( pQCoef[ scan[ n + subPos ]] )
+      {
+        lastNZPosInCG = n;
+        break;
+      }
+    }
+
+    for(n = 0; n <SCAN_SET_SIZE; n++ )
+    {
+      if( pQCoef[ scan[ n + subPos ]] )
+      {
+        firstNZPosInCG = n;
+        break;
+      }
+    }
+
+    for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
+    {
+      absSum += pQCoef[ scan[ n + subPos ]];
+    }
+
+    if(lastNZPosInCG>=0 && lastCG==-1) 
+    {
+      lastCG = 1 ; 
+    }
+    
+    if( lastNZPosInCG-firstNZPosInCG>=tsig )
+    {
+      UInt signbit = (pQCoef[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 ];
+          if(pQCoef[ blkPos ] != 0 )
+          {
+            if(deltaU[blkPos]>0)
+            {
+              curCost = - deltaU[blkPos]; 
+              curChange=1 ;
+            }
+            else 
+            {
+              //curChange =-1;
+              if(n==firstNZPosInCG && abs(pQCoef[blkPos])==1)
+              {
+                curCost=MAX_INT ; 
+              }
+              else
+              {
+                curCost = deltaU[blkPos]; 
+                curChange =-1;
+              }
+            }
+          }
+          else
+          {
+            if(n<firstNZPosInCG)
+            {
+              UInt thisSignBit = (pCoef[blkPos]>=0?0:1);
+              if(thisSignBit != signbit )
+              {
+                curCost = MAX_INT;
+              }
+              else
+              { 
+                curCost = - (deltaU[blkPos])  ;
+                curChange = 1 ;
+              }
+            }
+            else
+            {
+              curCost = - (deltaU[blkPos])  ;
+              curChange = 1 ;
+            }
+          }
+
+          if( curCost<minCostInc)
+          {
+            minCostInc = curCost ;
+            finalChange = curChange ;
+            minPos = blkPos ;
+          }
+        } //CG loop
+
+        if(pQCoef[minPos] == 32767 || pQCoef[minPos] == -32768)
+        {
+          finalChange = -1;
+        }
+
+        if(pCoef[minPos]>=0)
+        {
+          pQCoef[minPos] += finalChange ; 
+        }
+        else 
+        { 
+          pQCoef[minPos] -= finalChange ;
+        }  
+      } // Hide
+    }
+    if(lastCG==1) 
+    {
+      lastCG=0 ;
+    }
+  } // TU loop
+
+  return;
+}
+
+Void TComTrQuant::xQuant( TComDataCU* pcCU, 
+                          Int*        pSrc, 
+                          TCoeff*     pDes, 
+#if ADAPTIVE_QP_SELECTION
+                          Int*&       pArlDes,
+#endif
+                          Int         iWidth, 
+                          Int         iHeight, 
+                          UInt&       uiAcSum, 
+                          TextType    eTType, 
+                          UInt        uiAbsPartIdx )
+{
+  Int*   piCoef    = pSrc;
+  TCoeff* piQCoef   = pDes;
+#if ADAPTIVE_QP_SELECTION
+  Int*   piArlCCoef = pArlDes;
+#endif
+  Int   iAdd = 0;
+  
+  if ( m_bUseRDOQ && (eTType == TEXT_LUMA || RDOQ_CHROMA) )
+  {
+#if ADAPTIVE_QP_SELECTION
+    xRateDistOptQuant( pcCU, piCoef, pDes, pArlDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+#else
+    xRateDistOptQuant( pcCU, piCoef, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+#endif
+  }
+  else
+  {
+    const UInt   log2BlockSize   = g_aucConvertToBit[ iWidth ] + 2;
+
+    UInt scanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, iWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+    if (scanIdx == SCAN_ZIGZAG)
+    {
+      scanIdx = SCAN_DIAG;
+    }
+
+    if (iWidth != iHeight)
+    {
+      scanIdx = SCAN_DIAG;
+    }
+
+    const UInt * scan;
+    if (iWidth == iHeight)
+    {
+      scan = g_auiSigLastScan[ scanIdx ][ log2BlockSize - 1 ];
+    }
+    else
+    {
+      scan = g_sigScanNSQT[ log2BlockSize - 2 ];
+    }
+
+    Int deltaU[32*32] ;
+
+#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
+    {
+      qpScaled = Clip3( -qpBDOffset, 51, iQpBase);
+
+      if(qpScaled < 0)
+      {
+        qpScaled = qpScaled +  qpBDOffset;
+      }
+      else
+      {
+        qpScaled = g_aucChromaScale[ Clip3(0, 51, qpScaled) ] + qpBDOffset;
+      }
+    }
+    cQpBase.setQpParam(qpScaled, false, pcCU->getSlice()->getSliceType());
+#endif
+
+    Bool bNonSqureFlag = ( iWidth != iHeight );
+    UInt dir           = SCALING_LIST_SQT;
+    if( bNonSqureFlag )
+    {
+      dir = ( iWidth < iHeight )?  SCALING_LIST_VER: SCALING_LIST_HOR;
+      UInt uiWidthBit  = g_aucConvertToBit[ iWidth ] + 2;
+      UInt uiHeightBit = g_aucConvertToBit[ iHeight ] + 2;
+      iWidth  = 1 << ( ( uiWidthBit + uiHeightBit) >> 1 );
+      iHeight = iWidth;
+    }    
+
+    UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
+    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
+    assert(scalingListType < 6);
+    Int *piQuantCoeff = 0;
+    piQuantCoeff = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2, dir);
+
+#if FULL_NBIT
+    UInt uiBitDepth = g_uiBitDepth;
+#else
+    UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;
+#endif
+    UInt iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+    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);
+
+#if ADAPTIVE_QP_SELECTION
+    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);
+#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(iLevel) * piQuantCoeff[uiBlockPos] - (iLevel<<iQBits) )>> qBits8 );
+#endif
+      uiAcSum += iLevel;
+      iLevel *= iSign;        
+      piQCoef[uiBlockPos] = Clip3( -32768, 32767, iLevel );
+    } // for n
+    if( pcCU->getSlice()->getPPS()->getSignHideFlag() )
+    {
+      if(uiAcSum>=2)
+      {
+        signBitHidingHDQ( pcCU, piQCoef, piCoef, scan, deltaU, iWidth, iHeight ) ;
+      }
+    }
+  } //if RDOQ
+  //return;
+
+}
+
+Void TComTrQuant::xDeQuant( const TCoeff* pSrc, Int* pDes, Int iWidth, Int iHeight, Int scalingListType )
+{
+  
+  const TCoeff* piQCoef   = pSrc;
+  Int*   piCoef    = pDes;
+  UInt dir          = SCALING_LIST_SQT;
+  if( iWidth != iHeight )
+  {
+    dir          = ( iWidth < iHeight )? SCALING_LIST_VER: SCALING_LIST_HOR;
+    UInt uiWidthBit  = g_aucConvertToBit[ iWidth ]  + 2;
+    UInt uiHeightBit = g_aucConvertToBit[ iHeight ] + 2;
+    iWidth  = 1 << ( ( uiWidthBit + uiHeightBit) >> 1 );
+    iHeight = iWidth;
+  }    
+
+  if ( iWidth > (Int)m_uiMaxTrSize )
+  {
+    iWidth  = m_uiMaxTrSize;
+    iHeight = m_uiMaxTrSize;
+  }
+  
+  Int iShift,iAdd,iCoeffQ;
+  UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
+
+#if FULL_NBIT
+  UInt uiBitDepth = g_uiBitDepth;
+#else
+  UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;
+#endif
+  UInt iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize; 
+  iShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - iTransformShift;
+
+  TCoeff clipQCoef;
+  const Int bitRange = min( 15, ( Int )( 12 + uiLog2TrSize + uiBitDepth - m_cQP.m_iPer) );
+  const Int levelLimit = 1 << bitRange;
+
+  if(getUseScalingList())
+  {
+    iShift += 4;
+    if(iShift > m_cQP.m_iPer)
+    {
+      iAdd = 1 << (iShift - m_cQP.m_iPer - 1);
+    }
+    else
+    {
+      iAdd = 0;
+    }
+    Int *piDequantCoef = getDequantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2,dir);
+
+    if(iShift > m_cQP.m_iPer)
+    {
+      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);
+      }
+    }
+    else
+    {
+      for( Int n = 0; n < iWidth*iHeight; n++ )
+      {
+        clipQCoef = Clip3( -levelLimit, levelLimit - 1, piQCoef[n] );
+        iCoeffQ = (clipQCoef * piDequantCoef[n]) << (m_cQP.m_iPer - iShift);
+        piCoef[n] = Clip3(-32768,32767,iCoeffQ);
+      }
+    }
+  }
+  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 uiMaxWidth, UInt uiMaxHeight, UInt uiMaxTrSize, Int iSymbolMode, UInt *aTableLP4, UInt *aTableLP8, UInt *aTableLastPosVlcIndex,
+                       Bool bUseRDOQ,  Bool bEnc
+#if ADAPTIVE_QP_SELECTION
+                       , Bool bUseAdaptQpSelect
+#endif
+                       )
+{
+  m_uiMaxTrSize  = uiMaxTrSize;
+  m_bEnc         = bEnc;
+  m_bUseRDOQ     = bUseRDOQ;
+#if ADAPTIVE_QP_SELECTION
+  m_bUseAdaptQpSelect = bUseAdaptQpSelect;
+#endif
+}
+
+Void TComTrQuant::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 )
+{
+#if LOSSLESS_CODING
+  if((m_cQP.qp() == 0) && (pcCU->getSlice()->getSPS()->getUseLossless()))
+  {
+    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]);
+      }
+    }
+    return;
+  }
+#endif
+  UInt uiMode;  //luma intra pred
+  if(eTType == TEXT_LUMA && pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
+  {
+    uiMode = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  }
+  else
+  {
+    uiMode = REG_DCT;
+  }
+  
+  uiAbsSum = 0;
+  assert( (pcCU->getSlice()->getSPS()->getMaxTrSize() >= uiWidth) );
+
+  xT( uiMode, pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight );
+  xQuant( pcCU, m_plTempCoeff, rpcCoeff,
+#if ADAPTIVE_QP_SELECTION
+       rpcArlCoeff,
+#endif
+       uiWidth, uiHeight, uiAbsSum, eTType, uiAbsPartIdx );
+}
+
+#if LOSSLESS_CODING
+Void TComTrQuant::invtransformNxN( TComDataCU* pcCU, TextType eText, UInt uiMode,Pel* rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight,  Int scalingListType)
+#else
+Void TComTrQuant::invtransformNxN(                   TextType eText, UInt uiMode,Pel*& rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight, Int scalingListType)
+#endif
+{
+#if LOSSLESS_CODING
+  if((m_cQP.qp() == 0) && (pcCU->getSlice()->getSPS()->getUseLossless()))
+  {
+    for (UInt k = 0; k<uiHeight; k++)
+    {
+      for (UInt j = 0; j<uiWidth; j++)
+      {
+        rpcResidual[k*uiStride+j] = pcCoeff[k*uiWidth+j];
+      }
+    } 
+    return;
+  }
+#endif
+  xDeQuant( pcCoeff, m_plTempCoeff, uiWidth, uiHeight, scalingListType);
+  xIT( 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;
+  }
+  
+  UInt uiLumaTrMode, uiChromaTrMode;
+  pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx( uiAbsPartIdx ), uiLumaTrMode, uiChromaTrMode );
+  const UInt uiStopTrMode = eTxt == TEXT_LUMA ? uiLumaTrMode : uiChromaTrMode;
+  
+  if( uiTrMode == uiStopTrMode )
+  {
+    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;
+    if( pcCU->useNonSquareTrans( uiTrMode, uiAbsPartIdx ) )
+    {
+      Int trWidth  = uiWidth;
+      Int trHeight = uiHeight;
+      pcCU->getNSQTSize( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+
+      uiWidth  = trWidth;
+      uiHeight = trHeight;
+    }
+    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTxt];
+    assert(scalingListType < 6);
+#if LOSSLESS_CODING
+    invtransformNxN( pcCU, eTxt, REG_DCT, pResi, uiStride, rpcCoeff, uiWidth, uiHeight, scalingListType );
+#else  
+    invtransformNxN(       eTxt, REG_DCT, pResi, uiStride, rpcCoeff, uiWidth, uiHeight, scalingListType );
+#endif
+  }
+  else
+  {
+    uiTrMode++;
+    uiWidth  >>= 1;
+    uiHeight >>= 1;
+    Int trWidth = uiWidth, trHeight = uiHeight;
+    Int trLastWidth = uiWidth << 1, trLastHeight = uiHeight << 1;
+    pcCU->getNSQTSize ( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+    pcCU->getNSQTSize ( uiTrMode - 1, uiAbsPartIdx, trLastWidth, trLastHeight );
+    UInt uiAddrOffset = trHeight * uiStride;
+    UInt uiCoefOffset = trWidth * trHeight;
+    UInt uiPartOffset = pcCU->getTotalNumPart() >> ( uiTrMode << 1 );    
+    UInt uiInterTUSplitDirection = pcCU->getInterTUSplitDirection ( trWidth, trHeight, trLastWidth, trLastHeight );
+    if( uiInterTUSplitDirection != 2 )
+    {
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr                                                                                            , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr +     trWidth * uiInterTUSplitDirection +     uiAddrOffset * ( 1 - uiInterTUSplitDirection), uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + 2 * trWidth * uiInterTUSplitDirection + 2 * uiAddrOffset * ( 1 - uiInterTUSplitDirection), uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + 3 * trWidth * uiInterTUSplitDirection + 3 * uiAddrOffset * ( 1 - uiInterTUSplitDirection), uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff );
+    }
+    else
+    {
+      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 );
+    }
+  }
+}
+
+// ------------------------------------------------------------------------------------------------
+// Logical transform
+// ------------------------------------------------------------------------------------------------
+
+/** Wrapper function between HM interface and core NxN forward transform (2D) 
+ *  \param piBlkResi input data (residual)
+ *  \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
+ */
+Void TComTrQuant::xT( UInt uiMode, Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int iWidth, Int iHeight )
+{
+#if MATRIX_MULT  
+  Int iSize = iWidth; 
+  if( iWidth != iHeight)
+  {
+    xTrMxN( piBlkResi, psCoeff, uiStride, (UInt)iWidth, (UInt)iHeight );
+    return;
+  }
+  xTr(piBlkResi,psCoeff,uiStride,(UInt)iSize,uiMode);
+#else
+  Int j;
+  {
+    short block[ 64 * 64 ];
+    short coeff[ 64 * 64 ];
+    {
+      for (j = 0; j < iHeight; j++)
+      {    
+        memcpy( block + j * iWidth, piBlkResi + j * uiStride, iWidth * sizeof( short ) );      
+      }
+    }
+    xTrMxN( block, coeff, iWidth, iHeight, uiMode );
+    for ( j = 0; j < iHeight * iWidth; j++ )
+    {    
+      psCoeff[ j ] = coeff[ j ];
+    }
+    return ;
+  }
+#endif  
+}
+
+/** Wrapper function between HM interface and core NxN inverse transform (2D) 
+ *  \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
+ */
+Void TComTrQuant::xIT( UInt uiMode, Int* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight )
+{
+#if MATRIX_MULT  
+  Int iSize = iWidth;
+  if( iWidth != iHeight )
+  {
+    xITrMxN( plCoef, pResidual, uiStride, (UInt)iWidth, (UInt)iHeight );
+    return;
+  }
+  xITr(plCoef,pResidual,uiStride,(UInt)iSize,uiMode);
+#else
+  Int j;
+  {
+    short block[ 64 * 64 ];
+    short coeff[ 64 * 64 ];
+    for ( j = 0; j < iHeight * iWidth; j++ )
+    {    
+      coeff[j] = (short)plCoef[j];
+    }
+    xITrMxN( coeff, block, iWidth, iHeight, uiMode );
+    {
+      for ( j = 0; j < iHeight; j++ )
+      {    
+        memcpy( pResidual + j * uiStride, block + j * iWidth, iWidth * sizeof(short) );      
+      }
+    }
+    return ;
+  }
+#endif  
+}
+ 
+/** RDOQ with CABAC
+ * \param pcCU pointer to coding unit structure
+ * \param plSrcCoeff pointer to input buffer
+ * \param piDstCoeff reference to pointer to output buffer
+ * \param uiWidth block width
+ * \param uiHeight block height
+ * \param uiAbsSum reference to absolute sum of quantized transform coefficient
+ * \param eTType plane type / luminance or chrominance
+ * \param uiAbsPartIdx absolute partition index
+ * \returns Void
+ * Rate distortion optimized quantization for entropy
+ * coding engines using probability models like CABAC
+ */
+Void TComTrQuant::xRateDistOptQuant                 ( TComDataCU*                     pcCU,
+                                                      Int*                            plSrcCoeff,
+                                                      TCoeff*                         piDstCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                                      Int*&                           piArlDstCoeff,
+#endif
+                                                      UInt                            uiWidth,
+                                                      UInt                            uiHeight,
+                                                      UInt&                           uiAbsSum,
+                                                      TextType                        eTType,
+                                                      UInt                            uiAbsPartIdx )
+{
+  Int    iQBits      = m_cQP.m_iBits;
+  Double dTemp       = 0;
+  
+  UInt dir         = SCALING_LIST_SQT;
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiWidth ] + 2;
+  Int uiQ = g_quantScales[m_cQP.rem()];
+  if (uiWidth != uiHeight)
+  {
+    uiLog2TrSize += (uiWidth > uiHeight) ? -1 : 1;
+    dir            = ( uiWidth < uiHeight )?  SCALING_LIST_VER: SCALING_LIST_HOR;
+  }
+  
+#if FULL_NBIT
+  UInt uiBitDepth = g_uiBitDepth;
+#else
+  UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;  
+#endif
+  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];
+  assert(scalingListType < 6);
+ 
+  iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+  double dErrScale   = 0;
+  double *pdErrScaleOrg = getErrScaleCoeff(scalingListType,uiLog2TrSize-2,m_cQP.m_iRem,dir);
+  Int *piQCoefOrg = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2,dir);
+  Int *piQCoef = piQCoefOrg;
+  double *pdErrScale = pdErrScaleOrg;
+#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 (uiScanIdx == SCAN_ZIGZAG)
+  {
+    // Map value zigzag to diagonal scan
+    uiScanIdx = SCAN_DIAG;
+  }
+  Int blockType = uiLog2BlkSize;
+  if (uiWidth != uiHeight)
+  {
+    uiScanIdx = SCAN_DIAG;
+    blockType = 4;
+  }
+  
+#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;
+  if (uiWidth == uiHeight)
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize > 3 ? uiLog2BlkSize-2-1 : 0  ];
+    if( uiLog2BlkSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlkSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+  else
+  {
+    scanCG = g_sigCGScanNSQT[ uiLog2BlkSize - 2 ];
+  }
+  const UInt uiCGSize = (1 << MLS_CG_SIZE);         // 16
+  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;
+  Int     c2                  = 0;
+  UInt    uiNumOne            = 0;
+  Double  d64BaseCost         = 0;
+  Int     iLastScanPos        = -1;
+  dTemp                       = dErrScale;
+
+  UInt    c1Idx     = 0;
+  UInt    c2Idx     = 0;
+  Int     baseLevel;
+
+  const UInt * scan;
+  if (uiWidth == uiHeight)
+  {
+    scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize - 1 ];    
+  }
+  else
+  {
+    scan = g_sigScanNSQT[ uiLog2BlkSize - 2 ];
+  }
+
+    ::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;     
+
+    for (Int iCGScanPos = uiCGNum-1; iCGScanPos >= 0; iCGScanPos--)
+    {
+      UInt uiCGBlkPos = scanCG[ iCGScanPos ];
+      UInt uiCGPosY   = uiCGBlkPos / uiNumBlkSide;
+      UInt uiCGPosX   = uiCGBlkPos - (uiCGPosY * uiNumBlkSide);
+      if( uiWidth == 8 && uiHeight == 8 && (uiScanIdx == SCAN_HOR || uiScanIdx == SCAN_VER) )
+      {
+        uiCGPosY = (uiScanIdx == SCAN_HOR ? uiCGBlkPos : 0);
+        uiCGPosX = (uiScanIdx == SCAN_VER ? uiCGBlkPos : 0);
+      }
+      ::memset( &rdStats, 0, sizeof (coeffGroupRDStats));
+        
+      for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+      {
+        iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
+        //===== quantization =====
+        UInt    uiBlkPos          = scan[iScanPos];
+        // set coeff
+        uiQ  = piQCoef[uiBlkPos];
+        dTemp = pdErrScale[uiBlkPos];
+        Int lLevelDouble          = plSrcCoeff[ uiBlkPos ];
+        lLevelDouble              = (Int)min<Int64>((Int64)abs((Int)lLevelDouble) * uiQ , MAX_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;
+        d64BlockUncodedCost      += pdCostCoeff0[ iScanPos ];
+        piDstCoeff[ uiBlkPos ]    = uiMaxAbsLevel;
+
+        if ( uiMaxAbsLevel > 0 && iLastScanPos < 0 )
+        {
+          iLastScanPos            = iScanPos;
+          uiCtxSet                = (iScanPos < SCAN_SET_SIZE || eTType!=TEXT_LUMA) ? 0 : 2;
+          iCGLastScanPos          = iCGScanPos;
+        }
+
+        if ( iLastScanPos >= 0 )
+        {
+          //===== coefficient level estimation =====
+          UInt  uiLevel;
+          UInt  uiOneCtx         = 4 * uiCtxSet + c1;
+          UInt  uiAbsCtx         = uiCtxSet + c2;
+
+          if( iScanPos == iLastScanPos )
+          {
+            uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ], 
+                                                   lLevelDouble, uiMaxAbsLevel, 0, uiOneCtx, uiAbsCtx, uiGoRiceParam, 
+                                                   c1Idx, c2Idx, iQBits, dTemp, 1 );
+          }
+          else
+          {
+            UInt   uiPosY        = uiBlkPos >> uiLog2BlkSize;
+            UInt   uiPosX        = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+            UShort uiCtxSig      = getSigCtxInc( piDstCoeff, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+            uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
+                                                   lLevelDouble, uiMaxAbsLevel, uiCtxSig, uiOneCtx, uiAbsCtx, uiGoRiceParam, 
+                                                   c1Idx, c2Idx, iQBits, dTemp, 0 );
+            sigRateDelta[ uiBlkPos ] = m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 1 ] - m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 0 ];
+          }
+          deltaU[ uiBlkPos ]        = (lLevelDouble - ((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;
+          }
+          else // uiLevel == 0
+          {
+            rateIncUp   [ uiBlkPos ] = m_pcEstBitsSbac->m_greaterOneBits[ uiOneCtx ][ 0 ];
+          }
+          piDstCoeff[ uiBlkPos ] = uiLevel;
+          d64BaseCost           += pdCostCoeff [ iScanPos ];
+
+
+          baseLevel = (c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+          if( uiLevel >= baseLevel )
+          {
+            uiGoRiceParam = g_aauiGoRiceUpdate[ uiGoRiceParam ][ min<UInt>( uiLevel - baseLevel , 23 ) ];
+          }
+          if ( uiLevel >= 1)
+          {
+            c1Idx ++;
+          }
+
+          //===== update bin model =====
+          if( uiLevel > 1 )
+          {
+            c1 = 0; 
+            c2 += (c2 < 2);
+            uiNumOne++;
+            c2Idx ++;
+          }
+          else if( (c1 < 3) && (c1 > 0) && uiLevel)
+          {
+            c1++;
+          }
+
+          //===== context set update =====
+          if( ( iScanPos % SCAN_SET_SIZE == 0 ) && ( iScanPos > 0 ) )
+          {
+            c1                = 1;
+            c2                = 0;
+            uiGoRiceParam     = 0;
+
+            c1Idx   = 0;
+            c2Idx   = 0; 
+            uiCtxSet          = (iScanPos == SCAN_SET_SIZE || eTType!=TEXT_LUMA) ? 0 : 2;
+            if( uiNumOne > 0 )
+            {
+              uiCtxSet++;
+            }
+            uiNumOne    >>= 1;
+          }
+        }
+        else
+        {
+          d64BaseCost    += pdCostCoeff0[ iScanPos ];
+        }
+        rdStats.d64SigCost += pdCostSig[ iScanPos ];
+        if (iScanPosinCG == 0 )
+        {
+          rdStats.d64SigCost_0 = pdCostSig[ iScanPos ];
+        }
+        if (piDstCoeff[ uiBlkPos ] )
+        {
+          uiSigCoeffGroupFlag[ uiCGBlkPos ] = 1;
+          rdStats.d64CodedLevelandDist += pdCostCoeff[ iScanPos ] - pdCostSig[ iScanPos ];
+          rdStats.d64UncodedDist += pdCostCoeff0[ iScanPos ];
+          if ( iScanPosinCG != 0 )
+          {
+            rdStats.iNNZbeforePos0++;
+          }
+        }
+      } //end for (iScanPosinCG)
+
+      if (iCGLastScanPos >= 0) 
+      {
+        if( iCGScanPos )
+        {
+          if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
+          {
+            UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiScanIdx, uiWidth, uiHeight);
+            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 ) 
+              {
+                d64BaseCost -= rdStats.d64SigCost_0;
+                rdStats.d64SigCost -= rdStats.d64SigCost_0;
+              }
+              // rd-cost if SigCoeffGroupFlag = 0, initialization
+              Double d64CostZeroCG = d64BaseCost;
+
+              // add SigCoeffGroupFlag cost to total cost
+              UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiScanIdx, uiWidth, uiHeight);
+              if (iCGScanPos < iCGLastScanPos)
+              {
+                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 )      
+              {
+                uiSigCoeffGroupFlag[ uiCGBlkPos ] = 0;
+                d64BaseCost = d64CostZeroCG;
+                if (iCGScanPos < iCGLastScanPos)
+                {
+                  pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig); 
+                }
+                // reset coeffs to 0 in this block                
+                for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+                {
+                  iScanPos      = iCGScanPos*uiCGSize + iScanPosinCG;
+                  UInt uiBlkPos = scan[ iScanPos ];
+
+                  if (piDstCoeff[ uiBlkPos ])
+                  {
+                    piDstCoeff [ uiBlkPos ] = 0;
+                    pdCostCoeff[ iScanPos ] = pdCostCoeff0[ iScanPos ];
+                    pdCostSig  [ iScanPos ] = 0;
+                  }
+                }
+              } // end if ( d64CostAllZeros < d64BaseCost )      
+            }
+          } // end if if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
+        }
+        else
+        {
+          uiSigCoeffGroupFlag[ uiCGBlkPos ] = 1;
+        }
+      }
+    } //end for (iCGScanPos)
+
+  //===== estimate last position =====
+  if ( iLastScanPos < 0 )
+  {
+    return;
+  }
+
+  Double  d64BestCost         = 0;
+  Int     ui16CtxCbf          = 0;
+  Int     iBestLastIdxP1      = 0;
+  if( !pcCU->isIntra( uiAbsPartIdx ) && eTType == TEXT_LUMA && pcCU->getTransformIdx( uiAbsPartIdx ) == 0 )
+  {
+    ui16CtxCbf   = 0;
+    d64BestCost  = d64BlockUncodedCost + xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 0 ] );
+    d64BaseCost += xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 1 ] );
+  }
+  else
+  {
+    ui16CtxCbf   = pcCU->getCtxQtCbf( uiAbsPartIdx, eTType, pcCU->getTransformIdx( uiAbsPartIdx ) );
+    ui16CtxCbf   = ( eTType ? TEXT_CHROMA : eTType ) * NUM_QT_CBF_CTX + ui16CtxCbf;
+    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 ]; 
+      if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
+      {     
+        for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+        {
+          iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
+          if (iScanPos > iLastScanPos) continue;
+          UInt   uiBlkPos     = scan[iScanPos];
+
+          if( piDstCoeff[ uiBlkPos ] )
+          {
+            UInt   uiPosY       = uiBlkPos >> uiLog2BlkSize;
+            UInt   uiPosX       = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+
+            Double d64CostLast= uiScanIdx == SCAN_VER ? xGetRateLast( uiPosY, uiPosX, uiWidth ) : xGetRateLast( uiPosX, uiPosY, uiWidth );
+            Double totalCost = d64BaseCost + d64CostLast - pdCostSig[ iScanPos ];
+
+            if( totalCost < d64BestCost )
+            {
+              iBestLastIdxP1  = iScanPos + 1;
+              d64BestCost     = totalCost;
+            }
+            if( piDstCoeff[ uiBlkPos ] > 1 )
+            {
+              bFoundLast = true;
+              break;
+            }
+            d64BaseCost      -= pdCostCoeff[ iScanPos ];
+            d64BaseCost      += pdCostCoeff0[ iScanPos ];
+          }
+          else
+          {
+            d64BaseCost      -= pdCostSig[ iScanPos ];
+          }
+        } //end for 
+        if (bFoundLast)
+        {
+          break;
+        }
+      } // end if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
+    } // end for 
+
+  for ( Int scanPos = 0; scanPos < iBestLastIdxP1; scanPos++ )
+  {
+    Int blkPos = scan[ scanPos ];
+    Int 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;
+  }
+
+  if( pcCU->getSlice()->getPPS()->getSignHideFlag() && uiAbsSum>=2)
+  {
+    Int rdFactor = (Int)((Double)(g_invQuantScales[m_cQP.rem()]*g_invQuantScales[m_cQP.rem()]<<(2*m_cQP.m_iPer))/m_dLambda/16 + 0.5) ;
+
+    Int tsig = pcCU->getSlice()->getPPS()->getTSIG() ;
+
+    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 ;
+      absSum = 0 ;
+
+      for(n = SCAN_SET_SIZE-1; n >= 0; --n )
+      {
+        if( piDstCoeff[ scan[ n + subPos ]] )
+        {
+          lastNZPosInCG = n;
+          break;
+        }
+      }
+
+      for(n = 0; n <SCAN_SET_SIZE; n++ )
+      {
+        if( piDstCoeff[ scan[ n + subPos ]] )
+        {
+          firstNZPosInCG = n;
+          break;
+        }
+      }
+
+      for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
+      {
+        absSum += piDstCoeff[ scan[ n + subPos ]];
+      }
+
+      if(lastNZPosInCG>=0 && lastCG==-1) lastCG =1 ; 
+      
+      if( lastNZPosInCG-firstNZPosInCG>=tsig )
+      {
+        UInt signbit = (piDstCoeff[scan[subPos+firstNZPosInCG]]>0?0:1);
+        if( signbit!=(absSum&0x1) )  // hide but need tune
+        {
+          // calculate the cost 
+          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 uiBlkPos   = scan[ n + subPos ];
+            if(piDstCoeff[ uiBlkPos ] != 0 )
+            {
+              Int costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos] ;
+              Int costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos] 
+                -   ( abs(piDstCoeff[uiBlkPos])==1?((1<<15)+sigRateDelta[uiBlkPos]):0 );
+
+              if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1)
+              {
+                costDown -= (4<<15) ;
+              }
+
+              if(costUp<costDown)
+              {  
+                curCost = costUp;
+                curChange =  1 ;
+              }
+              else               
+              {
+                curChange = -1 ;
+                if(n==firstNZPosInCG && abs(piDstCoeff[uiBlkPos])==1)
+                {
+                  curCost = MAX_INT ;
+                }
+                else
+                {
+                  curCost = costDown ; 
+                }
+              }
+            }
+            else
+            {
+              curCost = rdFactor * ( - (abs(deltaU[uiBlkPos])) ) + (1<<15) + rateIncUp[uiBlkPos] + sigRateDelta[uiBlkPos] ; 
+              curChange = 1 ;
+
+              if(n<firstNZPosInCG)
+              {
+                UInt thissignbit = (plSrcCoeff[uiBlkPos]>=0?0:1);
+                if(thissignbit != signbit )
+                {
+                  curCost = MAX_INT;
+                }
+              }
+            }
+
+            if( curCost<minCostInc)
+            {
+              minCostInc = curCost ;
+              finalChange = curChange ;
+              minPos = uiBlkPos ;
+            }
+          }
+
+          if(piQCoef[minPos] == 32767 || piQCoef[minPos] == -32768)
+          {
+            finalChange = -1;
+          }
+
+          if(plSrcCoeff[minPos]>=0)
+          {
+            piDstCoeff[minPos] += finalChange ;
+          }
+          else
+          {
+            piDstCoeff[minPos] -= finalChange ; 
+          }          
+        }
+      }
+
+      if(lastCG==1)
+      {
+        lastCG=0 ;  
+      }
+    }
+  }
+}
+
+/** Context derivation process of coeff_abs_significant_flag
+ * \param pcCoeff pointer to prior coded transform coefficients
+ * \param posX column of current scan position
+ * \param posY row of current scan position
+ * \param blockType log2 value of block size if square block, or 4 otherwise
+ * \param width width of the block
+ * \param height height of the block
+ * \param textureType texture type (TEXT_LUMA...)
+ * \returns ctxInc for current scan position
+ */
+Int TComTrQuant::getSigCtxInc    ( TCoeff*                         pcCoeff,
+                                   Int                             posX,
+                                   Int                             posY,
+                                   Int                             blockType,
+                                   Int                             width
+                                  ,Int                             height
+                                  ,TextType                        textureType
+                                  )
+{
+  if ( blockType == 2 )
+  {
+    //LUMA map
+    const Int ctxIndMap4x4Luma[15] =
+    {
+      0, 1, 4, 5,
+      2, 3, 4, 5,
+      6, 6, 8, 8,
+      7, 7, 8
+    };
+    //CHROMA map
+    const Int ctxIndMap4x4Chroma[15] =
+    {
+      0, 1, 2, 4,
+      1, 1, 2, 4,
+      3, 3, 5, 5,
+      4, 4, 5
+    };
+
+    if (textureType == TEXT_LUMA)
+    {
+      return ctxIndMap4x4Luma[ 4 * posY + posX ];
+    }
+    else
+    {
+      return ctxIndMap4x4Chroma[ 4 * posY + posX ];
+    }
+  }
+  
+  if ( blockType == 3 )
+  {
+    const Int map8x8[16] =
+    {
+      0,  1,  2,  3,
+      4,  5,  6,  3,
+      8,  6,  6,  7,
+      9,  9,  7,  7
+    };
+    
+    Int offset = (textureType == TEXT_LUMA) ? 9 : 6;
+
+    if ( posX + posY == 0 )
+    {
+      return offset + 10;
+    }
+    return offset + map8x8[4 * (posY >> 1) + (posX >> 1)];
+  }
+
+  Int offset = (textureType == TEXT_LUMA) ? 20 : 17;
+  if( posX + posY == 0 )
+  {
+    return offset;
+  }
+#if SIGMAP_CONST_AT_HIGH_FREQUENCY
+  Int thredHighFreq = 3*(std::max(width, height)>>4);
+  if ((posX>>2) + (posY>>2) >= thredHighFreq)
+  {
+    return (textureType == TEXT_LUMA) ? 24 : 18;
+  }
+#endif
+  
+  const TCoeff *pData = pcCoeff + posX + posY * width;
+  
+  
+  Int cnt = 0;
+  if( posX < width - 1 )
+  {
+    cnt += pData[1] != 0;
+    if( posY < height - 1 )
+    {
+      cnt += pData[width+1] != 0;
+    }
+    if( posX < width - 2 )
+    {
+      cnt += pData[2] != 0;
+    }
+  }
+  if ( posY < height - 1 )
+  {
+    if( ( ( posX & 3 ) || ( posY & 3 ) ) && ( ( (posX+1) & 3 ) || ( (posY+2) & 3 ) ) )
+    {
+      cnt += pData[width] != 0;
+    }
+    if ( posY < height - 2 && cnt < 4 )
+    {
+      cnt += pData[2*width] != 0;
+    }
+  }
+
+  cnt = ( cnt + 1 ) >> 1;
+  return (( textureType == TEXT_LUMA && ((posX>>2) + (posY>>2)) > 0 ) ? 4 : 1) + offset + cnt;
+}
+
+/** 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; 
+  UInt   uiBestAbsLevel = 0;
+  
+  if( !bLast && uiMaxAbsLevel < 3 )
+  {
+    rd64CodedCostSig    = xGetRateSigCoef( 0, ui16CtxNumSig ); 
+    rd64CodedCost       = rd64CodedCost0 + rd64CodedCostSig;
+    if( uiMaxAbsLevel == 0 )
+    {
+      return uiBestAbsLevel;
+    }
+  }
+  else
+  {
+    rd64CodedCost       = MAX_DOUBLE;
+  }
+
+  if( !bLast )
+  {
+    dCurrCostSig        = xGetRateSigCoef( 1, ui16CtxNumSig );
+  }
+
+  UInt uiMinAbsLevel    = ( uiMaxAbsLevel > 1 ? uiMaxAbsLevel - 1 : 1 );
+  for( Int uiAbsLevel  = uiMaxAbsLevel; uiAbsLevel >= uiMinAbsLevel ; uiAbsLevel-- )
+  {
+    Double dErr         = Double( lLevelDouble  - ( uiAbsLevel << iQBits ) );
+    Double dCurrCost    = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx );
+    dCurrCost          += dCurrCostSig;
+
+    if( dCurrCost < rd64CodedCost )
+    {
+      uiBestAbsLevel    = uiAbsLevel;
+      rd64CodedCost     = dCurrCost;
+      rd64CodedCostSig  = dCurrCostSig;
+    }
+  }
+
+  return uiBestAbsLevel;
+}
+
+/** 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 ui16AbsGoRice Rice parameter for coeff_abs_level_minus3
+ * \returns cost of given absolute transform level
+ */
+__inline Double TComTrQuant::xGetICRateCost  ( UInt                            uiAbsLevel,
+                                               UShort                          ui16CtxNumOne,
+                                               UShort                          ui16CtxNumAbs,
+                                               UShort                          ui16AbsGoRice
+                                            ,  UInt                            c1Idx,
+                                               UInt                            c2Idx
+                                               ) const
+{
+  Double iRate = xGetIEPRate();
+  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+
+  if ( uiAbsLevel >= baseLevel )
+  {
+    UInt uiSymbol     = uiAbsLevel - baseLevel;
+    UInt uiMaxVlc     = g_auiGoRiceRange[ ui16AbsGoRice ];
+    Bool bExpGolomb   = ( uiSymbol > uiMaxVlc );
+
+    if( bExpGolomb )
+    {
+      uiAbsLevel  = uiSymbol - uiMaxVlc;
+      int iEGS    = 1;  for( UInt uiMax = 2; uiAbsLevel >= uiMax; uiMax <<= 1, iEGS += 2 );
+      iRate      += iEGS << 15;
+      uiSymbol    = min<UInt>( uiSymbol, ( uiMaxVlc + 1 ) );
+    }
+
+    UShort ui16PrefLen = UShort( uiSymbol >> ui16AbsGoRice ) + 1;
+    UShort ui16NumBins = min<UInt>( ui16PrefLen, g_auiGoRicePrefixLen[ ui16AbsGoRice ] ) + ui16AbsGoRice;
+
+    iRate += ui16NumBins << 15;
+
+    if (c1Idx < C1FLAG_NUMBER)
+    {
+      iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+
+      if (c2Idx < C2FLAG_NUMBER)
+      {
+        iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 1 ];
+      }
+    }
+  }
+  else
+  if( uiAbsLevel == 1 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
+  }
+  else if( uiAbsLevel == 2 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 0 ];
+  }
+  else
+  {
+    assert (0);
+  }
+  return xGetICost( iRate );
+}
+
+__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
+                                       UShort                          ui16CtxNumOne,
+                                       UShort                          ui16CtxNumAbs,
+                                       UShort                          ui16AbsGoRice
+                                     , UInt                            c1Idx,
+                                       UInt                            c2Idx
+                                       ) const
+{
+  Int iRate = 0;
+  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+
+  if ( uiAbsLevel >= baseLevel )
+  {
+    UInt uiSymbol     = uiAbsLevel - baseLevel;
+    UInt uiMaxVlc     = g_auiGoRiceRange[ ui16AbsGoRice ];
+    Bool bExpGolomb   = ( uiSymbol > uiMaxVlc );
+
+    if( bExpGolomb )
+    {
+      uiAbsLevel  = uiSymbol - uiMaxVlc;
+      int iEGS    = 1;  for( UInt uiMax = 2; uiAbsLevel >= uiMax; uiMax <<= 1, iEGS += 2 );
+      iRate      += iEGS << 15;
+      uiSymbol    = min<UInt>( uiSymbol, ( uiMaxVlc + 1 ) );
+    }
+
+    UShort ui16PrefLen = UShort( uiSymbol >> ui16AbsGoRice ) + 1;
+    UShort ui16NumBins = min<UInt>( ui16PrefLen, g_auiGoRicePrefixLen[ ui16AbsGoRice ] ) + ui16AbsGoRice;
+
+    iRate += ui16NumBins << 15;
+
+    if (c1Idx < C1FLAG_NUMBER)
+    {
+      iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+
+      if (c2Idx < C2FLAG_NUMBER)
+      {
+        iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 1 ];
+      }
+    }
+  }
+  else
+  if( uiAbsLevel == 0 )
+  {
+    return 0;
+  }
+  else if( uiAbsLevel == 1 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
+  }
+  else if( uiAbsLevel == 2 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 0 ];
+  }
+  else
+  {
+    assert(0);
+  }
+  return iRate;
+}
+
+__inline Double TComTrQuant::xGetRateSigCoeffGroup  ( UShort                    uiSignificanceCoeffGroup,
+                                                UShort                          ui16CtxNumSig ) const
+{
+  return xGetICost( m_pcEstBitsSbac->significantCoeffGroupBits[ ui16CtxNumSig ][ uiSignificanceCoeffGroup ] );
+}
+
+/** Calculates the cost of signaling the last significant coefficient in the block
+ * \param uiPosX X coordinate of the last significant coefficient
+ * \param uiPosY Y coordinate of the last significant coefficient
+ * \returns cost of last significant coefficient
+ */
+/*
+ * \param uiWidth width of the transform unit (TU)
+*/
+__inline Double TComTrQuant::xGetRateLast   ( const UInt                      uiPosX,
+                                              const UInt                      uiPosY,
+                                              const UInt                      uiBlkWdth     ) const
+{
+  UInt uiCtxX   = g_uiGroupIdx[uiPosX];
+  UInt uiCtxY   = g_uiGroupIdx[uiPosY];
+  Double uiCost = m_pcEstBitsSbac->lastXBits[ uiCtxX ] + m_pcEstBitsSbac->lastYBits[ uiCtxY ];
+  if( uiCtxX > 3 )
+  {
+    uiCost += xGetIEPRate() * ((uiCtxX-2)>>1);
+  }
+  if( uiCtxY > 3 )
+  {
+    uiCost += xGetIEPRate() * ((uiCtxY-2)>>1);
+  }
+  return xGetICost( uiCost );
+}
+
+ /** 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
+{
+  return xGetICost( m_pcEstBitsSbac->significantBits[ ui16CtxNumSig ][ uiSignificance ] );
+}
+
+/** Get the cost for a specific rate
+ * \param dRate rate of a bit
+ * \returns cost at the specific rate
+ */
+__inline Double TComTrQuant::xGetICost        ( Double                          dRate         ) const
+{
+  return m_dLambda * dRate;
+}
+
+/** Get the cost of an equal probable bit
+ * \returns cost of equal probable bit
+ */
+__inline Double TComTrQuant::xGetIEPRate      (                                               ) const
+{
+  return 32768;
+}
+
+/** 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
+ * \returns ctxInc for current scan position
+ */
+UInt TComTrQuant::getSigCoeffGroupCtxInc  ( const UInt*               uiSigCoeffGroupFlag,
+                                           const UInt                      uiCGPosX,
+                                           const UInt                      uiCGPosY,
+                                           const UInt                      scanIdx,
+                                           Int width, Int height)
+{
+  UInt uiRight = 0;
+  UInt uiLower = 0;
+
+  width >>= 2;
+  height >>= 2;
+  if( width == 2 && height == 2 ) // 8x8
+  {
+    if( scanIdx == SCAN_HOR )  
+    {
+      width = 1;
+      height = 4;
+    }
+    else if( scanIdx == SCAN_VER )
+    {
+      width = 4;
+      height = 1;
+    }
+  }
+  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);
+
+}
+/** set quantized matrix coefficient for encode
+ * \param scalingList quantaized matrix address
+ */
+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++)
+      {
+        xSetScalingListEnc(scalingList,list,size,qp);
+        xSetScalingListDec(scalingList,list,size,qp);
+        setErrScaleCoeff(list,size,qp,SCALING_LIST_SQT);
+        if(size == SCALING_LIST_32x32 || size == SCALING_LIST_16x16)
+        {
+          setErrScaleCoeff(list,size-1,qp,SCALING_LIST_HOR);
+          setErrScaleCoeff(list,size-1,qp,SCALING_LIST_VER);
+        }
+      }
+    }
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param scalingList quantaized matrix address
+ */
+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 dir)
+{
+
+  UInt uiLog2TrSize = g_aucConvertToBit[ g_scalingListSizeX[size] ] + 2;
+#if FULL_NBIT
+  UInt uiBitDepth = g_uiBitDepth;
+#else
+  UInt uiBitDepth = g_uiBitDepth + g_uiBitIncrement;  
+#endif
+
+  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+
+  UInt i,uiMaxNumCoeff = g_scalingListSize[size];
+  Int *piQuantcoeff;
+  double *pdErrScale;
+  piQuantcoeff   = getQuantCoeff(list, qp,size,dir);
+  pdErrScale     = getErrScaleCoeff(list, size, qp,dir);
+
+  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/(double)piQuantcoeff[i]/(double)piQuantcoeff[i]/(double)(1<<(2*g_uiBitIncrement));
+  }
+}
+
+/** set quantized matrix coefficient for encode
+ * \param scalingList quantaized matrix address
+ * \param listId List index
+ * \param sizeId size index
+ * \param uiQP Quantization parameter
+ */
+Void TComTrQuant::xSetScalingListEnc(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]);
+  Int *quantcoeff;
+  Int *coeff = scalingList->getScalingListAddress(sizeId,listId);
+  quantcoeff   = getQuantCoeff(listId, qp, sizeId, SCALING_LIST_SQT);
+
+  processScalingListEnc(coeff,quantcoeff,g_quantScales[qp]<<4,height,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+  if(sizeId == SCALING_LIST_32x32 || sizeId == SCALING_LIST_16x16) //for NSQT
+  {
+    quantcoeff   = getQuantCoeff(listId, qp, sizeId-1,SCALING_LIST_VER);
+    processScalingListEnc(coeff,quantcoeff,g_quantScales[qp]<<4,height,width>>2,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+    quantcoeff   = getQuantCoeff(listId, qp, sizeId-1,SCALING_LIST_HOR);
+    processScalingListEnc(coeff,quantcoeff,g_quantScales[qp]<<4,height>>2,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]);
+  Int *dequantcoeff;
+  Int *coeff = scalingList->getScalingListAddress(sizeId,listId);
+
+  dequantcoeff = getDequantCoeff(listId, qp, sizeId,SCALING_LIST_SQT);
+  processScalingListDec(coeff,dequantcoeff,g_invQuantScales[qp],height,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+  if(sizeId == SCALING_LIST_32x32 || sizeId == SCALING_LIST_16x16)
+  {
+    dequantcoeff   = getDequantCoeff(listId, qp, sizeId-1,SCALING_LIST_VER);
+    processScalingListDec(coeff,dequantcoeff,g_invQuantScales[qp],height,width>>2,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+    dequantcoeff   = getDequantCoeff(listId, qp, sizeId-1,SCALING_LIST_HOR);
+
+    processScalingListDec(coeff,dequantcoeff,g_invQuantScales[qp],height>>2,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++)
+      {
+        xsetFlatScalingList(list,size,qp);
+        setErrScaleCoeff(list,size,qp,SCALING_LIST_SQT);
+        if(size == SCALING_LIST_32x32 || size == SCALING_LIST_16x16)
+        {
+          setErrScaleCoeff(list,size-1,qp,SCALING_LIST_HOR);
+          setErrScaleCoeff(list,size-1,qp,SCALING_LIST_VER);
+        }
+      }
+    }
+  }
+}
+
+/** set flat matrix value to quantized coefficient
+ * \param list List ID
+ * \param uiQP Quantization parameter
+ * \param uiSize Size
+ */
+Void TComTrQuant::xsetFlatScalingList(UInt list, UInt size, UInt qp)
+{
+  UInt i,num = g_scalingListSize[size];
+  UInt numDiv4 = num>>2;
+  Int *quantcoeff;
+  Int *dequantcoeff;
+  Int quantScales = g_quantScales[qp];
+  Int invQuantScales = g_invQuantScales[qp]<<4;
+
+  quantcoeff   = getQuantCoeff(list, qp, size,SCALING_LIST_SQT);
+  dequantcoeff = getDequantCoeff(list, qp, size,SCALING_LIST_SQT);
+
+  for(i=0;i<num;i++)
+  { 
+    *quantcoeff++ = quantScales;
+    *dequantcoeff++ = invQuantScales;
+  }
+
+  if(size == SCALING_LIST_32x32 || size == SCALING_LIST_16x16)
+  {
+    quantcoeff   = getQuantCoeff(list, qp, size-1, SCALING_LIST_HOR);
+    dequantcoeff = getDequantCoeff(list, qp, size-1, SCALING_LIST_HOR);
+
+    for(i=0;i<numDiv4;i++)
+    {
+      *quantcoeff++ = quantScales;
+      *dequantcoeff++ = invQuantScales;
+    }
+    quantcoeff   = getQuantCoeff(list, qp, size-1 ,SCALING_LIST_VER);
+    dequantcoeff = getDequantCoeff(list, qp, size-1 ,SCALING_LIST_VER);
+
+    for(i=0;i<numDiv4;i++)
+    {
+      *quantcoeff++ = quantScales;
+      *dequantcoeff++ = invQuantScales;
+    }
+  }
+}
+
+/** set quantized matrix coefficient for encode
+ * \param coeff quantaized matrix address
+ * \param quantcoeff quantaized matrix address
+ * \param quantScales Q(QP%6)
+ * \param height height
+ * \param width width
+ * \param ratio ratio for upscale
+ * \param sizuNum matrix size
+ * \param dc dc parameter
+ */
+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];
+    }
+  }
+  if(ratio > 1)
+  {
+    quantcoeff[0] = quantScales / dc;
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param coeff quantaized matrix address
+ * \param dequantcoeff quantaized matrix address
+ * \param invQuantScales IQ(QP%6))
+ * \param height height
+ * \param width width
+ * \param ratio ratio for upscale
+ * \param sizuNum matrix size
+ * \param dc dc parameter
+ */
+Void TComTrQuant::processScalingListDec( Int *coeff, Int *dequantcoeff, Int invQuantScales, 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++)
+    {
+      dequantcoeff[j*width + i] = invQuantScales * coeff[sizuNum * (j * nsqth / ratio) + i * nsqtw /ratio];
+    }
+  }
+  if(ratio > 1)
+  {
+    dequantcoeff[0] = invQuantScales * dc;
+  }
+}
+
+/** initialization process of scaling list array
+ */
+Void TComTrQuant::initScalingList()
+{
+  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][SCALING_LIST_SQT] = new Int [g_scalingListSize[sizeId]];
+        m_dequantCoef [sizeId][listId][qp][SCALING_LIST_SQT] = new Int [g_scalingListSize[sizeId]];
+        m_errScale    [sizeId][listId][qp][SCALING_LIST_SQT] = new double [g_scalingListSize[sizeId]];
+        
+        if(sizeId == SCALING_LIST_8x8 || (sizeId == SCALING_LIST_16x16 && listId < 2))
+        {
+          for(UInt dir = SCALING_LIST_VER; dir < SCALING_LIST_DIR_NUM; dir++)
+          {
+            m_quantCoef   [sizeId][listId][qp][dir] = new Int [g_scalingListSize[sizeId]];
+            m_dequantCoef [sizeId][listId][qp][dir] = new Int [g_scalingListSize[sizeId]];
+            m_errScale    [sizeId][listId][qp][dir] = new double [g_scalingListSize[sizeId]];
+          }
+        }
+      }
+    }
+  }
+  //copy for NSQT
+  for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+  {
+    for(UInt dir = SCALING_LIST_VER; dir < SCALING_LIST_DIR_NUM; dir++)
+    {
+      m_quantCoef   [SCALING_LIST_16x16][3][qp][dir] = m_quantCoef   [SCALING_LIST_16x16][1][qp][dir];
+      m_dequantCoef [SCALING_LIST_16x16][3][qp][dir] = m_dequantCoef [SCALING_LIST_16x16][1][qp][dir];
+      m_errScale    [SCALING_LIST_16x16][3][qp][dir] = m_errScale    [SCALING_LIST_16x16][1][qp][dir];
+    }
+    m_quantCoef   [SCALING_LIST_32x32][3][qp][SCALING_LIST_SQT] = m_quantCoef   [SCALING_LIST_32x32][1][qp][SCALING_LIST_SQT];
+    m_dequantCoef [SCALING_LIST_32x32][3][qp][SCALING_LIST_SQT] = m_dequantCoef [SCALING_LIST_32x32][1][qp][SCALING_LIST_SQT];
+    m_errScale    [SCALING_LIST_32x32][3][qp][SCALING_LIST_SQT] = m_errScale    [SCALING_LIST_32x32][1][qp][SCALING_LIST_SQT];
+  }
+}
+/** destroy quantization matrix array
+ */
+Void TComTrQuant::destroyScalingList()
+{
+  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++)
+      {
+        if(m_quantCoef   [sizeId][listId][qp][SCALING_LIST_SQT]) delete [] m_quantCoef   [sizeId][listId][qp][SCALING_LIST_SQT];
+        if(m_dequantCoef [sizeId][listId][qp][SCALING_LIST_SQT]) delete [] m_dequantCoef [sizeId][listId][qp][SCALING_LIST_SQT];
+        if(m_errScale    [sizeId][listId][qp][SCALING_LIST_SQT]) delete [] m_errScale    [sizeId][listId][qp][SCALING_LIST_SQT];
+        if(sizeId == SCALING_LIST_8x8 || (sizeId == SCALING_LIST_16x16 && listId < 2))
+        {
+          for(UInt dir = SCALING_LIST_VER; dir < SCALING_LIST_DIR_NUM; dir++)
+          {
+            if(m_quantCoef   [sizeId][listId][qp][dir]) delete [] m_quantCoef   [sizeId][listId][qp][dir];
+            if(m_dequantCoef [sizeId][listId][qp][dir]) delete [] m_dequantCoef [sizeId][listId][qp][dir];
+            if(m_errScale    [sizeId][listId][qp][dir]) delete [] m_errScale    [sizeId][listId][qp][dir];
+          }
+        }
+      }
+    }
+  }
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComTrQuant.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComTrQuant.h	(revision 341)
@@ -0,0 +1,307 @@
+/* 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-2012, 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     TComTrQuant.h
+    \brief    transform and quantization class (header)
+*/
+
+#ifndef __TCOMTRQUANT__
+#define __TCOMTRQUANT__
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComDataCU.h"
+#include "ContextTables.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define QP_BITS                 15
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+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 scanZigzag[2];            ///< flag for zigzag scan
+  Int scanNonZigzag[2];         ///< flag for non zigzag scan
+} estBitsSbacStruct;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// QP class
+class QpParam
+{
+public:
+  QpParam();
+  
+  Int m_iQP;
+  Int m_iPer;
+  Int m_iRem;
+  
+public:
+  Int m_iBits;
+    
+  Void setQpParam( Int qpScaled, Bool bLowpass, SliceType eSliceType )
+  {
+    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
+
+/// transform and quantization class
+class TComTrQuant
+{
+public:
+  TComTrQuant();
+  ~TComTrQuant();
+  
+  // initialize class
+  Void init                 ( UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxTrSize, Int iSymbolMode = 0, UInt *aTable4 = NULL, UInt *aTable8 = NULL, UInt *aTableLastPosVlcIndex=NULL, Bool bUseRDOQ = false,  Bool bEnc = 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 );
+#if LOSSLESS_CODING
+  Void invtransformNxN( TComDataCU* pcCU, TextType eText, UInt uiMode,Pel* rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight,  Int scalingListType);
+#else
+  Void invtransformNxN(                   TextType eText, UInt uiMode,Pel*& rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight, Int scalingListType);
+#endif
+  Void invRecurTransformNxN ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eTxt, Pel* rpcResidual, UInt uiAddr,   UInt uiStride, UInt uiWidth, UInt uiHeight,
+                             UInt uiMaxTrMode,  UInt uiTrMode, TCoeff* rpcCoeff );
+  
+  // Misc functions
+  Void setQPforQuant( Int qpy, Bool bLowpass, SliceType eSliceType, TextType eTxtType, Int qpBdOffset, Int chromaQPOffset);
+
+#if RDOQ_CHROMA_LAMBDA 
+  Void setLambda(Double dLambdaLuma, Double dLambdaChroma) { m_dLambdaLuma = dLambdaLuma; m_dLambdaChroma = dLambdaChroma; }
+  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_dLambdaLuma : m_dLambdaChroma; }
+#else
+  Void setLambda(Double dLambda) { m_dLambda = dLambda;}
+#endif
+  Void setRDOQOffset( UInt uiRDOQOffset ) { m_uiRDOQOffset = uiRDOQOffset; }
+  
+  estBitsSbacStruct* m_pcEstBitsSbac;
+  
+  static Int      getSigCtxInc     ( TCoeff*                         pcCoeff,
+                                     Int                             posX,
+                                     Int                             posY,
+                                     Int                             blockType,
+                                     Int                             width
+                                    ,Int                             height
+                                    ,TextType                        textureType
+                                    );
+  static UInt getSigCoeffGroupCtxInc  ( const UInt*                   uiSigCoeffGroupFlag,
+                                       const UInt                       uiCGPosX,
+                                       const UInt                       uiCGPosY,
+                                       const UInt                     scanIdx,
+                                       Int width, Int height);
+  Void initScalingList                      ();
+  Void destroyScalingList                   ();
+  Void setErrScaleCoeff    ( UInt list, UInt size, UInt qp, UInt dir);
+  double* getErrScaleCoeff ( UInt list, UInt size, UInt qp, UInt dir) {return m_errScale[size][list][qp][dir];};    //!< get Error Scale Coefficent
+  Int* getQuantCoeff       ( UInt list, UInt qp, UInt size, UInt dir) {return m_quantCoef[size][list][qp][dir];};   //!< get Quant Coefficent
+  Int* getDequantCoeff     ( UInt list, UInt qp, UInt size, UInt dir) {return m_dequantCoef[size][list][qp][dir];}; //!< 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);
+  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);
+#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 ;} 
+  Double* getSliceSumC()    { return m_sliceSumC; }
+#endif
+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;
+#if RDOQ_CHROMA_LAMBDA
+  Double   m_dLambdaLuma;
+  Double   m_dLambdaChroma;
+#endif
+  Double   m_dLambda;
+  UInt     m_uiRDOQOffset;
+  UInt     m_uiMaxTrSize;
+  Bool     m_bEnc;
+  Bool     m_bUseRDOQ;
+#if ADAPTIVE_QP_SELECTION
+  Bool     m_bUseAdaptQpSelect;
+#endif
+
+  Bool     m_scalingListEnabledFlag;
+  Int      *m_quantCoef      [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM][SCALING_LIST_DIR_NUM]; ///< array of quantization matrix coefficient 4x4
+  Int      *m_dequantCoef    [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM][SCALING_LIST_DIR_NUM]; ///< array of dequantization matrix coefficient 4x4
+  double   *m_errScale       [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM][SCALING_LIST_DIR_NUM]; ///< array of quantization matrix coefficient 4x4
+private:
+  // forward Transform
+  Void xT   ( UInt uiMode,Pel* pResidual, UInt uiStride, Int* plCoeff, Int iWidth, Int iHeight );
+  
+  Void signBitHidingHDQ( TComDataCU* pcCU, TCoeff* pQCoef, TCoeff* pCoef, UInt const *scan, Int* deltaU, Int width, Int height );
+
+  // 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 );
+
+  // 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 Double xGetICRateCost   ( UInt                            uiAbsLevel,
+                                     UShort                          ui16CtxNumOne,
+                                     UShort                          ui16CtxNumAbs,
+                                     UShort                          ui16AbsGoRice 
+                                   , UInt                            c1Idx,
+                                     UInt                            c2Idx
+                                     ) 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 UInt                      uiBlkWdth     ) 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( const TCoeff* pSrc, Int* pDes, Int iWidth, Int iHeight, Int scalingListType );
+  
+  // inverse transform
+  Void xIT    ( UInt uiMode, Int* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight );
+  
+};// END CLASS DEFINITION TComTrQuant
+
+//! \}
+
+#endif // __TCOMTRQUANT__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWedgelet.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 341)
@@ -0,0 +1,1189 @@
+/* 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-2011, 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 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 files
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComWedgelet.h"
+
+#include <stdlib.h>
+#include <memory.h>
+
+using namespace std;
+
+
+TComWedgelet::TComWedgelet( UInt uiWidth, UInt uiHeight ) : m_uhXs     ( 0 ),
+                                                            m_uhYs     ( 0 ),
+                                                            m_uhXe     ( 0 ),
+                                                            m_uhYe     ( 0 ),
+                                                            m_uhOri    ( 0 ),
+                                                            m_eWedgeRes( FULL_PEL )
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+                                                            , m_bIsCoarse( false )
+#endif
+{
+  create( uiWidth, uiHeight );
+}
+
+TComWedgelet::TComWedgelet( const TComWedgelet &rcWedge ) : m_uhXs     ( rcWedge.m_uhXs      ),
+                                                            m_uhYs     ( rcWedge.m_uhYs      ),
+                                                            m_uhXe     ( rcWedge.m_uhXe      ),
+                                                            m_uhYe     ( rcWedge.m_uhYe      ),
+                                                            m_uhOri    ( rcWedge.m_uhOri     ),
+                                                            m_eWedgeRes( rcWedge.m_eWedgeRes ),
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+                                                            m_bIsCoarse( rcWedge.m_bIsCoarse ),
+                                                            m_uiAng    ( rcWedge.m_uiAng     ),
+#endif
+                                                            m_uiWidth  ( rcWedge.m_uiWidth   ),
+                                                            m_uiHeight ( rcWedge.m_uiHeight  ),
+                                                            m_pbPattern( (Bool*)xMalloc( Bool, (m_uiWidth * m_uiHeight) ) )
+{
+  ::memcpy( m_pbPattern, rcWedge.m_pbPattern, sizeof(Bool) * (m_uiWidth * m_uiHeight));
+}
+
+TComWedgelet::~TComWedgelet(void)
+{
+  destroy();
+}
+
+Void TComWedgelet::create( UInt uiWidth, UInt uiHeight )
+{
+  assert( uiWidth > 0 && uiHeight > 0 );
+
+  m_uiWidth   = uiWidth;
+  m_uiHeight  = uiHeight;
+
+  m_pbPattern = (Bool*)xMalloc( Bool, (m_uiWidth * m_uiHeight) );
+}
+
+Void TComWedgelet::destroy()
+{
+  if( m_pbPattern ) { xFree( m_pbPattern ); m_pbPattern = NULL; }
+}
+
+Void TComWedgelet::clear()
+{
+  ::memset( m_pbPattern, 0, (m_uiWidth * m_uiHeight) * sizeof(Bool) );
+}
+
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+Void TComWedgelet::findClosetAngle()
+{
+  UInt uiAng=0,uiOptAng=0;
+  UInt uiMinD=MAX_UINT;
+  UInt uiTmpD=0;
+  Int angTable[9]    = {0,    2,    5,   9,  13,  17,  21,  26,  32};
+  
+  UChar uhXs = m_uhXs;
+  UChar uhYs = m_uhYs;
+  UChar uhXe = m_uhXe;
+  UChar uhYe = m_uhYe;
+
+  for(uiAng=2; uiAng<=34; uiAng++)
+  {
+    Int iSign    = (uiAng<VER_IDX && uiAng>HOR_IDX ) ? -1 : 1;
+    Int iVer     = uiAng>17 ? 32 : angTable[(uiAng>10) ? (uiAng-10) : (10-uiAng)];
+    Int iHor     = uiAng<19 ? 32 : angTable[(uiAng>26) ? (uiAng-26) : (26-uiAng)];
+
+    uiTmpD  = abs(iVer*iSign*(uhXs-uhXe) - iHor*(uhYe-uhYs));
+    
+    if( uiTmpD < uiMinD )
+    {
+      uiMinD = uiTmpD;
+      uiOptAng = uiAng;
+    }
+  }
+  m_uiAng = uiOptAng;
+}
+
+Void TComWedgelet::setWedgelet( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UChar uhOri, WedgeResolution eWedgeRes, Bool bIsCoarse )
+#else
+Void TComWedgelet::setWedgelet( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UChar uhOri, WedgeResolution eWedgeRes )
+#endif
+{
+  m_uhXs      = uhXs;
+  m_uhYs      = uhYs;
+  m_uhXe      = uhXe;
+  m_uhYe      = uhYe;
+  m_uhOri     = uhOri;
+  m_eWedgeRes = eWedgeRes;
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+  m_bIsCoarse = bIsCoarse;
+#endif
+
+  xGenerateWedgePattern();
+}
+
+Bool TComWedgelet::checkNotPlain()
+{
+  for( UInt k = 1; k < (m_uiWidth * m_uiHeight); k++ )
+  {
+    if( m_pbPattern[0] != m_pbPattern[k] )
+    {
+      return true;
+    }
+  }
+  return false;
+}
+
+Bool TComWedgelet::checkIdentical( Bool* pbRefPattern )
+{
+  for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ )
+  {
+    if( m_pbPattern[k] != pbRefPattern[k] )
+    {
+      return false;
+    }
+  }
+  return true;
+}
+
+Bool TComWedgelet::checkInvIdentical( Bool* pbRefPattern )
+{
+  for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ )
+  {
+    if( m_pbPattern[k] == pbRefPattern[k] )
+    {
+      return false;
+    }
+  }
+  return true;
+}
+
+#if HHI_DMM_WEDGE_INTRA
+Bool TComWedgelet::checkPredDirAbovePossible( UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset )
+{
+  WedgeResolution eContDWedgeRes = g_aeWedgeResolutionList[(UInt)g_aucConvertToBit[uiPredDirBlockSize]];
+  UInt uiContDStartEndMax = 0;
+  UInt uiContDStartEndOffset = 0;
+  switch( eContDWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize>>1); uiContDStartEndOffset = (uiPredDirBlockOffset>>1); break; }
+  case(   FULL_PEL ): { uiContDStartEndMax =  uiPredDirBlockSize;     uiContDStartEndOffset =  uiPredDirBlockOffset;     break; }
+  case(   HALF_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize<<1); uiContDStartEndOffset = (uiPredDirBlockOffset<<1); break; }
+  }
+
+  if( m_uhOri == 2 || m_uhOri == 3 || m_uhOri == 4 )
+  {
+    UInt uiThisStartEndMax = 0;
+    switch( m_eWedgeRes )
+    {
+    case( DOUBLE_PEL ): { uiThisStartEndMax = (m_uiWidth>>1); break; }
+    case(   FULL_PEL ): { uiThisStartEndMax =  m_uiWidth;     break; }
+    case(   HALF_PEL ): { uiThisStartEndMax = (m_uiWidth<<1); break; }
+    }
+
+    UChar uhStartX = m_uhXs;
+    UChar uhStartY = m_uhYs;
+    UChar uhEndX   = m_uhXe;
+    UChar uhEndY   = m_uhYe;
+
+    if( 2 == m_uhOri )
+    {
+      std::swap( uhStartX, uhEndX );
+      std::swap( uhStartY, uhEndY );
+    }
+
+    UInt uiScaledEndX = (UInt)uhEndX;
+    Int iDeltaRes = (Int)eContDWedgeRes - (Int)m_eWedgeRes;
+    if( iDeltaRes > 0 ) { uiScaledEndX <<=  iDeltaRes; }
+    if( iDeltaRes < 0 ) { uiScaledEndX >>= -iDeltaRes; }
+
+    if( ((UInt)uhEndY == (uiThisStartEndMax-1)) && ((uiScaledEndX-uiContDStartEndOffset) > 0 && (uiScaledEndX-uiContDStartEndOffset) < (uiContDStartEndMax-1)) )
+    {
+      return true;
+    }
+  }
+
+  return false;
+}
+
+Bool TComWedgelet::checkPredDirLeftPossible( UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset )
+{
+  WedgeResolution eContDWedgeRes = g_aeWedgeResolutionList[(UInt)g_aucConvertToBit[uiPredDirBlockSize]];
+  UInt uiContDStartEndMax = 0;
+  UInt uiContDStartEndOffset = 0;
+  switch( eContDWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize>>1); uiContDStartEndOffset = (uiPredDirBlockOffset>>1); break; }
+  case(   FULL_PEL ): { uiContDStartEndMax =  uiPredDirBlockSize;     uiContDStartEndOffset =  uiPredDirBlockOffset;     break; }
+  case(   HALF_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize<<1); uiContDStartEndOffset = (uiPredDirBlockOffset<<1); break; }
+  }
+
+  if( m_uhOri == 1 || m_uhOri == 2 || m_uhOri == 5 )
+  {
+    UInt uiThisStartEndMax = 0;
+    switch( m_eWedgeRes )
+    {
+    case( DOUBLE_PEL ): { uiThisStartEndMax = (m_uiHeight>>1); break; }
+    case(   FULL_PEL ): { uiThisStartEndMax =  m_uiHeight;     break; }
+    case(   HALF_PEL ): { uiThisStartEndMax = (m_uiHeight<<1); break; }
+    }
+
+    UChar uhStartX = m_uhXs;
+    UChar uhStartY = m_uhYs;
+    UChar uhEndX   = m_uhXe;
+    UChar uhEndY   = m_uhYe;
+
+    if( 1 == m_uhOri || 5 == m_uhOri )
+    {
+      std::swap( uhStartX, uhEndX );
+      std::swap( uhStartY, uhEndY );
+    }
+
+    UInt uiScaledEndY = (UInt)uhEndY;
+    Int iDeltaRes = (Int)eContDWedgeRes - (Int)m_eWedgeRes;
+    if( iDeltaRes > 0 ) { uiScaledEndY <<=  iDeltaRes; }
+    if( iDeltaRes < 0 ) { uiScaledEndY >>= -iDeltaRes; }
+
+    if( ((UInt)uhEndX == (uiThisStartEndMax-1)) && ((uiScaledEndY-uiContDStartEndOffset) > 0 && (uiScaledEndY-uiContDStartEndOffset) < (uiContDStartEndMax-1)) )
+    {
+      return true;
+    }
+  }
+
+  return false;
+}
+
+Void TComWedgelet::getPredDirStartEndAbove( UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset, Int iDeltaEnd )
+{
+  ruhXs = 0;
+  ruhYs = 0;
+  ruhXe = 0;
+  ruhYe = 0;
+
+  // get start/end of reference (=this) wedgelet
+  UInt uiRefStartX = (UInt)getStartX();
+  UInt uiRefStartY = (UInt)getStartY();
+  UInt uiRefEndX   = (UInt)getEndX();
+  UInt uiRefEndY   = (UInt)getEndY();
+
+  WedgeResolution eContDWedgeRes = g_aeWedgeResolutionList[(UInt)g_aucConvertToBit[uiPredDirBlockSize]];
+  UInt uiContDStartEndMax = 0;
+  UInt uiContDStartEndOffset = 0;
+  switch( eContDWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize>>1); uiContDStartEndOffset = (uiPredDirBlockOffset>>1); break; }
+  case(   FULL_PEL ): { uiContDStartEndMax =  uiPredDirBlockSize;     uiContDStartEndOffset =  uiPredDirBlockOffset;     break; }
+  case(   HALF_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize<<1); uiContDStartEndOffset = (uiPredDirBlockOffset<<1); break; }
+  }
+  Int iContDMaxPos = (Int)uiContDStartEndMax - 1;
+
+  // swap if start/end if line orientation is not from top to bottom
+  if( 2 == (UInt)getOri() )
+  {
+    std::swap( uiRefStartX, uiRefEndX );
+    std::swap( uiRefStartY, uiRefEndY );
+  }
+
+  // calc slopes
+  Int iA_DeltaX = (Int)uiRefEndX - (Int)uiRefStartX;
+  Int iA_DeltaY = (Int)uiRefEndY - (Int)uiRefStartY;
+
+  // get aligned end x value of ref wedge
+  UInt uiScaledRefEndX = uiRefEndX;
+  Int iDeltaRes = (Int)eContDWedgeRes - (Int)m_eWedgeRes;
+  if( iDeltaRes > 0 ) { uiScaledRefEndX <<=  iDeltaRes; }
+  if( iDeltaRes < 0 ) { uiScaledRefEndX >>= -iDeltaRes; }
+
+  assert( uiScaledRefEndX >= uiContDStartEndOffset );
+  Int iAlignedRefEndX = (Int)uiScaledRefEndX - (Int)uiContDStartEndOffset;
+
+  // special for straight vertical wedge
+  if( iA_DeltaX == 0 )
+  {
+    ruhXs = (UChar)iAlignedRefEndX;
+    ruhYs = 0;
+
+    Int iXe = iAlignedRefEndX + iDeltaEnd;
+    if( iXe < 0 )
+    {
+      ruhXe = 0;
+      ruhYe = (UChar)min( max( (iContDMaxPos + iXe), 0 ), iContDMaxPos );
+
+      return;
+    }
+    else if( iXe > iContDMaxPos )
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)min( max( (iContDMaxPos - (iXe - iContDMaxPos)), 0 ), iContDMaxPos );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iXe;
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+  }
+
+  // special for straight horizontal short bottom line
+  if( iA_DeltaY == 0 )
+  {
+    switch( (UInt)getOri() )
+    {
+    case( 2 ):
+      {
+        ruhXs = (UChar)(iAlignedRefEndX-1);
+        ruhYs = 0;
+        ruhXe = 0;
+        ruhYe = (UChar)min( max( iDeltaEnd, 0 ), iContDMaxPos );
+
+        return;
+      }
+    case( 3 ):
+      {
+        ruhXs = (UChar)(iAlignedRefEndX+1);
+        ruhYs = 0;
+        ruhXe = (UChar)iContDMaxPos;
+        ruhYe = (UChar)min( max( -iDeltaEnd, 0 ), iContDMaxPos );
+
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    default:
+      {
+        assert( 0 );
+        return;
+      }
+    }
+  }
+
+  // set start point depending on slope
+  if( abs( iA_DeltaX ) >= abs( iA_DeltaY ) ) { if( iA_DeltaX < 0 ) { ruhXs = (UChar)(iAlignedRefEndX-1); ruhYs = 0; }
+                                                if( iA_DeltaX > 0 ) { ruhXs = (UChar)(iAlignedRefEndX+1); ruhYs = 0; } }
+  else                                                             { ruhXs = (UChar)(iAlignedRefEndX);   ruhYs = 0;   }
+
+  // calc end point and determine orientation
+  Int iVirtualEndX = (Int)ruhXs + roftoi( (Double)iContDMaxPos * ((Double)iA_DeltaX / (Double)iA_DeltaY) );
+
+  if( iVirtualEndX < 0 )
+  {
+    Int iYe = roftoi( (Double)(0 - (Int)ruhXs) * ((Double)iA_DeltaY / (Double)iA_DeltaX) ) + iDeltaEnd;
+    if( iYe < (Int)uiContDStartEndMax )
+    {
+      ruhXe = 0;
+      ruhYe = (UChar)max( iYe, 0 );
+
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)min( (iYe - iContDMaxPos), iContDMaxPos );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+  }
+  else if( iVirtualEndX > iContDMaxPos )
+  {
+    Int iYe = roftoi( (Double)(iContDMaxPos - (Int)ruhXs) * ((Double)iA_DeltaY / (Double)iA_DeltaX) ) - iDeltaEnd;
+    if( iYe < (Int)uiContDStartEndMax )
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)max( iYe, 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)max( (iContDMaxPos - (iYe - iContDMaxPos)), 0 );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+  }
+  else
+  {
+    Int iXe = iVirtualEndX + iDeltaEnd;
+    if( iXe < 0 )
+    {
+      ruhXe = 0;
+      ruhYe = (UChar)max( (iContDMaxPos + iXe), 0 );
+
+      return;
+    }
+    else if( iXe > iContDMaxPos )
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)max( (iContDMaxPos - (iXe - iContDMaxPos)), 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iXe;
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+  }
+}
+
+Void TComWedgelet::getPredDirStartEndLeft( UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset, Int iDeltaEnd )
+{
+  ruhXs = 0;
+  ruhYs = 0;
+  ruhXe = 0;
+  ruhYe = 0;
+
+  // get start/end of reference (=this) wedgelet
+  UInt uiRefStartX = (UInt)getStartX();
+  UInt uiRefStartY = (UInt)getStartY();
+  UInt uiRefEndX   = (UInt)getEndX();
+  UInt uiRefEndY   = (UInt)getEndY();
+
+  WedgeResolution eContDWedgeRes = g_aeWedgeResolutionList[(UInt)g_aucConvertToBit[uiPredDirBlockSize]];
+  UInt uiContDStartEndMax = 0;
+  UInt uiContDStartEndOffset = 0;
+  switch( eContDWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize>>1); uiContDStartEndOffset = (uiPredDirBlockOffset>>1); break; }
+  case(   FULL_PEL ): { uiContDStartEndMax =  uiPredDirBlockSize;     uiContDStartEndOffset =  uiPredDirBlockOffset;     break; }
+  case(   HALF_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize<<1); uiContDStartEndOffset = (uiPredDirBlockOffset<<1); break; }
+  }
+  Int iContDMaxPos = (Int)uiContDStartEndMax - 1;
+
+  // swap if start/end if line orientation is not from left to right
+  if( 1 == (UInt)getOri() || 5 == (UInt)getOri() )
+  {
+    std::swap( uiRefStartX, uiRefEndX );
+    std::swap( uiRefStartY, uiRefEndY );
+  }
+
+  Int iL_DeltaX = (Int)uiRefEndX - (Int)uiRefStartX;
+  Int iL_DeltaY = (Int)uiRefEndY - (Int)uiRefStartY;
+
+  UInt uiScaledRefEndY = uiRefEndY;
+  Int iDeltaRes = (Int)eContDWedgeRes - (Int)m_eWedgeRes;
+  if( iDeltaRes > 0 ) { uiScaledRefEndY <<=  iDeltaRes; }
+  if( iDeltaRes < 0 ) { uiScaledRefEndY >>= -iDeltaRes; }
+
+  assert( uiScaledRefEndY >= uiContDStartEndOffset );
+  Int iAlignedRefEndY = (Int)uiScaledRefEndY - (Int)uiContDStartEndOffset;
+
+  // special for straight horizontal wedge
+  if( iL_DeltaY == 0 )
+  {
+    ruhXs = 0;
+    ruhYs = (UChar)iAlignedRefEndY;
+
+    Int iYe = iAlignedRefEndY - iDeltaEnd;
+    if( iYe < 0 )
+    {
+      ruhXe = (UChar)min( max( (iContDMaxPos + iYe), 0 ), iContDMaxPos );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else if( iYe > iContDMaxPos )
+    {
+      ruhXe = (UChar)min( max( (iContDMaxPos - (iYe - iContDMaxPos)), 0 ), iContDMaxPos );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)iYe;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+
+  // special for straight vertical short right line
+  if( iL_DeltaX == 0 )
+  {
+    switch( (UInt)getOri() )
+    {
+    case( 1 ):
+      {
+        ruhXs = 0;
+        ruhYs = (UChar)(iAlignedRefEndY+1);
+        ruhXe = (UChar)min( max( iDeltaEnd, 0 ), iContDMaxPos );
+        ruhYe = (UChar)iContDMaxPos;
+
+        return;
+      }
+    case( 2 ):
+      {
+        ruhXs = 0;
+        ruhYs = (UChar)(iAlignedRefEndY-1);
+        ruhXe = (UChar)min( max( -iDeltaEnd, 0 ), iContDMaxPos );
+        ruhYe = 0;
+
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    default:
+      {
+        assert( 0 );
+        return;
+      }
+    }
+  }
+
+  // set start point depending on slope
+  if( abs( iL_DeltaY ) >= abs( iL_DeltaX ) ) { if( iL_DeltaY < 0 ) { ruhYs = (UChar)(iAlignedRefEndY-1); ruhXs = 0; }
+                                               if( iL_DeltaY > 0 ) { ruhYs = (UChar)(iAlignedRefEndY+1); ruhXs = 0; } }
+  else                                       {                       ruhYs = (UChar)(iAlignedRefEndY);   ruhXs = 0;   }
+
+  // calc end point and determine orientation
+  Int iVirtualEndY = (Int)ruhYs + roftoi( (Double)iContDMaxPos * ((Double)iL_DeltaY / (Double)iL_DeltaX) );
+
+  if( iVirtualEndY < 0 )
+  {
+    Int iXe = roftoi( (Double)(0 - (Int)ruhYs ) * ((Double)iL_DeltaX / (Double)iL_DeltaY) ) - iDeltaEnd;
+    if( iXe < (Int)uiContDStartEndMax )
+    {
+      ruhXe = (UChar)max( iXe, 0 );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)min( (iXe - iContDMaxPos), iContDMaxPos );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+  else if( iVirtualEndY > iContDMaxPos )
+  {
+    Int iXe = roftoi( (Double)(iContDMaxPos - (Int)ruhYs ) * ((Double)iL_DeltaX / (Double)iL_DeltaY) ) + iDeltaEnd;
+    if( iXe < (Int)uiContDStartEndMax )
+    {
+      ruhXe = (UChar)max( iXe, 0 );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)max( (iContDMaxPos - (iXe - iContDMaxPos)), 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+  else
+  {
+    Int iYe = iVirtualEndY - iDeltaEnd;
+    if( iYe < 0 )
+    {
+      ruhXe = (UChar)max( (iContDMaxPos + iYe), 0 );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else if( iYe > iContDMaxPos )
+    {
+      ruhXe = (UChar)max( (iContDMaxPos - (iYe - iContDMaxPos)), 0 );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)iYe;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+}
+#endif
+
+Void TComWedgelet::xGenerateWedgePattern()
+{
+  UInt uiTempBlockSize = 0;
+  UChar uhXs = 0, uhYs = 0, uhXe = 0, uhYe = 0;
+  switch( m_eWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiTempBlockSize =  m_uiWidth;     uhXs = (m_uhXs<<1); uhYs = (m_uhYs<<1); uhXe = (m_uhXe<<1); uhYe = (m_uhYe<<1); } break;
+  case(   FULL_PEL ): { uiTempBlockSize =  m_uiWidth;     uhXs =  m_uhXs;     uhYs =  m_uhYs;     uhXe =  m_uhXe;     uhYe =  m_uhYe;     } break;
+  case(   HALF_PEL ): { uiTempBlockSize = (m_uiWidth<<1); uhXs =  m_uhXs;     uhYs =  m_uhYs;     uhXe =  m_uhXe;     uhYe =  m_uhYe;     } break;
+  }
+
+  if( m_eWedgeRes == DOUBLE_PEL) // fix for line-end problem with DOUBLE_PEL resolution
+  {
+    if( m_uhOri == 1 ) { uhXs = uiTempBlockSize-1; }
+    if( m_uhOri == 2 ) { uhXe = uiTempBlockSize-1; uhYs = uiTempBlockSize-1; }
+    if( m_uhOri == 3 ) { uhYe = uiTempBlockSize-1; }
+    if( m_uhOri == 4 ) { uhYe = uiTempBlockSize-1; }
+    if( m_uhOri == 5 ) { uhXs = uiTempBlockSize-1; }
+  }
+
+  Bool* pbTempPattern = new Bool[ (uiTempBlockSize * uiTempBlockSize) ];
+  ::memset( pbTempPattern, 0, (uiTempBlockSize * uiTempBlockSize) * sizeof(Bool) );
+  Int iTempStride = uiTempBlockSize;
+
+  xDrawEdgeLine( uhXs, uhYs, uhXe, uhYe, pbTempPattern, iTempStride );
+
+  switch( m_uhOri )
+  {
+  case( 0 ): { for( UInt iX = 0;                 iX < uhXs;            iX++ ) { UInt iY = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY++; } } } break;
+  case( 1 ): { for( UInt iY = 0;                 iY < uhYs;            iY++ ) { UInt iX = uiTempBlockSize-1; while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX--; } } } break;
+  case( 2 ): { for( UInt iX = uiTempBlockSize-1; iX > uhXs;            iX-- ) { UInt iY = uiTempBlockSize-1; while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY--; } } } break;
+  case( 3 ): { for( UInt iY = uiTempBlockSize-1; iY > uhYs;            iY-- ) { UInt iX = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX++; } } } break;
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+  case( 4 ): 
+    { 
+      if( (uhXs+uhXe) < uiTempBlockSize ) { for( UInt iY = 0; iY < uiTempBlockSize; iY++ ) { UInt iX = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX++; } } }
+      else                                { for( UInt iY = 0; iY < uiTempBlockSize; iY++ ) { UInt iX = uiTempBlockSize-1; while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX--; } } }
+    }
+    break;
+  case( 5 ): 
+    { 
+      if( (uhYs+uhYe) < uiTempBlockSize ) { for( UInt iX = 0; iX < uiTempBlockSize; iX++ ) { UInt iY = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY++; } } }
+      else                                { for( UInt iX = 0; iX < uiTempBlockSize; iX++ ) { UInt iY = uiTempBlockSize-1; while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY--; } } }
+    }
+#else
+  case( 4 ): { for( UInt iY = 0;               iY < uiTempBlockSize; iY++ ) { UInt iX = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX++; } } } break;
+  case( 5 ): { for( UInt iX = 0;               iX < uiTempBlockSize; iX++ ) { UInt iY = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY++; } } } break;
+#endif
+  }
+
+  clear();
+  switch( m_eWedgeRes )
+  {
+  case( DOUBLE_PEL ): { for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ ) { m_pbPattern[k] = pbTempPattern[k]; }; } break;
+  case(   FULL_PEL ): { for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ ) { m_pbPattern[k] = pbTempPattern[k]; }; } break;
+  case(   HALF_PEL ): // sub-sampling by factor 2
+    {
+      Int iStride = getStride();
+
+      UInt uiOffX, uiOffY;
+      switch( m_uhOri )
+      {
+      case( 0 ): { uiOffX = 0; uiOffY = 0; } break;
+      case( 1 ): { uiOffX = 1; uiOffY = 0; } break;
+      case( 2 ): { uiOffX = 1; uiOffY = 1; } break;
+      case( 3 ): { uiOffX = 0; uiOffY = 1; } break;
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+      case( 4 ): 
+        { 
+          if( (uhXs+uhXe) < uiTempBlockSize ) { uiOffX = 0; uiOffY = 0; }
+          else                                { uiOffX = 1; uiOffY = 0; }
+        } 
+        break;
+      case( 5 ): 
+        { 
+          if( (uhYs+uhYe) < uiTempBlockSize ) { uiOffX = 0; uiOffY = 0; }
+          else                                { uiOffX = 0; uiOffY = 1; }
+        } 
+        break;
+#else
+      case( 4 ): { uiOffX = 0; uiOffY = 0; } break;
+      case( 5 ): { uiOffX = 0; uiOffY = 0; } break;
+#endif
+      default:   { uiOffX = 0; uiOffY = 0; } break;
+      }
+
+      for(Int iY = 0; iY < m_uiHeight; iY++)
+      {
+        for(Int iX = 0; iX < m_uiWidth; iX++)
+        {
+          m_pbPattern[(iY * iStride) + iX] = pbTempPattern[(((iY<<1)+uiOffY) * iTempStride) + ((iX<<1)+uiOffX)];
+        }
+      }
+    }
+    break;
+  }
+
+  if( pbTempPattern )
+  {
+    delete [] pbTempPattern;
+    pbTempPattern = NULL;
+  }
+}
+
+Void TComWedgelet::xDrawEdgeLine( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, Bool* pbPattern, Int iPatternStride )
+{
+  Int x0 = (Int)uhXs;
+  Int y0 = (Int)uhYs;
+  Int x1 = (Int)uhXe;
+  Int y1 = (Int)uhYe;
+
+  // direction independent Bresenham line
+  bool steep = (abs(y1 - y0) > abs(x1 - x0));
+  if( steep )
+  {
+    std::swap( x0, y0 );
+    std::swap( x1, y1 );
+  }
+
+  bool backward = ( x0 > x1 );
+  if( backward )
+  {
+    std::swap( x0, x1 );
+    std::swap( y0, y1 );
+  }
+
+  Int deltax = x1 - x0;
+  Int deltay = abs(y1 - y0);
+  double error = 0.0;
+  double deltaerr = (double)deltay / (double)deltax;
+
+  Int ystep;
+  Int y = y0;
+  if( y0 < y1 ) ystep =  1;
+  else          ystep = -1;
+
+  for( Int x = x0; x <= x1; x++ )
+  {
+    if( steep ) { pbPattern[(x * iPatternStride) + y] = true; }
+    else        { pbPattern[(y * iPatternStride) + x] = true; }
+
+    error += deltaerr;
+    if( error >= 0.5)
+    {
+      y += ystep;
+      error = error - 1.0;
+    }
+  }
+}
+
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+TComWedgeNode::TComWedgeNode()
+{
+  m_uiPatternIdx = NO_IDX;
+  for( UInt uiPos = 0; uiPos < NUM_WEDGE_REFINES; uiPos++ )
+  {
+    m_uiRefineIdx[uiPos] = NO_IDX;
+  }
+}
+
+UInt TComWedgeNode::getPatternIdx()
+{
+  return m_uiPatternIdx;
+}
+UInt TComWedgeNode::getRefineIdx( UInt uiPos )
+{
+  assert( uiPos < NUM_WEDGE_REFINES );
+  return m_uiRefineIdx[uiPos];
+}
+Void TComWedgeNode::setPatternIdx( UInt uiIdx )
+{
+  m_uiPatternIdx = uiIdx;
+}
+Void TComWedgeNode::setRefineIdx( UInt uiIdx, UInt uiPos )
+{
+  assert( uiPos < NUM_WEDGE_REFINES );
+  m_uiRefineIdx[uiPos] = uiIdx;  
+}
+#endif
+
+#if HHI_DMM_PRED_TEX
+TComWedgeDist::TComWedgeDist()
+{
+  init();
+}
+
+TComWedgeDist::~TComWedgeDist()
+{
+}
+
+Void TComWedgeDist::init()
+{
+  m_afpDistortFunc[0] = TComWedgeDist::xGetSAD4;
+  m_afpDistortFunc[1] = TComWedgeDist::xGetSAD8;
+  m_afpDistortFunc[2] = TComWedgeDist::xGetSAD16;
+  m_afpDistortFunc[3] = TComWedgeDist::xGetSAD32;
+
+  m_afpDistortFunc[4] = TComWedgeDist::xGetSSE4;
+  m_afpDistortFunc[5] = TComWedgeDist::xGetSSE8;
+  m_afpDistortFunc[6] = TComWedgeDist::xGetSSE16;
+  m_afpDistortFunc[7] = TComWedgeDist::xGetSSE32;
+}
+
+UInt TComWedgeDist::xGetSAD4( WedgeDistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComWedgeDist::xGetSAD8( WedgeDistParam* pcDtParam )
+{
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComWedgeDist::xGetSAD16( WedgeDistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComWedgeDist::xGetSAD32( WedgeDistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComWedgeDist::xGetSSE4( WedgeDistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  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;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComWedgeDist::xGetSSE8( WedgeDistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  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;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComWedgeDist::xGetSSE16( WedgeDistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  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;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComWedgeDist::xGetSSE32( WedgeDistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  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;
+  }
+
+  return ( uiSum );
+}
+
+Void TComWedgeDist::setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, WedgeDist eWDist, WedgeDistParam& rcDistParam )
+{
+  // set Block Width / Height
+  rcDistParam.iCols    = uiBlkWidth;
+  rcDistParam.iRows    = uiBlkHeight;
+  rcDistParam.DistFunc = m_afpDistortFunc[eWDist + g_aucConvertToBit[ rcDistParam.iCols ] ];
+
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+UInt TComWedgeDist::getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, WedgeDist eWDist )
+{
+  WedgeDistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eWDist, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+  cDtParam.iStep      = 1;
+
+  return cDtParam.DistFunc( &cDtParam );
+}
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWedgelet.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWedgelet.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWedgelet.h	(revision 341)
@@ -0,0 +1,258 @@
+/* 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-2011, 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 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 __TCOMWEDGELET__
+#define __TCOMWEDGELET__
+
+// Include files
+#include <assert.h>
+#include "CommonDef.h"
+
+#include <vector>
+
+enum WedgeResolution
+{
+  DOUBLE_PEL,
+  FULL_PEL,
+  HALF_PEL
+};
+
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+#define NUM_WEDGE_REFINES 8
+#define NO_IDX MAX_UINT
+#endif
+
+// ====================================================================================================================
+// Class definition TComWedgelet
+// ====================================================================================================================
+class TComWedgelet
+{
+private:
+  UChar           m_uhXs;                       // line start X pos
+  UChar           m_uhYs;                       // line start Y pos
+  UChar           m_uhXe;                       // line end   X pos
+  UChar           m_uhYe;                       // line end   Y pos
+  UChar           m_uhOri;                      // orientation index
+  WedgeResolution m_eWedgeRes;                  // start/end pos resolution
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+  Bool            m_bIsCoarse; 
+  UInt            m_uiAng;
+#endif
+
+  UInt  m_uiWidth;
+  UInt  m_uiHeight;
+
+  Bool* m_pbPattern;
+
+  Void  xGenerateWedgePattern();
+  Void  xDrawEdgeLine( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, Bool* pbPattern, Int iPatternStride );
+
+public:
+  TComWedgelet( UInt uiWidth, UInt uiHeight );
+  TComWedgelet( const TComWedgelet &rcWedge );
+  virtual ~TComWedgelet();
+
+  Void  create ( UInt iWidth, UInt iHeight );   ///< create  wedgelet pattern
+  Void  destroy();                              ///< destroy wedgelet pattern
+  Void  clear  ();                              ///< clear   wedgelet pattern
+
+  UInt            getWidth   () { return m_uiWidth; }
+  UInt            getStride  () { return m_uiWidth; }
+  UInt            getHeight  () { return m_uiHeight; }
+  WedgeResolution getWedgeRes() { return m_eWedgeRes; }
+  Bool*           getPattern () { return m_pbPattern; }
+  UChar           getStartX  () { return m_uhXs; }
+  UChar           getStartY  () { return m_uhYs; }
+  UChar           getEndX    () { return m_uhXe; }
+  UChar           getEndY    () { return m_uhYe; }
+  UChar           getOri     () { return m_uhOri; }
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+  Bool            getIsCoarse() { return m_bIsCoarse; }
+  UInt            getAng     () { return m_uiAng; }
+  Void            findClosetAngle();
+
+  Void  setWedgelet( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UChar uhOri, WedgeResolution eWedgeRes, Bool bIsCoarse = false );
+#else
+  Void  setWedgelet( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UChar uhOri, WedgeResolution eWedgeRes );
+#endif
+
+  Bool  checkNotPlain();
+  Bool  checkIdentical( Bool* pbRefPattern );
+  Bool  checkInvIdentical( Bool* pbRefPattern );
+
+#if HHI_DMM_WEDGE_INTRA
+  Bool  checkPredDirAbovePossible( UInt uiPredDirBlockSize, UInt uiPredDirBlockOffsett );
+  Bool  checkPredDirLeftPossible ( UInt uiPredDirBlockSize, UInt uiPredDirBlockOffsett );
+
+  Void  getPredDirStartEndAbove( UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset, Int iDeltaEnd );
+  Void  getPredDirStartEndLeft ( UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset, Int iDeltaEnd );
+#endif
+};  // END CLASS DEFINITION TComWedgelet
+
+// type definition wedgelet pattern list
+typedef std::vector<TComWedgelet> WedgeList;
+
+// ====================================================================================================================
+// Class definition TComWedgeRef
+// ====================================================================================================================
+class TComWedgeRef
+{
+private:
+  UChar           m_uhXs;                       // line start X pos
+  UChar           m_uhYs;                       // line start Y pos
+  UChar           m_uhXe;                       // line end   X pos
+  UChar           m_uhYe;                       // line end   Y pos
+  UInt            m_uiRefIdx;                   // index of corresponding pattern of TComWedgelet object in wedge list
+
+public:
+  TComWedgeRef() {}
+  virtual ~TComWedgeRef() {}
+
+  UChar           getStartX  () { return m_uhXs; }
+  UChar           getStartY  () { return m_uhYs; }
+  UChar           getEndX    () { return m_uhXe; }
+  UChar           getEndY    () { return m_uhYe; }
+  UInt            getRefIdx  () { return m_uiRefIdx; }
+
+  Void  setWedgeRef( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UInt uiRefIdx ) { m_uhXs = uhXs; m_uhYs = uhYs; m_uhXe = uhXe; m_uhYe = uhYe; m_uiRefIdx = uiRefIdx; }
+};  // END CLASS DEFINITION TComWedgeRef
+
+// type definition wedgelet reference list
+typedef std::vector<TComWedgeRef> WedgeRefList;
+
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+// ====================================================================================================================
+// Class definition TComWedgeNode
+// ====================================================================================================================
+class TComWedgeNode
+{
+private:
+  UInt            m_uiPatternIdx;
+  UInt            m_uiRefineIdx[NUM_WEDGE_REFINES];
+
+public:
+  TComWedgeNode();
+  virtual ~TComWedgeNode() {}
+
+  UInt            getPatternIdx();
+  UInt            getRefineIdx ( UInt uiPos );
+
+  Void            setPatternIdx( UInt uiIdx );
+  Void            setRefineIdx ( UInt uiIdx, UInt uiPos );
+};  // END CLASS DEFINITION TComWedgeNode
+
+// type definition wedgelet node list
+typedef std::vector<TComWedgeNode> WedgeNodeList;
+#endif
+
+#if HHI_DMM_PRED_TEX
+enum WedgeDist
+{
+  WedgeDist_SAD  = 0,
+  WedgeDist_SSE  = 4,
+};
+
+class WedgeDistParam;
+typedef UInt (*FpWedgeDistFunc) (WedgeDistParam*);
+
+/// distortion parameter class
+class WedgeDistParam
+{
+public:
+  Pel*  pOrg;
+  Pel*  pCur;
+  Int   iStrideOrg;
+  Int   iStrideCur;
+  Int   iRows;
+  Int   iCols;
+  Int   iStep;
+  FpWedgeDistFunc DistFunc;
+  Int   iSubShift;
+
+  WedgeDistParam()
+  {
+    pOrg = NULL;
+    pCur = NULL;
+    iStrideOrg = 0;
+    iStrideCur = 0;
+    iRows = 0;
+    iCols = 0;
+    iStep = 1;
+    DistFunc = NULL;
+    iSubShift = 0;
+  }
+};
+
+// ====================================================================================================================
+// Class definition TComWedgeDist
+// ====================================================================================================================
+class TComWedgeDist
+{
+private:
+  Int                     m_iBlkWidth;
+  Int                     m_iBlkHeight;
+  FpWedgeDistFunc         m_afpDistortFunc[8];
+
+public:
+  TComWedgeDist();
+  virtual ~TComWedgeDist();
+
+  Void init();
+  Void setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, WedgeDist eWDist, WedgeDistParam& rcDistParam );
+  UInt getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, WedgeDist eWDist = WedgeDist_SAD );
+
+private:
+  static UInt xGetSAD4          ( WedgeDistParam* pcDtParam );
+  static UInt xGetSAD8          ( WedgeDistParam* pcDtParam );
+  static UInt xGetSAD16         ( WedgeDistParam* pcDtParam );
+  static UInt xGetSAD32         ( WedgeDistParam* pcDtParam );
+
+  static UInt xGetSSE4          ( WedgeDistParam* pcDtParam );
+  static UInt xGetSSE8          ( WedgeDistParam* pcDtParam );
+  static UInt xGetSSE16         ( WedgeDistParam* pcDtParam );
+  static UInt xGetSSE32         ( WedgeDistParam* pcDtParam );
+
+};// END CLASS DEFINITION TComWedgeDist
+#endif
+
+// ====================================================================================================================
+// Function definition roftoi (mathematically correct rounding of float to int)
+// ====================================================================================================================
+__inline Int roftoi( Double value )
+{
+  (value < -0.5) ? (value -= 0.5) : (value += 0.5);
+  return ( (Int)value );
+}
+#endif // __TCOMWEDGELET__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 341)
@@ -0,0 +1,440 @@
+/* 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-2012, 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     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+// Include files
+#include "TComSlice.h"
+#include "TComWeightPrediction.h"
+#include "TComInterpolationFilter.h"
+
+// ====================================================================================================================
+// 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_uiBitDepth + g_uiBitIncrement );
+  Int shift   = wp0[0].shift + shiftNum;
+  Int round   = (1<<(shift-1)) * bRound;
+  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] = weightBidir(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidir(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidir(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidir(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;
+  shift   = wp0[1].shift + shiftNum;
+  round   = (1<<(shift-1));
+  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] = weightBidir(w0,pSrcU0[x], w1,pSrcU1[x], round, shift, offset); x--;
+      pDstU[x] = weightBidir(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   = (1<<(shift-1));
+  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] = weightBidir(w0,pSrcV0[x], w1,pSrcV1[x], round, shift, offset); x--;
+      pDstV[x] = weightBidir(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_uiBitDepth + g_uiBitIncrement );
+  Int shift   = wp0[0].shift + shiftNum;
+  Int round   = (1<<(shift-1));
+  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] = weightUnidir(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidir(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidir(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidir(w0,pSrcY0[x], round, shift, offset); x--;
+    }
+    pSrcY0 += iSrc0Stride;
+    pDstY  += iDstStride;
+  }
+  
+  // Chroma U : --------------------------------------------
+  w0      = wp0[1].w;
+  offset  = wp0[1].offset;
+  shift   = wp0[1].shift + shiftNum;
+  round   = (1<<(shift-1));
+
+  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] = weightUnidir(w0,pSrcU0[x], round, shift, offset); x--;
+      pDstU[x] = weightUnidir(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   = (1<<(shift-1));
+
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstV[x] = weightUnidir(w0,pSrcV0[x], round, shift, offset); x--;
+      pDstV[x] = weightUnidir(w0,pSrcV0[x], round, shift, offset); x--;
+    }
+    pSrcV0 += iSrc0Stride;
+    pDstV  += 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, Int ibdi)
+{
+  TComSlice*      pcSlice       = pcCU->getSlice();
+  TComPPS*        pps           = pcCU->getSlice()->getPPS();
+  UInt            uiWPBiPredIdc = pps->getWPBiPredIdc();
+  wpScalingParam* pwp;
+  Bool            bBiDir        = (iRefIdx0>=0 && iRefIdx1>=0);
+  Bool            bUniDir       = !bBiDir;
+
+  m_ibdi = ibdi;
+
+  if ( bUniDir || (uiWPBiPredIdc==1) )
+  { // explicit --------------------
+    if ( iRefIdx0 >= 0 )
+    {
+      pcSlice->getWpScaling(REF_PIC_LIST_0, iRefIdx0, wp0);
+    }
+    if ( iRefIdx1 >= 0 )
+    {
+      pcSlice->getWpScaling(REF_PIC_LIST_1, iRefIdx1, wp1);
+    }
+  }
+  else if ( uiWPBiPredIdc == 2 )
+  { // implicit --------------------
+    Int poc0    = pcSlice->getRefPOC(REF_PIC_LIST_0, iRefIdx0);
+    Int poc1    = pcSlice->getRefPOC(REF_PIC_LIST_1, iRefIdx1);
+    Int pocCur  = pcSlice->getPOC();
+    Int td      = Clip3(-128,127,poc1 - poc0);
+    Int tb      = Clip3(-128,127,pocCur - poc0);
+    Int tx      = ( td != 0 ) ? ( ( 16384 + abs( td / 2 ) ) / td ) : (0);
+    Int DistScaleFactor = Clip3( -1024, 1023, ( tb * tx + 32 ) >> 6 );
+
+    Bool  implicitScale=true;
+    if ( poc1==poc0 || (DistScaleFactor>>2)<(-64) || (DistScaleFactor>>2)>128 )
+    {
+      implicitScale = false;
+    }
+
+    for ( int e=0 ; e<2 ; e++ )
+    {
+      pwp = (e==0) ? m_wp0 : m_wp1;
+      for ( int k=0 ; k<3 ; k++ ) // 3 components: Y,U,V
+      {   
+        pwp->uiLog2WeightDenom = 5;  pwp->iOffset = 0;  pwp->bPresentFlag = true;  
+        if ( implicitScale )
+        {
+          pwp->iWeight = (e==0) ? (64 - (DistScaleFactor >> 2)) : (DistScaleFactor >> 2);
+        }
+        else
+        {
+          pwp->iWeight = 32;
+        }
+        pwp++;
+      }
+
+    }
+
+    wp0 = m_wp0;
+    wp1 = m_wp1;
+  }
+  else
+  {
+    assert(0);
+  }
+
+  if ( iRefIdx0 < 0 )
+  {
+    wp0 = NULL;
+  }
+  if ( iRefIdx1 < 0 )
+  {
+    wp1 = NULL;
+  }
+
+  if ( bBiDir )
+  { // Bi-Dir case
+    for ( int yuv=0 ; yuv<3 ; yuv++ )
+    {
+      wp0[yuv].w      = wp0[yuv].iWeight;
+      wp0[yuv].o      = wp0[yuv].iOffset * (1 << (m_ibdi-8));
+      wp1[yuv].w      = wp1[yuv].iWeight;
+      wp1[yuv].o      = wp1[yuv].iOffset * (1 << (m_ibdi-8));
+      wp0[yuv].offset = wp0[yuv].o + wp1[yuv].o;
+      wp0[yuv].shift  = wp0[yuv].uiLog2WeightDenom + 1;
+      wp0[yuv].round  = (1 << wp0[yuv].uiLog2WeightDenom);
+      wp1[yuv].offset = wp0[yuv].offset;
+      wp1[yuv].shift  = wp0[yuv].shift;
+      wp1[yuv].round  = wp0[yuv].round;
+    }
+  }
+  else
+  {  // Unidir
+    pwp = (iRefIdx0>=0) ? wp0 : wp1 ;
+    if ( uiWPBiPredIdc == 2 )
+    {
+      for ( int yuv=0 ; yuv<3 ; yuv++ )
+      {
+        pwp[yuv].w      = 1;
+        pwp[yuv].offset = 0;
+        pwp[yuv].shift  = 0;
+        pwp[yuv].round  = 0;
+      }
+    }
+    else {
+      for ( int yuv=0 ; yuv<3 ; yuv++ )
+      {
+        pwp[yuv].w      = pwp[yuv].iWeight;
+        pwp[yuv].offset = pwp[yuv].iOffset * (1 << (m_ibdi-8));
+        pwp[yuv].shift  = pwp[yuv].uiLog2WeightDenom;
+        pwp[yuv].round  = (pwp[yuv].uiLog2WeightDenom>=1) ? (1 << (pwp[yuv].uiLog2WeightDenom-1)) : (0);
+      }
+    }
+  }
+}
+
+/** 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->getWPBiPredIdc() != 0 );
+
+  Int ibdi = (g_uiBitDepth+g_uiBitIncrement);
+  getWpScaling(pcCU, iRefIdx0, iRefIdx1, pwp0, pwp1, ibdi);
+
+  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
+  {
+    addWeightBi(pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight, pwp0, pwp1, rpcYuvDst );
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    addWeightUni( pcYuvSrc0, uiPartIdx, iWidth, iHeight, pwp0, rpcYuvDst );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    addWeightUni( pcYuvSrc1, uiPartIdx, iWidth, iHeight, pwp1, rpcYuvDst );
+  }
+  else
+  {
+    assert (0);
+  }
+}
+
+/** 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 iPartIdx, Int iRefIdx)
+{ 
+  wpScalingParam  *pwp, *pwpTmp;
+  if ( iRefIdx < 0 )
+  {
+    iRefIdx   = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+  }
+  assert (iRefIdx >= 0);
+
+  Int ibdi = (g_uiBitDepth+g_uiBitIncrement);
+
+  if ( eRefPicList == REF_PIC_LIST_0 )
+  {
+    getWpScaling(pcCU, iRefIdx, -1, pwp, pwpTmp, ibdi);
+  }
+  else
+  {
+    getWpScaling(pcCU, -1, iRefIdx, pwpTmp, pwp, ibdi);
+  }
+  addWeightUni( pcYuvSrc, uiPartAddr, iWidth, iHeight, pwp, rpcYuvPred );
+}
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 341)
@@ -0,0 +1,91 @@
+/* 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-2012, 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     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+#ifndef __TCOMWEIGHTPREDICTION__
+#define __TCOMWEIGHTPREDICTION__
+
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+#include "TComPattern.h"
+#include "TComTrQuant.h"
+#include "TComInterpolationFilter.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+/// weighting prediction class
+class TComWeightPrediction
+{
+  wpScalingParam  m_wp0[3], m_wp1[3];
+  Int             m_ibdi;
+
+public:
+  TComWeightPrediction();
+
+  Void  getWpScaling( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1, wpScalingParam *&wp0 , wpScalingParam *&wp1 , Int ibdi=(g_uiBitDepth+g_uiBitIncrement));
+
+  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  xWeightedPredictionUni( TComDataCU* pcCU, TComYuv* pcYuvSrc, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Int iRefIdx=-1 );
+  Void  xWeightedPredictionBi( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* rpcYuvDst );
+
+  __inline  Pel   xClip  ( Int x );
+  __inline  Pel   weightBidir( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset);
+  __inline  Pel   weightUnidir( Int w0, Pel P0, Int round, Int shift, Int offset);
+
+};
+
+inline  Pel TComWeightPrediction::xClip( Int x )
+{ 
+  Int max = (Int)g_uiIBDI_MAX;
+  Pel pel = (Pel)( (x < 0) ? 0 : (x > max) ? max : x );
+  return( pel );
+}
+
+inline  Pel TComWeightPrediction::weightBidir( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset)
+{
+  return xClip( ( (w0*(P0 + IF_INTERNAL_OFFS) + w1*(P1 + IF_INTERNAL_OFFS) + round + (offset << (shift-1))) >> shift ) );
+}
+inline  Pel TComWeightPrediction::weightUnidir( Int w0, Pel P0, Int round, Int shift, Int offset) 
+{
+  return xClip( ( (w0*(P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset );
+}
+
+#endif 
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComYuv.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComYuv.cpp	(revision 341)
@@ -0,0 +1,743 @@
+/* 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-2012, 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     TComYuv.cpp
+    \brief    general YUV buffer class
+    \todo     this should be merged with TComPicYuv
+*/
+
+#include <stdlib.h>
+#include <memory.h>
+#include <assert.h>
+#include <math.h>
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComInterpolationFilter.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComYuv::TComYuv()
+{
+  m_apiBufY = NULL;
+  m_apiBufU = NULL;
+  m_apiBufV = NULL;
+}
+
+TComYuv::~TComYuv()
+{
+}
+
+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 );
+  
+  // set width and height
+  m_iWidth   = iWidth;
+  m_iHeight  = iHeight;
+  m_iCWidth  = iWidth  >> 1;
+  m_iCHeight = iHeight >> 1;
+}
+
+Void TComYuv::destroy()
+{
+  // memory free
+  xFree( m_apiBufY ); m_apiBufY = NULL;
+  xFree( m_apiBufU ); m_apiBufU = NULL;
+  xFree( m_apiBufV ); m_apiBufV = 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-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+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);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+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);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+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-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*uiWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+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;
+  }
+}
+
+#if DEPTH_MAP_GENERATION
+Void TComYuv::copyPartToPartYuvPdm   ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY )
+{
+  copyPartToPartLumaPdm   (pcYuvDst, uiPartIdx, iWidth, iHeight, uiSubSampExpX, uiSubSampExpY );
+}
+#endif
+
+Void TComYuv::copyPartToPartYuv   ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  copyPartToPartLuma   (pcYuvDst, uiPartIdx, iWidth, iHeight );
+  copyPartToPartChroma (pcYuvDst, uiPartIdx, iWidth>>1, iHeight>>1 );
+}
+
+#if DEPTH_MAP_GENERATION
+Void TComYuv::copyPartToPartLumaPdm  ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY )
+{
+  UInt uiBlkX = g_auiRasterToPelX[ g_auiZscanToRaster[ uiPartIdx ] ] >> uiSubSampExpX;
+  UInt uiBlkY = g_auiRasterToPelY[ g_auiZscanToRaster[ uiPartIdx ] ] >> uiSubSampExpY;
+  Pel* pSrc   = getLumaAddr(uiPartIdx);
+  Pel* pDst   = pcYuvDst->getLumaAddr() + uiBlkY * pcYuvDst->getStride() + uiBlkX;
+
+  if( pSrc == pDst )
+  {
+    //th not a good idea
+    //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) );
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+}
+#endif
+
+Void TComYuv::copyPartToPartLuma  ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  Pel* pSrc =           getLumaAddr(uiPartIdx);
+  Pel* pDst = pcYuvDst->getLumaAddr(uiPartIdx);
+  if( pSrc == pDst )
+  {
+    //th not a good idea
+    //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) );
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+}
+
+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)
+  {
+    //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::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] = Clip( pSrc0[x] + pSrc1[x] );      
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void
+TComYuv::add( TComYuv* pcYuvAdd, Int iWidth, Int iHeight, Bool bSubtract )
+{
+  addLuma   ( pcYuvAdd, iWidth,    iHeight,    bSubtract );
+  addChroma ( pcYuvAdd, iWidth>>1, iHeight>>1, bSubtract );
+}
+
+
+Void
+TComYuv::addLuma( TComYuv* pcYuvAdd, Int iWidth, Int iHeight, Bool bSubtract )
+{
+  Int   iScale      = ( bSubtract ? -1 : 1 );
+  Int   iAddStride  = pcYuvAdd->getStride();
+  Int   iDstStride  = getStride();
+  Pel*  pAddSamples = pcYuvAdd->getLumaAddr();
+  Pel*  pDstSamples = getLumaAddr();
+
+  for( Int iY = 0; iY < iHeight; iY++, pDstSamples += iDstStride, pAddSamples += iAddStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pDstSamples[iX] += iScale * pAddSamples[iX];
+    }
+  }
+}
+
+Void
+TComYuv::addChroma( TComYuv* pcYuvAdd, Int iWidth, Int iHeight, Bool bSubtract )
+{
+  Int   iScale        = ( bSubtract ? -1 : 1 );
+  Int   iAddStride    = pcYuvAdd->getCStride();
+  Int   iDstStride    = getCStride();
+  Pel*  pAddSamplesCb = pcYuvAdd->getCbAddr();
+  Pel*  pAddSamplesCr = pcYuvAdd->getCrAddr();
+  Pel*  pDstSamplesCb = getCbAddr();
+  Pel*  pDstSamplesCr = getCrAddr();
+
+  for( Int iY = 0; iY < iHeight; iY++, pDstSamplesCb += iDstStride, pAddSamplesCb += iAddStride,
+                                       pDstSamplesCr += iDstStride, pAddSamplesCr += iAddStride  )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pDstSamplesCb[iX] += iScale * pAddSamplesCb[iX];
+      pDstSamplesCr[iX] += iScale * pAddSamplesCr[iX];
+    }
+  }
+}
+
+Void
+TComYuv::clip( Int iWidth, Int iHeight )
+{
+  clipLuma   ( iWidth,    iHeight    );
+  clipChroma ( iWidth>>1, iHeight>>1 );
+}
+
+Void
+TComYuv::clipLuma( Int iWidth, Int iHeight )
+{
+  Int   iStride  = getStride();
+  Pel*  pSamples = getLumaAddr();
+  for( Int iY = 0; iY < iHeight; iY++, pSamples += iStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pSamples[iX] = xClip( pSamples[iX] );
+    }
+  }
+}
+
+Void
+TComYuv::clipChroma( Int iWidth, Int iHeight )
+{
+  Int   iStride    = getCStride();
+  Pel*  pSamplesCb = getCbAddr();
+  Pel*  pSamplesCr = getCrAddr();
+  for( Int iY = 0; iY < iHeight; iY++, pSamplesCb += iStride, pSamplesCr += iStride )
+  {
+    for( Int iX = 0; iX < iWidth; iX++ )
+    {
+      pSamplesCb[iX] = xClip( pSamplesCb[iX] );
+      pSamplesCr[iX] = xClip( pSamplesCr[iX] );
+    }
+  }
+}
+
+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 )
+{
+  Int x, y;
+  
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDst  = getLumaAddr( uiTrUnitIdx, uiPartSize );
+  
+  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] = Clip( pSrc0[x] + pSrc1[x] );
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::addClipChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  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 );
+  
+  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] = Clip( pSrcU0[x] + pSrcU1[x] );
+      pDstV[x] = Clip( pSrcV0[x] + pSrcV1[x] );
+    }
+    
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+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 )
+{
+  Int x, y;
+  
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDst  = getLumaAddr( uiTrUnitIdx, uiPartSize );
+  
+  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-- )
+    {
+      pDst[x] = pSrc0[x] - pSrc1[x];
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::subtractChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  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 );
+  
+  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-- )
+    {
+      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::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_uiBitDepth + g_uiBitIncrement );
+  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 ] = Clip( ( pSrcY0[ x + 0 ] + pSrcY1[ x + 0 ] + offset ) >> shiftNum );
+      pDstY[ x + 1 ] = Clip( ( pSrcY0[ x + 1 ] + pSrcY1[ x + 1 ] + offset ) >> shiftNum );
+      pDstY[ x + 2 ] = Clip( ( pSrcY0[ x + 2 ] + pSrcY1[ x + 2 ] + offset ) >> shiftNum );
+      pDstY[ x + 3 ] = Clip( ( pSrcY0[ x + 3 ] + pSrcY1[ x + 3 ] + offset ) >> shiftNum );
+    }
+    pSrcY0 += iSrc0Stride;
+    pSrcY1 += iSrc1Stride;
+    pDstY  += iDstStride;
+  }
+  
+  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] = Clip((pSrcU0[x] + pSrcU1[x] + offset) >> shiftNum);
+      pDstV[x] = Clip((pSrcV0[x] + pSrcV1[x] + offset) >> shiftNum); x--;
+      pDstU[x] = Clip((pSrcU0[x] + pSrcU1[x] + offset) >> shiftNum);
+      pDstV[x] = Clip((pSrcV0[x] + pSrcV1[x] + offset) >> shiftNum); x--;
+    }
+    
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+#if DEPTH_MAP_GENERATION
+Void TComYuv::addAvgPdm( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY )
+{
+  Int x, y;
+
+  UInt uiBlkX  = g_auiRasterToPelX[ g_auiZscanToRaster[ iPartUnitIdx ] ] >> uiSubSampExpX;
+  UInt uiBlkY  = g_auiRasterToPelY[ g_auiZscanToRaster[ iPartUnitIdx ] ] >> uiSubSampExpY;
+  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcY1  = pcYuvSrc1->getLumaAddr( iPartUnitIdx );
+  Pel* pDstY   = getLumaAddr() + uiBlkY * getStride() + uiBlkX;
+
+  UInt  iSrc0Stride = pcYuvSrc0->getStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getStride();
+  UInt  iDstStride  = getStride();
+
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; x-- )
+    {
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + 1) >> 1;
+    }
+    pSrcY0 += iSrc0Stride;
+    pSrcY1 += iSrc1Stride;
+    pDstY  += iDstStride;
+  }
+}
+#endif
+
+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 ] = (pDst[x ]<<1) - pSrc[x ] ;
+#else
+      pDst[x ] = Clip( (pDst[x ]<<1) - 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 ] = (pDstU[x ]<<1) - pSrcU[x ] ;
+      pDstV[x ] = (pDstV[x ]<<1) - pSrcV[x ] ;
+#else
+      pDstU[x ] = Clip( (pDstU[x ]<<1) - pSrcU[x ] );
+      pDstV[x ] = Clip( (pDstV[x ]<<1) - pSrcV[x ] );
+#endif
+    }
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComYuv.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TComYuv.h	(revision 341)
@@ -0,0 +1,205 @@
+/* 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-2012, 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     TComYuv.h
+    \brief    general YUV buffer class (header)
+    \todo     this should be merged with TComPicYuv \n
+              check usage of removeHighFreq function
+*/
+
+#ifndef __TCOMYUV__
+#define __TCOMYUV__
+#include <assert.h>
+#include "CommonDef.h"
+#include "TComPicYuv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// general YUV buffer class
+class TComYuv
+{
+private:
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Pel*    m_apiBufY;
+  Pel*    m_apiBufU;
+  Pel*    m_apiBufV;
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  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;
+  }
+  
+public:
+  
+  TComYuv();
+  virtual ~TComYuv();
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Memory management
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    create            ( UInt iWidth, UInt iHeight );  ///< 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 );
+  
+  //  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 );
+  
+  //  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 );
+  
+  //  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 );
+  
+  //  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 );
+
+#if DEPTH_MAP_GENERATION
+  Void    copyPartToPartYuvPdm  ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight, UInt uiSubSampExpX, UInt uiSubSampExpY );
+  Void    copyPartToPartLumaPdm ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight, UInt uiSubSampExpX, UInt uiSubSampExpY );
+#endif
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  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    addClipPartLuma   ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize ); //GT
+
+  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 );
+  
+  //  (pcYuvSrc0 + pcYuvSrc1)/2 for YUV partition
+  Void    addAvg            ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight );
+
+#if DEPTH_MAP_GENERATION
+  Void    addAvgPdm         ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, UInt uiSubSampExpX, UInt uiSubSampExpY );
+#endif
+
+  //   Remove High frequency
+  Void    removeHighFreq    ( TComYuv* pcYuvSrc, UInt uiPartIdx, UInt uiWidht, UInt uiHeight );
+  Void    add               ( TComYuv* pcYuvAdd, Int iWidth, Int iHeight, Bool bSubtract = false );
+  Void    addLuma           ( TComYuv* pcYuvAdd, Int iWidth, Int iHeight, Bool bSubtract );
+  Void    addChroma         ( TComYuv* pcYuvAdd, Int iWidth, Int iHeight, Bool bSubtract );
+
+  Void    clip              ( Int iWidth, Int iHeight );
+  Void    clipLuma          ( Int iWidth, Int iHeight );
+  Void    clipChroma        ( Int iWidth, Int iHeight );
+  // ------------------------------------------------------------------------------------------------------------------
+  //  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; }
+  
+  //  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 ); }
+  
+  //  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 ); }
+
+  //  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;  }  
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Miscellaneous
+  // ------------------------------------------------------------------------------------------------------------------
+
+  __inline Pel  xClip  (Pel x )      { return ( (x < 0) ? 0 : (x > (Pel)g_uiIBDI_MAX) ? (Pel)g_uiIBDI_MAX : x ); }
+};// END CLASS DEFINITION TComYuv
+
+//! \}
+
+#endif // __TCOMYUV__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TypeDef.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibCommon/TypeDef.h	(revision 341)
@@ -0,0 +1,926 @@
+/* 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-2012, 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     TypeDef.h
+    \brief    Define basic types, new types and enumerations
+*/
+
+#ifndef _TYPEDEF__
+#define _TYPEDEF__
+
+//! \ingroup TLibCommon
+//! \{
+
+// MV-HEVC
+#define QC_IV_AS_LT_B0046                 1   //JCT3V-B0046: inter-view reference pictures are treated as long-term pictures 
+#define QC_REM_IDV_B0046                  1   //JCT3V-B0046: removal of IDV NAL unit type
+#define DV_V_RESTRICTION_B0037            1   //JCT3V-B0037: disparity vector vertical range restriction
+#define QC_TMVP_IDX_MOD_B0046             1   //JCT3V-B0046: the reference index for temporal merging candidate is set to 0, as defined in HEVC
+
+// 3D-HEVC
+#define QC_MVHEVC_B0046                   0   //JCT3V-B0046: disable 3DHEVC tools
+
+#if !QC_MVHEVC_B0046
+
+///// ***** DMM *********
+#define HHI_DMM_WEDGE_INTRA               1   // depth model modes independent on texture (explicit and intra-predicted Wedgelet prediction)
+#define HHI_DMM_PRED_TEX                  1   // depth model modes dependent on texture (inter-component Wedgelet and Contour prediction )
+                                              // HHIQC_DMMFASTSEARCH_B0039, fast Wedgelet search for DMM modes 1 and 3
+                                              // HHI_DMM_DELTADC_Q1_C0034   JCT3V-C0034: no quantization and fast encoder search for DMM delta DC values
+                                              // FIX_DMM_CTX_INIT_C0034 JCT3V-C0034 fix for wrong init type of DMM contexts (UChar instead of Short)
+
+#define LGE_EDGE_INTRA_A0070              1   // JCT3V-A0070
+#define LGE_DMM3_SIMP_C0044               1
+
+///// ***** SDC *********
+#define RWTH_SDC_DLT_B0036                1   // JCT3V-B0036: Simplified Depth Coding + Depth Lookup Table
+                                              // SAIT_SDC_C0096 JCT3V-C0096: Improved Simple Depth Coding(removal of DMM2 among four SDC modes(DC, Planar, DMM1 and DMM2))
+                                              // FIX_SDC_ENC_C0143, JCT3V-C0143 fix for unnecessary encoder checks in case of SDC
+
+///// ***** TMVP/AMVP *********
+#define TMVP_DEPTH_SWITCH                 1   // JCT3V-B0092 additional encoder option only 
+#define QC_TMVP_MRG_REFIDX_C0047          1   // only enabled when QC_TMVP_IDX_MOD_B0046 is enabled.
+#define INTER_VIEW_VECTOR_SCALING_C0115   1   // JCT3V-C0115 Inter-view vector scaling for TMVP & flag
+#define INTER_VIEW_VECTOR_SCALING_C0116   1   // JCT3V-C0116 Inter-view vector scaling for AMVP
+
+///// ***** INTERVIEW MOTION PARAMETER PREDICTION *********
+#define H3D_IVMP                          1   // Inter-view motion parameter prediction
+                                              // HHI_INTER_VIEW_MOTION_PRED 
+                                              // SAIT_IMPROV_MOTION_PRED_M24829, improved inter-view motion vector prediction
+                                              // SHARP_INTERVIEW_DECOUPLE_B0111, decoupling inter-view candidate
+                                              // QC_MRG_CANS_B0048             , JCT3V-B0048, B0086, B0069
+                                              // OL_DISMV_POS_B0069            , different pos for disparity MV candidate, B0069
+                                              // MTK_INTERVIEW_MERGE_A0049     , second part
+                                              // QC_C0051_FIXED_BY_MTK             1   // Bug fix for C0051 implementation
+                                              // QC_AMVP_MRG_UNIFY_IVCAN_C0051     1
+
+
+///// ***** INTERVIEW RESIDUAL PREDICTION *********
+#define H3D_IVRP                          1   // Inter-view residual prediction
+                                              // HHI_INTER_VIEW_RESIDUAL_PRED
+                                              // QC_SIMPLIFIEDIVRP_M24938 
+                                              // MTK_C0138_FIXED                   // Fix for IBP coding structure in view direction (not CTC)
+                                              // MTK_MDIVRP_C0138
+                                              // LG_RESTRICTEDRESPRED_M24766       1   // Restricted inter-view residual prediction
+                                              // FIX_LG_RESTRICTEDRESPRED_M24766   1
+
+///// ***** DISPARITY VECTOR DERIVATION *********
+#define H3D_NBDV                          1   // Neighboring block disparity derivation 
+                                              // JCT3V-A0097 
+                                              // LGE_DVMCP_A0126
+                                              // LGE_DVMCP_MEM_REDUCTION_B0135     
+                                              // DV_DERIVATION_PARALLEL_B0096, enable parallel derivation of disparity vector
+                                              // QC_SIMPLE_NBDV_B0047
+                                              // FIX_LGE_DVMCP_B0133
+                                              // LGE_IVMP_PARALLEL_MERGE_B0136, B0136 support of parallel merge/skip in disparity vector derivation
+                                              // FIX_LGE_IVMP_PARALLEL_MERGE_B0136
+
+                                              // QC_NBDV_LDB_FIX_C0055
+                                              // MTK_SAIT_TEMPORAL_FIRST_ORDER_C0141_C0097
+                                              // MTK_RELEASE_DV_CONSTRAINT_C0129   
+                                              // MTK_SIMPLIFY_DVTC_C0135           
+                                              // FIX_CHROMA_RESIDUAL_C0129         
+
+///// ***** MOTION PARAMETER INHERITANCE  *********
+#define MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137   1   // JCT3V-C0137
+#define HHI_MPI                           0   // motion parameter inheritance from texture picture for depth map coding
+#if HHI_MPI
+#define FIX_MPI_B0065                     1   // JCT3V-B0065, fix the MPI bug when RQT is off
+#endif
+#define MTK_UNCONSTRAINED_MVI_B0083       1    //JCT3V-B0083
+
+///// ***** VIEW SYNTHESIS OPTIMIZAION *********
+#define HHI_VSO                           1
+#define HHI_VSO_LS_TABLE_M23714           1   // m23714, enable table base Lagrange multiplier optimization 
+#define HHI_VSO_DIST_INT                  1   // Allow negative synthesized view distortion change
+#define HHI_VSO_COLOR_PLANES              1   // Compute VSO distortion on color planes 
+#define HHI_VSO_RM_ASSERTIONS             0   // Output VSO assertions
+#define HHI_VSO_SYNTH_DIST_OUT            0   // Output of synthesized view distortion instead of depth distortion in encoder output
+#define SAIT_VSO_EST_A0033                1   // JCT3V-A0033 modification 3
+#define LGE_VSO_EARLY_SKIP_A0093          1   // JCT3V-A0093 modification 4
+#define LGE_WVSO_A0119                    1   // JCT3V-A0119 & JCT3V-B0131 Depth Metric with a weighted depth fidelity term
+
+
+///// ***** ILLUMINATION COMPENSATON *********
+#define LGE_ILLUCOMP_B0045                1   // JCT2-B0045 Illumination compensation for Luma and Chroma
+                                              // LGE_ILLUCOMP_B0045_ENCSIMP
+                                              // FIX_LGE_ILLUCOMP_B0045            
+#if LGE_ILLUCOMP_B0045
+#define LGE_ILLUCOMP_DEPTH_C0046          1   // JCT2-C0046 Apply illumination compensation to depth
+#if LGE_ILLUCOMP_DEPTH_C0046
+#define FIX_ILLUCOMP_DEPTH                1
+#endif
+#endif
+
+///// ***** INTERVIEW SKIP *********
+#define HHI_INTERVIEW_SKIP                1
+
+///// ***** QUADTREE LIMITATION *********
+#define H3D_QTL                            1 // OL_QTLIMIT_dPREDCODING_B0068 //JCT3V-B0068
+                                             // HHI_QTLPC_RAU_OFF_C0160     // JCT3V-C0160 change 2: quadtree limitation and predictive coding switched off in random access units 
+
+///// ***** OTHERS *********
+#define LG_ZEROINTRADEPTHRESI_A0087       1   // JCT2-A0087
+#define HHI_FULL_PEL_DEPTH_MAP_MV_ACC     1   // full-pel mv accuracy for depth maps
+#define VIDYO_VPS_INTEGRATION             1   // Integration of VPS
+#define HHI_DEPTH_INTRA_SEARCH_RAU_C0160  1   // JCT3V-C0160 change 1: full Intra search in depth random access units 
+#define FIX_POZNAN_CABAC_INIT_FLAG        1
+#define FIX_LGE_WP_FOR_3D_C0223           1   // JCT3V-C0223 Weighted Prediction Bug-fix for 3D-HEVC. Caution! There is still crush using WP with Residual Prediction.
+#define FIX_APPENCTOP_T_ONLY              1   // For Texture-only coding
+
+///// ***** FCO  *********
+#define FLEX_CODING_ORDER_M23723          1
+#if FLEX_CODING_ORDER_M23723
+#define DISABLE_FCO_FOR_VSO               0 // Optional compile settings to disable VSO with FCO.
+#define FCO_DVP_REFINE_C0132_C0170        0 // depth oriented disparity vector prediction from JCT3V-C0132 and JCT3V-C0170
+#define FCO_FIX                           0 // Bug fix for C0137 and C0152 on FCO
+#define FCO_FIX_SPS_CHANGE                0 // Sending camera parameters in SPS of depth for depth to disparity conversion used by VSP and DoDVP
+#else
+#define DISABLE_FCO_FOR_VSO               0 // Optional compile settings to disable VSO with FCO.
+#define FCO_DVP_REFINE_C0132_C0170        0 // depth oriented disparity vector prediction from JCT3V-C0132 and JCT3V-C0170
+#define FCO_FIX                           0 // Fixing bugs from HTM 6.0 which 
+#define FCO_FIX_SPS_CHANGE                0 // Fixing bugs from HTM 6.0 which 
+#endif
+
+///// ***** VSP *********
+#define MERL_VSP_C0152                    1 // JCT3V-C0152: 1: enable VSP-related tools; 0: disable VSP-related tools
+                                            // LGE_SIMP_DVP_REFINE_C0112            
+                                            // MERL_MTK_VSP_DVP_REFINE_C0152_C0131
+#if MERL_VSP_C0152
+#define MERL_VSP_C0152_BugFix_ForNoDepthCase     1// MERL bugfix for test condition of no depth
+/*
+ * Two macros are used to configure combinations of JCT3V-C0152 and JCT3V-C0131
+ * 
+ *   a) (full) A full JCT3V-C0152 implementation, including JCT3V-C0131 
+ *      #define MERL_VSP_COMPENSATION_C0152          1
+ *      #define MERL_MTK_VSP_DVP_REFINE_C0152_C0131  1
+ * 
+ *   b) (mvp2off) For partial JCT3V-C0152 excluding overlaps from JCT3V-C0131
+ *      #define MERL_VSP_COMPENSATION_C0152          1
+ *      #define MERL_MTK_VSP_DVP_REFINE_C0152_C0131  0
+ * 
+ *   c) (nocand) For JCT3V-C0131 only
+ *      #define MERL_VSP_COMPENSATION_C0152          0
+ *      #define MERL_MTK_VSP_DVP_REFINE_C0152_C0131  1
+ */
+
+#define MERL_VSP_COMPENSATION_C0152          1 // JCT3V-C0152: 1: add VSP merge candidate to merging candidate list; 0: not to add   (nocand).
+
+
+#define MERL_VSP_BLOCKSIZE_C0152             4 // JCT3V-C0152: VSP block size, supported values: 1, 2 and 4.
+#define VSP_MERGE_POS                        5 // JCT3V-C0152: fixed position of VSP candidate in merge list, supported values: 5.
+                                               //MTK_DVPREFINE_BVSP_BUG_FIX               1
+
+#else // !MERL_VSP_C0152
+#define MERL_VSP_COMPENSATION_C0152          0 // JCT3V-C0152: 1: add VSP merge candidate to merging candidate list; 0: not to add
+#define MERL_VSP_BLOCKSIZE_C0152             4 // JCT3V-C0152: VSP block size, supported values: 1, 2 and 4.
+#endif
+
+
+///// ***** DERIVED PARAMETERS *********
+#if H3D_NBDV                    
+#define DIS_CANS                          1
+#define MCP_DIS_CANS                      7
+#endif                                  
+
+#define HHI_INTERVIEW_SKIP_LAMBDA_SCALE   1
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#define DMM_WEDGEMODEL_MIN_SIZE           4
+#define DMM_WEDGEMODEL_MAX_SIZE          32
+#define DMM_WEDGE_PREDDIR_DELTAEND_MAX    4
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+#define LGE_EDGE_INTRA_MIN_SIZE           4
+#define LGE_EDGE_INTRA_MAX_SIZE           32
+#define LGE_EDGE_INTRA_THRESHOLD          20
+#define LGE_EDGE_INTRA_MAX_EDGE_NUM_PER_4x4 8
+#define LGE_EDGE_INTRA_DELTA_DC           1 
+#define LGE_EDGE_INTRA_PIXEL_DIFFERENCE   1
+#endif
+
+
+#if H3D_NBDV                           
+#define DVFROM_LEFTBELOW                  1
+#define DVFROM_LEFT                       2
+#define DVFROM_ABOVERIGHT                 3
+#define DVFROM_ABOVE                      4
+#define DVFROM_ABOVELEFT                  5
+#define DVFROM_COL                        6
+#endif
+
+
+#if HHI_DMM_PRED_TEX || HHI_DMM_WEDGE_INTRA
+#define DMM3_SIMPLIFY_TR                  1
+#endif
+
+
+#if RWTH_SDC_DLT_B0036
+#define Log2( n ) ( log((double)n) / log(2.0) )
+#define HS_REFERENCE_SUBSAMPLE_C0154      1
+#endif
+
+#define HHI_MPI_MERGE_POS                 0
+#endif
+
+
+///// ***** HM 6.1 *********
+
+//// REMOVED HM 6.1 Guard macros (corresponding to macros removed in HM 6.3.1)
+/*
+#define SKIPFRAME_BUGFIX                  1 ///< bug fix to enable skipFrame at decoder
+#define START_DECODING_AT_CRA             1 ///< H0496, start decoding at clear random access point
+#define NO_COMBINED_PARALLEL              1 ///< Disallow any combined usage of parallel tools among Tile, EntropySlice and Wavefont
+#define PARALLEL_MERGE                    1 ///< H0082 parallel merge/skip
+#define MVP_AT_ENTROPYSLICE_BOUNDARY      1  //< H0362 enable motion prediction accross entropy slice boundary
+#define FAST_DECISION_FOR_MRG_RD_COST     1  ////< H0178: Fast Decision for Merge 2Nx2N RDCost
+#define PIC_CROPPING                      1  ///< Picture cropping and size constraints
+#define NAL_REF_FLAG                      1  ///< Change nal_ref_idc to nal_ref_flag (JCTVC-F463)
+#define REMOVE_DIV_OPERATION      1  ///< H0238: Simplified intra horizontal and vertical filtering
+#define LOGI_INTRA_NAME_3MPM      1  ///< H0407: logical Intra mode naming (sequential angular mode numbering) and 3 MPM mode coding
+#define LEVEL_CTX_LUMA_RED        1  ///<H0130: Luma level context reduction
+#define REMOVE_INFER_SIGGRP       1  ///<H0131: Remove inferred significant_coeff_group_flag
+#define SET_MERGE_TMVP_REFIDX     1  ///< H0278/H0199: Setting the merge TMVP refidx to 0 for the non-first partition
+#define MULTILEVEL_SIGMAP_EXT     1  ///< H0526: multi-level significance map extended to smaller TUs
+#define MULTIBITS_DATA_HIDING     1  ///< H0481: multiple sign bit hiding
+#define DEQUANT_CLIPPING          1  ///< H0312/H0541: transformed coefficients clipping before de-quantization
+#define REMOVE_NON_SCALED         1 ///< H0164/H0250: Removal of non-scaled merge candidate
+#define MRG_IDX_CTX_RED           1 ///< H0251: Merge index context reduction
+#define SIMP_MRG_PRUN             1 ///< H0252: simplification of merge pruning process
+#define AMVP_PRUNING_SIMPLIFICATION         1     ///H0316: simplify the pruning process of AMVP by exempting the temporal candidate
+#define AMVP_ZERO_CHECKING_REMOVAL          1     ///H0239/H0316: remove zero motion vector checking of AMVP
+#define H0111_MVD_L1_ZERO         1  ///< H0111: modification of bi-prediction
+#define CLIPSCALEDMVP               1  ///< H0216: Clipping scaled MV to 16 bit
+#define UNIFIED_TRANSFORM_TREE      1   ///< H0123: unified tree structure for TU
+#define SIGMAP_CTX_SUBBLOCK       1 ///< H0290: 4x4 sub-block based region for significant_flag context selection
+#define LAST_CTX_REDUCTION        1  ///< H0537/H514: contexts reduction for last position coding
+#define AMP_CTX                   1 ///<H0545: context reduction for asymmetric partition
+#define RESTRICT_GR1GR2FLAG_NUMBER    1 ///< H0554: Throughput improvement of CABAC coefficients level coding
+#define EIGHT_BITS_RICE_CODE        1 ///< H0498 : 8 bits rice codes
+#define SAO_UNIT_INTERLEAVING      1   ///< H0273
+#define ALF_SINGLE_FILTER_SHAPE    1     //< !!! H0068: Single filter type : 9x7 cross + 3x3 square
+#define ALF_16_BA_GROUPS        1     ///< H0409 16 BA groups
+#define LCU_SYNTAX_ALF          1     ///< H0274 LCU-syntax ALF
+#define ALF_CHROMA_COEF_PRED_HARMONIZATION 1 ///< H0483: ALF chroma coeff pred harmonization
+#define CABAC_LINEAR_INIT       1     ///< H0535 : linear CABAC initialization
+#define UNIFIED_TRANSFORM       1     ///< H0492: unify square and non-square transform
+#define G519_TU_AMP_NSQT_HARMONIZATION  1   ///< G519: Harmonization of implicit TU, AMP and NSQT
+#define CHROMA_MODE_CODING                   1     //H0326/H0475 : 2-length fixed, bypass coding for chroma intra prediction mode
+#define NSQT_LFFIX                           1     ///< Bug fix related to NSQT and deblocking filter
+#define H0736_AVC_STYLE_QP_RANGE             1    ///< H0736: AVC style qp range and wrapping.
+#define H0204_QP_PREDICTION                  1    ///< H0204: improved QP prediction
+#define BURST_IPCM                        1           ///< H0051: Burst IPCM
+#define H0137_0138_LIST_MODIFICATION      1           // Enabled reference picture lists combination (H0137) and reference picture list modification (H0138) updates
+#define LTRP_MULT                       1           ///< enable/disable multiple long term reference pictures with same POC LSB
+#define OL_FLUSH 1          // Set to 1 to enable Wavefront Flush.
+#define FIXED_NUMBER_OF_TILES_SLICE_MODE                1
+#define SCALING_LIST                  1 //JCTVC-H0230/H0461/H0237
+#define DEFAULT_DC                    1 // JCTVC-H0242
+#define RPS_IN_SPS                    1 // Adopted during discussion of JCTVC-H0423
+#define H0412_REF_PIC_LIST_RESTRICTION 1
+#define H0566_TLA                     1
+#define H0567_DPB_PARAMETERS_PER_TEMPORAL_LAYER 1
+#define DBL_H0473_PART_1          1   //Deblocking filtering simplification
+#define DBL_CONTROL               1   //PPS deblocking_filter_control_present_flag (JCTVC-H0398); condition for inherit params flag in SH (JCTVC-H0424)
+#define DBL_STRONG_FILTER_CLIP    1   //Introduction of strong filter clipping in deblocking filter (JCTVC-H0275)
+#define H0388                       1 // JCTVC-H0388
+#define TILES_WPP_ENTRY_POINT_SIGNALLING        1 // JCTVC-H0556. Assumes either Tiles is ON or WPP is ON (not both simultaneously).
+#define REMOVE_TILE_DEPENDENCE                  1 // remove tile_boundary_independence_flag and dependent tiles
+#define TILES_OR_ENTROPY_SYNC_IDC               1 // tiles_or_entropy_coding_sync_idc flag
+#define COMPLETE_SLICES_IN_TILE     1 // Among the constraints between slices and tiles, all slices within a tile shall be complete (JCTVC-H0348/JCTVC-H0463) for SliceMode 1&2
+#define WPP_SIMPLIFICATION          1 // JCTVC-H0349/JCTVC-0517
+*/
+
+
+#define LOSSLESS_CODING                   1 ///< H0530: lossless and lossy (mixed) coding
+#if LOSSLESS_CODING
+#define SEQUENCE_LEVEL_LOSSLESS           0 ///< H0530: used only for sequence or frame-level lossless coding
+#endif
+
+#define LOG2_PARALLEL_MERGE_LEVEL_MINUS2  0 //< H0082 parallel merge level 0-> 4x4, 1-> 8x8, 2->16x16, 3->32x32, 4->64x64
+
+#if LOG2_PARALLEL_MERGE_LEVEL_MINUS2
+#define CU_BASED_MRG_CAND_LIST            1  //< H0240: single merge candidate list for all PUs inside a 8x8 CU conditioned on LOG2_PARALLEL_MERGE_LEVEL_MINUS2 > 0
+#define FIX_CU_BASED_MRG_CAND_LIST_B0136  1  //< B0136 bug fix for CU_BASED_MRG_CAND_LIST
+#endif
+
+#define DISABLING_CLIP_FOR_BIPREDME         1  ///< Ticket #175
+#define SIGMAP_CONST_AT_HIGH_FREQUENCY      1      ///< H0095 method2.1: const significance map at high freaquency
+
+#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 REMOVE_SAO_LCU_ENC_CONSTRAINTS_1 0  ///< disable the encoder constraint that does not test SAO/BO mode for chroma in interleaved mode
+#define REMOVE_SAO_LCU_ENC_CONSTRAINTS_2 0  ///< disable the encoder constraint that reduce the range of SAO/EO for chroma in interleaved mode
+#define REMOVE_SAO_LCU_ENC_CONSTRAINTS_3 0  ///< disable the encoder constraint that conditionally disable SAO for chroma for entire slice in interleaved mode
+#define COLLOCATED_REF_IDX      1           ///< H0442: signal collocated reference index
+
+
+#define MAX_NUM_SPS                32
+#define MAX_NUM_PPS                256
+#define MAX_NUM_APS                32         //< !!!KS: number not defined in WD yet
+
+#define MRG_MAX_NUM_CANDS_SIGNALED         5   //<G091: value of maxNumMergeCand signaled in slice header
+
+#define WEIGHTED_CHROMA_DISTORTION  1   ///< F386: weighting of chroma for RDO
+#define RDOQ_CHROMA_LAMBDA          1   ///< F386: weighting of chroma for RDOQ
+#define ALF_CHROMA_LAMBDA           1   ///< F386: weighting of chroma for ALF
+#define SAO_CHROMA_LAMBDA           1   ///< F386: weighting of chroma for SAO
+
+#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 NS_HAD                               1
+
+#define APS_BITS_FOR_SAO_BYTE_LENGTH 12
+#define APS_BITS_FOR_ALF_BYTE_LENGTH 8
+
+
+
+#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
+
+#if LGE_EDGE_INTRA_A0070
+#if LGE_EDGE_INTRA_DELTA_DC
+#define FAST_UDI_MAX_RDMODE_NUM               37          ///< maximum number of RD comparison in fast-UDI estimation loop
+#else
+#define FAST_UDI_MAX_RDMODE_NUM               36          ///< maximum number of RD comparison in fast-UDI estimation loop
+#endif
+#else
+#define FAST_UDI_MAX_RDMODE_NUM               35          ///< maximum number of RD comparison in fast-UDI estimation loop
+#endif
+
+#define ZERO_MVD_EST                          0           ///< Zero Mvd Estimation in normal mode
+
+#define NUM_INTRA_MODE 36
+#define LM_CHROMA_IDX  35
+
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+enum MODE_IDX
+{
+  DMM_WEDGE_FULL_IDX         = NUM_INTRA_MODE,
+  DMM_WEDGE_FULL_D_IDX       = NUM_INTRA_MODE+1,
+  DMM_WEDGE_PREDTEX_IDX      = NUM_INTRA_MODE+2,
+  DMM_WEDGE_PREDTEX_D_IDX    = NUM_INTRA_MODE+3,
+  DMM_CONTOUR_PREDTEX_IDX    = NUM_INTRA_MODE+4,
+  DMM_CONTOUR_PREDTEX_D_IDX  = NUM_INTRA_MODE+5,
+  DMM_WEDGE_PREDDIR_IDX      = NUM_INTRA_MODE+6,
+  DMM_WEDGE_PREDDIR_D_IDX    = NUM_INTRA_MODE+7
+};
+#define NUM_DMM_MODE 8
+#elif HHI_DMM_WEDGE_INTRA && !HHI_DMM_PRED_TEX
+enum MODE_IDX
+{
+  DMM_WEDGE_FULL_IDX         = NUM_INTRA_MODE,
+  DMM_WEDGE_FULL_D_IDX       = NUM_INTRA_MODE+1,
+  DMM_WEDGE_PREDDIR_IDX      = NUM_INTRA_MODE+2,
+  DMM_WEDGE_PREDDIR_D_IDX    = NUM_INTRA_MODE+3
+};
+#define NUM_DMM_MODE 4
+#elif !HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+enum MODE_IDX
+{
+  DMM_WEDGE_PREDTEX_IDX      = NUM_INTRA_MODE,
+  DMM_WEDGE_PREDTEX_D_IDX    = NUM_INTRA_MODE+1,
+  DMM_CONTOUR_PREDTEX_IDX    = NUM_INTRA_MODE+2,
+  DMM_CONTOUR_PREDTEX_D_IDX  = NUM_INTRA_MODE+3,
+};
+#define NUM_DMM_MODE 4
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#define EDGE_INTRA_IDX  (NUM_INTRA_MODE+NUM_DMM_MODE)
+#endif // HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#if LGE_EDGE_INTRA_DELTA_DC
+#define EDGE_INTRA_DELTA_IDX          (EDGE_INTRA_IDX+1)
+#endif
+#endif // LGE_EDGE_INTRA
+
+#define IBDI_DISTORTION                0           ///< enable/disable SSE modification when IBDI is used (JCTVC-D152)
+#define FIXED_ROUNDING_FRAME_MEMORY    0           ///< enable/disable fixed rounding to 8-bitdepth of frame memory when IBDI is used
+
+#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 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 OL_FLUSH_ALIGN 0    // Align flush to byte boundary.  This preserves byte operations in CABAC (faster) but at the expense of an average
+                            // of 4 bits per flush.
+                            // Setting to 0 will slow cabac by an as yet unknown amount.
+                            // This is here just to perform timing tests -- OL_FLUSH_ALIGN should be 0 for WPP.
+
+#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        6                     // 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, does not use g_uiBitIncrement anymore to support > 8 bit data
+
+
+#define AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE      1          ///< OPTION IDENTIFIER. mode==1 -> Limit maximum number of largest coding tree blocks in a slice
+#define AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE    2          ///< OPTION IDENTIFIER. mode==2 -> Limit maximum number of bins/bits in a slice
+#define AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE    3
+
+// Entropy slice options
+#define SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE            1          ///< OPTION IDENTIFIER. Limit maximum number of largest coding tree blocks in an entropy slice
+#define SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE         2          ///< OPTION IDENTIFIER. Limit maximum number of bins/bits in an entropy slice
+
+#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 MAX_MARKER_PER_NALU                 1000
+
+#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 SCALING_LIST_OUTPUT_RESULT    0 //JCTVC-G880/JCTVC-G1016 quantization matrices
+#define H0566_TLA_SET_FOR_SWITCHING_POINTS 1
+
+
+#define CABAC_INIT_FLAG             1 // JCTVC-H0540
+#define CABAC_INIT_PRESENT_FLAG     1
+
+
+// ====================================================================================================================
+// VPS INTEGRATION
+// ====================================================================================================================
+#if !QC_MVHEVC_B0046
+#if VIDYO_VPS_INTEGRATION
+#define MAX_NUM_VPS 10
+#endif
+#else
+#define MAX_NUM_VPS 1
+#endif
+
+
+// ====================================================================================================================
+// Basic type redefinition
+// ====================================================================================================================
+
+typedef       void                Void;
+typedef       bool                Bool;
+
+typedef       char                Char;
+typedef       unsigned char       UChar;
+typedef       short               Short;
+typedef       unsigned short      UShort;
+typedef       int                 Int;
+typedef       unsigned int        UInt;
+typedef       double              Double;
+
+// ====================================================================================================================
+// 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
+#else
+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
+
+
+// ====================================================================================================================
+// Define Distortion Types
+// ====================================================================================================================
+typedef       Int64           RMDist;     ///< renderer model distortion
+
+#if HHI_VSO_DIST_INT
+typedef       Int              Dist;       ///< RDO distortion
+#define       RDO_DIST_MIN     MIN_INT
+#define       RDO_DIST_MAX     MAX_INT
+#else
+typedef       UInt             Dist;       ///< RDO distortion
+#define       RDO_DIST_MIN     0
+#define       RDO_DIST_MAX     MAX_UINT
+#endif
+
+/// parameters for adaptive loop filter
+class TComPicSym;
+
+#define NUM_DOWN_PART 4
+
+enum SAOTypeLen
+{
+  SAO_EO_LEN    = 4,
+  SAO_BO_LEN    = 4,
+  SAO_MAX_BO_CLASSES = 32
+};
+
+enum SAOType
+{
+  SAO_EO_0 = 0,
+  SAO_EO_1,
+  SAO_EO_2,
+  SAO_EO_3,
+  SAO_BO,
+  MAX_NUM_SAO_TYPE
+};
+
+typedef struct _SaoQTPart
+{
+  Int         iBestType;
+  Int         iLength;
+  Int         bandPosition ;
+  Int         iOffset[4];
+  Int         StartCUX;
+  Int         StartCUY;
+  Int         EndCUX;
+  Int         EndCUY;
+
+  Int         PartIdx;
+  Int         PartLevel;
+  Int         PartCol;
+  Int         PartRow;
+
+  Int         DownPartsIdx[NUM_DOWN_PART];
+  Int         UpPartIdx;
+
+  Bool        bSplit;
+
+  //---- encoder only start -----//
+  Bool        bProcessed;
+  Double      dMinCost;
+  Int64       iMinDist;
+  Int         iMinRate;
+  //---- encoder only end -----//
+} SAOQTPart;
+
+typedef struct _SaoLcuParam
+{
+  Bool       mergeUpFlag;
+  Bool       mergeLeftFlag;
+  Int        typeIdx;
+  Int        bandPosition;
+  Int        offset[4];
+  Int        runDiff;
+  Int        run;
+  Int        partIdx;
+  Int        partIdxTmp;
+  Int        length;
+} SaoLcuParam;
+
+struct SAOParam
+{
+  Bool       bSaoFlag[3];
+  SAOQTPart* psSaoPart[3];
+  Int        iMaxSplitLevel;
+  Int        iNumClass[MAX_NUM_SAO_TYPE];
+  Bool         oneUnitFlag[3];
+  SaoLcuParam* saoLcuParam[3];
+  Int          numCuInHeight;
+  Int          numCuInWidth;
+  ~SAOParam();
+};
+
+struct ALFParam
+{
+  Int alf_flag;                           ///< indicates use of ALF
+  Int num_coeff;                          ///< number of filter coefficients
+  Int filter_shape;
+  Int *filterPattern;
+  Int startSecondFilter;
+  Int filters_per_group;
+  Int predMethod;
+  Int *nbSPred;
+  Int **coeffmulti;
+  Int minKStart;
+  Int componentID;
+  Int* kMinTab;
+  //constructor, operator
+  ALFParam():componentID(-1){}
+  ALFParam(Int cID){create(cID);}
+  ALFParam(const ALFParam& src) {*this = src;}
+  ~ALFParam(){destroy();}
+  const ALFParam& operator= (const ALFParam& src);
+private:
+  Void create(Int cID);
+  Void destroy();
+  Void copy(const ALFParam& src);
+};
+
+struct AlfUnitParam
+{
+  Int   mergeType;
+  Bool  isEnabled;
+  Bool  isNewFilt;
+  Int   storedFiltIdx;
+  ALFParam* alfFiltParam;
+  //constructor, operator
+  AlfUnitParam();
+  AlfUnitParam(const AlfUnitParam& src){ *this = src;}
+  const AlfUnitParam& operator= (const AlfUnitParam& src);
+  Bool operator == (const AlfUnitParam& cmp);
+};
+
+struct AlfParamSet
+{
+  Bool isEnabled[3];
+  Bool isUniParam[3];
+  Int  numLCUInWidth;
+  Int  numLCUInHeight;
+  Int  numLCU;
+  AlfUnitParam* alfUnitParam[3];
+  //constructor, operator
+  AlfParamSet(){create();}
+  ~AlfParamSet(){destroy();}
+  Void create(Int width =0, Int height=0, Int num=0);
+  Void init();
+  Void releaseALFParam();
+  Void createALFParam();
+private:
+  Void destroy();
+};
+
+
+
+/// parameters for deblocking filter
+typedef struct _LFCUParam
+{
+  Bool bInternalEdge;                     ///< indicates internal edge
+  Bool bLeftEdge;                         ///< indicates left edge
+  Bool bTopEdge;                          ///< indicates top edge
+} LFCUParam;
+
+// ====================================================================================================================
+// Enumeration
+// ====================================================================================================================
+
+/// supported slice type
+enum SliceType
+{
+  I_SLICE,
+  P_SLICE,
+  B_SLICE
+};
+
+/// chroma formats (according to semantics of chroma_format_idc)
+enum ChromaFormat
+{
+  CHROMA_400  = 0,
+  CHROMA_420  = 1,
+  CHROMA_422  = 2,
+  CHROMA_444  = 3
+};
+
+/// 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
+};
+
+
+enum BlenMod
+{
+    BLEND_NONE  = -1,
+    BLEND_AVRG  = 0,
+    BLEND_LEFT  = 1,
+    BLEND_RIGHT = 2,
+    BLEND_GEN   =  3
+};
+
+/// supported prediction type
+enum PredMode
+{
+  MODE_SKIP,            ///< SKIP mode
+  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
+};
+
+/// reference list index
+enum RefPicList
+{
+  REF_PIC_LIST_0 = 0,   ///< reference list 0
+  REF_PIC_LIST_1 = 1,   ///< reference list 1
+  REF_PIC_LIST_C = 2,   ///< combined reference list for uni-prediction in B-Slices
+  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 SAIT_VSO_EST_A0033
+  DF_VSD      = 29,      ///< general size VSD
+  DF_VSD4     = 30,      ///<   4xM VSD
+  DF_VSD8     = 31,      ///<   8xM VSD
+  DF_VSD16    = 32,      ///<  16xM VSD
+  DF_VSD32    = 33,      ///<  32xM VSD
+  DF_VSD64    = 34,      ///<  64xM VSD
+  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
+};
+
+/// index for SBAC based RD optimization
+enum CI_IDX
+{
+  CI_CURR_BEST = 0,     ///< best mode index
+  CI_NEXT_BEST,         ///< next best index
+  CI_TEMP_BEST,         ///< temporal index
+  CI_CHROMA_INTRA,      ///< chroma intra index
+  CI_QT_TRAFO_TEST,
+  CI_QT_TRAFO_ROOT,
+  CI_NUM,               ///< total number
+};
+
+/// motion vector predictor direction used in AMVP
+enum MVP_DIR
+{
+  MD_LEFT = 0,          ///< MVP of left block
+  MD_ABOVE,             ///< MVP of above block
+  MD_ABOVE_RIGHT,       ///< MVP of above right block
+  MD_BELOW_LEFT,        ///< MVP of below left block
+  MD_ABOVE_LEFT         ///< MVP of above left block
+};
+
+/// motion vector prediction mode used in AMVP
+enum AMVP_MODE
+{
+  AM_NONE = 0,          ///< no AMVP mode
+  AM_EXPL,              ///< explicit signalling of motion vector index
+};
+
+/// coefficient scanning type used in ACS
+enum COEFF_SCAN_TYPE
+{
+  SCAN_ZIGZAG = 0,      ///< typical zigzag scan
+  SCAN_HOR,             ///< horizontal first scan
+  SCAN_VER,              ///< vertical first scan
+  SCAN_DIAG              ///< up-right diagonal scan
+};
+
+// Renderer
+enum
+{
+  VIEWPOS_INVALID = -1,
+  VIEWPOS_LEFT    = 0,
+  VIEWPOS_RIGHT   = 1,
+  VIEWPOS_MERGED  = 2
+};
+
+//! \}
+
+#endif
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/AnnexBread.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 341)
@@ -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-2012, 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 <stdint.h>
+#include <cassert>
+#include <vector>
+#include "AnnexBread.h"
+
+using namespace std;
+
+//! \ingroup TLibDecoder
+//! \{
+
+/**
+ * Parse an AVC AnnexB Bytestream bs to extract a single nalUnit
+ * while accumulating bytestream statistics into stats.
+ *
+ * If EOF occurs while trying to extract a NALunit, an exception
+ * of std::ios_base::failure is thrown.  The contsnts of stats will
+ * be correct at this point.
+ */
+static void
+_byteStreamNALUnit(
+  InputByteStream& bs,
+  vector<uint8_t>& nalUnit,
+  AnnexBStats& stats)
+{
+  /* At the beginning of the decoding process, the decoder initialises its
+   * current position in the byte stream to the beginning of the byte stream.
+   * It then extracts and discards each leading_zero_8bits syntax element (if
+   * present), moving the current position in the byte stream forward one
+   * byte at a time, until the current position in the byte stream is such
+   * that the next four bytes in the bitstream form the four-byte sequence
+   * 0x00000001.
+   */
+  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();
+    assert(leading_zero_8bits == 0);
+    stats.m_numLeadingZero8BitsBytes++;
+  }
+
+  /* 1. When the next four bytes in the bitstream form the four-byte sequence
+   * 0x00000001, the next byte in the byte stream (which is a zero_byte
+   * syntax element) is extracted and discarded and the current position in
+   * the byte stream is set equal to the position of the byte following this
+   * discarded byte.
+   */
+  /* NB, the previous step guarantees this will succeed -- if EOF was
+   * encountered, an exception will stop execution getting this far */
+  if (bs.peekBytes(24/8) != 0x000001)
+  {
+    uint8_t zero_byte = bs.readByte();
+    assert(zero_byte == 0);
+    stats.m_numZeroByteBytes++;
+  }
+
+  /* 2. The next three-byte sequence in the byte stream (which is a
+   * start_code_prefix_one_3bytes) is extracted and discarded and the current
+   * position in the byte stream is set equal to the position of the byte
+   * following this three-byte sequence.
+   */
+  /* NB, (1) guarantees that the next three bytes are 0x00 00 01 */
+  uint32_t start_code_prefix_one_3bytes = bs.readBytes(24/8);
+  assert(start_code_prefix_one_3bytes == 0x000001);
+  stats.m_numStartCodePrefixBytes += 3;
+
+  /* 3. NumBytesInNALunit is set equal to the number of bytes starting with
+   * the byte at the current position in the byte stream up to and including
+   * the last byte that precedes the location of any of the following
+   * conditions:
+   *   a. A subsequent byte-aligned three-byte sequence equal to 0x000000, or
+   *   b. A subsequent byte-aligned three-byte sequence equal to 0x000001, or
+   *   c. The end of the byte stream, as determined by unspecified means.
+   */
+  /* 4. NumBytesInNALunit bytes are removed from the bitstream and the
+   * current position in the byte stream is advanced by NumBytesInNALunit
+   * bytes. This sequence of bytes is nal_unit( NumBytesInNALunit ) and is
+   * decoded using the NAL unit decoding process
+   */
+  /* NB, (unsigned)x > 2 implies n!=0 && n!=1 */
+  while (bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) > 1) // since 0x000002 tile marker may exist in the bitstream
+  {
+    nalUnit.push_back(bs.readByte());
+  }
+  
+  /* 5. When the current position in the byte stream is:
+   *  - not at the end of the byte stream (as determined by unspecified means)
+   *  - and the next bytes in the byte stream do not start with a three-byte
+   *    sequence equal to 0x000001
+   *  - and the next bytes in the byte stream do not start with a four byte
+   *    sequence equal to 0x00000001,
+   * the decoder extracts and discards each trailing_zero_8bits syntax
+   * element, moving the current position in the byte stream forward one byte
+   * at a time, until the current position in the byte stream is such that:
+   *  - the next bytes in the byte stream form the four-byte sequence
+   *    0x00000001 or
+   *  - the end of the byte stream has been encountered (as determined by
+   *    unspecified means).
+   */
+  /* NB, (3) guarantees there are at least three bytes available or none */
+  while ((bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) != 0x000001)
+  &&     (bs.eofBeforeNBytes(32/8) || bs.peekBytes(32/8) != 0x00000001))
+  {
+    uint8_t trailing_zero_8bits = bs.readByte();
+    assert(trailing_zero_8bits == 0);
+    stats.m_numTrailingZero8BitsBytes++;
+  }
+}
+
+/**
+ * Parse an AVC AnnexB Bytestream bs to extract a single nalUnit
+ * while accumulating bytestream statistics into stats.
+ *
+ * Returns false if EOF was reached (NB, nalunit data may be valid),
+ *         otherwise true.
+ */
+bool
+byteStreamNALUnit(
+  InputByteStream& bs,
+  vector<uint8_t>& nalUnit,
+  AnnexBStats& stats)
+{
+  bool eof = false;
+  try
+  {
+    _byteStreamNALUnit(bs, nalUnit, stats);
+  }
+  catch (...)
+  {
+    eof = true;
+  }
+  stats.m_numBytesInNALUnit = unsigned(nalUnit.size());
+  return eof;
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/AnnexBread.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/AnnexBread.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/AnnexBread.h	(revision 341)
@@ -0,0 +1,179 @@
+/* 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-2012, 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
+
+#include <stdint.h>
+#include <istream>
+#include <vector>
+
+//! \ingroup TLibDecoder
+//! \{
+
+class InputByteStream
+{
+public:
+  /**
+   * Create a bytestream reader that will extract bytes from
+   * istream.
+   *
+   * NB, it isn't safe to access istream while in use by a
+   * InputByteStream.
+   *
+   * Side-effects: the exception mask of istream is set to eofbit
+   */
+  InputByteStream(std::istream& istream)
+  : m_NumFutureBytes(0)
+  , m_FutureBytes(0)
+  , m_Input(istream)
+  {
+    istream.exceptions(std::istream::eofbit);
+  }
+
+  /**
+   * Reset the internal state.  Must be called if input stream is
+   * modified externally to this class
+   */
+  void reset()
+  {
+    m_NumFutureBytes = 0;
+    m_FutureBytes = 0;
+  }
+
+  /**
+   * returns true if an EOF will be encountered within the next
+   * n bytes.
+   */
+  bool eofBeforeNBytes(unsigned n)
+  {
+    assert(n <= 4);
+    if (m_NumFutureBytes >= n)
+      return false;
+
+    n -= m_NumFutureBytes;
+    try
+    {
+      for (unsigned i = 0; i < n; i++)
+      {
+        m_FutureBytes = (m_FutureBytes << 8) | m_Input.get();
+        m_NumFutureBytes++;
+      }
+    }
+    catch (...)
+    {
+      return true;
+    }
+    return false;
+  }
+
+  /**
+   * return the next n bytes in the stream without advancing
+   * the stream pointer.
+   *
+   * Returns: an unsigned integer representing an n byte bigendian
+   * word.
+   *
+   * If an attempt is made to read past EOF, an n-byte word is
+   * returned, but the portion that required input bytes beyond EOF
+   * is undefined.
+   *
+   */
+  uint32_t peekBytes(unsigned n)
+  {
+    eofBeforeNBytes(n);
+    return m_FutureBytes >> 8*(m_NumFutureBytes - n);
+  }
+
+  /**
+   * consume and return one byte from the input.
+   *
+   * If bytestream is already at EOF prior to a call to readByte(),
+   * an exception std::ios_base::failure is thrown.
+   */
+  uint8_t readByte()
+  {
+    if (!m_NumFutureBytes)
+    {
+      uint8_t byte = m_Input.get();
+      return byte;
+    }
+    m_NumFutureBytes--;
+    uint8_t wanted_byte = m_FutureBytes >> 8*m_NumFutureBytes;
+    m_FutureBytes &= ~(0xff << 8*m_NumFutureBytes);
+    return wanted_byte;
+  }
+
+  /**
+   * consume and return n bytes from the input.  n bytes from
+   * bytestream are interpreted as bigendian when assembling
+   * the return value.
+   */
+  uint32_t readBytes(unsigned n)
+  {
+    uint32_t val = 0;
+    for (unsigned i = 0; i < n; i++)
+      val = (val << 8) | readByte();
+    return val;
+  }
+
+private:
+  unsigned m_NumFutureBytes; /* number of valid bytes in m_FutureBytes */
+  uint32_t m_FutureBytes; /* bytes that have been peeked */
+  std::istream& m_Input; /* Input stream to read from */
+};
+
+/**
+ * Statistics associated with AnnexB bytestreams
+ */
+struct AnnexBStats
+{
+  unsigned m_numLeadingZero8BitsBytes;
+  unsigned m_numZeroByteBytes;
+  unsigned m_numStartCodePrefixBytes;
+  unsigned m_numBytesInNALUnit;
+  unsigned m_numTrailingZero8BitsBytes;
+
+  AnnexBStats& operator+=(const AnnexBStats& rhs)
+  {
+    this->m_numLeadingZero8BitsBytes += rhs.m_numLeadingZero8BitsBytes;
+    this->m_numZeroByteBytes += rhs.m_numZeroByteBytes;
+    this->m_numStartCodePrefixBytes += rhs.m_numStartCodePrefixBytes;
+    this->m_numBytesInNALUnit += rhs.m_numBytesInNALUnit;
+    this->m_numTrailingZero8BitsBytes += rhs.m_numTrailingZero8BitsBytes;
+    return *this;
+  }
+};
+
+bool byteStreamNALUnit(InputByteStream& bs, std::vector<uint8_t>& nalUnit, AnnexBStats& stats);
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/NALread.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/NALread.cpp	(revision 341)
@@ -0,0 +1,153 @@
+/* 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-2012, 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 <vector>
+#include <algorithm>
+#include <ostream>
+
+#include "NALread.h"
+#include "TLibCommon/NAL.h"
+#include "TLibCommon/TComBitStream.h"
+
+using namespace std;
+
+//! \ingroup TLibDecoder
+//! \{
+static void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, TComInputBitstream *pcBitstream)
+{
+  unsigned zeroCount = 0;
+  vector<uint8_t>::iterator it_read, it_write;
+
+  UInt *auiStoredTileMarkerLocation = new UInt[MAX_MARKER_PER_NALU];
+  // Remove tile markers and note the bitstream location
+  for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++ )
+  {
+    Bool bTileMarkerFound = false;
+    if ( ( it_read - nalUnitBuf.begin() ) < ( nalUnitBuf.size() - 2 ) )
+    {
+      if ( (*(it_read) == 0x00) && (*(it_read+1) == 0x00) && (*(it_read+2) == 0x02) ) // tile marker detected
+      {
+        it_read += 2;
+        UInt uiDistance  = (UInt) (it_write - nalUnitBuf.begin());
+        UInt uiCount     = pcBitstream->getTileMarkerLocationCount();
+        bTileMarkerFound = true;
+        pcBitstream->setTileMarkerLocation( uiCount, uiDistance );
+        auiStoredTileMarkerLocation[uiCount] = uiDistance;
+        pcBitstream->setTileMarkerLocationCount( uiCount + 1 );
+        
+      }
+    }
+
+    if (!bTileMarkerFound)
+    {
+      *it_write = *it_read;
+      it_write++;
+    }
+  }
+  nalUnitBuf.resize(it_write - nalUnitBuf.begin());
+
+  for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++, it_write++)
+  {
+    if (zeroCount == 2 && *it_read == 0x03)
+    {
+      // update tile marker location
+      UInt uiDistance = (UInt) (it_read - nalUnitBuf.begin());
+      for (UInt uiIdx=0; uiIdx<pcBitstream->getTileMarkerLocationCount(); uiIdx++)
+      {
+        if (auiStoredTileMarkerLocation[ uiIdx ] >= uiDistance)
+        {
+          pcBitstream->setTileMarkerLocation( uiIdx, pcBitstream->getTileMarkerLocation( uiIdx )-1 );
+        }
+      }
+      it_read++;
+      zeroCount = 0;
+    }
+    zeroCount = (*it_read == 0x00) ? zeroCount+1 : 0;
+    *it_write = *it_read;
+  }
+
+  nalUnitBuf.resize(it_write - nalUnitBuf.begin());
+  delete [] auiStoredTileMarkerLocation;
+}
+
+/**
+ * create a NALunit structure with given header values and storage for
+ * a bitstream
+ */
+void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf)
+{
+  /* perform anti-emulation prevention */
+  TComInputBitstream *pcBitstream = new TComInputBitstream(NULL);
+  convertPayloadToRBSP(nalUnitBuf, pcBitstream);
+
+  nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf);
+  // copy the tile marker location information
+  nalu.m_Bitstream->setTileMarkerLocationCount( pcBitstream->getTileMarkerLocationCount() );
+  for (UInt uiIdx=0; uiIdx < nalu.m_Bitstream->getTileMarkerLocationCount(); uiIdx++)
+  {
+    nalu.m_Bitstream->setTileMarkerLocation( uiIdx, pcBitstream->getTileMarkerLocation(uiIdx) );
+  }
+  delete pcBitstream;
+  TComInputBitstream& bs = *nalu.m_Bitstream;
+
+  bool forbidden_zero_bit = bs.read(1);
+  assert(forbidden_zero_bit == 0);
+
+  nalu.m_nalRefFlag  = (bs.read(1) != 0 );
+  nalu.m_nalUnitType = (NalUnitType) bs.read(6);
+
+#if QC_MVHEVC_B0046
+  //nalu.m_layerId    = bs.read(6);
+  nalu.m_layerId    = bs.read(5);
+  nalu.m_temporalId = bs.read(3) - 1;
+#else
+  nalu.m_temporalId = bs.read(3);
+ //  unsigned reserved_one_5bits = bs.read(5);
+ //  assert(reserved_one_5bits == 1);
+#if VIDYO_VPS_INTEGRATION
+  nalu.m_layerId  = bs.read(5) - 1;
+#else
+  nalu.m_viewId   = bs.read(4)-1;
+  nalu.m_isDepth  = bs.read(1);
+#endif
+  if ( nalu.m_temporalId )
+  {
+#if QC_REM_IDV_B0046
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR);
+#else
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDV );
+#endif
+  }
+#endif
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/NALread.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/NALread.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/NALread.h	(revision 341)
@@ -0,0 +1,54 @@
+/* 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-2012, 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
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComBitStream.h"
+#include "../TLibCommon/NAL.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+/**
+ * A convenience wrapper to NALUnit that also provides a
+ * bitstream object.
+ */
+struct InputNALUnit : public NALUnit
+{
+  TComInputBitstream* m_Bitstream;
+};
+
+void read(InputNALUnit& nalu, std::vector<uint8_t>& nalUnitBuf);
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/SEIread.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/SEIread.cpp	(revision 341)
@@ -0,0 +1,117 @@
+/* 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-2012, 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/TComBitStream.h"
+#include "TLibCommon/SEI.h"
+#include "SEIread.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+static void parseSEIuserDataUnregistered(TComInputBitstream& bs, SEIuserDataUnregistered &sei, unsigned payloadSize);
+static void parseSEIpictureDigest(TComInputBitstream& bs, SEIpictureDigest& sei, unsigned payloadSize);
+
+/**
+ * unmarshal a single SEI message from bitstream bs
+ */
+void parseSEImessage(TComInputBitstream& bs, SEImessages& seis)
+{
+  unsigned payloadType = 0;
+  for (unsigned char byte = 0xff; 0xff == byte; )
+  {
+    payloadType += byte = bs.read(8);
+  }
+
+  unsigned payloadSize = 0;
+  for (unsigned char byte = 0xff; 0xff == byte; )
+  {
+    payloadSize += byte = bs.read(8);
+  }
+
+  switch (payloadType)
+  {
+  case SEI::USER_DATA_UNREGISTERED:
+    seis.user_data_unregistered = new SEIuserDataUnregistered;
+    parseSEIuserDataUnregistered(bs, *seis.user_data_unregistered, payloadSize);
+    break;
+  case SEI::PICTURE_DIGEST:
+    seis.picture_digest = new SEIpictureDigest;
+    parseSEIpictureDigest(bs, *seis.picture_digest, payloadSize);
+    break;
+  default:
+    assert(!"Unhandled SEI message");
+  }
+}
+
+/**
+ * parse bitstream bs and unpack a user_data_unregistered SEI message
+ * of payloasSize bytes into sei.
+ */
+static void parseSEIuserDataUnregistered(TComInputBitstream& bs, SEIuserDataUnregistered &sei, unsigned payloadSize)
+{
+  assert(payloadSize >= 16);
+  for (unsigned i = 0; i < 16; i++)
+  {
+    sei.uuid_iso_iec_11578[i] = bs.read(8);
+  }
+
+  sei.userDataLength = payloadSize - 16;
+  if (!sei.userDataLength)
+  {
+    sei.userData = 0;
+    return;
+  }
+
+  sei.userData = new unsigned char[sei.userDataLength];
+  for (unsigned i = 0; i < sei.userDataLength; i++)
+  {
+    sei.userData[i] = bs.read(8);
+  }
+}
+
+/**
+ * parse bitstream bs and unpack a picture_digest SEI message
+ * of payloadSize bytes into sei.
+ */
+static void parseSEIpictureDigest(TComInputBitstream& bs, SEIpictureDigest& sei, unsigned payloadSize)
+{
+  assert(payloadSize >= 17);
+  sei.method = static_cast<SEIpictureDigest::Method>(bs.read(8));
+  assert(SEIpictureDigest::MD5 == sei.method);
+  for (unsigned i = 0; i < 16; i++)
+  {
+    sei.digest[i] = bs.read(8);
+  }
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/SEIread.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/SEIread.h	(revision 341)
@@ -0,0 +1,44 @@
+/* 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-2012, 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
+
+//! \ingroup TLibDecoder
+//! \{
+
+class TComInputBitstream;
+class SEImessages;
+
+void parseSEImessage(TComInputBitstream& bs, SEImessages& seis);
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 341)
@@ -0,0 +1,79 @@
+/* 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-2012, 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     TDecBinCoder.h
+    \brief    binary entropy decoder interface
+*/
+
+#ifndef __TDEC_BIN_CODER__
+#define __TDEC_BIN_CODER__
+
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComBitStream.h"
+
+//! \ingroup TLibDecoder
+//! \{
+class TDecBinCABAC;
+
+class TDecBinIf
+{
+public:
+  virtual Void  init              ( TComInputBitstream* pcTComBitstream )     = 0;
+  virtual Void  uninit            ()                                          = 0;
+
+  virtual Void  start             ()                                          = 0;
+  virtual Void  finish            ()                                          = 0;
+  virtual Void  flush            ()                                           = 0;
+
+  virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel )  = 0;
+  virtual Void  decodeBinEP       ( UInt& ruiBin                           )  = 0;
+  virtual Void  decodeBinsEP      ( UInt& ruiBins, Int numBins             )  = 0;
+  virtual Void  decodeBinTrm      ( UInt& ruiBin                           )  = 0;
+  
+  virtual Void  resetBac          ()                                          = 0;
+  virtual Void  decodeNumSubseqIPCM( Int& numSubseqIPCM )                  = 0;
+  virtual Void  decodePCMAlignBits()                                          = 0;
+  virtual Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode)              = 0;
+
+  virtual ~TDecBinIf() {}
+
+  virtual Void  copyState         ( TDecBinIf* pcTDecBinIf )                  = 0;
+  virtual TDecBinCABAC*   getTDecBinCABAC   ()  { return 0; }
+#if !OL_FLUSH_ALIGN
+  virtual Int   getBitsReadAhead() { return 0; }
+#endif
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 341)
@@ -0,0 +1,363 @@
+/* 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-2012, 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     TDecBinCoderCABAC.cpp
+    \brief    binary entropy decoder of CABAC
+*/
+
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+TDecBinCABAC::TDecBinCABAC()
+: m_pcTComBitstream( 0 )
+{
+}
+
+TDecBinCABAC::~TDecBinCABAC()
+{
+}
+
+Void
+TDecBinCABAC::init( TComInputBitstream* pcTComBitstream )
+{
+  m_pcTComBitstream = pcTComBitstream;
+}
+
+Void
+TDecBinCABAC::uninit()
+{
+  m_pcTComBitstream = 0;
+}
+
+Void
+TDecBinCABAC::start()
+{
+#if OL_FLUSH_ALIGN
+  assert( m_pcTComBitstream->getNumBitsUntilByteAligned() == 0 );
+#endif
+  
+  m_uiRange    = 510;
+  m_bitsNeeded = -8;
+  m_uiValue    = m_pcTComBitstream->readByte() << 8;
+#if !OL_FLUSH_ALIGN
+  m_uiLastByte = m_pcTComBitstream->readByte();
+  m_uiValue   |= m_uiLastByte;
+#else
+  m_uiValue   |= m_pcTComBitstream->readByte();
+#endif
+}
+
+Void
+TDecBinCABAC::finish()
+{
+}
+
+Void 
+TDecBinCABAC::flush()
+{
+#if OL_FLUSH_ALIGN
+  while (m_pcTComBitstream->getNumBitsLeft() > 0 && m_pcTComBitstream->getNumBitsUntilByteAligned() != 0)
+  {
+    UInt uiBits;
+    m_pcTComBitstream->read ( 1, uiBits );
+  }
+  start();
+#else
+  m_uiRange    = 510;
+  Int iExtra = 16+m_bitsNeeded+1; // m_bitsNeeded is -ve: iExtra is many bits to read to make up 16.
+  UInt uiExtraBits;
+  m_pcTComBitstream->read(iExtra, uiExtraBits);
+  m_uiValue = (m_uiLastByte << iExtra) | uiExtraBits;
+  m_uiValue &= 0xffff;
+  m_uiLastByte = m_uiValue;
+  m_uiLastByte &= 0xff;
+  m_bitsNeeded = -8;
+#endif // OL_FLUSH_ALIGN
+}
+
+/**
+ - Copy CABAC state.
+ .
+ \param pcTDecBinIf The source CABAC engine.
+ */
+Void
+TDecBinCABAC::copyState( TDecBinIf* pcTDecBinIf )
+{
+  TDecBinCABAC* pcTDecBinCABAC = pcTDecBinIf->getTDecBinCABAC();
+  m_uiRange   = pcTDecBinCABAC->m_uiRange;
+  m_uiValue   = pcTDecBinCABAC->m_uiValue;
+  m_bitsNeeded= pcTDecBinCABAC->m_bitsNeeded;
+#if !OL_FLUSH_ALIGN
+  m_uiLastByte= pcTDecBinCABAC->m_uiLastByte;
+#endif
+}
+
+
+Void
+TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel )
+{
+  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();
+    rcCtxModel.updateMPS();
+    
+    if ( scaledRange >= ( 256 << 7 ) )
+    {
+      return;
+    }
+    
+    m_uiRange = scaledRange >> 6;
+    m_uiValue += m_uiValue;
+    
+    if ( ++m_bitsNeeded == 0 )
+    {
+      m_bitsNeeded = -8;
+#if !OL_FLUSH_ALIGN
+      m_uiLastByte = m_pcTComBitstream->readByte();
+      m_uiValue += m_uiLastByte;    
+#else
+      m_uiValue += m_pcTComBitstream->readByte();      
+#endif
+    }
+  }
+  else
+  {
+    // LPS path
+    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 )
+    {
+#if !OL_FLUSH_ALIGN
+      m_uiLastByte = m_pcTComBitstream->readByte();
+      m_uiValue += m_uiLastByte << m_bitsNeeded;
+#else
+      m_uiValue += m_pcTComBitstream->readByte() << m_bitsNeeded;
+#endif
+      m_bitsNeeded -= 8;
+    }
+  }
+}
+
+Void
+TDecBinCABAC::decodeBinEP( UInt& ruiBin )
+{
+  m_uiValue += m_uiValue;
+  
+  if ( ++m_bitsNeeded >= 0 )
+  {
+    m_bitsNeeded = -8;
+#if !OL_FLUSH_ALIGN
+    m_uiLastByte = m_pcTComBitstream->readByte();
+    m_uiValue += m_uiLastByte;
+#else
+    m_uiValue += m_pcTComBitstream->readByte();
+#endif
+  }
+  
+  ruiBin = 0;
+  UInt scaledRange = m_uiRange << 7;
+  if ( m_uiValue >= scaledRange )
+  {
+    ruiBin = 1;
+    m_uiValue -= scaledRange;
+  }
+}
+
+Void TDecBinCABAC::decodeBinsEP( UInt& ruiBin, Int numBins )
+{
+  UInt bins = 0;
+  
+  while ( numBins > 8 )
+  {
+#if !OL_FLUSH_ALIGN
+    m_uiLastByte = m_pcTComBitstream->readByte();
+    m_uiValue = ( m_uiValue << 8 ) + ( m_uiLastByte << ( 8 + m_bitsNeeded ) );
+#else
+    m_uiValue = ( m_uiValue << 8 ) + ( m_pcTComBitstream->readByte() << ( 8 + m_bitsNeeded ) );
+#endif
+    
+    UInt scaledRange = m_uiRange << 15;
+    for ( Int i = 0; i < 8; i++ )
+    {
+      bins += bins;
+      scaledRange >>= 1;
+      if ( m_uiValue >= scaledRange )
+      {
+        bins++;
+        m_uiValue -= scaledRange;
+      }
+    }
+    numBins -= 8;
+  }
+  
+  m_bitsNeeded += numBins;
+  m_uiValue <<= numBins;
+  
+  if ( m_bitsNeeded >= 0 )
+  {
+#if !OL_FLUSH_ALIGN
+    m_uiLastByte = m_pcTComBitstream->readByte();
+    m_uiValue += m_uiLastByte << m_bitsNeeded;
+#else
+    m_uiValue += m_pcTComBitstream->readByte() << m_bitsNeeded;
+#endif
+    m_bitsNeeded -= 8;
+  }
+  
+  UInt scaledRange = m_uiRange << ( numBins + 7 );
+  for ( Int i = 0; i < numBins; i++ )
+  {
+    bins += bins;
+    scaledRange >>= 1;
+    if ( m_uiValue >= scaledRange )
+    {
+      bins++;
+      m_uiValue -= scaledRange;
+    }
+  }
+  
+  ruiBin = bins;
+}
+
+Void
+TDecBinCABAC::decodeBinTrm( UInt& ruiBin )
+{
+  m_uiRange -= 2;
+  UInt scaledRange = m_uiRange << 7;
+  if( m_uiValue >= scaledRange )
+  {
+    ruiBin = 1;
+  }
+  else
+  {
+    ruiBin = 0;
+    if ( scaledRange < ( 256 << 7 ) )
+    {
+      m_uiRange = scaledRange >> 6;
+      m_uiValue += m_uiValue;
+      
+      if ( ++m_bitsNeeded == 0 )
+      {
+        m_bitsNeeded = -8;
+#if !OL_FLUSH_ALIGN
+        m_uiLastByte = m_pcTComBitstream->readByte();
+        m_uiValue += m_uiLastByte;    
+#else
+        m_uiValue += m_pcTComBitstream->readByte();      
+#endif
+      }
+    }
+  }
+}
+
+/** Reset BAC register values.
+ * \returns Void
+ */
+Void TDecBinCABAC::resetBac()
+{
+  m_uiRange    = 510;
+  m_bitsNeeded = -8;
+  m_uiValue    = m_pcTComBitstream->read( 16 );
+}
+
+/** Decode subsequent_pcm_num.
+ * \param numSubseqIPCM
+ * \returns Void
+ */
+Void TDecBinCABAC::decodeNumSubseqIPCM( Int& numSubseqIPCM )
+{
+  UInt bit = 0;
+
+  numSubseqIPCM = 0;
+
+  do
+  {
+    m_uiValue += m_uiValue;
+    if ( ++m_bitsNeeded >= 0 )
+    {
+      m_bitsNeeded = -8;
+#if !OL_FLUSH_ALIGN
+      m_uiLastByte = m_pcTComBitstream->readByte();
+      m_uiValue += m_uiLastByte;
+#else
+      m_uiValue += m_pcTComBitstream->readByte();
+#endif
+    }
+    bit = ((m_uiValue&128)>>7);
+    numSubseqIPCM++;
+  }
+  while( bit && (numSubseqIPCM < 3 ));
+
+  if( bit && (numSubseqIPCM == 3 ))
+  {
+    numSubseqIPCM++;
+  }
+
+  numSubseqIPCM --;
+}
+
+/** Decode PCM alignment zero bits.
+ * \returns Void
+ */
+Void TDecBinCABAC::decodePCMAlignBits()
+{
+  Int iNum = m_pcTComBitstream->getNumBitsUntilByteAligned();
+  
+  UInt uiBit = 0;
+  m_pcTComBitstream->read( iNum, uiBit );
+}
+
+/** Read a PCM code.
+ * \param uiLength code bit-depth
+ * \param ruiCode pointer to PCM code value
+ * \returns Void
+ */
+Void  TDecBinCABAC::xReadPCMCode(UInt uiLength, UInt& ruiCode)
+{
+  assert ( uiLength > 0 );
+  m_pcTComBitstream->read (uiLength, ruiCode);
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 341)
@@ -0,0 +1,89 @@
+/* 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-2012, 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     TDecBinCoderCABAC.h
+    \brief    binary entropy decoder of CABAC
+*/
+
+#ifndef __TDEC_BIN_CODER_CABAC__
+#define __TDEC_BIN_CODER_CABAC__
+
+#include "TLibCommon/TComCABACTables.h"
+#include "TDecBinCoder.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+class TDecBinCABAC : public TDecBinIf
+{
+public:
+  TDecBinCABAC ();
+  virtual ~TDecBinCABAC();
+  
+  Void  init              ( TComInputBitstream* pcTComBitstream );
+  Void  uninit            ();
+  
+  Void  start             ();
+  Void  finish            ();
+  Void  flush             ();
+  
+  Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel );
+  Void  decodeBinEP       ( UInt& ruiBin                           );
+  Void  decodeBinsEP      ( UInt& ruiBin, Int numBins              );
+  Void  decodeBinTrm      ( UInt& ruiBin                           );
+  
+  Void  resetBac          ();
+  Void  decodeNumSubseqIPCM( Int& numSubseqIPCM ) ;
+  Void  decodePCMAlignBits();
+  Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode );
+  
+  Void  copyState         ( TDecBinIf* pcTDecBinIf );
+  TDecBinCABAC* getTDecBinCABAC()  { return this; }
+#if !OL_FLUSH_ALIGN
+  Int   getBitsReadAhead() { return -m_bitsNeeded; }
+#endif
+
+private:
+  TComInputBitstream* m_pcTComBitstream;
+  UInt                m_uiRange;
+  UInt                m_uiValue;
+#if !OL_FLUSH_ALIGN
+  UInt                m_uiLastByte;
+#endif
+  Int                 m_bitsNeeded;
+};
+
+//! \}
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 341)
@@ -0,0 +1,2952 @@
+/* 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-2012, 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     TDecCAVLC.cpp
+    \brief    CAVLC decoder class
+*/
+
+#include "TDecCAVLC.h"
+#include "SEIread.h"
+#include "TDecSlice.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+#define READ_CODE(length, code, name)     xReadCodeTr ( length, code, name )
+#define READ_UVLC(        code, name)     xReadUvlcTr (         code, name )
+#define READ_SVLC(        code, name)     xReadSvlcTr (         code, name )
+#define READ_FLAG(        code, name)     xReadFlagTr (         code, name )
+
+Void  xTraceSPSHeader (TComSPS *pSPS)
+{
+  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
+}
+
+Void  xTracePPSHeader (TComPPS *pPPS)
+{
+  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
+}
+
+Void  xTraceAPSHeader (TComAPS *pAPS)
+{
+  fprintf( g_hTrace, "=========== Adaptation Parameter Set ===========\n");
+}
+
+Void  xTraceSliceHeader (TComSlice *pSlice)
+{
+  fprintf( g_hTrace, "=========== Slice ===========\n");
+}
+
+
+Void  TDecCavlc::xReadCodeTr           (UInt length, UInt& rValue, const Char *pSymbolName)
+{
+  xReadCode (length, rValue);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s u(%d) : %d\n", pSymbolName, length, rValue ); 
+  fflush ( g_hTrace );
+}
+
+Void  TDecCavlc::xReadUvlcTr           (UInt& rValue, const Char *pSymbolName)
+{
+  xReadUvlc (rValue);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s u(v) : %d\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+Void  TDecCavlc::xReadSvlcTr           (Int& rValue, const Char *pSymbolName)
+{
+  xReadSvlc(rValue);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s s(v) : %d\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+Void  TDecCavlc::xReadFlagTr           (UInt& rValue, const Char *pSymbolName)
+{
+  xReadFlag(rValue);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s u(1) : %d\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+#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
+
+
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCavlc::TDecCavlc()
+{
+  m_iSliceGranularity = 0;
+
+  m_aaiTempScale            = new Int* [ MAX_VIEW_NUM ];
+  m_aaiTempOffset           = new Int* [ MAX_VIEW_NUM ];
+  m_aaiTempPdmScaleNomDelta = new Int* [ MAX_VIEW_NUM ];
+  m_aaiTempPdmOffset        = new Int* [ MAX_VIEW_NUM ];
+  for( UInt uiVId = 0; uiVId < MAX_VIEW_NUM; uiVId++ )
+  {
+    m_aaiTempScale            [ uiVId ] = new Int [ MAX_VIEW_NUM ];
+    m_aaiTempOffset           [ uiVId ] = new Int [ MAX_VIEW_NUM ];
+    m_aaiTempPdmScaleNomDelta [ uiVId ] = new Int [ MAX_VIEW_NUM ];
+    m_aaiTempPdmOffset        [ uiVId ] = new Int [ MAX_VIEW_NUM ];
+  }
+}
+
+TDecCavlc::~TDecCavlc()
+{
+  for( UInt uiVId = 0; uiVId < MAX_VIEW_NUM; uiVId++ )
+  {
+    delete [] m_aaiTempScale            [ uiVId ];
+    delete [] m_aaiTempOffset           [ uiVId ];
+    delete [] m_aaiTempPdmScaleNomDelta [ uiVId ];
+    delete [] m_aaiTempPdmOffset        [ uiVId ];
+  }
+  delete [] m_aaiTempScale;
+  delete [] m_aaiTempOffset;
+  delete [] m_aaiTempPdmScaleNomDelta;
+  delete [] m_aaiTempPdmOffset;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * unmarshal a sequence of SEI messages from bitstream.
+ */
+void TDecCavlc::parseSEI(SEImessages& seis)
+{
+  assert(!m_pcBitstream->getNumBitsUntilByteAligned());
+  do
+  {
+    parseSEImessage(*m_pcBitstream, seis);
+    /* SEI messages are an integer number of bytes, something has failed
+     * in the parsing if bitstream not byte-aligned */
+    assert(!m_pcBitstream->getNumBitsUntilByteAligned());
+  } while (0x80 != m_pcBitstream->peekBits(8));
+  assert(m_pcBitstream->getNumBitsLeft() == 8); /* rsbp_trailing_bits */
+}
+void TDecCavlc::parseShortTermRefPicSet( TComSPS* sps, TComReferencePictureSet* rps, Int idx )
+{
+  UInt code;
+  UInt interRPSPred;
+  READ_FLAG(interRPSPred, "inter_ref_pic_set_prediction_flag");  rps->setInterRPSPrediction(interRPSPred);
+  if (interRPSPred) 
+  {
+    UInt bit;
+    READ_UVLC(code, "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+    Int rIdx =  idx - 1 - code;
+    assert (rIdx <= idx && rIdx >= 0);
+    TComReferencePictureSet*   rpsRef = sps->getRPSList()->getReferencePictureSet(rIdx);
+    Int k = 0, k0 = 0, k1 = 0;
+    READ_CODE(1, bit, "delta_rps_sign"); // delta_RPS_sign
+    READ_UVLC(code, "abs_delta_rps_minus1");  // absolute delta RPS minus 1
+    Int deltaRPS = (1 - (bit<<1)) * (code + 1); // delta_RPS
+    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 
+      Int refIdc = bit;
+      if (refIdc == 0) 
+      {
+        READ_CODE(1, bit, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
+        refIdc = bit<<1; //second bit is "1" if refIdc is 2, "0" if refIdc = 0.
+      }
+      if (refIdc == 1 || refIdc == 2)
+      {
+        Int deltaPOC = deltaRPS + ((j < rpsRef->getNumberOfPictures())? rpsRef->getDeltaPOC(j) : 0);
+        rps->setDeltaPOC(k, deltaPOC);
+        rps->setUsed(k, (refIdc == 1));
+
+        if (deltaPOC < 0) {
+          k0++;
+        }
+        else 
+        {
+          k1++;
+        }
+        k++;
+      }  
+      rps->setRefIdc(j,refIdc);  
+    }
+    rps->setNumRefIdc(rpsRef->getNumberOfPictures()+1);  
+    rps->setNumberOfPictures(k);
+    rps->setNumberOfNegativePictures(k0);
+    rps->setNumberOfPositivePictures(k1);
+    rps->sortDeltaPOC();
+  }
+  else
+  {
+    READ_UVLC(code, "num_negative_pics");           rps->setNumberOfNegativePictures(code);
+    READ_UVLC(code, "num_positive_pics");           rps->setNumberOfPositivePictures(code);
+    Int prev = 0;
+    Int poc;
+    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
+    {
+      READ_UVLC(code, "delta_poc_s0_minus1");
+      poc = prev-code-1;
+      prev = poc;
+      rps->setDeltaPOC(j,poc);
+      READ_FLAG(code, "used_by_curr_pic_s0_flag");  rps->setUsed(j,code);
+    }
+    prev = 0;
+    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
+    {
+      READ_UVLC(code, "delta_poc_s1_minus1");
+      poc = prev+code+1;
+      prev = poc;
+      rps->setDeltaPOC(j,poc);
+      READ_FLAG(code, "used_by_curr_pic_s1_flag");  rps->setUsed(j,code);
+    }
+    rps->setNumberOfPictures(rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures());
+  }
+#if PRINT_RPS_INFO
+  rps->printDeltaPOC();
+#endif
+}
+
+Void TDecCavlc::parseAPS(TComAPS* aps)
+{
+#if ENC_DEC_TRACE  
+  xTraceAPSHeader(aps);
+#endif
+
+  UInt uiCode;
+  READ_UVLC(uiCode, "aps_id");                             aps->setAPSID(uiCode);
+  READ_FLAG(uiCode, "aps_scaling_list_data_present_flag"); aps->setScalingListEnabled( (uiCode==1)?true:false );
+  READ_FLAG(uiCode, "aps_deblocking_filter_flag");         aps->setLoopFilterOffsetInAPS( (uiCode==1)?true:false );
+  if(aps->getScalingListEnabled())
+  {
+    parseScalingList( aps->getScalingList() );
+  }
+  if(aps->getLoopFilterOffsetInAPS())
+  {
+    xParseDblParam( aps );    
+  }
+  READ_FLAG(uiCode, "aps_sao_interleaving_flag");      aps->setSaoInterleavingFlag( (uiCode==1)?true:false );
+  if(!aps->getSaoInterleavingFlag())
+  {
+    READ_FLAG(uiCode, "aps_sample_adaptive_offset_flag");      aps->setSaoEnabled( (uiCode==1)?true:false );
+  if(aps->getSaoEnabled())
+  {
+    aps->getSaoParam()->bSaoFlag[0] = true;
+    xParseSaoParam( aps->getSaoParam() );
+  }
+  }
+  READ_FLAG(uiCode, "aps_adaptive_loop_filter_flag");      aps->setAlfEnabled( (uiCode==1)?true:false );
+  if(aps->getAlfEnabled())
+  {
+    xParseAlfParam( aps->getAlfParam());
+  }
+  READ_FLAG( uiCode, "aps_extension_flag");
+  if (uiCode)
+  {
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "aps_extension_data_flag");
+    }
+  }
+
+}
+
+Void  TDecCavlc::xParseDblParam       ( TComAPS* aps )
+{
+  UInt uiSymbol;
+  Int iSymbol;
+
+  parseDFFlag(uiSymbol, "loop_filter_disable");
+  aps->setLoopFilterDisable(uiSymbol?true:false);
+
+  if (!aps->getLoopFilterDisable())
+  {
+    parseDFSvlc(iSymbol, "beta_offset_div2");
+    aps->setLoopFilterBetaOffset(iSymbol);
+    parseDFSvlc(iSymbol, "tc_offset_div2");
+    aps->setLoopFilterTcOffset(iSymbol);
+  }
+}
+/** parse SAO parameters
+ * \param pSaoParam
+ */
+Void TDecCavlc::xParseSaoParam(SAOParam* pSaoParam)
+{
+  UInt uiSymbol;
+
+  int i,j, compIdx; 
+  int numCuInWidth; 
+  int numCuInHeight; 
+  Bool repeatedRow[3];
+  if (pSaoParam->bSaoFlag[0])                                                                    
+  {     
+    READ_FLAG (uiSymbol, "sao_cb_enable_flag");            pSaoParam->bSaoFlag[1]   = uiSymbol? true:false;  
+    READ_FLAG (uiSymbol, "sao_cr_enable_flag");            pSaoParam->bSaoFlag[2]   = uiSymbol? true:false;  
+    READ_UVLC (uiSymbol, "sao_num_lcu_in_width_minus1");   pSaoParam->numCuInWidth  = uiSymbol + 1;                          
+    READ_UVLC (uiSymbol, "sao_num_lcu_in_height_minus1");  pSaoParam->numCuInHeight = uiSymbol + 1;                          
+    numCuInWidth  = pSaoParam->numCuInWidth;
+    numCuInHeight = pSaoParam->numCuInHeight;
+
+    READ_FLAG (uiSymbol, "sao_one_luma_unit_flag");  pSaoParam->oneUnitFlag[0] = uiSymbol? true:false;  
+    if (pSaoParam->oneUnitFlag[0] )
+      xParseSaoOffset(&(pSaoParam->saoLcuParam[0][0]));
+
+    if (pSaoParam->bSaoFlag[1])
+    {
+      READ_FLAG (uiSymbol, "sao_one_cb_unit_flag");  pSaoParam->oneUnitFlag[1] = uiSymbol? true:false;  
+      if (pSaoParam->oneUnitFlag[1] )
+        xParseSaoOffset(&(pSaoParam->saoLcuParam[1][0]));
+    }
+    if (pSaoParam->bSaoFlag[2])
+    {
+      READ_FLAG (uiSymbol, "sao_one_cr_unit_flag");  pSaoParam->oneUnitFlag[2] = uiSymbol? true:false;  
+      if (pSaoParam->oneUnitFlag[2] )
+        xParseSaoOffset(&(pSaoParam->saoLcuParam[2][0]));
+    }
+    for (j=0;j<numCuInHeight;j++)
+    {
+      for (compIdx=0;compIdx<3;compIdx++)
+      {
+        repeatedRow[compIdx] = 0;
+      }
+      for (i=0;i<numCuInWidth;i++)
+      {
+        for (compIdx=0; compIdx<3; compIdx++)
+        {
+          if (pSaoParam->bSaoFlag[compIdx]  && !pSaoParam->oneUnitFlag[compIdx]) 
+          {
+            if (j>0 && i==0) 
+            {
+              READ_FLAG (uiSymbol, "sao_repeat_row_flag");  repeatedRow[compIdx] = uiSymbol? true:false; 
+            }
+            xParseSaoUnit (i,j, compIdx, pSaoParam, repeatedRow[compIdx]);
+          }
+        }
+      }
+    }
+  }
+}
+/** copy SAO parameter
+ * \param dst  
+ * \param src 
+ */
+inline Void copySaoOneLcuParam(SaoLcuParam* dst,  SaoLcuParam* src)
+{
+  Int i;
+  dst->partIdx = src->partIdx;
+  dst->typeIdx = src->typeIdx;
+  if (dst->typeIdx != -1)
+  {
+    if (dst->typeIdx == SAO_BO)
+    {
+      dst->bandPosition = src->bandPosition ;
+    }
+    else
+    {
+      dst->bandPosition = 0;
+    }
+    dst->length  = src->length;
+    for (i=0;i<dst->length;i++)
+    {
+      dst->offset[i] = src->offset[i];
+    }
+  }
+  else
+  {
+    dst->length  = 0;
+    for (i=0;i<SAO_BO_LEN;i++)
+    {
+      dst->offset[i] = 0;
+    }
+  }
+}
+/** parse SAO offset
+ * \param saoLcuParam SAO LCU parameters
+ */
+Void TDecCavlc::xParseSaoOffset(SaoLcuParam* saoLcuParam)
+{
+  UInt uiSymbol;
+  Int iSymbol;
+  static Int typeLength[MAX_NUM_SAO_TYPE] = {
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_BO_LEN
+  }; 
+
+  READ_UVLC (uiSymbol, "sao_type_idx");   saoLcuParam->typeIdx = (Int)uiSymbol - 1;       
+  if (uiSymbol)
+  {
+    saoLcuParam->length = typeLength[saoLcuParam->typeIdx];
+    if( saoLcuParam->typeIdx == SAO_BO )
+    {
+      READ_CODE( 5, uiSymbol, "sao_band_position"); saoLcuParam->bandPosition = uiSymbol; 
+      for(Int i=0; i< saoLcuParam->length; i++)
+      {
+        READ_SVLC (iSymbol, "sao_offset");    saoLcuParam->offset[i] = iSymbol;   
+      }   
+    }
+    else if( saoLcuParam->typeIdx < 4 )
+    {
+      READ_UVLC (uiSymbol, "sao_offset");  saoLcuParam->offset[0] = uiSymbol;
+      READ_UVLC (uiSymbol, "sao_offset");  saoLcuParam->offset[1] = uiSymbol;
+      READ_UVLC (uiSymbol, "sao_offset");  saoLcuParam->offset[2] = -(Int)uiSymbol;
+      READ_UVLC (uiSymbol, "sao_offset");  saoLcuParam->offset[3] = -(Int)uiSymbol;
+    }
+  }
+  else
+  {
+    saoLcuParam->length = 0;
+  }
+}
+
+/** parse SAO unit
+ * \param rx x-axis location
+ * \param ry y-axis location
+ * \param compIdx color component index
+ * \param saoParam SAO parameters
+ * \param repeatedRow repeat row flag
+ */
+void TDecCavlc::xParseSaoUnit(Int rx, Int ry, Int compIdx, SAOParam* saoParam, Bool& repeatedRow )
+{
+  int addr, addrUp, addrLeft; 
+  int numCuInWidth  = saoParam->numCuInWidth;
+  SaoLcuParam* saoOneLcu;
+  SaoLcuParam* saoOneLcuUp;
+  SaoLcuParam* saoOneLcuLeft;
+  UInt uiSymbol;
+  Int  iSymbol;
+  Int  runLeft;
+  UInt maxValue;
+
+  addr      =  rx + ry*numCuInWidth;
+  addrLeft  =  (addr%numCuInWidth == 0) ? -1 : addr - 1;
+  addrUp    =  (addr<numCuInWidth)      ? -1 : addr - numCuInWidth;
+
+  saoOneLcu = &(saoParam->saoLcuParam[compIdx][addr]);      
+  if (!repeatedRow)
+  {
+    runLeft = (addrLeft>=0 )  ? saoParam->saoLcuParam[compIdx][addrLeft].run : -1;
+    if (rx == 0 || runLeft==0)
+    {
+      saoOneLcu->mergeLeftFlag = 0;
+      if (ry == 0)
+      {
+        maxValue = numCuInWidth-rx-1;
+        UInt length = 0;
+        UInt val = 0;
+        if (maxValue)
+        {
+          for(UInt i=0; i<32; i++)
+          {
+            if(maxValue&0x1)
+            {
+              length = i+1;
+            }
+            maxValue = (maxValue >> 1);
+          }
+          if(length)
+          {
+            READ_CODE(length, val, "sao_run_diff");
+          }
+        }
+        uiSymbol = val;
+        saoOneLcu->runDiff = uiSymbol; 
+        xParseSaoOffset(saoOneLcu);
+        saoOneLcu->run = saoOneLcu->runDiff;
+      }
+      else 
+      {
+        saoOneLcuUp = &(saoParam->saoLcuParam[compIdx][addrUp]);
+        READ_SVLC (iSymbol , "sao_run_diff"     );  saoOneLcu->runDiff = iSymbol; 
+        READ_FLAG (uiSymbol, "sao_merge_up_flag");  saoOneLcu->mergeUpFlag   = uiSymbol? true:false;
+        if (!saoOneLcu->mergeUpFlag)
+        {
+          xParseSaoOffset(saoOneLcu);
+        }
+        else
+        {
+          saoOneLcuUp = &(saoParam->saoLcuParam[compIdx][addrUp]);
+          copySaoOneLcuParam(saoOneLcu, saoOneLcuUp);
+        }
+        saoOneLcu->run = saoOneLcu->runDiff + saoOneLcuUp->run;
+      }
+    }
+    else
+    {
+      saoOneLcuLeft = &(saoParam->saoLcuParam[compIdx][addrLeft]);
+      copySaoOneLcuParam(saoOneLcu, saoOneLcuLeft);
+      saoOneLcu->mergeLeftFlag = 1;
+      saoOneLcu->run = saoOneLcuLeft->run-1;
+    }
+  }
+  else
+  {
+    if (ry > 0)
+    {
+      saoOneLcuUp = &(saoParam->saoLcuParam[compIdx][addrUp]);
+      copySaoOneLcuParam(saoOneLcu, saoOneLcuUp);
+      saoOneLcu->mergeLeftFlag = 0;
+      saoOneLcu->run = saoOneLcuUp->run;
+    }
+  }
+}
+
+
+Void TDecCavlc::xParseAlfParam(AlfParamSet* pAlfParamSet, Bool bSentInAPS, Int firstLCUAddr, Bool acrossSlice, Int numLCUInWidth, Int numLCUInHeight)
+{
+  Int  numLCU;
+  UInt uiSymbol;
+  Bool isEnabled[NUM_ALF_COMPONENT];
+  Bool isUniParam[NUM_ALF_COMPONENT];
+  
+  isEnabled[ALF_Y] = true;
+  READ_FLAG(uiSymbol, "alf_cb_enable_flag");  isEnabled[ALF_Cb] = ((uiSymbol ==1)?true:false);
+  READ_FLAG(uiSymbol, "alf_cr_enable_flag");  isEnabled[ALF_Cr] = ((uiSymbol ==1)?true:false);
+  READ_FLAG(uiSymbol, "alf_one_luma_unit_per_slice_flag");   isUniParam[ALF_Y] = ((uiSymbol ==1)?true:false);
+  
+  isUniParam[ALF_Cb] = true;
+  if (isEnabled[ALF_Cb])
+  {
+    READ_FLAG(uiSymbol, "alf_one_cb_unit_per_slice_flag");   isUniParam[ALF_Cb] = ((uiSymbol ==1)?true:false);
+  }
+  
+  isUniParam[ALF_Cr] = true;
+  if (isEnabled[ALF_Cr])
+  {
+    READ_FLAG(uiSymbol, "alf_one_cr_unit_per_slice_flag");   isUniParam[ALF_Cr] = ((uiSymbol ==1)?true:false);
+  }
+  
+  if(bSentInAPS)
+  {
+    READ_UVLC(uiSymbol, "alf_num_lcu_in_width_minus1");  numLCUInWidth = uiSymbol+1;
+    READ_UVLC(uiSymbol, "alf_num_lcu_in_height_minus1");  numLCUInHeight = uiSymbol+1;
+    numLCU = numLCUInWidth*numLCUInHeight;
+  }
+  else //sent in slice header
+  {
+    READ_UVLC(uiSymbol, "alf_num_lcu_in_slice_minus1");  numLCU = uiSymbol+1;
+  }
+  
+  assert(pAlfParamSet != NULL);
+  
+  pAlfParamSet->create(numLCUInWidth, numLCUInHeight, numLCU);
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    pAlfParamSet->isEnabled[compIdx] = isEnabled[compIdx];
+    pAlfParamSet->isUniParam[compIdx]= isUniParam[compIdx];
+  }
+  
+  parseAlfParamSet(pAlfParamSet, firstLCUAddr, acrossSlice);
+}
+
+
+Void TDecCavlc::parseAlfParamSet(AlfParamSet* pAlfParamSet, Int firstLCUAddr, Bool alfAcrossSlice)
+{
+  Int numLCUInWidth = pAlfParamSet->numLCUInWidth;
+  Int numLCU        = pAlfParamSet->numLCU;
+  
+  static Bool isRepeatedRow   [NUM_ALF_COMPONENT];
+  static Int  numStoredFilters[NUM_ALF_COMPONENT];
+  static Int* run             [NUM_ALF_COMPONENT];
+  
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    isRepeatedRow[compIdx]    = false;
+    numStoredFilters[compIdx] = 0;
+    
+    run[compIdx] = new Int[numLCU+1];
+    run[compIdx][0] = -1; 
+  }
+  
+  UInt uiSymbol;
+  Int  iSymbol, ry, rx, addrUp;
+  
+  for(Int i=0; i< numLCU; i++)
+  {
+    rx    = (i+ firstLCUAddr)% numLCUInWidth;
+    ry    = (i+ firstLCUAddr)/ numLCUInWidth;
+    
+    for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+    {
+      AlfUnitParam& alfUnitParam = pAlfParamSet->alfUnitParam[compIdx][i];
+      
+      if(pAlfParamSet->isEnabled[compIdx])
+      {
+        if(!pAlfParamSet->isUniParam[compIdx])
+        {
+          addrUp = i-numLCUInWidth;
+          if(rx ==0 && addrUp >=0)
+          {
+            READ_FLAG(uiSymbol, "alf_repeat_row _flag"); isRepeatedRow[compIdx] = ((uiSymbol ==1)?true:false);
+          }
+          
+          if(isRepeatedRow[compIdx])
+          {
+            alfUnitParam.mergeType = ALF_MERGE_UP;
+            assert(addrUp >=0);
+            run[compIdx][i] = run[compIdx][addrUp];
+          }
+          else
+          {
+            if(rx == 0 || run[compIdx][i] < 0)
+            {             
+              if(addrUp < 0)
+              {
+                //alf_run_diff u(v)
+                parseAlfFixedLengthRun(uiSymbol, rx, numLCUInWidth);
+                run[compIdx][i] = uiSymbol;
+              }
+              else
+              {
+                //alf_run_diff s(v)
+                READ_SVLC(iSymbol, "alf_run_diff");
+                run[compIdx][i] = run[compIdx][addrUp] + iSymbol;
+                assert(run[compIdx][i] >= 0);
+              }
+              
+              if(ry > 0 && (addrUp >=0 || alfAcrossSlice))
+              {
+                //alf_merge_up_flag
+                READ_FLAG(uiSymbol, "alf_merge_up_flag");  alfUnitParam.mergeType = ((uiSymbol ==1)?ALF_MERGE_UP:ALF_MERGE_DISABLED);
+              }
+              else
+              {
+                alfUnitParam.mergeType = ALF_MERGE_DISABLED;
+              }
+              
+              if(alfUnitParam.mergeType != ALF_MERGE_UP)
+              {
+                //alf_lcu_enable_flag
+                READ_FLAG(uiSymbol, "alf_lcu_enable_flag");  alfUnitParam.isEnabled = ((uiSymbol ==1)?true:false);
+                
+                if(alfUnitParam.isEnabled)
+                {
+                  if(numStoredFilters[compIdx] > 0)
+                  {
+                    //alf_new_filter_set_flag
+                    READ_FLAG(uiSymbol, "alf_new_filter_set_flag");  alfUnitParam.isNewFilt = ((uiSymbol ==1)?true:false);
+                    
+                    if(!alfUnitParam.isNewFilt)
+                    {
+                      //alf_stored_filter_set_idx
+                      parseAlfStoredFilterIdx(uiSymbol, numStoredFilters[compIdx]);
+                      
+                      alfUnitParam.storedFiltIdx = uiSymbol;
+                      
+                      assert( alfUnitParam.storedFiltIdx < numStoredFilters[compIdx]);
+                    }
+                  }
+                  else
+                  {
+                    alfUnitParam.isNewFilt = true;
+                  }
+                  
+                  if(alfUnitParam.isNewFilt)
+                  {
+                    alfUnitParam.alfFiltParam = new ALFParam(compIdx);
+                    xParseAlfParam(alfUnitParam.alfFiltParam);
+                    alfUnitParam.alfFiltParam->alf_flag = 1;
+                    
+                    numStoredFilters[compIdx]++;
+                  }
+                }
+                
+              }
+            }
+            else
+            {
+              alfUnitParam.mergeType = ALF_MERGE_LEFT;
+            }
+            
+            run[compIdx][i+1] = run[compIdx][i] -1;
+          }
+          
+        }
+        else // uni-param
+        {
+          if(i == 0)
+          {
+            alfUnitParam.mergeType = ALF_MERGE_DISABLED;
+            
+            //alf_lcu_enable_flag
+            READ_FLAG(uiSymbol, "alf_lcu_enable_flag");  alfUnitParam.isEnabled = ((uiSymbol ==1)?true:false);
+            if(alfUnitParam.isEnabled)
+            {
+              alfUnitParam.isNewFilt = true;
+              alfUnitParam.alfFiltParam = new ALFParam(compIdx);
+              xParseAlfParam(alfUnitParam.alfFiltParam);
+              alfUnitParam.alfFiltParam->alf_flag = 1;
+            }
+          }
+          else
+          {
+            alfUnitParam.mergeType = ALF_MERGE_FIRST;
+          }
+          
+        }
+      }
+      else
+      {
+        alfUnitParam.mergeType = ALF_MERGE_DISABLED;
+        alfUnitParam.isEnabled = false;
+      }
+    }
+  }
+  
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    delete[] run[compIdx];
+  }
+}
+
+
+Void TDecCavlc::parseAlfFixedLengthRun( UInt& idx, UInt rx, UInt numLCUInWidth )
+{
+  assert(numLCUInWidth > rx);
+  
+  UInt length = 0;  
+  UInt maxNumRun = numLCUInWidth - rx - 1; 
+  
+  for(UInt i=0; i<32; i++)
+  {
+    if(maxNumRun&0x1)
+    {
+      length = i+1;
+    }
+    maxNumRun = (maxNumRun >> 1);
+  }
+  
+  idx = 0;
+  if(length)
+  {
+    READ_CODE( length, idx, "alf_run_diff" );
+  }
+  else
+  {
+    idx = 0;
+  }
+}
+
+
+Void TDecCavlc::parseAlfStoredFilterIdx( UInt& idx, UInt numFilterSetsInBuffer )
+{
+  assert(numFilterSetsInBuffer > 0);
+  
+  UInt length = 0;  
+  UInt maxValue = numFilterSetsInBuffer - 1;
+  
+  for(UInt i=0; i<32; i++)
+  {
+    if(maxValue&0x1)
+    {
+      length = i+1;
+    }
+    maxValue = (maxValue >> 1);
+  }
+  
+  idx = 0;
+  if(length)
+  {
+    READ_CODE( length, idx, "alf_stored_filter_set_idx" );
+  }
+  else
+  {
+    idx = 0;
+  }
+}
+
+
+Void TDecCavlc::xParseAlfParam(ALFParam* pAlfParam)
+{
+  UInt uiSymbol;
+  Int iSymbol;
+  Int sqrFiltLengthTab[NUM_ALF_FILTER_SHAPE] = {ALF_FILTER_LEN}; 
+
+  switch(pAlfParam->componentID)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      pAlfParam->filter_shape = ALF_CROSS9x7_SQUARE3x3;
+      pAlfParam->num_coeff = sqrFiltLengthTab[pAlfParam->filter_shape];
+      pAlfParam->filters_per_group = 1;
+      for(Int pos=0; pos< pAlfParam->num_coeff; pos++)
+      {
+        READ_SVLC(iSymbol, "alf_filt_coeff");
+        pAlfParam->coeffmulti[0][pos] = iSymbol;
+      }
+    }
+    break;
+  case ALF_Y:
+    {
+  pAlfParam->filters_per_group = 0;
+  memset (pAlfParam->filterPattern, 0 , sizeof(Int)*NO_VAR_BINS);
+  pAlfParam->filter_shape = 0;
+  pAlfParam->num_coeff = sqrFiltLengthTab[pAlfParam->filter_shape];
+
+  // filters_per_fr
+  READ_UVLC (uiSymbol, "alf_no_filters_minus1");
+  pAlfParam->filters_per_group = uiSymbol + 1;
+
+  if(uiSymbol == 1) // filters_per_group == 2
+  {
+    READ_UVLC (uiSymbol, "alf_start_second_filter");
+    pAlfParam->startSecondFilter = uiSymbol;
+    pAlfParam->filterPattern [uiSymbol] = 1;
+  }
+  else if (uiSymbol > 1) // filters_per_group > 2
+  {
+    pAlfParam->filters_per_group = 1;
+    Int numMergeFlags = 16;
+    for (Int i=1; i<numMergeFlags; i++) 
+    {
+      READ_FLAG (uiSymbol,  "alf_filter_pattern");
+      pAlfParam->filterPattern[i] = uiSymbol;
+      pAlfParam->filters_per_group += uiSymbol;
+    }
+  }
+
+  if (pAlfParam->filters_per_group > 1)
+  {
+    READ_FLAG (uiSymbol, "alf_pred_method");
+    pAlfParam->predMethod = uiSymbol;
+  }
+  for(Int idx = 0; idx < pAlfParam->filters_per_group; ++idx)
+  {
+    READ_FLAG (uiSymbol,"alf_nb_pred_luma");
+    pAlfParam->nbSPred[idx] = uiSymbol;
+  }
+
+  Int minScanVal = MIN_SCAN_POS_CROSS;
+
+  // Determine maxScanVal
+  Int maxScanVal = 0;
+  Int *pDepthInt = pDepthIntTabShapes[pAlfParam->filter_shape];
+  for(Int idx = 0; idx < pAlfParam->num_coeff; idx++)
+  {
+    maxScanVal = max(maxScanVal, pDepthInt[idx]);
+  }
+
+  // Golomb parameters
+  if( pAlfParam->filters_per_group > 1 )
+  {
+  READ_UVLC (uiSymbol, "alf_min_kstart_minus1");
+  pAlfParam->minKStart = 1 + uiSymbol;
+
+  Int kMin = pAlfParam->minKStart;
+
+  for(Int scanPos = minScanVal; scanPos < maxScanVal; scanPos++)
+  {
+    READ_FLAG (uiSymbol, "alf_golomb_index_bit");
+    pAlfParam->kMinTab[scanPos] = kMin + uiSymbol;
+    kMin = pAlfParam->kMinTab[scanPos];
+  }
+  }
+
+  Int scanPos;
+  for(Int idx = 0; idx < pAlfParam->filters_per_group; ++idx)
+  {
+    for(Int i = 0; i < pAlfParam->num_coeff; i++)
+    {
+      scanPos = pDepthInt[i] - 1;
+      Int k = (pAlfParam->filters_per_group == 1) ? kTableTabShapes[ALF_CROSS9x7_SQUARE3x3][i] : pAlfParam->kMinTab[scanPos];
+      pAlfParam->coeffmulti[idx][i] = xGolombDecode(k);
+    }
+  }
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID for ALF\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+Int TDecCavlc::xGolombDecode(Int k)
+{
+  UInt uiSymbol;
+  Int q = -1;
+  Int nr = 0;
+  Int a;
+
+  uiSymbol = 1;
+  while (uiSymbol)
+  {
+    xReadFlag(uiSymbol);
+    q++;
+  }
+  for(a = 0; a < k; ++a)          // read out the sequential log2(M) bits
+  {
+    xReadFlag(uiSymbol);
+    if(uiSymbol)
+      nr += 1 << a;
+  }
+  nr += q << k;
+  if(nr != 0)
+  {
+    xReadFlag(uiSymbol);
+    nr = (uiSymbol)? nr: -nr;
+  }
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s ge(v) : %d\n", "alf_coeff_luma", nr ); 
+#endif
+  return nr;
+}
+
+Void TDecCavlc::parsePPS(TComPPS* pcPPS, ParameterSetManagerDecoder *parameterSet)
+{
+#if ENC_DEC_TRACE  
+  xTracePPSHeader (pcPPS);
+#endif
+  UInt  uiCode;
+
+  Int   iCode;
+
+  READ_UVLC( uiCode, "pic_parameter_set_id");                      pcPPS->setPPSId (uiCode);
+  READ_UVLC( uiCode, "seq_parameter_set_id");                      pcPPS->setSPSId (uiCode);
+
+  READ_FLAG ( uiCode, "sign_data_hiding_flag" ); pcPPS->setSignHideFlag( uiCode );
+  if( pcPPS->getSignHideFlag() )
+  {
+    READ_CODE( 4, uiCode, "sign_hiding_threshold"); pcPPS->setTSIG(uiCode);
+  }
+
+#if CABAC_INIT_FLAG
+  READ_FLAG( uiCode,   "cabac_init_present_flag" );            pcPPS->setCabacInitPresentFlag( uiCode ? true : false );
+#endif
+  // entropy_coding_mode_flag
+  // We code the entropy_coding_mode_flag, it's needed for tests.
+  READ_FLAG( uiCode, "entropy_coding_mode_flag" );                 pcPPS->setEntropyCodingMode( uiCode ? true : false );
+  if (pcPPS->getEntropyCodingMode())
+  {
+  }
+  
+  // num_ref_idx_l0_default_active_minus1
+  // num_ref_idx_l1_default_active_minus1
+  READ_SVLC(iCode, "pic_init_qp_minus26" );                        pcPPS->setPicInitQPMinus26(iCode);
+  READ_FLAG( uiCode, "constrained_intra_pred_flag" );              pcPPS->setConstrainedIntraPred( uiCode ? true : false );
+  READ_FLAG( uiCode, "enable_temporal_mvp_flag" );                 pcPPS->setEnableTMVPFlag( uiCode ? true : false );
+  READ_CODE( 2, uiCode, "slice_granularity" );                     pcPPS->setSliceGranularity(uiCode);
+
+  // alf_param() ?
+
+  READ_UVLC( uiCode, "max_cu_qp_delta_depth");
+  if(uiCode == 0)
+  {
+    pcPPS->setUseDQP (false);
+    pcPPS->setMaxCuDQPDepth( 0 );
+  }
+  else
+  {
+    pcPPS->setUseDQP (true);
+    pcPPS->setMaxCuDQPDepth(uiCode - 1);
+  }
+
+  READ_SVLC( iCode, "chroma_qp_offset");
+  pcPPS->setChromaQpOffset(iCode);
+
+  READ_SVLC( iCode, "chroma_qp_offset_2nd");
+  pcPPS->setChromaQpOffset2nd(iCode);
+
+  READ_FLAG( uiCode, "weighted_pred_flag" );          // Use of Weighting Prediction (P_SLICE)
+  pcPPS->setUseWP( uiCode==1 );
+  READ_CODE( 2, uiCode, "weighted_bipred_idc" );      // Use of Bi-Directional Weighting Prediction (B_SLICE)
+  pcPPS->setWPBiPredIdc( uiCode );
+//printf("TDecCavlc::parsePPS():\tm_bUseWeightPred=%d\tm_uiBiPredIdc=%d\n", pcPPS->getUseWP(), pcPPS->getWPBiPredIdc());
+
+  READ_FLAG( uiCode, "output_flag_present_flag" );
+  pcPPS->setOutputFlagPresentFlag( uiCode==1 );
+
+  if(parameterSet->getPrefetchedSPS(pcPPS->getSPSId())->getTilesOrEntropyCodingSyncIdc()==1)
+  {
+    READ_FLAG ( uiCode, "tile_info_present_flag" );
+    pcPPS->setColumnRowInfoPresent(uiCode);
+    READ_FLAG ( uiCode, "tile_control_present_flag" );
+    pcPPS->setTileBehaviorControlPresentFlag(uiCode);
+    if( pcPPS->getColumnRowInfoPresent() == 1 )
+    {
+      READ_UVLC ( uiCode, "num_tile_columns_minus1" );   
+      pcPPS->setNumColumnsMinus1( uiCode );  
+      READ_UVLC ( uiCode, "num_tile_rows_minus1" );  
+      pcPPS->setNumRowsMinus1( uiCode );  
+      READ_FLAG ( uiCode, "uniform_spacing_flag" );  
+      pcPPS->setUniformSpacingIdr( uiCode );
+
+      if( pcPPS->getUniformSpacingIdr() == 0 )
+      {
+        UInt* columnWidth = (UInt*)malloc(pcPPS->getNumColumnsMinus1()*sizeof(UInt));
+        for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
+        { 
+          READ_UVLC( uiCode, "column_width" );  
+          columnWidth[i] = uiCode;  
+        }
+        pcPPS->setColumnWidth(columnWidth);
+        free(columnWidth);
+
+        UInt* rowHeight = (UInt*)malloc(pcPPS->getNumRowsMinus1()*sizeof(UInt));
+        for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
+        {
+          READ_UVLC( uiCode, "row_height" );  
+          rowHeight[i] = uiCode;  
+        }
+        pcPPS->setRowHeight(rowHeight);
+        free(rowHeight);  
+      }
+    }
+
+
+    if(pcPPS->getTileBehaviorControlPresentFlag() == 1)
+    {
+      Int iNumColTilesMinus1 = (pcPPS->getColumnRowInfoPresent() == 1)?(pcPPS->getNumColumnsMinus1()):(pcPPS->getSPS()->getNumColumnsMinus1());
+      Int iNumRowTilesMinus1 = (pcPPS->getColumnRowInfoPresent() == 1)?(pcPPS->getNumColumnsMinus1()):(pcPPS->getSPS()->getNumRowsMinus1());
+      pcPPS->setLFCrossTileBoundaryFlag(true); //default
+
+      if(iNumColTilesMinus1 !=0 || iNumRowTilesMinus1 !=0)
+      {
+          READ_FLAG ( uiCode, "loop_filter_across_tile_flag" );  
+          pcPPS->setLFCrossTileBoundaryFlag( (uiCode == 1)?true:false );
+      }
+    }
+  }
+  else if(parameterSet->getPrefetchedSPS(pcPPS->getSPSId())->getTilesOrEntropyCodingSyncIdc()==2)
+  {
+    READ_UVLC( uiCode, "num_substreams_minus1" );                pcPPS->setNumSubstreams(uiCode+1);
+  }
+
+  READ_FLAG( uiCode, "deblocking_filter_control_present_flag" ); 
+  pcPPS->setDeblockingFilterControlPresent( uiCode ? true : false);
+  READ_UVLC( uiCode, "log2_parallel_merge_level_minus2");
+  assert(uiCode == LOG2_PARALLEL_MERGE_LEVEL_MINUS2);
+  pcPPS->setLog2ParallelMergeLevelMinus2 (uiCode);
+
+  READ_FLAG( uiCode, "pps_extension_flag");
+  if (uiCode)
+  {
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "pps_extension_data_flag");
+    }
+  }
+}
+#if QC_MVHEVC_B0046
+Void TDecCavlc::parseVPS(TComVPS* pcVPS)
+{
+  UInt  uiCode;
+  READ_CODE( 4, uiCode,  "video_parameter_set_id"   );       pcVPS->setVPSId( uiCode );
+  READ_FLAG( uiCode,     "temporal_id_nesting_flag" );       pcVPS->setTemporalNestingFlag( uiCode ? true:false );
+  READ_CODE( 2, uiCode,  "vps_reserved_zero_2bits" );         assert( !uiCode );
+  READ_CODE( 6, uiCode,  "vps_max_layers_minus1" );               pcVPS->setMaxLayers( uiCode + 1 );
+  READ_CODE( 3, uiCode,  "vps_max_sub_layers_minus1" );      pcVPS->setMaxTLayers( uiCode + 1 );
+  READ_CODE( 12, uiCode, "vps_extension_offset"      );      assert( !uiCode );
+  for(UInt i = 0; i <= pcVPS->getMaxTLayers()-1; i++)
+  {
+    READ_UVLC( uiCode,  "max_dec_pic_buffering[i]" );     pcVPS->setMaxDecPicBuffering( uiCode, i );
+    READ_UVLC( uiCode,  "num_reorder_pics[i]" );          pcVPS->setNumReorderPics( uiCode, i );
+    READ_UVLC( uiCode,  "max_latency_increase[i]" );      pcVPS->setMaxLatencyIncrease( uiCode, i );
+  }
+  READ_UVLC( uiCode,                 "vps_num_hrd_parameters"   ); pcVPS->setNumHRDParameters(uiCode);
+  assert(pcVPS->getNumHRDParameters()==0);
+  for ( UInt i = 0; i < pcVPS->getNumHRDParameters(); i ++)
+  {
+   //   if( i > 0 )  
+    //{
+    //  READ_UVLC (0, "op_num_layer_id_values_minus1[ opIdx ]");
+    //  for( i = 0; i <= op_num_layer_id_values_minus1[ opIdx ]; i++ )  
+    //    READ_UVLC(0, 6, "op_layer_id[ opIdx ][ i ]");
+    //}  
+    //hrd_parameters( i  = =  0, vps_max_sub_layers_minus1 );  
+  }
+ 
+  READ_CODE( 1, uiCode, "bit_equal_to_one" );             assert( uiCode );
+  //vps_extension_byte_alignment_reserved_one_bit
+  xReadVPSAlignOne();
+  READ_CODE( 8, uiCode, "num_additional_layer_operation_points" );     pcVPS->setNumAddiLayerOperationPoints( uiCode );
+  READ_CODE( 8, uiCode, "num_additional_profile_level_sets"     );     pcVPS->setNumAddiProLevelSets( uiCode);
+
+
+  for(UInt i=0; i <= pcVPS->getMaxLayers()-1; i++)
+  {
+    READ_CODE( 4,  uiCode,             "num_types_zero_4bits[i]" );   assert( !uiCode );
+    READ_CODE( 4,  uiCode,             "type_zero_4bits[i]"      );   assert( !uiCode );
+    READ_CODE( 8,  uiCode,             "view_id[i]" );                pcVPS->setViewId(uiCode, i);
+    // WRITE_SVLC( pcVPS->getViewOrderIdx(i),                  "view_order_idx[i]" );
+    if(i)
+    {
+      READ_CODE( 6, uiCode,  "num_direct_ref_layers[ i ]" );    pcVPS->setNumDirectRefLayer(uiCode, i);
+      for (UInt j = 0; j< pcVPS->getNumDirectRefLayer(i); j++)
+      {
+        READ_CODE( 6, uiCode, "ref_layer_id[i][j]" );         pcVPS->setDirectRefLayerId (uiCode, i, j);
+      }
+    }
+  }
+  for( UInt i=1; i<=pcVPS->getNumAddiProLevelSets(); i++)
+  {
+    //profile_tier_level
+  }
+  for( UInt i=1; i<= pcVPS->getNumAddiLayerOperationPoints(); i++)
+  {   
+    if(pcVPS->getMaxLayers() == 3)
+    {
+      pcVPS->setNumOpLayerIdMinus1((i < pcVPS->getNumAddiLayerOperationPoints() ? 1: 2), (i-1)); 
+    }
+    else if( i==1 )
+    {
+      assert(pcVPS->getNumAddiLayerOperationPoints()==1);
+      pcVPS->setNumOpLayerIdMinus1(pcVPS->getMaxLayers()-1, (i-1)); 
+    }
+    READ_UVLC( uiCode,           "op_num_layer_id_values_minus1[ opIdx ]" ); pcVPS->setNumOpLayerIdMinus1(uiCode, i-1);
+    for(UInt j = 0; j <= pcVPS->getNumOpLayerIdMinus1(i-1); j++ )
+    {
+      READ_UVLC( uiCode,           "op_layer_id[ opIdx ][ i ]" ); pcVPS->setNumOpLayerId(uiCode, i-1, j);
+    }
+    if (pcVPS->getNumAddiProLevelSets())
+    {
+      //profile_level_idx[ i ]
+    }
+  }
+  return;
+}
+#else
+#if VIDYO_VPS_INTEGRATION
+Void TDecCavlc::parseVPS(TComVPS* pcVPS)
+{
+  UInt  uiCode;
+  Int   iCode;
+  
+  READ_CODE( 3, uiCode, "max_temporal_layers_minus1" );   pcVPS->setMaxTLayers( uiCode + 1 );
+  READ_CODE( 5, uiCode, "max_layers_minus1" );            pcVPS->setMaxLayers( uiCode + 1 );
+  READ_FLAG( uiCode,  "temporal_id_nesting_flag" );       pcVPS->setTemporalNestingFlag( uiCode ? true:false );
+  READ_UVLC( uiCode,  "video_parameter_set_id" );         pcVPS->setVPSId( uiCode );
+  for(UInt i = 0; i <= pcVPS->getMaxTLayers()-1; i++)
+  {
+    READ_UVLC( uiCode,  "max_dec_pic_buffering[i]" );     pcVPS->setMaxDecPicBuffering( uiCode, i );
+    READ_UVLC( uiCode,  "num_reorder_pics[i]" );          pcVPS->setNumReorderPics( uiCode, i );
+    READ_UVLC( uiCode,  "max_latency_increase[i]" );      pcVPS->setMaxLatencyIncrease( uiCode, i );
+  }
+  
+  READ_CODE( 1, uiCode, "bit_equal_to_one" );             assert( uiCode );
+  
+  if( pcVPS->getMaxLayers() - 1 > 0 )
+  {
+    READ_UVLC( uiCode,  "extension_type" );               pcVPS->setExtensionType( uiCode );
+    
+    pcVPS->setViewOrderIdx( 0, 0 );
+    pcVPS->setViewId( 0, 0 );
+    pcVPS->setDepthFlag( 0, 0 );
+    for(UInt i = 1; i <= pcVPS->getMaxLayers()-1; i++)
+    {
+      READ_FLAG( uiCode, "dependent_flag[i]" );           pcVPS->setDependentFlag( uiCode ? true:false, i);
+      if( pcVPS->getDependentFlag(i) )
+      {
+        READ_UVLC( uiCode,  "delta_reference_layer_id_minus1[i]" ); pcVPS->setDependentLayer( i - uiCode + 1, i );
+        if( pcVPS->getExtensionType() == VPS_EXTENSION_TYPE_MULTI_VIEW )
+        {
+          READ_UVLC( uiCode,  "view_id[i]" );             pcVPS->setViewId( uiCode, i );
+          READ_FLAG( uiCode,  "depth_flag[i]" );          pcVPS->setDepthFlag( uiCode ? true:false, i ); 
+          READ_SVLC( iCode,  "view_order_idx[i]" );       pcVPS->setViewOrderIdx( iCode, i );
+        }
+        
+      }
+    }
+#if INTER_VIEW_VECTOR_SCALING_C0115
+    READ_FLAG( uiCode,  "inter_view_vector_scaling_flag" );    pcVPS->setIVScalingFlag( uiCode ? true:false); 
+#endif
+  }
+  
+  READ_FLAG( uiCode,  "vps_extension_flag" );          assert(!uiCode);
+  //future extensions go here..
+  
+  return;
+}
+
+#endif
+#endif
+#if HHI_MPI || H3D_QTL
+Void TDecCavlc::parseSPS(TComSPS* pcSPS, Bool bIsDepth)
+#else
+Void TDecCavlc::parseSPS(TComSPS* pcSPS)
+#endif
+{
+#if ENC_DEC_TRACE  
+  xTraceSPSHeader (pcSPS);
+#endif
+  
+  UInt  uiCode;
+#if !QC_MVHEVC_B0046
+  Int   iCode;
+#endif
+  READ_CODE( 8,  uiCode, "profile_idc" );                        pcSPS->setProfileIdc( uiCode );
+  READ_CODE( 8,  uiCode, "reserved_zero_8bits" );
+  READ_CODE( 8,  uiCode, "level_idc" );                          pcSPS->setLevelIdc( uiCode );
+  READ_UVLC(     uiCode, "seq_parameter_set_id" );               pcSPS->setSPSId( uiCode );
+#if VIDYO_VPS_INTEGRATION
+  READ_UVLC(     uiCode, "video_parameter_set_id" );             pcSPS->setVPSId( uiCode );
+#endif
+  READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( uiCode );
+  READ_CODE( 3,  uiCode, "max_temporal_layers_minus1" );         pcSPS->setMaxTLayers( uiCode+1 );
+  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, "pic_cropping_flag");                   pcSPS->setPicCroppingFlag ( uiCode ? true : false );
+  if (uiCode != 0)
+  {
+    READ_UVLC(   uiCode, "pic_crop_left_offset" );               pcSPS->setPicCropLeftOffset( uiCode );
+    READ_UVLC(   uiCode, "pic_crop_right_offset" );              pcSPS->setPicCropRightOffset( uiCode );
+    READ_UVLC(   uiCode, "pic_crop_top_offset" );                pcSPS->setPicCropTopOffset( uiCode );
+    READ_UVLC(   uiCode, "pic_crop_bottom_offset" );             pcSPS->setPicCropBottomOffset( uiCode );
+  }
+
+#if FULL_NBIT
+  READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+  g_uiBitDepth = 8 + uiCode;
+  g_uiBitIncrement = 0;
+  pcSPS->setBitDepth(g_uiBitDepth);
+  pcSPS->setBitIncrement(g_uiBitIncrement);
+#else
+  READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+  g_uiBitDepth = 8;
+  g_uiBitIncrement = uiCode;
+  pcSPS->setBitDepth(g_uiBitDepth);
+  pcSPS->setBitIncrement(g_uiBitIncrement);
+#endif
+  
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  g_iDeltaDCsQuantOffset = g_uiBitIncrement - 2;
+#endif
+
+  pcSPS->setQpBDOffsetY( (Int) (6*uiCode) );
+
+  g_uiBASE_MAX  = ((1<<(g_uiBitDepth))-1);
+  
+#if IBDI_NOCLIP_RANGE
+  g_uiIBDI_MAX  = g_uiBASE_MAX << g_uiBitIncrement;
+#else
+  g_uiIBDI_MAX  = ((1<<(g_uiBitDepth+g_uiBitIncrement))-1);
+#endif
+  READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
+  pcSPS->setQpBDOffsetC( (Int) (6*uiCode) );
+
+  READ_FLAG( uiCode, "pcm_enabled_flag" ); pcSPS->setUsePCM( uiCode ? true : false );
+
+  if( pcSPS->getUsePCM() )
+  {
+    READ_CODE( 4, uiCode, "pcm_bit_depth_luma_minus1" );           pcSPS->setPCMBitDepthLuma   ( 1 + uiCode );
+    READ_CODE( 4, uiCode, "pcm_bit_depth_chroma_minus1" );         pcSPS->setPCMBitDepthChroma ( 1 + uiCode );
+  }
+
+#if LOSSLESS_CODING
+  READ_FLAG( uiCode, "qpprime_y_zero_transquant_bypass_flag" );    pcSPS->setUseLossless ( uiCode ? true : false );
+#endif
+
+  READ_UVLC( uiCode,    "log2_max_pic_order_cnt_lsb_minus4" );   pcSPS->setBitsForPOC( 4 + uiCode );
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+    READ_UVLC ( uiCode, "max_dec_pic_buffering");
+    pcSPS->setMaxDecPicBuffering( uiCode, i);
+    READ_UVLC ( uiCode, "num_reorder_pics" );
+    pcSPS->setNumReorderPics(uiCode, i);
+    READ_UVLC ( uiCode, "max_latency_increase");
+    pcSPS->setMaxLatencyIncrease( uiCode, i );
+  }
+
+  READ_FLAG( uiCode, "restricted_ref_pic_lists_flag" );
+  pcSPS->setRestrictedRefPicListsFlag( uiCode );
+  if( pcSPS->getRestrictedRefPicListsFlag() )
+  {
+    READ_FLAG( uiCode, "lists_modification_present_flag" );
+    pcSPS->setListsModificationPresentFlag(uiCode);
+  }
+  else 
+  {
+    pcSPS->setListsModificationPresentFlag(true);
+  }
+  READ_UVLC( uiCode, "log2_min_coding_block_size_minus3" );
+  UInt log2MinCUSize = uiCode + 3;
+  READ_UVLC( uiCode, "log2_diff_max_min_coding_block_size" );
+  UInt uiMaxCUDepthCorrect = uiCode;
+  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + uiMaxCUDepthCorrect) ); g_uiMaxCUWidth  = 1<<(log2MinCUSize + uiMaxCUDepthCorrect);
+  pcSPS->setMaxCUHeight ( 1<<(log2MinCUSize + uiMaxCUDepthCorrect) ); g_uiMaxCUHeight = 1<<(log2MinCUSize + uiMaxCUDepthCorrect);
+  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() );
+  pcSPS->setMaxTrSize( 1<<(uiCode + pcSPS->getQuadtreeTULog2MinSize()) );
+
+  if(log2MinCUSize == 3)
+  {
+    xReadFlag( uiCode ); pcSPS->setDisInter4x4( uiCode ? true : false );
+  }
+
+  if( pcSPS->getUsePCM() )
+  {
+    READ_UVLC( uiCode, "log2_min_pcm_coding_block_size_minus3" );  pcSPS->setPCMLog2MinSize (uiCode+3); 
+    READ_UVLC( uiCode, "log2_diff_max_min_pcm_coding_block_size" ); pcSPS->setPCMLog2MaxSize ( uiCode+pcSPS->getPCMLog2MinSize() );
+  }
+
+  READ_UVLC( uiCode, "max_transform_hierarchy_depth_inter" );    pcSPS->setQuadtreeTUMaxDepthInter( uiCode+1 );
+  READ_UVLC( uiCode, "max_transform_hierarchy_depth_intra" );    pcSPS->setQuadtreeTUMaxDepthIntra( uiCode+1 );
+  g_uiAddCUDepth = 0;
+  while( ( pcSPS->getMaxCUWidth() >> uiMaxCUDepthCorrect ) > ( 1 << ( pcSPS->getQuadtreeTULog2MinSize() + g_uiAddCUDepth )  ) )
+  {
+    g_uiAddCUDepth++;
+  }
+  pcSPS->setMaxCUDepth( uiMaxCUDepthCorrect+g_uiAddCUDepth  ); 
+  g_uiMaxCUDepth  = uiMaxCUDepthCorrect+g_uiAddCUDepth;
+  // BB: these parameters may be removed completly and replaced by the fixed values
+  pcSPS->setMinTrDepth( 0 );
+  pcSPS->setMaxTrDepth( 1 );
+  READ_FLAG( uiCode, "scaling_list_enabled_flag" );                 pcSPS->setScalingListFlag ( uiCode );
+  READ_FLAG( uiCode, "chroma_pred_from_luma_enabled_flag" );        pcSPS->setUseLMChroma ( uiCode ? true : false ); 
+  READ_FLAG( uiCode, "deblocking_filter_in_aps_enabled_flag" );     pcSPS->setUseDF ( uiCode ? true : false );  
+  READ_FLAG( uiCode, "loop_filter_across_slice_flag" );             pcSPS->setLFCrossSliceBoundaryFlag( uiCode ? true : false);
+  READ_FLAG( uiCode, "asymmetric_motion_partitions_enabled_flag" ); pcSPS->setUseAMP( uiCode );
+  READ_FLAG( uiCode, "non_square_quadtree_enabled_flag" );          pcSPS->setUseNSQT( uiCode );
+  READ_FLAG( uiCode, "sample_adaptive_offset_enabled_flag" );       pcSPS->setUseSAO ( uiCode ? true : false );  
+  READ_FLAG( uiCode, "adaptive_loop_filter_enabled_flag" );         pcSPS->setUseALF ( uiCode ? true : false );
+  if(pcSPS->getUseALF())
+  {
+    READ_FLAG( uiCode, "alf_coef_in_slice_flag" );      pcSPS->setUseALFCoefInSlice ( uiCode ? true : false );
+  }
+  if( pcSPS->getUsePCM() )
+  {
+    READ_FLAG( uiCode, "pcm_loop_filter_disable_flag" );           pcSPS->setPCMFilterDisableFlag ( uiCode ? true : false );
+  }
+
+  READ_FLAG( uiCode, "temporal_id_nesting_flag" );               pcSPS->setTemporalIdNestingFlag ( uiCode > 0 ? true : false );
+
+
+  TComRPSList* rpsList = pcSPS->getRPSList();
+  TComReferencePictureSet* rps;
+
+  READ_UVLC( uiCode, "num_short_term_ref_pic_sets" );
+  rpsList->create(uiCode);
+
+  for(UInt i=0; i< rpsList->getNumberOfReferencePictureSets(); i++)
+  {
+    rps = rpsList->getReferencePictureSet(i);
+    parseShortTermRefPicSet(pcSPS,rps,i);
+  }
+  READ_FLAG( uiCode, "long_term_ref_pics_present_flag" );          pcSPS->setLongTermRefsPresent(uiCode);
+  
+  // AMVP mode for each depth (AM_NONE or AM_EXPL)
+  for (Int i = 0; i < pcSPS->getMaxCUDepth(); i++)
+  {
+    xReadFlag( uiCode );
+    pcSPS->setAMVPMode( i, (AMVP_MODE)uiCode );
+  }
+
+  READ_CODE(2, uiCode, "tiles_or_entropy_coding_sync_idc");         pcSPS->setTilesOrEntropyCodingSyncIdc(uiCode);
+
+  if(pcSPS->getTilesOrEntropyCodingSyncIdc() == 1)
+  {
+    READ_UVLC ( uiCode, "num_tile_columns_minus1" );
+    pcSPS->setNumColumnsMinus1( uiCode );  
+    READ_UVLC ( uiCode, "num_tile_rows_minus1" ); 
+    pcSPS->setNumRowsMinus1( uiCode ); 
+    READ_FLAG ( uiCode, "uniform_spacing_flag" ); 
+    pcSPS->setUniformSpacingIdr( uiCode );
+    if( pcSPS->getUniformSpacingIdr() == 0 )
+    {
+      UInt* columnWidth = (UInt*)malloc(pcSPS->getNumColumnsMinus1()*sizeof(UInt));
+      for(UInt i=0; i<pcSPS->getNumColumnsMinus1(); i++)
+      { 
+        READ_UVLC( uiCode, "column_width" );
+        columnWidth[i] = uiCode;  
+      }
+      pcSPS->setColumnWidth(columnWidth);
+      free(columnWidth);
+
+      UInt* rowHeight = (UInt*)malloc(pcSPS->getNumRowsMinus1()*sizeof(UInt));
+      for(UInt i=0; i<pcSPS->getNumRowsMinus1(); i++)
+      {
+        READ_UVLC( uiCode, "row_height" );
+        rowHeight[i] = uiCode;  
+      }
+      pcSPS->setRowHeight(rowHeight);
+      free(rowHeight);  
+    }
+    pcSPS->setLFCrossTileBoundaryFlag(true); //default
+
+    if( pcSPS->getNumColumnsMinus1() !=0 || pcSPS->getNumRowsMinus1() != 0)
+    {
+        READ_FLAG ( uiCode, "loop_filter_across_tile_flag" );  
+        pcSPS->setLFCrossTileBoundaryFlag( (uiCode==1)?true:false);
+    }
+  }
+  READ_FLAG( uiCode, "sps_extension_flag");
+#if !QC_MVHEVC_B0046
+  if(uiCode)
+  {
+    READ_FLAG( uiCode, "interview_refs_present_flag");
+    if(uiCode)
+    {
+      READ_UVLC( uiCode, "num_usable_interview_refs_minus1" );
+      pcSPS->setNumberOfUsableInterViewRefs( uiCode + 1 );
+
+      Int prev = 0;
+      for( Int j = 0 ; j < pcSPS->getNumberOfUsableInterViewRefs(); j++ )
+      {
+        READ_UVLC(uiCode, "delta_usable_interview_ref_minus1");
+        pcSPS->setUsableInterViewRef( j, (prev - uiCode - 1) );
+        prev = pcSPS->getUsableInterViewRef( j );
+      }
+    }
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    READ_FLAG( uiCode, "enable_dmm_flag" ); 
+    pcSPS->setUseDMM( uiCode );
+#endif
+
+#if HHI_MPI
+    if( bIsDepth )
+    {
+      READ_FLAG( uiCode, "use_mvi_flag" );
+      pcSPS->setUseMVI( uiCode );
+    }
+#endif
+#if H3D_QTL
+    if( bIsDepth )
+    {
+      READ_FLAG( uiCode, "use_qtlpc_flag" );
+      pcSPS->setUseQTLPC( uiCode );
+    }
+#endif
+    
+#if RWTH_SDC_DLT_B0036
+    if( bIsDepth )
+    {
+      READ_FLAG( uiCode, "use_dlt_flag" );
+      pcSPS->setUseDLT( uiCode );
+      if( pcSPS->getUseDLT() )
+      {
+        // decode mapping
+        UInt uiNumDepthValues;
+        // parse number of values in DLT
+        xReadUvlc( uiNumDepthValues );
+        
+        // parse actual DLT values
+        UInt* auiIdx2DepthValue = (UInt*) calloc(uiNumDepthValues, sizeof(UInt));
+        for(UInt d=0; d<uiNumDepthValues; d++)
+        {
+          xReadUvlc( uiCode );
+          auiIdx2DepthValue[d] = uiCode;
+        }
+        
+        pcSPS->setDepthLUTs(auiIdx2DepthValue, uiNumDepthValues);
+        
+        // clean memory
+        free(auiIdx2DepthValue);
+      }
+      else
+        pcSPS->setDepthLUTs();
+    }
+#endif
+
+    READ_FLAG( uiCode, "base_view_flag" );
+    if( uiCode )
+    { // baseview SPS -> set standard values
+      pcSPS->initMultiviewSPS         ( 0 );
+#if DEPTH_MAP_GENERATION
+      pcSPS->setPredDepthMapGeneration( 0, false );
+#endif
+#if H3D_IVRP
+    pcSPS->setMultiviewResPredMode  ( 0 );
+#endif
+    }
+    else
+    {
+      READ_FLAG( uiCode, "depth_flag" ); 
+      if( uiCode )
+      {
+#if FCO_FIX_SPS_CHANGE
+        UInt  uiViewId, uiCamParPrecision;
+        Int   iVOI;
+        Bool  bCamParSlice;
+        READ_UVLC( uiCode, "view_id" ); 
+        READ_SVLC( iCode, "view_order_idx" );
+        uiViewId = uiCode;
+        iVOI = iCode;
+
+        if ( uiViewId == 0 )
+        {
+          pcSPS->initMultiviewSPSDepth    ( uiViewId, iVOI );
+        }
+        else
+        {
+          READ_UVLC( uiCamParPrecision, "camera_parameter_precision" );
+          READ_FLAG( uiCode, "camera_parameter_in_slice_header" );    bCamParSlice = ( uiCode == 1 );
+          if( !bCamParSlice )
+          {
+            for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+            {
+              READ_SVLC( iCode, "coded_scale" );   m_aaiTempScale [ uiBaseId ][ uiViewId ] = iCode;
+              READ_SVLC( iCode, "coded_offset" );   m_aaiTempOffset[ uiBaseId ][ uiViewId ] = iCode;
+              READ_SVLC( iCode, "inverse_coded_scale_plus_coded_scale" );   m_aaiTempScale [ uiViewId ][ uiBaseId ] = iCode - m_aaiTempScale [ uiBaseId ][ uiViewId ];
+              READ_SVLC( iCode, "inverse_coded_offset_plus_coded_offset" );   m_aaiTempOffset[ uiViewId ][ uiBaseId ] = iCode - m_aaiTempOffset[ uiBaseId ][ uiViewId ];
+            }
+          }
+          pcSPS->initMultiviewSPSDepth( uiViewId, iVOI, uiCamParPrecision, bCamParSlice, m_aaiTempScale, m_aaiTempOffset );
+
+        }
+#else
+        READ_UVLC( uiCode, "view_id" ); 
+        READ_SVLC(  iCode, "view_order_idx" ); 
+        pcSPS->initMultiviewSPSDepth    ( uiCode, iCode );
+#endif
+#if DEPTH_MAP_GENERATION
+#if FCO_FIX_SPS_CHANGE
+        pcSPS->setPredDepthMapGeneration( uiViewId, true );
+#else
+        pcSPS->setPredDepthMapGeneration( uiCode, true );
+#endif
+#endif
+#if H3D_IVRP
+      pcSPS->setMultiviewResPredMode  ( 0 );
+#endif
+      }
+      else
+      {
+        UInt  uiViewId, uiCamParPrecision;
+        Int   iVOI;
+        Bool  bCamParSlice;
+        READ_UVLC( uiViewId, "view_id" );  uiViewId++;
+        READ_SVLC( iVOI, "view_order_idx" );
+        READ_UVLC( uiCamParPrecision, "camera_parameter_precision" );
+        READ_FLAG( uiCode, "camera_parameter_in_slice_header" );    bCamParSlice = ( uiCode == 1 );
+        if( !bCamParSlice )
+        {
+          for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+          {
+            READ_SVLC( iCode, "coded_scale" );   m_aaiTempScale [ uiBaseId ][ uiViewId ] = iCode;
+            READ_SVLC( iCode, "coded_offset" );   m_aaiTempOffset[ uiBaseId ][ uiViewId ] = iCode;
+            READ_SVLC( iCode, "inverse_coded_scale_plus_coded_scale" );   m_aaiTempScale [ uiViewId ][ uiBaseId ] = iCode - m_aaiTempScale [ uiBaseId ][ uiViewId ];
+            READ_SVLC( iCode, "inverse_coded_offset_plus_coded_offset" );   m_aaiTempOffset[ uiViewId ][ uiBaseId ] = iCode - m_aaiTempOffset[ uiBaseId ][ uiViewId ];
+          }
+        }
+        pcSPS->initMultiviewSPS( uiViewId, iVOI, uiCamParPrecision, bCamParSlice, m_aaiTempScale, m_aaiTempOffset );
+
+#if DEPTH_MAP_GENERATION
+        UInt uiPredDepthMapGeneration = 0, uiPdmPrecision = 0;
+#if H3D_IVMP
+        UInt uiMultiviewMvPredMode = 0;
+#endif
+#if H3D_IVRP
+      UInt uiMultiviewResPredMode = 0;
+#endif
+        READ_UVLC( uiPredDepthMapGeneration, "Pdm_generation" );
+        if( uiPredDepthMapGeneration )
+        {
+          READ_UVLC( uiPdmPrecision, "Pdm_precision" );
+          for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+          {
+            READ_SVLC( iCode, "Pdm_scale_nom_delta" );   m_aaiTempPdmScaleNomDelta[ uiViewId ][ uiBaseId ] = iCode;
+            READ_SVLC( iCode, "Pdm_offset" );   m_aaiTempPdmOffset       [ uiViewId ][ uiBaseId ] = iCode;
+          }
+#if H3D_IVMP
+          READ_UVLC( uiMultiviewMvPredMode, "multi_view_mv_pred_mode" );
+#endif
+#if H3D_IVRP
+          READ_FLAG( uiMultiviewResPredMode, "multi_view_residual_pred_mode" );
+#endif
+        }
+#if H3D_IVMP
+        pcSPS->setPredDepthMapGeneration( uiViewId, false, uiPredDepthMapGeneration, uiMultiviewMvPredMode, uiPdmPrecision, m_aaiTempPdmScaleNomDelta, m_aaiTempPdmOffset );
+#else
+        pcSPS->setPredDepthMapGeneration( uiViewId, false, uiPredDepthMapGeneration, 0, uiPdmPrecision, m_aaiTempPdmScaleNomDelta, m_aaiTempPdmOffset );
+#endif
+#endif
+#if H3D_IVRP
+      pcSPS->setMultiviewResPredMode  ( uiMultiviewResPredMode );
+#endif
+      }
+    }
+    READ_FLAG( uiCode, "sps_extension2_flag");
+    if (uiCode)
+    {
+      while ( xMoreRbspData() )
+      {
+        READ_FLAG( uiCode, "sps_extension2_data_flag");
+      }
+    }
+  }
+#endif
+}
+
+Void TDecCavlc::readTileMarker   ( UInt& uiTileIdx, UInt uiBitsUsed )
+{
+  xReadCode ( uiBitsUsed, uiTileIdx );
+}
+
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet, bool isDepth)
+#else
+Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet)
+#endif
+{
+  UInt  uiCode;
+  Int   iCode;
+  
+#if ENC_DEC_TRACE
+  xTraceSliceHeader(rpcSlice);
+#endif
+  Int numCUs = ((rpcSlice->getSPS()->getPicWidthInLumaSamples()+rpcSlice->getSPS()->getMaxCUWidth()-1)/rpcSlice->getSPS()->getMaxCUWidth())*((rpcSlice->getSPS()->getPicHeightInLumaSamples()+rpcSlice->getSPS()->getMaxCUHeight()-1)/rpcSlice->getSPS()->getMaxCUHeight());
+  Int maxParts = (1<<(rpcSlice->getSPS()->getMaxCUDepth()<<1));
+  Int numParts = (1<<(rpcSlice->getPPS()->getSliceGranularity()<<1));
+  UInt lCUAddress = 0;
+  Int reqBitsOuter = 0;
+  while(numCUs>(1<<reqBitsOuter))
+  {
+    reqBitsOuter++;
+  }
+  Int reqBitsInner = 0;
+  while((numParts)>(1<<reqBitsInner)) 
+  {
+    reqBitsInner++;
+  }
+
+  READ_FLAG( uiCode, "first_slice_in_pic_flag" );
+  UInt address;
+  UInt innerAddress = 0;
+
+#if LGE_ILLUCOMP_B0045
+  // IC flag is on only first_slice_in_pic
+  if (uiCode)
+  {
+    UInt uiCodeTmp = 0;
+    if ( rpcSlice->getSPS()->getViewId() 
+#if !LGE_ILLUCOMP_DEPTH_C0046
+        && !rpcSlice->getSPS()->isDepth()
+#endif
+        )
+    {
+      READ_FLAG (uiCodeTmp, "applying IC flag");
+    }
+    rpcSlice->setApplyIC(uiCodeTmp);
+  }
+#endif
+
+  if(!uiCode)
+  {
+    READ_CODE( reqBitsOuter+reqBitsInner, address, "slice_address" );
+    lCUAddress = address >> reqBitsInner;
+    innerAddress = address - (lCUAddress<<reqBitsInner);
+  }
+  //set uiCode to equal slice start address (or entropy slice start address)
+  uiCode=(maxParts*lCUAddress)+(innerAddress*(maxParts>>(rpcSlice->getPPS()->getSliceGranularity()<<1)));
+  
+  rpcSlice->setEntropySliceCurStartCUAddr( uiCode );
+  rpcSlice->setEntropySliceCurEndCUAddr(numCUs*maxParts);
+
+  //   slice_type
+  READ_UVLC (    uiCode, "slice_type" );            rpcSlice->setSliceType((SliceType)uiCode);
+  // lightweight_slice_flag
+  READ_FLAG( uiCode, "entropy_slice_flag" );
+  Bool bEntropySlice = uiCode ? true : false;
+
+  if (bEntropySlice)
+  {
+    rpcSlice->setNextSlice        ( false );
+    rpcSlice->setNextEntropySlice ( true  );
+  }
+  else
+  {
+    rpcSlice->setNextSlice        ( true  );
+    rpcSlice->setNextEntropySlice ( false );
+    
+    uiCode=(maxParts*lCUAddress)+(innerAddress*(maxParts>>(rpcSlice->getPPS()->getSliceGranularity()<<1)));
+    rpcSlice->setSliceCurStartCUAddr(uiCode);
+    rpcSlice->setSliceCurEndCUAddr(numCUs*maxParts);
+  }
+  TComPPS* pps = NULL;
+  TComSPS* sps = NULL;
+
+  if (!bEntropySlice)
+  {
+    READ_UVLC (    uiCode, "pic_parameter_set_id" );  rpcSlice->setPPSId(uiCode);
+    pps = parameterSetManager->getPrefetchedPPS(uiCode);
+    sps = parameterSetManager->getPrefetchedSPS(pps->getSPSId());
+    rpcSlice->setSPS(sps);
+    rpcSlice->setPPS(pps);
+    if( pps->getOutputFlagPresentFlag() )
+    {
+      READ_FLAG( uiCode, "pic_output_flag" );
+      rpcSlice->setPicOutputFlag( uiCode ? true : false );
+    }
+    else
+    {
+      rpcSlice->setPicOutputFlag( true );
+    }
+#if QC_REM_IDV_B0046
+#if !QC_MVHEVC_B0046
+  if(rpcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_IDR && rpcSlice->getSPS()->getViewId() == 0) 
+#else
+  if(rpcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_IDR && rpcSlice->getViewId() == 0) 
+#endif
+#else
+    if(rpcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_IDR) 
+#endif
+    { 
+      READ_UVLC( uiCode, "idr_pic_id" );  //ignored
+      READ_FLAG( uiCode, "no_output_of_prior_pics_flag" );  //ignored
+      rpcSlice->setPOC(0);
+      TComReferencePictureSet* rps = rpcSlice->getLocalRPS();
+      rps->setNumberOfNegativePictures(0);
+      rps->setNumberOfPositivePictures(0);
+      rps->setNumberOfLongtermPictures(0);
+      rps->setNumberOfPictures(0);
+      rpcSlice->setRPS(rps);
+    }
+    else
+    {
+      READ_CODE(sps->getBitsForPOC(), uiCode, "pic_order_cnt_lsb");  
+      Int iPOClsb = uiCode;
+      Int iPrevPOC = rpcSlice->getPrevPOC();
+      Int iMaxPOClsb = 1<< sps->getBitsForPOC();
+      Int iPrevPOClsb = iPrevPOC%iMaxPOClsb;
+      Int iPrevPOCmsb = iPrevPOC-iPrevPOClsb;
+      Int iPOCmsb;
+      if( ( iPOClsb  <  iPrevPOClsb ) && ( ( iPrevPOClsb - iPOClsb )  >=  ( iMaxPOClsb / 2 ) ) )
+      {
+        iPOCmsb = iPrevPOCmsb + iMaxPOClsb;
+      }
+      else if( (iPOClsb  >  iPrevPOClsb )  && ( (iPOClsb - iPrevPOClsb )  >  ( iMaxPOClsb / 2 ) ) ) 
+      {
+        iPOCmsb = iPrevPOCmsb - iMaxPOClsb;
+      }
+      else
+      {
+        iPOCmsb = iPrevPOCmsb;
+      }
+      rpcSlice->setPOC( iPOCmsb+iPOClsb );
+#if QC_REM_IDV_B0046
+#if !QC_MVHEVC_B0046
+      if( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR &&  rpcSlice->getSPS()->getViewId() && rpcSlice->getPOC() == 0 )
+#else
+      if( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR &&  rpcSlice->getViewId() && rpcSlice->getPOC() == 0 )
+#endif
+#else
+      if( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDV && rpcSlice->getPOC() == 0 )
+#endif
+      {
+        TComReferencePictureSet* rps = rpcSlice->getLocalRPS();
+        rps->setNumberOfNegativePictures(0);
+        rps->setNumberOfPositivePictures(0);
+        rps->setNumberOfLongtermPictures(0);
+        rps->setNumberOfPictures(0);
+        rpcSlice->setRPS(rps);
+      }
+      else
+      {
+        TComReferencePictureSet* 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
+        {
+          rps = rpcSlice->getLocalRPS();
+          parseShortTermRefPicSet(sps,rps, sps->getRPSList()->getNumberOfReferencePictureSets());
+          rpcSlice->setRPS(rps);
+        }
+        else // use reference to short-term reference picture set in PPS
+        {
+          READ_UVLC( uiCode, "short_term_ref_pic_set_idx"); rpcSlice->setRPS(sps->getRPSList()->getReferencePictureSet(uiCode));
+          rps = rpcSlice->getRPS();
+        }
+        if(sps->getLongTermRefsPresent())
+        {
+          Int offset = rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures();
+          READ_UVLC( uiCode, "num_long_term_pics");             rps->setNumberOfLongtermPictures(uiCode);
+          Int prev = 0;
+          Int prevMsb=0;
+          Int prevDeltaPocLt=0;
+          for(Int j=rps->getNumberOfLongtermPictures()+offset-1 ; j > offset-1; j--)
+          {
+            READ_UVLC(uiCode,"delta_poc_lsb_lt"); 
+            prev += uiCode;
+
+            READ_FLAG(uiCode,"delta_poc_msb_present_flag");
+            Int decDeltaPOCMsbPresent=uiCode;
+
+            if(decDeltaPOCMsbPresent==1)
+            {
+              READ_UVLC(uiCode, "delta_poc_msb_cycle_lt_minus1");
+              if(  (j==(rps->getNumberOfLongtermPictures()+offset-1)) || (prev!=prevDeltaPocLt) )
+              {
+                prevMsb=(1+uiCode); 
+              }
+              else
+              {
+                prevMsb+=(1+uiCode); 
+              }
+              Int decMaxPocLsb = 1<<rpcSlice->getSPS()->getBitsForPOC();
+              rps->setPOC(j,rpcSlice->getPOC()-prev-(prevMsb)*decMaxPocLsb); 
+              rps->setDeltaPOC(j,-(Int)(prev+(prevMsb)*decMaxPocLsb));
+            }
+            else
+            {
+              rps->setPOC(j,rpcSlice->getPOC()-prev);          
+              rps->setDeltaPOC(j,-(Int)prev);
+            }
+            prevDeltaPocLt=prev;
+            READ_FLAG( uiCode, "used_by_curr_pic_lt_flag");     rps->setUsed(j,uiCode);
+          }
+          offset += rps->getNumberOfLongtermPictures();
+          rps->setNumberOfPictures(offset);        
+        }  
+      }
+    }
+
+    if(sps->getUseSAO() || sps->getUseALF() || sps->getScalingListFlag() || sps->getUseDF())
+    {
+      //!!!KS: order is different in WD5! 
+      if (sps->getUseALF())
+      {
+        READ_FLAG(uiCode, "slice_adaptive_loop_filter_flag");
+        rpcSlice->setAlfEnabledFlag((Bool)uiCode);
+      }
+      if (sps->getUseSAO())
+      {
+        READ_FLAG(uiCode, "slice_sao_interleaving_flag");        rpcSlice->setSaoInterleavingFlag(uiCode);
+        READ_FLAG(uiCode, "slice_sample_adaptive_offset_flag");  rpcSlice->setSaoEnabledFlag((Bool)uiCode);
+        if (rpcSlice->getSaoEnabledFlag() && rpcSlice->getSaoInterleavingFlag())
+        {
+          READ_FLAG(uiCode, "sao_cb_enable_flag");  rpcSlice->setSaoEnabledFlagCb((Bool)uiCode);
+          READ_FLAG(uiCode, "sao_cr_enable_flag");  rpcSlice->setSaoEnabledFlagCr((Bool)uiCode);
+        }
+        else
+        {
+          rpcSlice->setSaoEnabledFlagCb(0);
+          rpcSlice->setSaoEnabledFlagCr(0);
+        }
+      }
+      READ_UVLC (    uiCode, "aps_id" );  rpcSlice->setAPSId(uiCode);
+    }
+    if (!rpcSlice->isIntra())
+    {
+      READ_FLAG( uiCode, "num_ref_idx_active_override_flag");
+      if (uiCode)
+      {
+        READ_CODE (3, uiCode, "num_ref_idx_l0_active_minus1" );  rpcSlice->setNumRefIdx( REF_PIC_LIST_0, uiCode + 1 );
+        if (rpcSlice->isInterB())
+        {
+          READ_CODE (3, uiCode, "num_ref_idx_l1_active_minus1" );  rpcSlice->setNumRefIdx( REF_PIC_LIST_1, uiCode + 1 );
+        }
+        else
+        {
+          rpcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+        }
+      }
+      else
+      {
+        rpcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
+        rpcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+      }
+    }
+    TComRefPicListModification* refPicListModification = rpcSlice->getRefPicListModification();
+    if( !rpcSlice->isIntra() )
+    {
+#if QC_MVHEVC_B0046
+    if( !rpcSlice->getViewId() || !rpcSlice->getSPS()->getListsModificationPresentFlag() )
+#else
+      if( !rpcSlice->getSPS()->getListsModificationPresentFlag() )
+#endif
+      {
+        refPicListModification->setRefPicListModificationFlagL0( 0 );
+      }
+      else
+      {
+        READ_FLAG( uiCode, "ref_pic_list_modification_flag_l0" ); refPicListModification->setRefPicListModificationFlagL0( uiCode ? 1 : 0 );
+      }
+      
+      if(refPicListModification->getRefPicListModificationFlagL0())
+      {
+        uiCode = 0;
+        Int i = 0;
+        Int NumPocTotalCurr = rpcSlice->getNumPocTotalCurrMvc();
+        if ( NumPocTotalCurr > 1 )
+        {
+          Int length = 1;
+          NumPocTotalCurr --;
+          while ( NumPocTotalCurr >>= 1) 
+          {
+            length ++;
+          }
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          {
+            READ_CODE( length, uiCode, "list_entry_l0" );
+            refPicListModification->setRefPicSetIdxL0(i, uiCode );
+          }
+        }
+        else
+        {
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          {
+            refPicListModification->setRefPicSetIdxL0(i, 0 );
+          }
+        }
+      }
+    }
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL0(0);
+    }
+    if(rpcSlice->isInterB())
+    {
+#if QC_MVHEVC_B0046
+    if( !rpcSlice->getViewId() || !rpcSlice->getSPS()->getListsModificationPresentFlag() )
+#else
+      if( !rpcSlice->getSPS()->getListsModificationPresentFlag() )
+#endif
+      {
+        refPicListModification->setRefPicListModificationFlagL1( 0 );
+      }
+      else
+      {
+        READ_FLAG( uiCode, "ref_pic_list_modification_flag_l1" ); refPicListModification->setRefPicListModificationFlagL1( uiCode ? 1 : 0 );
+      }
+      if(refPicListModification->getRefPicListModificationFlagL1())
+      {
+        uiCode = 0;
+        Int i = 0;
+        Int NumPocTotalCurr = rpcSlice->getNumPocTotalCurrMvc();
+        if ( NumPocTotalCurr > 1 )
+        {
+          Int length = 1;
+          NumPocTotalCurr --;
+          while ( NumPocTotalCurr >>= 1) 
+          {
+            length ++;
+          }
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          {
+            READ_CODE( length, uiCode, "list_entry_l1" );
+            refPicListModification->setRefPicSetIdxL1(i, uiCode );
+          }
+        }
+        else
+        {
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          {
+            refPicListModification->setRefPicSetIdxL1(i, 0 );
+          }
+        }
+      }
+    }  
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL1(0);
+    }
+  }
+  else
+  {
+    // initialize from previous slice
+    pps = rpcSlice->getPPS();
+    sps = rpcSlice->getSPS();
+  }
+  // ref_pic_list_combination( )
+  //!!!KS: ref_pic_list_combination() should be conditioned on entropy_slice_flag
+  if (rpcSlice->isInterB())
+  {
+    READ_FLAG( uiCode, "ref_pic_list_combination_flag" );       rpcSlice->setRefPicListCombinationFlag( uiCode ? 1 : 0 );
+    if(uiCode)
+    {
+      READ_UVLC( uiCode, "num_ref_idx_lc_active_minus1" );      rpcSlice->setNumRefIdx( REF_PIC_LIST_C, uiCode + 1 );
+      
+#if QC_MVHEVC_B0046
+    if( rpcSlice->getViewId() && rpcSlice->getSPS()->getListsModificationPresentFlag() )
+#else
+    if(rpcSlice->getSPS()->getListsModificationPresentFlag() )
+#endif
+      {
+        READ_FLAG( uiCode, "ref_pic_list_modification_flag_lc" ); rpcSlice->setRefPicListModificationFlagLC( uiCode ? 1 : 0 );
+        if(uiCode)
+        {
+          for (UInt i=0;i<rpcSlice->getNumRefIdx(REF_PIC_LIST_C);i++)
+          {
+            READ_FLAG( uiCode, "pic_from_list_0_flag" );
+            rpcSlice->setListIdFromIdxOfLC(i, uiCode);
+          if (((rpcSlice->getListIdFromIdxOfLC(i) == REF_PIC_LIST_0) && (rpcSlice->getNumRefIdx( REF_PIC_LIST_0 ) == 1)) || ((rpcSlice->getListIdFromIdxOfLC(i) == REF_PIC_LIST_1) && (rpcSlice->getNumRefIdx( REF_PIC_LIST_1 ) == 1)) )
+          {
+            uiCode = 0;
+          }
+          else
+          {
+            READ_UVLC( uiCode, "ref_idx_list_curr" );
+          }
+            rpcSlice->setRefIdxFromIdxOfLC(i, uiCode);
+            rpcSlice->setRefIdxOfLC((RefPicList)rpcSlice->getListIdFromIdxOfLC(i), rpcSlice->getRefIdxFromIdxOfLC(i), i);
+          }
+        }
+      }
+      else
+      {
+        rpcSlice->setRefPicListModificationFlagLC(false);
+      }
+    }
+    else
+    {
+      rpcSlice->setRefPicListModificationFlagLC(false);
+      rpcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
+    }
+  }
+  else
+  {
+    rpcSlice->setRefPicListCombinationFlag(false);      
+  }
+  
+  if (rpcSlice->isInterB())
+  {
+    READ_FLAG( uiCode, "mvd_l1_zero_flag" );       rpcSlice->setMvdL1ZeroFlag( (uiCode ? true : false) );
+  }
+
+#if CABAC_INIT_FLAG
+  rpcSlice->setCabacInitFlag( false ); // default
+  if(pps->getCabacInitPresentFlag() && !rpcSlice->isIntra())
+  {
+    READ_FLAG(uiCode, "cabac_init_flag");
+    rpcSlice->setCabacInitFlag( uiCode ? true : false );
+  }
+#else
+  if(pps->getEntropyCodingMode() && !rpcSlice->isIntra())
+  {
+    READ_UVLC(uiCode, "cabac_init_idc");
+    rpcSlice->setCABACinitIDC(uiCode);
+  }
+  else if (pps->getEntropyCodingMode() && rpcSlice->isIntra())
+  {
+    rpcSlice->setCABACinitIDC(0);
+  }
+#endif
+
+  if(!bEntropySlice)
+  {
+    READ_SVLC( iCode, "slice_qp_delta" ); 
+    rpcSlice->setSliceQp (26 + pps->getPicInitQPMinus26() + iCode);
+
+    assert( rpcSlice->getSliceQp() >= -sps->getQpBDOffsetY() );
+    assert( rpcSlice->getSliceQp() <=  51 );
+
+    if (rpcSlice->getPPS()->getDeblockingFilterControlPresent())
+    {
+      if ( rpcSlice->getSPS()->getUseDF() )
+      {
+        READ_FLAG ( uiCode, "inherit_dbl_param_from_APS_flag" ); rpcSlice->setInheritDblParamFromAPS(uiCode ? 1 : 0);
+      } else
+      {
+        rpcSlice->setInheritDblParamFromAPS(0);
+      }
+      if(!rpcSlice->getInheritDblParamFromAPS())
+      {
+        READ_FLAG ( uiCode, "disable_deblocking_filter_flag" );  rpcSlice->setLoopFilterDisable(uiCode ? 1 : 0);
+        if(!rpcSlice->getLoopFilterDisable())
+        {
+          READ_SVLC( iCode, "beta_offset_div2" ); rpcSlice->setLoopFilterBetaOffset(iCode);
+          READ_SVLC( iCode, "tc_offset_div2" ); rpcSlice->setLoopFilterTcOffset(iCode);
+        }
+      }
+   }
+    if ( rpcSlice->getSliceType() == B_SLICE )
+    {
+      READ_FLAG( uiCode, "collocated_from_l0_flag" );
+      rpcSlice->setColDir(uiCode);
+    }
+
+#if COLLOCATED_REF_IDX
+    if ( rpcSlice->getSliceType() != I_SLICE &&
+      ((rpcSlice->getColDir()==0 && rpcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
+      (rpcSlice->getColDir() ==1 && rpcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
+    {
+      READ_UVLC( uiCode, "collocated_ref_idx" );
+      rpcSlice->setColRefIdx(uiCode);
+    }
+#endif
+    
+    if ( (pps->getUseWP() && rpcSlice->getSliceType()==P_SLICE) || (pps->getWPBiPredIdc() && rpcSlice->getSliceType()==B_SLICE) )
+    {
+      xParsePredWeightTable(rpcSlice);
+      rpcSlice->initWpScaling();
+    }
+  }
+ 
+  if (!bEntropySlice)
+  {
+    if( rpcSlice->getSPS()->hasCamParInSliceHeader() )
+    {
+      UInt uiViewId = rpcSlice->getSPS()->getViewId();
+      for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+      {
+        READ_SVLC( iCode, "coded_scale" );   m_aaiTempScale [ uiBaseId ][ uiViewId ] = iCode;
+        READ_SVLC( iCode, "coded_offset" );   m_aaiTempOffset[ uiBaseId ][ uiViewId ] = iCode;
+        READ_SVLC( iCode, "inverse_coded_scale_plus_coded_scale" );   m_aaiTempScale [ uiViewId ][ uiBaseId ] = iCode - m_aaiTempScale [ uiBaseId ][ uiViewId ];
+        READ_SVLC( iCode, "inverse_coded_offset_plus_coded_offset" );   m_aaiTempOffset[ uiViewId ][ uiBaseId ] = iCode - m_aaiTempOffset[ uiBaseId ][ uiViewId ];
+      }
+      rpcSlice->initMultiviewSlice( m_aaiTempScale, m_aaiTempOffset );
+    }
+  }
+
+#if ( HHI_MPI || H3D_IVMP )
+  #if ( HHI_MPI && H3D_IVMP )
+  const int iExtraMergeCandidates = ( sps->getUseMVI() || sps->getMultiviewMvPredMode() ) ? 1 : 0;
+  #elif HHI_MPI
+  const int iExtraMergeCandidates = sps->getUseMVI() ? 1 : 0;
+  #elif MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  const int iExtraMergeCandidates = (  (isDepth || sps->getMultiviewMvPredMode()) ) ? 1 : 0;   
+  #else
+  const int iExtraMergeCandidates = sps->getMultiviewMvPredMode() ? 1 : 0;
+  #endif
+  READ_UVLC( uiCode, "5_minus_max_num_merge_cand");
+  rpcSlice->setMaxNumMergeCand(MRG_MAX_NUM_CANDS + iExtraMergeCandidates - uiCode);
+  assert(rpcSlice->getMaxNumMergeCand()==(MRG_MAX_NUM_CANDS_SIGNALED+iExtraMergeCandidates));
+#else
+  READ_UVLC( uiCode, "5_minus_max_num_merge_cand");
+  rpcSlice->setMaxNumMergeCand(MRG_MAX_NUM_CANDS - uiCode);
+  assert(rpcSlice->getMaxNumMergeCand()==MRG_MAX_NUM_CANDS_SIGNALED);
+#endif
+
+  if (!bEntropySlice)
+  {
+    if(sps->getUseALF() && rpcSlice->getAlfEnabledFlag())
+    {
+      UInt uiNumLCUsInWidth   = sps->getPicWidthInLumaSamples()  / g_uiMaxCUWidth;
+      UInt uiNumLCUsInHeight  = sps->getPicHeightInLumaSamples() / g_uiMaxCUHeight;
+
+      uiNumLCUsInWidth  += ( sps->getPicWidthInLumaSamples() % g_uiMaxCUWidth ) ? 1 : 0;
+      uiNumLCUsInHeight += ( sps->getPicHeightInLumaSamples() % g_uiMaxCUHeight ) ? 1 : 0;
+
+      Int uiNumCUsInFrame = uiNumLCUsInWidth* uiNumLCUsInHeight; 
+      if(sps->getUseALFCoefInSlice())
+      {
+        alfParamSet.releaseALFParam();
+        alfParamSet.init();
+        Bool isAcrossSlice = sps->getLFCrossSliceBoundaryFlag();   
+        Int numSUinLCU    = 1<< (g_uiMaxCUDepth << 1); 
+        Int firstLCUAddr   = rpcSlice->getSliceCurStartCUAddr() / numSUinLCU;  
+        xParseAlfParam(&alfParamSet, false, firstLCUAddr, isAcrossSlice, uiNumLCUsInWidth, uiNumLCUsInHeight);
+      }
+
+      if(!sps->getUseALFCoefInSlice())
+      {
+      xParseAlfCuControlParam(alfCUCtrl, uiNumCUsInFrame);
+      }
+
+    }
+  }
+  
+  //!!!KS: The following syntax is not aligned with the working draft, TRACE support needs to be added
+  rpcSlice->setTileMarkerFlag ( 0 ); // default
+  if (!bEntropySlice)
+  {
+    xReadCode(1, uiCode); // read flag indicating if tile markers transmitted
+    rpcSlice->setTileMarkerFlag( uiCode );
+  }
+
+  Int tilesOrEntropyCodingSyncIdc = rpcSlice->getSPS()->getTilesOrEntropyCodingSyncIdc();
+  UInt *entryPointOffset          = NULL;
+  UInt numEntryPointOffsets, offsetLenMinus1;
+
+  rpcSlice->setNumEntryPointOffsets ( 0 ); // default
+  
+  if (tilesOrEntropyCodingSyncIdc>0)
+  {
+    READ_UVLC(numEntryPointOffsets, "num_entry_point_offsets"); rpcSlice->setNumEntryPointOffsets ( numEntryPointOffsets );
+    if (numEntryPointOffsets>0)
+    {
+      READ_UVLC(offsetLenMinus1, "offset_len_minus1");
+    }
+    entryPointOffset = new UInt[numEntryPointOffsets];
+    for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+    {
+      Int bitsRead = m_pcBitstream->getNumBitsRead();
+      READ_CODE(offsetLenMinus1+1, uiCode, "entry_point_offset");
+      entryPointOffset[ idx ] = uiCode;
+      if ( idx == 0 && tilesOrEntropyCodingSyncIdc == 2 )
+      {
+        // Subtract distance from NALU header start to provide WPP 0-th substream the correct size.
+        entryPointOffset[ idx ] -= ( bitsRead + numEntryPointOffsets*(offsetLenMinus1+1) ) >> 3;
+      }
+    }
+  }
+
+  if ( tilesOrEntropyCodingSyncIdc == 1 ) // tiles
+  {
+    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 ( tilesOrEntropyCodingSyncIdc == 2 ) // wavefront
+  {
+    Int numSubstreams = pps->getNumSubstreams();
+    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;
+  }
+
+  if (!bEntropySlice)
+  {
+    // Reading location information
+
+      // read out trailing bits
+    m_pcBitstream->readOutTrailingBits();
+  }
+  return;
+}
+
+Void TDecCavlc::xParseAlfCuControlParam(AlfCUCtrlInfo& cAlfParam, Int iNumCUsInPic)
+{
+  UInt uiSymbol;
+  Int iSymbol;
+
+  READ_FLAG (uiSymbol, "alf_cu_control_flag");
+  cAlfParam.cu_control_flag = uiSymbol;
+  if (cAlfParam.cu_control_flag)
+  {
+    READ_UVLC (uiSymbol, "alf_cu_control_max_depth"); 
+    cAlfParam.alf_max_depth = uiSymbol;
+
+    READ_SVLC (iSymbol, "alf_length_cu_control_info");
+    cAlfParam.num_alf_cu_flag = (UInt)(iSymbol + iNumCUsInPic);
+
+    cAlfParam.alf_cu_flag.resize(cAlfParam.num_alf_cu_flag);
+
+    for(UInt i=0; i< cAlfParam.num_alf_cu_flag; i++)
+    {
+      READ_FLAG (cAlfParam.alf_cu_flag[i], "alf_cu_flag");
+    }
+  }
+}
+
+#if !CABAC_INIT_FLAG
+Void TDecCavlc::resetEntropy          (TComSlice* pcSlice)
+{
+}
+#endif
+
+Void TDecCavlc::parseTerminatingBit( UInt& ruiBit )
+{
+  ruiBit = false;
+  Int iBitsLeft = m_pcBitstream->getNumBitsLeft();
+  if(iBitsLeft <= 8)
+  {
+    UInt uiPeekValue = m_pcBitstream->peekBits(iBitsLeft);
+    if (uiPeekValue == (1<<(iBitsLeft-1)))
+    {
+      ruiBit = true;
+    }
+  }
+}
+
+Void TDecCavlc::parseSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+#if LGE_ILLUCOMP_B0045
+Void TDecCavlc::parseICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+#endif
+
+#if H3D_IVMP
+Void TDecCavlc::parseMVPIdx( Int& riMVPIdx, Int iAMVPCands )
+#else
+Void TDecCavlc::parseMVPIdx( Int& riMVPIdx )
+#endif
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parsePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parsePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+/** Parse I_PCM information. 
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU depth
+ * \returns Void
+ *
+ * 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 )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{ 
+  assert(0);
+}
+
+Void TDecCavlc::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseInterDir( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseRefFrmIdx( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int qp;
+  Int  iDQp;
+  
+  xReadSvlc( iDQp );
+
+  Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+ qpBdOffsetY)) -  qpBdOffsetY;
+
+  UInt uiAbsQpCUPartIdx = (uiAbsPartIdx>>(8-(pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()<<1)))<<(8-(pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()<<1)) ;
+  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 )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf )
+{
+  assert(0);
+}
+
+
+Void TDecCavlc::parseMergeFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMergeIndex ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+#if H3D_IVRP
+Void
+TDecCavlc::parseResPredFlag( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+#endif
+
+#if RWTH_SDC_DLT_B0036
+Void TDecCavlc::parseSDCFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+Void TDecCavlc::parseSDCPredMode    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+Void TDecCavlc::parseSDCResidualData     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPart )
+{
+  assert(0);
+}
+#endif
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TDecCavlc::xReadCode (UInt uiLength, UInt& ruiCode)
+{
+  assert ( uiLength > 0 );
+  m_pcBitstream->read (uiLength, ruiCode);
+}
+
+Void TDecCavlc::xReadUvlc( UInt& ruiVal)
+{
+  UInt uiVal = 0;
+  UInt uiCode = 0;
+  UInt uiLength;
+  m_pcBitstream->read( 1, uiCode );
+  
+  if( 0 == uiCode )
+  {
+    uiLength = 0;
+    
+    while( ! ( uiCode & 1 ))
+    {
+      m_pcBitstream->read( 1, uiCode );
+      uiLength++;
+    }
+    
+    m_pcBitstream->read( uiLength, uiVal );
+    
+    uiVal += (1 << uiLength)-1;
+  }
+  
+  ruiVal = uiVal;
+}
+
+Void TDecCavlc::xReadSvlc( Int& riVal)
+{
+  UInt uiBits = 0;
+  m_pcBitstream->read( 1, uiBits );
+  if( 0 == uiBits )
+  {
+    UInt uiLength = 0;
+    
+    while( ! ( uiBits & 1 ))
+    {
+      m_pcBitstream->read( 1, uiBits );
+      uiLength++;
+    }
+    
+    m_pcBitstream->read( uiLength, uiBits );
+    
+    uiBits += (1 << uiLength);
+    riVal = ( uiBits & 1) ? -(Int)(uiBits>>1) : (Int)(uiBits>>1);
+  }
+  else
+  {
+    riVal = 0;
+  }
+}
+
+Void TDecCavlc::xReadFlag (UInt& ruiCode)
+{
+  m_pcBitstream->read( 1, ruiCode );
+}
+
+#if QC_MVHEVC_B0046
+/** Parse VPS alignment one bits.
+ * \returns Void
+ */
+Void TDecCavlc::xReadVPSAlignOne( )
+{
+  UInt uiNumberOfBits = m_pcBitstream->getNumBitsUntilByteAligned();
+
+  if(uiNumberOfBits)
+  {
+    UInt uiBits;
+    UInt uiSymbol;
+
+    for(uiBits = 0; uiBits < uiNumberOfBits; uiBits++)
+    {
+      xReadFlag( uiSymbol );
+
+      if(!uiSymbol)
+      {
+        printf("\nWarning! vps_extension_byte_alignment_reserved_one_bit include a non-zero value.\n");
+      }
+    }
+  }
+}
+#endif
+/** Parse PCM alignment zero bits.
+ * \returns Void
+ */
+Void TDecCavlc::xReadPCMAlignZero( )
+{
+  UInt uiNumberOfBits = m_pcBitstream->getNumBitsUntilByteAligned();
+
+  if(uiNumberOfBits)
+  {
+    UInt uiBits;
+    UInt uiSymbol;
+
+    for(uiBits = 0; uiBits < uiNumberOfBits; uiBits++)
+    {
+      xReadFlag( uiSymbol );
+
+      if(uiSymbol)
+      {
+        printf("\nWarning! pcm_align_zero include a non-zero value.\n");
+      }
+    }
+  }
+}
+
+Void TDecCavlc::xReadUnaryMaxSymbol( UInt& ruiSymbol, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    ruiSymbol = 0;
+    return;
+  }
+  
+  xReadFlag( ruiSymbol );
+  
+  if (ruiSymbol == 0 || uiMaxSymbol == 1)
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCont;
+  
+  do
+  {
+    xReadFlag( uiCont );
+    uiSymbol++;
+  }
+  while( uiCont && (uiSymbol < uiMaxSymbol-1) );
+  
+  if( uiCont && (uiSymbol == uiMaxSymbol-1) )
+  {
+    uiSymbol++;
+  }
+  
+  ruiSymbol = uiSymbol;
+}
+
+Void TDecCavlc::xReadExGolombLevel( UInt& ruiSymbol )
+{
+  UInt uiSymbol ;
+  UInt uiCount = 0;
+  do
+  {
+    xReadFlag( uiSymbol );
+    uiCount++;
+  }
+  while( uiSymbol && (uiCount != 13));
+  
+  ruiSymbol = uiCount-1;
+  
+  if( uiSymbol )
+  {
+    xReadEpExGolomb( uiSymbol, 0 );
+    ruiSymbol += uiSymbol+1;
+  }
+  
+  return;
+}
+
+Void TDecCavlc::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
+{
+  UInt uiSymbol = 0;
+  UInt uiBit = 1;
+  
+  
+  while( uiBit )
+  {
+    xReadFlag( uiBit );
+    uiSymbol += uiBit << uiCount++;
+  }
+  
+  uiCount--;
+  while( uiCount-- )
+  {
+    xReadFlag( uiBit );
+    uiSymbol += uiBit << uiCount;
+  }
+  
+  ruiSymbol = uiSymbol;
+  
+  return;
+}
+
+UInt TDecCavlc::xGetBit()
+{
+  UInt ruiCode;
+  m_pcBitstream->read( 1, ruiCode );
+  return ruiCode;
+}
+
+
+/** parse explicit wp tables
+ * \param TComSlice* pcSlice
+ * \returns Void
+ */
+Void TDecCavlc::xParsePredWeightTable( TComSlice* pcSlice )
+{
+  wpScalingParam  *wp;
+  Bool            bChroma     = true; // color always present in HEVC ?
+  TComPPS*        pps         = pcSlice->getPPS();
+  SliceType       eSliceType  = pcSlice->getSliceType();
+  Int             iNbRef       = (eSliceType == B_SLICE ) ? (2) : (1);
+  UInt            uiLog2WeightDenomLuma, uiLog2WeightDenomChroma;
+  UInt            uiMode      = 0;
+
+  if ( (eSliceType==P_SLICE && pps->getUseWP()) || (eSliceType==B_SLICE && pps->getWPBiPredIdc()==1 && pcSlice->getRefPicListCombinationFlag()==0) )
+    uiMode = 1; // explicit
+  else if ( eSliceType==B_SLICE && pps->getWPBiPredIdc()==2 )
+    uiMode = 2; // implicit
+  else if (eSliceType==B_SLICE && pps->getWPBiPredIdc()==1 && pcSlice->getRefPicListCombinationFlag())
+    uiMode = 3; // combined explicit
+
+  if ( uiMode == 1 )  // explicit
+  {
+    printf("\nTDecCavlc::xParsePredWeightTable(poc=%d) explicit...\n", pcSlice->getPOC());
+    Int iDeltaDenom;
+    // decode delta_luma_log2_weight_denom :
+    READ_UVLC( uiLog2WeightDenomLuma, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+    if( bChroma ) 
+    {
+      READ_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );     // se(v): delta_chroma_log2_weight_denom
+      assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)>=0);
+      uiLog2WeightDenomChroma = (UInt)(iDeltaDenom + uiLog2WeightDenomLuma);
+    }
+
+    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
+    {
+      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+      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;
+
+        UInt  uiCode;
+        READ_FLAG( uiCode, "luma_weight_lX_flag" );           // u(1): luma_weight_l0_flag
+        wp[0].bPresentFlag = ( uiCode == 1 );
+        if ( wp[0].bPresentFlag ) 
+        {
+          Int iDeltaWeight;
+          READ_SVLC( iDeltaWeight, "delta_luma_weight_lX" );  // se(v): delta_luma_weight_l0[i]
+          wp[0].iWeight = (iDeltaWeight + (1<<wp[0].uiLog2WeightDenom));
+          READ_SVLC( wp[0].iOffset, "luma_offset_lX" );       // se(v): luma_offset_l0[i]
+        }
+        else 
+        {
+          wp[0].iWeight = (1 << wp[0].uiLog2WeightDenom);
+          wp[0].iOffset = 0;
+        }
+        if ( bChroma ) 
+        {
+          READ_FLAG( uiCode, "chroma_weight_lX_flag" );      // u(1): chroma_weight_l0_flag
+          wp[1].bPresentFlag = ( uiCode == 1 );
+          wp[2].bPresentFlag = ( uiCode == 1 );
+          if ( wp[1].bPresentFlag ) 
+          {
+            for ( Int j=1 ; j<3 ; j++ ) 
+            {
+              Int iDeltaWeight;
+              READ_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );  // se(v): chroma_weight_l0[i][j]
+              wp[j].iWeight = (iDeltaWeight + (1<<wp[1].uiLog2WeightDenom));
+
+              Int iDeltaChroma;
+              READ_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );  // se(v): delta_chroma_offset_l0[i][j]
+              wp[j].iOffset = iDeltaChroma - ( ( (g_uiIBDI_MAX>>1)*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) + (g_uiIBDI_MAX>>1);
+            }
+          }
+          else 
+          {
+            for ( Int j=1 ; j<3 ; j++ ) 
+            {
+              wp[j].iWeight = (1 << wp[j].uiLog2WeightDenom);
+              wp[j].iOffset = 0;
+            }
+          }
+        }
+      }
+
+      for ( Int iRefIdx=pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+
+        wp[0].bPresentFlag = false;
+        wp[1].bPresentFlag = false;
+        wp[2].bPresentFlag = false;
+      }
+    }
+  }
+  else if ( uiMode == 2 )  // implicit
+  {
+    printf("\nTDecCavlc::xParsePredWeightTable(poc=%d) implicit...\n", pcSlice->getPOC());
+  }
+  else if ( uiMode == 3 )  // combined explicit
+  {
+    printf("\nTDecCavlc::xParsePredWeightTable(poc=%d) combined explicit...\n", pcSlice->getPOC());
+    Int iDeltaDenom;
+    // decode delta_luma_log2_weight_denom :
+    READ_UVLC ( uiLog2WeightDenomLuma, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+    if( bChroma ) 
+    {
+      READ_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );      // ue(v): delta_chroma_log2_weight_denom
+      assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)>=0);
+      uiLog2WeightDenomChroma = (UInt)(iDeltaDenom + uiLog2WeightDenomLuma);
+    }
+
+    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(REF_PIC_LIST_C) ; iRefIdx++ ) 
+    {
+      pcSlice->getWpScalingLC(iRefIdx, wp);
+
+      wp[0].uiLog2WeightDenom = uiLog2WeightDenomLuma;
+      wp[1].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+      wp[2].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+
+      UInt  uiCode;
+      READ_FLAG( uiCode, "luma_weight_lc_flag" );                  // u(1): luma_weight_lc_flag
+      wp[0].bPresentFlag = ( uiCode == 1 );
+      if ( wp[0].bPresentFlag ) 
+      {
+        Int iDeltaWeight;
+        READ_SVLC( iDeltaWeight, "delta_luma_weight_lc" );          // se(v): delta_luma_weight_lc
+        wp[0].iWeight = (iDeltaWeight + (1<<wp[0].uiLog2WeightDenom));
+        READ_SVLC( wp[0].iOffset, "luma_offset_lc" );               // se(v): luma_offset_lc
+      }
+      else 
+      {
+        wp[0].iWeight = (1 << wp[0].uiLog2WeightDenom);
+        wp[0].iOffset = 0;
+      }
+      if ( bChroma ) 
+      {
+        READ_FLAG( uiCode, "chroma_weight_lc_flag" );                // u(1): chroma_weight_lc_flag
+        wp[1].bPresentFlag = ( uiCode == 1 );
+        wp[2].bPresentFlag = ( uiCode == 1 );
+        if ( wp[1].bPresentFlag ) 
+        {
+          for ( Int j=1 ; j<3 ; j++ ) 
+          {
+            Int iDeltaWeight;
+            READ_SVLC( iDeltaWeight, "delta_chroma_weight_lc" );      // se(v): delta_chroma_weight_lc
+            wp[j].iWeight = (iDeltaWeight + (1<<wp[1].uiLog2WeightDenom));
+
+            Int iDeltaChroma;
+            READ_SVLC( iDeltaChroma, "delta_chroma_offset_lc" );      // se(v): delta_chroma_offset_lc
+            wp[j].iOffset = iDeltaChroma - ( ( (g_uiIBDI_MAX>>1)*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) + (g_uiIBDI_MAX>>1);
+          }
+        }
+        else 
+        {
+          for ( Int j=1 ; j<3 ; j++ ) 
+          {
+            wp[j].iWeight = (1 << wp[j].uiLog2WeightDenom);
+            wp[j].iOffset = 0;
+          }
+        }
+      }
+    }
+
+    for ( Int iRefIdx=pcSlice->getNumRefIdx(REF_PIC_LIST_C) ; iRefIdx<2*MAX_NUM_REF ; iRefIdx++ ) 
+    {
+      pcSlice->getWpScalingLC(iRefIdx, wp);
+
+      wp[0].bPresentFlag = false;
+      wp[1].bPresentFlag = false;
+      wp[2].bPresentFlag = false;
+    }
+  }
+  else
+  {
+    printf("\n wrong weight pred table syntax \n ");
+    assert(0);
+  }
+}
+
+/** decode quantization matrix
+ * \param scalingList quantization matrix information
+ */
+Void TDecCavlc::parseScalingList(TComScalingList* scalingList)
+{
+  UInt  code, sizeId, listId;
+  Bool scalingListPredModeFlag;
+  READ_FLAG( code, "scaling_list_present_flag" );
+  scalingList->setScalingListPresentFlag ( (code==1)?true:false );
+  if(scalingList->getScalingListPresentFlag() == false)
+  {
+      //for each size
+    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+1)));
+          if( sizeId > SCALING_LIST_8x8 )
+          {
+            scalingList->setScalingListDC(sizeId,listId,scalingList->getScalingListDC(sizeId, scalingList->getRefMatrixId (sizeId,listId)));
+          }
+          scalingList->processRefMatrix( sizeId, listId, scalingList->getRefMatrixId (sizeId,listId));
+          
+        }
+        else //DPCM Mode
+        {
+          xDecodeScalingList(scalingList, sizeId, listId);
+        }
+      }
+    }
+  }
+
+  return;
+}
+/** decode DPCM
+ * \param scalingList  quantization matrix information
+ * \param sizeId size index
+ * \param listId list index
+ */
+Void TDecCavlc::xDecodeScalingList(TComScalingList *scalingList, UInt sizeId, UInt listId)
+{
+  Int i,coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+  Int data;
+  Int scalingListDcCoefMinus8 = 0;
+  Int nextCoef = SCALING_LIST_START_VALUE;
+  UInt* scan  = g_auiFrameScanXY [ (sizeId == 0)? 1 : 2 ];
+  Bool stopNow = false;
+  Int *dst = scalingList->getScalingListAddress(sizeId, listId);
+
+  scalingList->setUseDefaultScalingMatrixFlag(sizeId,listId,false);
+  if( sizeId > SCALING_LIST_8x8 )
+  {
+    READ_SVLC( scalingListDcCoefMinus8, "scaling_list_dc_coef_minus8");
+    scalingList->setScalingListDC(sizeId,listId,scalingListDcCoefMinus8 + 8);
+    if(scalingListDcCoefMinus8 == -8)
+    {
+      scalingList->processDefaultMarix(sizeId,listId);
+    }
+  }
+
+  if( !scalingList->getUseDefaultScalingMatrixFlag(sizeId,listId))
+  {
+    for(i = 0; i < coefNum && !stopNow ; i++)
+    {
+      READ_SVLC( data, "scaling_list_delta_coef");
+      nextCoef = (nextCoef + data + 256 ) % 256;
+      if(sizeId < SCALING_LIST_16x16)
+      {
+        if( i == 0 && nextCoef == 0 )
+        {
+          scalingList->processDefaultMarix(sizeId,listId);
+          stopNow = true;
+        }
+      }
+      if(!stopNow)
+      {
+        dst[scan[i]] = nextCoef;
+      }
+    }
+  }
+}
+
+Void TDecCavlc::parseDFFlag(UInt& ruiVal, const Char *pSymbolName)
+{
+  READ_FLAG(ruiVal, pSymbolName);
+}
+Void TDecCavlc::parseDFSvlc(Int&  riVal, const Char *pSymbolName)
+{
+  READ_SVLC(riVal, pSymbolName);
+}
+
+Bool TDecCavlc::xMoreRbspData()
+{ 
+  Int bitsLeft = m_pcBitstream->getNumBitsLeft();
+
+  // if there are more than 8 bits, it cannot be rbsp_trailing_bits
+  if (bitsLeft > 8)
+  {
+    return true;
+  }
+
+  UChar lastByte = m_pcBitstream->peekBits(bitsLeft);
+  Int cnt = bitsLeft;
+
+  // remove trailing bits equal to zero
+  while ((cnt>0) && ((lastByte & 1) == 0))
+  {
+    lastByte >>= 1;
+    cnt--;
+  }
+  // remove bit equal to one
+  cnt--;
+
+  // we should not have a negative number of bits
+  assert (cnt>=0);
+
+  // we have more data, if cnt is not zero
+  return (cnt>0);
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 341)
@@ -0,0 +1,195 @@
+/* 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-2012, 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     TDecCAVLC.h
+    \brief    CAVLC decoder class (header)
+*/
+
+#ifndef __TDECCAVLC__
+#define __TDECCAVLC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TDecEntropy.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class SEImessages;
+
+/// CAVLC decoder class
+class TDecCavlc : public TDecEntropyIf
+{
+public:
+  TDecCavlc();
+  virtual ~TDecCavlc();
+  
+protected:
+  Void  xReadCode             (UInt   uiLength, UInt& ruiCode);
+  Void  xReadUvlc             (UInt&  ruiVal);
+  Void  xReadSvlc             (Int&   riVal);
+  Void  xReadFlag             (UInt&  ruiCode);
+  Void  xReadEpExGolomb       ( UInt& ruiSymbol, UInt uiCount );
+  Void  xReadExGolombLevel    ( UInt& ruiSymbol );
+  Void  xReadUnaryMaxSymbol   ( UInt& ruiSymbol, UInt uiMaxSymbol );
+#if ENC_DEC_TRACE
+  Void  xReadCodeTr           (UInt  length, UInt& rValue, const Char *pSymbolName);
+  Void  xReadUvlcTr           (              UInt& rValue, const Char *pSymbolName);
+  Void  xReadSvlcTr           (               Int& rValue, const Char *pSymbolName);
+  Void  xReadFlagTr           (              UInt& rValue, const Char *pSymbolName);
+#endif
+#if QC_MVHEVC_B0046
+  Void  xReadVPSAlignOne      ();
+#endif
+  Void  xReadPCMAlignZero     ();
+
+  UInt  xGetBit             ();
+  
+  void  parseShortTermRefPicSet            (TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Int idx);
+private:
+  TComInputBitstream*   m_pcBitstream;
+  Int           m_iSliceGranularity; //!< slice granularity
+  
+  Int**    m_aaiTempScale;
+  Int**    m_aaiTempOffset;
+  Int**    m_aaiTempPdmScaleNomDelta;
+  Int**    m_aaiTempPdmOffset;
+  
+public:
+
+  /// rest entropy coder by intial QP and IDC in CABAC
+#if !CABAC_INIT_FLAG
+  Void  resetEntropy        (Int  iQp, Int iID) { printf("Not supported yet\n"); assert(0); exit(1);}
+  Void  resetEntropy        ( TComSlice* pcSlice  );
+#else
+  Void  resetEntropy        ( TComSlice* pcSlice  )     { assert(0); };
+#endif
+  Void  setBitstream        ( TComInputBitstream* p )   { m_pcBitstream = p; }
+  /// set slice granularity
+  Void setSliceGranularity(Int iSliceGranularity)  {m_iSliceGranularity = iSliceGranularity;}
+
+  /// get slice granularity
+  Int  getSliceGranularity()                       {return m_iSliceGranularity;             }
+  Void  parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
+  Void  parseQtCbf          ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void  parseQtRootCbf      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf );
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void  parseVPS            ( TComVPS* pcVPS );
+#endif
+#if HHI_MPI || H3D_QTL
+  Void  parseSPS            ( TComSPS* pcSPS, Bool bIsDepth );
+#else
+  Void  parseSPS            ( TComSPS* pcSPS );
+#endif
+  Void  parsePPS            ( TComPPS* pcPPS, ParameterSetManagerDecoder *parameterSet);
+  Void  parseSEI(SEImessages&);
+  Void  parseAPS            ( TComAPS* pAPS );
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet, bool isDepth);
+#else
+  Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet);
+#endif
+  Void  parseTerminatingBit ( UInt& ruiBit );
+  
+#if H3D_IVMP
+  Void  parseMVPIdx         ( Int& riMVPIdx, Int iAMVPCands );
+#else
+  Void  parseMVPIdx         ( Int& riMVPIdx );
+#endif
+  
+  Void  parseSkipFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if LGE_ILLUCOMP_B0045
+  Void  parseICFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void parseMergeFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void parseMergeIndex      ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth );
+#if H3D_IVRP
+  Void parseResPredFlag     ( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void parseSplitFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  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, UInt uiDepth );
+  Void parseRefFrmIdx       ( TComDataCU* pcCU, Int& riRefFrmIdx,  UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  Void parseMvd             ( TComDataCU* pcCU, UInt uiAbsPartAddr,UInt uiPartIdx,    UInt uiDepth, RefPicList eRefList );
+  
+  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 parseIPCMInfo        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+
+  Void readTileMarker     ( UInt& uiTileIdx, UInt uiBitsUsed );
+  Void updateContextTables  ( SliceType eSliceType, Int iQp ) { return; }
+  Void decodeFlush() {};
+
+  Void xParsePredWeightTable ( TComSlice* pcSlice );
+  Void  parseScalingList               ( TComScalingList* scalingList );
+  Void xDecodeScalingList    ( TComScalingList *scalingList, UInt sizeId, UInt listId);
+  Void parseDFFlag         ( UInt& ruiVal, const Char *pSymbolName );
+  Void parseDFSvlc         ( Int&  riVal,  const Char *pSymbolName  );
+#if RWTH_SDC_DLT_B0036
+  Void parseSDCFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseSDCPredMode    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseSDCResidualData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPart );
+#endif
+protected:
+  Void  xParseDblParam       ( TComAPS* aps );
+  Void  xParseSaoParam       ( SAOParam* pSaoParam );
+  Void  xParseSaoOffset      (SaoLcuParam* saoLcuParam);
+  Void  xParseSaoUnit        (Int rx, Int ry, Int compIdx, SAOParam* saoParam, Bool& repeatedRow );
+  Void  xParseAlfParam(AlfParamSet* pAlfParamSet, Bool bSentInAPS = true, Int firstLCUAddr = 0, Bool acrossSlice = true, Int numLCUInWidth= -1, Int numLCUInHeight= -1);
+  Void  parseAlfParamSet(AlfParamSet* pAlfParamSet, Int firstLCUAddr, Bool alfAcrossSlice);
+  Void  parseAlfFixedLengthRun(UInt& idx, UInt rx, UInt numLCUInWidth);
+  Void  parseAlfStoredFilterIdx(UInt& idx, UInt numFilterSetsInBuffer);
+  Void  xParseAlfParam       ( ALFParam* pAlfParam );
+  Void  xParseAlfCuControlParam(AlfCUCtrlInfo& cAlfParam, Int iNumCUsInPic);
+  Int   xGolombDecode        ( Int k );
+  Bool  xMoreRbspData();
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECCAVLC_H__9732DD64_59B0_4A41_B29E_1A5B18821EAD__INCLUDED_)
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCu.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCu.cpp	(revision 341)
@@ -0,0 +1,1400 @@
+/* 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-2012, 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     TDecCu.cpp
+    \brief    CU decoder class
+*/
+
+#include "TDecCu.h"
+
+#if RWTH_SDC_DLT_B0036
+#define GetDepthValue2Idx(val)     (pcCU->getSlice()->getSPS()->depthValue2idx(val))
+#define GetIdx2DepthValue(val)     (pcCU->getSlice()->getSPS()->idx2DepthValue(val))
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCu::TDecCu()
+{
+  m_ppcYuvResi = NULL;
+  m_ppcYuvReco = NULL;
+#if H3D_IVRP
+  m_ppcYuvResPred = NULL;
+#endif
+  m_ppcCU      = NULL;
+}
+
+TDecCu::~TDecCu()
+{
+}
+
+Void TDecCu::init( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcTrQuant         = pcTrQuant;
+  m_pcPrediction      = pcPrediction;
+}
+
+/**
+ \param    uiMaxDepth    total number of allowable depth
+ \param    uiMaxWidth    largest CU width
+ \param    uiMaxHeight   largest CU height
+ */
+Void TDecCu::create( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight )
+{
+  m_uiMaxDepth = uiMaxDepth+1;
+  
+  m_ppcYuvResi = new TComYuv*[m_uiMaxDepth-1];
+  m_ppcYuvReco = new TComYuv*[m_uiMaxDepth-1];
+#if H3D_IVRP
+  m_ppcYuvResPred = new TComYuv*   [m_uiMaxDepth-1];
+#endif
+  m_ppcCU      = new TComDataCU*[m_uiMaxDepth-1];
+  
+  UInt uiNumPartitions;
+  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
+  {
+    uiNumPartitions = 1<<( ( m_uiMaxDepth - ui - 1 )<<1 );
+    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 );
+#if H3D_IVRP
+    m_ppcYuvResPred[ui] = new TComYuv;    m_ppcYuvResPred[ui]->create( uiWidth, uiHeight );
+#endif
+    m_ppcCU     [ui] = new TComDataCU; m_ppcCU     [ui]->create( uiNumPartitions, uiWidth, uiHeight, true, uiMaxWidth >> (m_uiMaxDepth - 1) );
+  }
+  
+  m_bDecodeDQP = false;
+
+  // initialize partition order.
+  UInt* piTmp = &g_auiZscanToRaster[0];
+  initZscanToRaster(m_uiMaxDepth, 1, 0, piTmp);
+  initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
+  
+  // initialize conversion matrix from partition index to pel
+  initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
+  initMotionReferIdx ( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
+}
+
+Void TDecCu::destroy()
+{
+  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
+  {
+    m_ppcYuvResi[ui]->destroy(); delete m_ppcYuvResi[ui]; m_ppcYuvResi[ui] = NULL;
+    m_ppcYuvReco[ui]->destroy(); delete m_ppcYuvReco[ui]; m_ppcYuvReco[ui] = NULL;
+#if H3D_IVRP
+    m_ppcYuvResPred[ui]->destroy(); delete m_ppcYuvResPred[ui]; m_ppcYuvResPred[ui] = NULL;
+#endif
+    m_ppcCU     [ui]->destroy(); delete m_ppcCU     [ui]; m_ppcCU     [ui] = NULL;
+  }
+  
+  delete [] m_ppcYuvResi; m_ppcYuvResi = NULL;
+  delete [] m_ppcYuvReco; m_ppcYuvReco = NULL;
+#if H3D_IVRP
+  delete [] m_ppcYuvResPred; m_ppcYuvResPred = NULL;
+#endif
+  delete [] m_ppcCU     ; m_ppcCU      = NULL;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param    pcCU        pointer of CU data
+ \param    ruiIsLast   last data?
+ */
+Void TDecCu::decodeCU( TComDataCU* pcCU, UInt& ruiIsLast )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    setdQPFlag(true);
+  }
+
+  pcCU->setNumSucIPCM(0);
+
+  // start from the top level CU
+  xDecodeCU( pcCU, 0, 0, ruiIsLast);
+}
+
+/** \param    pcCU        pointer of CU data
+ */
+Void TDecCu::decompressCU( TComDataCU* pcCU )
+{
+  xDecompressCU( pcCU, pcCU, 0,  0 );
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**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>>(pcSlice->getPPS()->getSliceGranularity());
+  UInt uiPosX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiPosY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+
+#if HHI_MPI
+  const UInt uiCUWidth  = pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1 ? g_uiMaxCUWidth>>uiDepth  : pcCU->getWidth (uiAbsPartIdx);
+  const UInt uiCUHeight = pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1 ? g_uiMaxCUHeight>>uiDepth : pcCU->getHeight(uiAbsPartIdx);
+  if(((uiPosX+uiCUWidth)%uiGranularityWidth==0||(uiPosX+uiCUWidth==uiWidth))
+    &&((uiPosY+uiCUHeight)%uiGranularityWidth==0||(uiPosY+uiCUHeight==uiHeight)))
+#else
+  if(((uiPosX+pcCU->getWidth(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosX+pcCU->getWidth(uiAbsPartIdx)==uiWidth))
+    &&((uiPosY+pcCU->getHeight(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosY+pcCU->getHeight(uiAbsPartIdx)==uiHeight)))
+#endif
+  {
+    m_pcEntropyDecoder->decodeTerminatingBit( uiIsLast );
+  }
+  else
+  {
+    uiIsLast=0;
+  }
+  
+  if(uiIsLast) 
+  {
+    if(pcSlice->isNextEntropySlice()&&!pcSlice->isNextSlice()) 
+    {
+      pcSlice->setEntropySliceCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
+    }
+    else 
+    {
+      pcSlice->setSliceCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
+      pcSlice->setEntropySliceCurEndCUAddr(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);
+  UInt uiQNumParts      = uiCurNumParts>>2;
+  
+  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;
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getEntropySliceCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getEntropySliceCurStartCUAddr();
+  if((!bStartInCU) && ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    if(pcCU->getNumSucIPCM() == 0)
+    {
+#if HHI_MPI
+      if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 || uiDepth < pcCU->getTextureModeDepth( uiAbsPartIdx ) )
+#endif
+      m_pcEntropyDecoder->decodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+    }
+  }
+  else
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  {
+    UInt uiIdx = uiAbsPartIdx;
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      setdQPFlag(true);
+      pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
+    }
+
+    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->getEntropySliceCurStartCUAddr();
+      if ( bSubInSlice )
+      {
+        if ( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+        {
+          xDecodeCU( pcCU, uiIdx, uiDepth+1, ruiIsLast );
+        }
+        else
+        {
+          pcCU->setOutsideCUPart( uiIdx, uiDepth+1 );
+        }
+      }
+      if(ruiIsLast)
+      {
+        break;
+      }
+      
+      uiIdx += uiQNumParts;
+    }
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      if ( getdQPFlag() )
+      {
+        UInt uiQPSrcPartIdx;
+        if ( pcPic->getCU( pcCU->getAddr() )->getEntropySliceStartCU(uiAbsPartIdx) != pcSlice->getEntropySliceCurStartCUAddr() )
+        {
+          uiQPSrcPartIdx = pcSlice->getEntropySliceCurStartCUAddr() % pcPic->getNumPartInCU();
+        }
+        else
+        {
+          uiQPSrcPartIdx = uiAbsPartIdx;
+        }
+        pcCU->setQPSubParts( pcCU->getRefQP( uiQPSrcPartIdx ), uiAbsPartIdx, uiDepth ); // set QP to default QP
+      }
+    }
+    return;
+  }
+  
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    setdQPFlag(true);
+    pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
+  }
+
+  // decode CU mode and the partition size
+  if( !pcCU->getSlice()->isIntra() && pcCU->getNumSucIPCM() == 0 )
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 )
+#endif
+  {
+    m_pcEntropyDecoder->decodeSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+ 
+  if( pcCU->isSkipped(uiAbsPartIdx) )
+  {
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+#if H3D_IVMP
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+    Int numValidMergeCand = 0;
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS_MEM; ++ui )
+#else
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+    Int numValidMergeCand = 0;
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+#endif
+    {
+      uhInterDirNeighbours[ui] = 0;
+    }
+    m_pcEntropyDecoder->decodeMergeIndex( pcCU, 0, uiAbsPartIdx, SIZE_2Nx2N, uhInterDirNeighbours, cMvFieldNeighbours, uiDepth );
+#if HHI_MPI
+    if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == uiDepth )
+    {
+      TComDataCU *pcTextureCU = pcCU->getSlice()->getTexturePic()->getCU( pcCU->getAddr() );
+      pcCU->copyTextureMotionDataFrom( pcTextureCU, uiDepth, pcCU->getZorderIdxInCU() + uiAbsPartIdx, uiAbsPartIdx );
+
+      UInt uiCurrPartNumb = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+
+      for( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+      {
+        const UChar uhNewDepth = max<UInt>( uiDepth, pcTextureCU->getDepth( uiAbsPartIdx + ui ) );
+#if MERL_VSP_C0152
+        Int vspIdx = pcTextureCU->getVSPIndex( uiAbsPartIdx + ui);
+        pcCU->setVSPIndex( uiAbsPartIdx + ui, vspIdx);
+#endif
+        pcCU->setPredictionMode( uiAbsPartIdx + ui, MODE_SKIP );
+        pcCU->setPartitionSize( uiAbsPartIdx + ui, SIZE_2Nx2N );
+        pcCU->setDepth( uiAbsPartIdx + ui, uhNewDepth );
+        pcCU->setWidth( uiAbsPartIdx + ui, g_uiMaxCUWidth>>uhNewDepth );
+        pcCU->setHeight( uiAbsPartIdx + ui, g_uiMaxCUHeight>>uhNewDepth );
+      }
+#if LGE_ILLUCOMP_DEPTH_C0046
+      m_pcEntropyDecoder->decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+    }
+    else
+    {
+#endif
+    UInt uiMergeIndex = pcCU->getMergeIndex(uiAbsPartIdx);
+#if MERL_VSP_C0152
+    Int iVSPIndexTrue[3] = {-1, -1, -1};
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, iVSPIndexTrue, uiMergeIndex );
+    {
+      Int iVSPIdx = 0;
+      Int numVspIdx;
+      numVspIdx = 3;
+      for (Int i = 0; i < numVspIdx; i++)
+      {
+        if (iVSPIndexTrue[i] == uiMergeIndex)
+          {
+            iVSPIdx = i+1;
+            break;
+          }
+      }
+      pcCU->setVSPIndexSubParts( iVSPIdx, uiAbsPartIdx, 0, uiDepth );  //Initialize the VSP, may change later in get InterMergeCandidates()
+    }
+#else
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+#endif
+    pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiAbsPartIdx, 0, uiDepth );
+
+    TComMv cTmpMv( 0, 0 );
+    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+    {        
+      if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+      {
+        pcCU->setMVPIdxSubParts( 0, RefPicList( uiRefListIdx ), uiAbsPartIdx, 0, uiDepth);
+        pcCU->setMVPNumSubParts( 0, RefPicList( uiRefListIdx ), uiAbsPartIdx, 0, uiDepth);
+        pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+        pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+      }
+    }
+#if LGE_ILLUCOMP_B0045
+    m_pcEntropyDecoder->decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+#if HHI_MPI
+    }
+#endif
+    xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+    return;
+  }
+
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 )
+  {
+#endif
+  if( pcCU->getNumSucIPCM() == 0 ) 
+  {
+    m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );
+    m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth ); 
+    pcCU->setTrIdxSubParts( 0, uiAbsPartIdx, uiDepth );
+  }
+
+  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+  {
+    m_pcEntropyDecoder->decodeIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+
+    if(pcCU->getIPCMFlag(uiAbsPartIdx))
+    {
+      xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+      return;
+    }
+  }
+
+#if ! HHI_MPI
+  UInt uiCurrWidth      = pcCU->getWidth ( uiAbsPartIdx );
+  UInt uiCurrHeight     = pcCU->getHeight( uiAbsPartIdx );
+#endif
+  
+  // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
+  m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
+  
+#if LGE_ILLUCOMP_B0045
+#if LGE_ILLUCOMP_DEPTH_C0046 && HHI_MPI
+  if( pcCU->getTextureModeDepth( uiAbsPartIdx ) != uiDepth )
+  {
+#endif
+  m_pcEntropyDecoder->decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+
+#if LGE_ILLUCOMP_DEPTH_C0046 && HHI_MPI
+  }
+#endif
+
+#if HHI_MPI
+    if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == uiDepth )
+    {
+      assert( pcCU->getZorderIdxInCU() == 0 );
+      TComDataCU *pcTextureCU = pcCU->getSlice()->getTexturePic()->getCU( pcCU->getAddr() );
+      pcCU->copyTextureMotionDataFrom( pcTextureCU, uiDepth, pcCU->getZorderIdxInCU() + uiAbsPartIdx, uiAbsPartIdx );
+
+      UInt uiCurrPartNumb = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+
+      for( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+      {
+        const UChar uhNewDepth = max<UInt>( uiDepth, pcTextureCU->getDepth( uiAbsPartIdx + ui ) );
+#if MERL_VSP_C0152
+        Int vspIdx = pcTextureCU->getVSPIndex( uiAbsPartIdx + ui);
+        pcCU->setVSPIndex( uiAbsPartIdx + ui, vspIdx);
+#endif
+        pcCU->setPredictionMode( uiAbsPartIdx + ui, MODE_INTER );
+        pcCU->setPartitionSize( uiAbsPartIdx + ui, SIZE_2Nx2N );
+        pcCU->setDepth( uiAbsPartIdx + ui, uhNewDepth );
+        pcCU->setWidth( uiAbsPartIdx + ui, g_uiMaxCUWidth>>uhNewDepth );
+        pcCU->setHeight( uiAbsPartIdx + ui, g_uiMaxCUHeight>>uhNewDepth );
+      }
+#if LGE_ILLUCOMP_DEPTH_C0046
+      m_pcEntropyDecoder->decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+      if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+      {
+        UInt uiIdx = uiAbsPartIdx;
+        if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+        {
+          setdQPFlag(true);
+          pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
+        }
+
+        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->getEntropySliceCurStartCUAddr();
+          if ( bSubInSlice )
+          {
+            if ( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+            {
+              xDecodeCU( pcCU, uiIdx, uiDepth+1, ruiIsLast );
+            }
+            else
+            {
+              pcCU->setOutsideCUPart( uiIdx, uiDepth+1 );
+            }
+          }
+          if(ruiIsLast)
+          {
+            break;
+          }
+          uiIdx += uiQNumParts;
+        }
+        if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+        {
+          if ( getdQPFlag() )
+          {
+            UInt uiQPSrcPartIdx;
+            if ( pcPic->getCU( pcCU->getAddr() )->getEntropySliceStartCU(uiAbsPartIdx) != pcSlice->getEntropySliceCurStartCUAddr() )
+            {
+              uiQPSrcPartIdx = pcSlice->getEntropySliceCurStartCUAddr() % pcPic->getNumPartInCU();
+            }
+            else
+            {
+              uiQPSrcPartIdx = uiAbsPartIdx;
+            }
+            pcCU->setQPSubParts( pcCU->getRefQP( uiQPSrcPartIdx ), uiAbsPartIdx, uiDepth ); // set QP to default QP
+          }
+        }
+        return;
+      }
+    }
+  }
+
+  UInt uiCurrWidth      = pcCU->getWidth ( uiAbsPartIdx );
+  UInt uiCurrHeight     = pcCU->getHeight( uiAbsPartIdx );
+#endif
+
+  // Coefficient decoding
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, uiCurrWidth, uiCurrHeight, bCodeDQP );
+  setdQPFlag( bCodeDQP );
+  xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+}
+
+Void TDecCu::xFinishDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
+{
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    if( getdQPFlag() )
+    {
+      pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
+    }
+  }
+
+  if( pcCU->getNumSucIPCM() > 0 )
+  {
+    ruiIsLast = 0;
+    return;
+  }
+
+  ruiIsLast = xDecodeSliceEnd( pcCU, uiAbsPartIdx, uiDepth);
+}
+
+Void TDecCu::xDecompressCU( TComDataCU* pcCU, TComDataCU* pcCUCur, 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;
+  
+  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getEntropySliceCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getEntropySliceCurStartCUAddr();
+  if(bStartInCU||( uiRPelX >= pcSlice->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  {
+    UInt uiNextDepth = uiDepth + 1;
+    UInt uiQNumParts = pcCU->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->getEntropySliceCurStartCUAddr())&&(pcCU->getSCUAddr()+uiIdx<pcSlice->getEntropySliceCurEndCUAddr());
+      if(binSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xDecompressCU(pcCU, m_ppcCU[uiNextDepth], uiIdx, uiNextDepth );
+      }
+      
+      uiIdx += uiQNumParts;
+    }
+    return;
+  }
+  
+  // Residual reconstruction
+  m_ppcYuvResi[uiDepth]->clear();
+  
+  m_ppcCU[uiDepth]->copySubCU( pcCU, uiAbsPartIdx, uiDepth );
+  
+  switch( m_ppcCU[uiDepth]->getPredictionMode(0) )
+  {
+    case MODE_SKIP:
+    case MODE_INTER:
+      xReconInter( m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth );
+      break;
+    case MODE_INTRA:
+#if RWTH_SDC_DLT_B0036
+      if( m_ppcCU[uiDepth]->getSDCFlag(0) )
+        xReconIntraSDC( m_ppcCU[uiDepth], 0, uiDepth );
+      else
+#endif
+      xReconIntraQT( m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth );
+      break;
+    default:
+      assert(0);
+      break;
+  }
+#if LOSSLESS_CODING 
+  if ( m_ppcCU[uiDepth]->isLosslessCoded(0) && (m_ppcCU[uiDepth]->getIPCMFlag(0) == false))
+  {
+    xFillPCMBuffer(m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth);    
+  }
+#endif
+  
+  xCopyToPic( m_ppcCU[uiDepth], pcPic, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecCu::xReconInter( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+#if HHI_MPI
+#if FIX_MPI_B0065
+  if( pcCU->getTextureModeDepth( 0 ) != -1 )
+  {
+    TComDataCU *pcTextureCU = pcCU->getSlice()->getTexturePic()->getCU( pcCU->getAddr() );
+    if( uiDepth == pcTextureCU->getDepth(uiAbsPartIdx))
+    {
+      PartSize partSize = pcTextureCU->getPartitionSize(uiAbsPartIdx);
+      pcCU->setPartSizeSubParts( partSize, 0, uiDepth );
+    }
+    else
+    {
+      pcCU->setPartSizeSubParts( SIZE_NxN, 0, uiDepth );
+    }
+  }
+#else
+  if( pcCU->getTextureModeDepth( 0 ) != -1 )
+    pcCU->setPartSizeSubParts( SIZE_NxN, 0, uiDepth );
+#endif
+#endif
+  
+  // inter prediction
+#if MERL_VSP_C0152
+  m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth], uiAbsPartIdx );
+#else
+  m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth] );
+#endif
+#if H3D_IVRP
+  if (pcCU->getMergeFlag(0) && pcCU->getMergeIndex(0)==0 && pcCU->getResPredAvail(0))
+  {
+    m_pcPrediction->residualPrediction(pcCU, m_ppcYuvReco[uiDepth], m_ppcYuvResPred[uiDepth]);
+  }
+#endif
+
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( 0 ) != -1 )
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+#endif
+
+  // inter recon
+  xDecodeInterTexture( pcCU, 0, uiDepth );
+  
+  // 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 ) );
+  }
+  else
+  {
+#if H3D_IVRP
+    if (pcCU->getMergeFlag(0) && pcCU->getMergeIndex(0)==0 && pcCU->getResPredAvail(0))
+    {
+      m_ppcYuvReco[uiDepth]->clip( pcCU->getWidth( 0 ), pcCU->getHeight( 0 ) );
+    }
+#endif
+    m_ppcYuvReco[uiDepth]->copyPartToPartYuv( m_ppcYuvReco[uiDepth],0, pcCU->getWidth( 0 ),pcCU->getHeight( 0 ));
+  }
+}
+
+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  ();
+  
+  //===== 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 );
+#if LGE_EDGE_INTRA_A0070
+  if( uiLumaPredMode >= EDGE_INTRA_IDX )
+  {
+    m_pcPrediction->predIntraLumaEdge( pcCU, pcCU->getPattern(), uiAbsPartIdx, uiWidth, uiHeight, piPred, uiStride
+#if LGE_EDGE_INTRA_DELTA_DC
+      , uiLumaPredMode == EDGE_INTRA_DELTA_IDX
+#endif
+      );
+  } 
+  else
+#endif
+  
+  //===== get prediction signal =====
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( uiLumaPredMode >= NUM_INTRA_MODE )
+  {
+    m_pcPrediction->predIntraLumaDMM( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail, false );
+  } 
+  else
+  {
+#endif
+  m_pcPrediction->predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  }
+#endif
+  
+  //===== inverse transform =====
+  m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)TEXT_LUMA];
+  assert(scalingListType < 6);
+#if LOSSLESS_CODING
+  m_pcTrQuant->invtransformNxN( pcCU, TEXT_LUMA, pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType );
+#else  
+  m_pcTrQuant->invtransformNxN(       TEXT_LUMA, pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType );
+#endif
+
+  
+  //===== 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 ] = Clip( pPred[ uiX ] + pResi[ uiX ] );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pResi     += 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();
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
+
+  if( uiChromaPredMode == LM_CHROMA_IDX && uiChromaId == 0 )
+  {
+    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, 
+                                     m_pcPrediction->getPredicBuf       (),
+                                     m_pcPrediction->getPredicBufWidth  (),
+                                     m_pcPrediction->getPredicBufHeight (),
+                                     bAboveAvail, bLeftAvail, 
+                                     true );
+
+    m_pcPrediction->getLumaRecPixels( pcCU->getPattern(), uiWidth, uiHeight );
+  }
+  
+  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 == LM_CHROMA_IDX )
+  {
+    m_pcPrediction->predLMIntraChroma( pcCU->getPattern(), pPatChroma, piPred, uiStride, uiWidth, uiHeight, uiChromaId );
+  }
+  else
+  {
+    if( uiChromaPredMode == DM_CHROMA_IDX )
+    {
+      uiChromaPredMode = pcCU->getLumaIntraDir( 0 );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      mapDMMtoIntraMode( uiChromaPredMode );
+#endif
+    }
+    m_pcPrediction->predIntraChromaAng( pcCU->getPattern(), pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );  
+  }
+
+  //===== inverse transform =====
+  if(eText == TEXT_CHROMA_U)
+  {
+    m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), eText, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset() );
+  }
+  else
+  {
+    m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), eText, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset2nd() );
+  }
+
+  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eText];
+  assert(scalingListType < 6);
+#if LOSSLESS_CODING
+  m_pcTrQuant->invtransformNxN( pcCU, eText, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType );
+#else  
+  m_pcTrQuant->invtransformNxN(       eText, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType );
+#endif
+
+  //===== 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 ] = Clip( pPred[ uiX ] + pResi[ uiX ] );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pResi     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+  }
+}
+
+Void
+TDecCu::xIntraRecQT( 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 )
+  {
+    xIntraRecLumaBlk  ( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv );
+    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++ )
+    {
+      xIntraRecQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv, pcPredYuv, pcResiYuv );
+    }
+  }
+}
+
+Void
+TDecCu::xReconIntraQT( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt  uiInitTrDepth = ( pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1 );
+  UInt  uiNumPart     = pcCU->getNumPartInter();
+  UInt  uiNumQParts   = pcCU->getTotalNumPart() >> 2;
+  
+  if (pcCU->getIPCMFlag(0))
+  {
+    xReconPCM( pcCU, uiAbsPartIdx, uiDepth );
+    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] );
+  }
+
+}
+
+#if RWTH_SDC_DLT_B0036
+Void TDecCu::xReconIntraSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiWidth        = pcCU->getWidth  ( 0 );
+  UInt uiHeight       = pcCU->getHeight ( 0 );
+  
+  TComYuv* pcRecoYuv  = m_ppcYuvReco[uiDepth];
+  TComYuv* pcPredYuv  = m_ppcYuvReco[uiDepth];
+  TComYuv* pcResiYuv  = m_ppcYuvResi[uiDepth];
+  
+  UInt    uiStride    = pcRecoYuv->getStride  ();
+  Pel*    piReco      = pcRecoYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred      = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piResi      = pcResiYuv->getLumaAddr( uiAbsPartIdx );
+  
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  
+  UInt    uiLumaPredMode    = pcCU->getLumaIntraDir     ( uiAbsPartIdx );
+  
+  AOF( uiWidth == uiHeight );
+  AOF( uiAbsPartIdx == 0 );
+  AOF( pcCU->getSDCAvailable(uiAbsPartIdx) );
+  AOF( pcCU->getSDCFlag(uiAbsPartIdx) );
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern   ( pcCU, 0, uiAbsPartIdx );
+  pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, 0, m_pcPrediction->getPredicBuf(), m_pcPrediction->getPredicBufWidth(), m_pcPrediction->getPredicBufHeight(), bAboveAvail, bLeftAvail );
+  
+  //===== get prediction signal =====
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( uiLumaPredMode >= NUM_INTRA_MODE )
+  {
+    m_pcPrediction->predIntraLumaDMM( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail, false );
+  }
+  else
+  {
+#endif
+    m_pcPrediction->predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  }
+#endif
+  
+  // number of segments depends on prediction mode
+  UInt uiNumSegments = 1;  
+  Bool* pbMask = NULL;
+  UInt uiMaskStride = 0;
+  
+  if( uiLumaPredMode == DMM_WEDGE_FULL_IDX || uiLumaPredMode == DMM_WEDGE_PREDDIR_IDX )
+  {
+    Int uiTabIdx = (uiLumaPredMode == DMM_WEDGE_FULL_IDX)?pcCU->getWedgeFullTabIdx(uiAbsPartIdx):pcCU->getWedgePredDirTabIdx(uiAbsPartIdx);
+    
+    WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+    TComWedgelet* pcWedgelet = &(pacWedgeList->at( uiTabIdx ));
+    
+    uiNumSegments = 2;
+    pbMask = pcWedgelet->getPattern();
+    uiMaskStride = pcWedgelet->getStride();
+  }
+  
+  // get DC prediction for each segment
+  Pel apDCPredValues[2];
+  xAnalyzeSegmentsSDC(piPred, uiStride, uiWidth, apDCPredValues, uiNumSegments, pbMask, uiMaskStride);
+  
+  // reconstruct residual based on mask + DC residuals
+  Pel apDCResiValues[2];
+  Pel apDCRecoValues[2];
+  for( UInt ui = 0; ui < uiNumSegments; ui++ )
+  {
+    Pel   pPredIdx    = GetDepthValue2Idx( apDCPredValues[ui] );
+    Pel   pResiIdx    = pcCU->getSDCSegmentDCOffset(ui, uiAbsPartIdx);
+    Pel   pRecoValue  = GetIdx2DepthValue( pPredIdx + pResiIdx );
+    
+    apDCRecoValues[ui]  = pRecoValue;
+    apDCResiValues[ui]  = pRecoValue - apDCPredValues[ui];
+  }
+  
+  //===== reconstruction =====
+  Bool*pMask      = pbMask;
+  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++ )
+    {
+      UChar ucSegment = pMask?(UChar)pMask[uiX]:0;
+      assert( ucSegment < uiNumSegments );
+      
+      Pel pPredVal= apDCPredValues[ucSegment];
+      Pel pResiDC = apDCResiValues[ucSegment];
+      
+      pReco    [ uiX ] = Clip( pPredVal + pResiDC );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pResi     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+    pMask     += uiMaskStride;
+  }
+  
+  // clear UV
+  UInt  uiStrideC     = pcPredYuv->getCStride();
+  Pel   *pRecCb       = pcPredYuv->getCbAddr();
+  Pel   *pRecCr       = pcPredYuv->getCrAddr();
+  
+  for (Int y=0; y<uiHeight/2; y++)
+  {
+    for (Int x=0; x<uiWidth/2; x++)
+    {
+      pRecCb[x] = (Pel)(128<<g_uiBitIncrement);
+      pRecCr[x] = (Pel)(128<<g_uiBitIncrement);
+    }
+    
+    pRecCb += uiStrideC;
+    pRecCr += uiStrideC;
+  }
+}
+#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
+ * \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
+ */
+Void
+TDecCu::xIntraLumaRecQT( 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 )
+  {
+    xIntraRecLumaBlk  ( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv );
+  }
+  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 );
+    }
+  }
+}
+
+Void TDecCu::xCopyToPic( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth )
+{
+  UInt uiCUAddr = pcCU->getAddr();
+  
+  m_ppcYuvReco[uiDepth]->copyToPicYuv  ( pcPic->getPicYuvRec (), uiCUAddr, 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    uiLumaTrMode, uiChromaTrMode;
+  
+  pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx( uiAbsPartIdx ), uiLumaTrMode, uiChromaTrMode );
+  
+  // Y
+  piCoeff = pcCU->getCoeffY();
+  pResi = m_ppcYuvResi[uiDepth]->getLumaAddr();
+
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_LUMA, pResi, 0, m_ppcYuvResi[uiDepth]->getStride(), uiWidth, uiHeight, uiLumaTrMode, 0, piCoeff );
+  
+  // Cb and Cr
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset() );
+
+  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, uiChromaTrMode, 0, piCoeff );
+
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset2nd() );
+
+  piCoeff = pcCU->getCoeffCr(); pResi = m_ppcYuvResi[uiDepth]->getCrAddr();
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_V, pResi, 0, m_ppcYuvResi[uiDepth]->getCStride(), uiWidth, uiHeight, uiChromaTrMode, 0, piCoeff );
+}
+
+/** Function for deriving reconstructed luma/chroma samples of a PCM mode CU.
+ * \param pcCU pointer to current CU
+ * \param uiPartIdx part index
+ * \param piPCM pointer to PCM code arrays
+ * \param piReco pointer to reconstructed sample arrays
+ * \param uiStride stride of reconstructed sample arrays
+ * \param uiWidth CU width
+ * \param uiHeight CU height
+ * \param ttText texture component type
+ * \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_uiBitDepth + g_uiBitIncrement - 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_uiBitDepth + g_uiBitIncrement - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+  }
+
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piReco[uiX] = (piPCM[uiX] << uiPcmLeftShiftBit);
+      piPicReco[uiX] = piReco[uiX];
+    }
+    piPCM += uiWidth;
+    piReco += uiStride;
+    piPicReco += uiPicStride;
+  }
+}
+
+/** Function for reconstructing a PCM mode CU.
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU Depth
+ * \returns Void
+ */
+Void TDecCu::xReconPCM( TComDataCU* pcCU, UInt uiAbsPartIdx, 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);
+}
+
+#if LOSSLESS_CODING 
+/** Function for filling the PCM buffer of a CU using its reconstructed sample array 
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU Depth
+ * \returns Void
+ */
+Void TDecCu::xFillPCMBuffer(TComDataCU* pCU, UInt absPartIdx, 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;
+  }
+
+}
+#endif
+
+#if RWTH_SDC_DLT_B0036
+Void TDecCu::xAnalyzeSegmentsSDC( Pel* pOrig, UInt uiStride, UInt uiSize, Pel* rpSegMeans, UInt uiNumSegments, Bool* pMask, UInt uiMaskStride )
+{
+  Int iSumDepth[2];
+  memset(iSumDepth, 0, sizeof(Int)*2);
+  Int iSumPix[2];
+  memset(iSumPix, 0, sizeof(Int)*2);
+#if HS_REFERENCE_SUBSAMPLE_C0154
+  Int subSamplePix;
+  if ( uiSize == 64 || uiSize == 32 )
+  {
+    subSamplePix = 2;
+  }
+  else
+  {
+    subSamplePix = 1;
+  }
+  for (Int y=0; y<uiSize; y+=subSamplePix)
+  {
+    for (Int x=0; x<uiSize; x+=subSamplePix)
+    {
+      UChar ucSegment = pMask?(UChar)pMask[x]:0;
+      assert( ucSegment < uiNumSegments );
+  
+      iSumDepth[ucSegment] += pOrig[x];
+      iSumPix[ucSegment]   += 1;
+    }
+    pOrig  += uiStride*subSamplePix;
+    pMask  += uiMaskStride*subSamplePix;
+  }
+#else
+  for (Int y=0; y<uiSize; y++)
+  {
+    for (Int x=0; x<uiSize; x++)
+    {
+      UChar ucSegment = pMask?(UChar)pMask[x]:0;
+      assert( ucSegment < uiNumSegments );
+      
+      iSumDepth[ucSegment] += pOrig[x];
+      iSumPix[ucSegment]   += 1;
+    }
+    
+    pOrig  += uiStride;
+    pMask  += uiMaskStride;
+  }
+#endif
+  // compute mean for each segment
+  for( UChar ucSeg = 0; ucSeg < uiNumSegments; ucSeg++ )
+  {
+    if( iSumPix[ucSeg] > 0 )
+      rpSegMeans[ucSeg] = iSumDepth[ucSeg] / iSumPix[ucSeg];
+    else
+      rpSegMeans[ucSeg] = 0;  // this happens for zero-segments
+  }
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCu.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecCu.h	(revision 341)
@@ -0,0 +1,139 @@
+/* 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-2012, 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     TDecCu.h
+    \brief    CU decoder class (header)
+*/
+
+#ifndef __TDECCU__
+#define __TDECCU__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TDecEntropy.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU decoder class
+class TDecCu
+{
+private:
+  UInt                m_uiMaxDepth;       ///< max. number of depth
+  TComYuv**           m_ppcYuvResi;       ///< array of residual buffer
+  TComYuv**           m_ppcYuvReco;       ///< array of prediction & reconstruction buffer
+#if H3D_IVRP
+  TComYuv**           m_ppcYuvResPred;    ///< residual prediction buffer
+#endif
+  TComDataCU**        m_ppcCU;            ///< CU data array
+
+  // access channel
+  TComTrQuant*        m_pcTrQuant;
+  TComPrediction*     m_pcPrediction;
+  TDecEntropy*        m_pcEntropyDecoder;
+
+  Bool                m_bDecodeDQP;
+  
+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 );
+  
+  /// destroy internal buffers
+  Void  destroy                 ();
+
+  /// decode CU information
+  Void  decodeCU                ( TComDataCU* pcCU, UInt& ruiIsLast );
+  
+  /// reconstruct CU information
+  Void  decompressCU            ( TComDataCU* pcCU );
+  
+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, TComDataCU* pcCUCur,  UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void xReconInter              ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void  xReconIntraQT           ( TComDataCU* pcCU, UInt uiAbsPartIdx, 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  xIntraRecQT             ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
+  
+  Void  xReconPCM               ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+
+  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 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;           }
+#if LOSSLESS_CODING 
+  Void xFillPCMBuffer           (TComDataCU* pCU, UInt absPartIdx, UInt depth);
+#endif
+#if RWTH_SDC_DLT_B0036
+  Void  xAnalyzeSegmentsSDC       ( Pel* pOrig,
+                                   UInt uiStride,
+                                   UInt uiSize,
+                                   Pel* rpSegMeans,
+                                   UInt uiNumSegments,
+                                   Bool* pMask,
+                                   UInt uiMaskStride );
+  
+  Void xReconIntraSDC           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+};
+
+//! \}
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 341)
@@ -0,0 +1,881 @@
+/* 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-2012, 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     TDecEntropy.cpp
+    \brief    entropy decoder class
+*/
+
+#include "TDecEntropy.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+Void TDecEntropy::setEntropyDecoder         ( TDecEntropyIf* p )
+{
+  m_pcEntropyDecoderIf = p;
+}
+
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+Void TDecEntropy::decodeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** decode merge flag
+ * \param pcSubCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \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 );
+}
+
+#if LGE_ILLUCOMP_B0045
+Void TDecEntropy::decodeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  pcCU->setICFlagSubParts( false , uiAbsPartIdx, 0, uiDepth );
+
+  if (pcCU->isIntra(uiAbsPartIdx) || (pcCU->getSlice()->getViewId() == 0) 
+#if !LGE_ILLUCOMP_DEPTH_C0046
+      || pcCU->getSlice()->getSPS()->isDepth()
+#endif
+      )
+  {
+    return;
+  }
+
+  if(!pcCU->getSlice()->getApplyIC())
+    return;
+
+#if LGE_ILLUCOMP_DEPTH_C0046
+  if(pcCU->isICFlagRequired(uiAbsPartIdx, uiDepth)) //This modification is not needed after integrating JCT3V-C0137
+#else
+  if(pcCU->isICFlagRequired(uiAbsPartIdx))
+#endif
+    m_pcEntropyDecoderIf->parseICFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+#endif
+/** 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 uiDepth
+ * \returns Void
+ */
+Void TDecEntropy::decodeMergeIndex( TComDataCU* pcCU, UInt uiPartIdx, UInt uiAbsPartIdx, PartSize eCUMode, UChar* puhInterDirNeighbours, TComMvField* pcMvFieldNeighbours, UInt uiDepth )
+{
+  UInt uiMergeIndex = 0;
+  m_pcEntropyDecoderIf->parseMergeIndex( pcCU, uiMergeIndex, uiAbsPartIdx, uiDepth );
+  pcCU->setMergeIndexSubParts( uiMergeIndex, uiAbsPartIdx, uiPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parsePredMode( pcCU, uiAbsPartIdx, uiDepth );
+  
+#if RWTH_SDC_DLT_B0036
+  // if B-Slice, code SDC flag later
+  if( !pcCU->getSlice()->isInterB() && pcCU->isIntra(uiAbsPartIdx) && pcCU->getSlice()->getSPS()->isDepth() )
+  {
+    // decode SDC flag
+    decodeSDCFlag(pcCU, uiAbsPartIdx, uiDepth);
+  }
+#endif
+}
+
+Void TDecEntropy::decodePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+#if RWTH_SDC_DLT_B0036
+  if( !pcCU->getSlice()->isInterB() && pcCU->isIntra(uiAbsPartIdx) && pcCU->getSDCFlag(uiAbsPartIdx)  )
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    return;
+  }
+#endif
+  
+  m_pcEntropyDecoderIf->parsePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  
+#if RWTH_SDC_DLT_B0036
+  if( pcCU->getSlice()->isInterB() && pcCU->getSlice()->getSPS()->isDepth() && pcCU->isIntra(uiAbsPartIdx) )
+  {
+    // decode SDC flag
+    decodeSDCFlag(pcCU, uiAbsPartIdx, uiDepth);
+    
+    if( pcCU->getSDCFlag(uiAbsPartIdx) )
+    {
+      // part size is also known for SDC intra
+      pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+      pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    }
+  }
+#endif
+}
+
+Void TDecEntropy::decodePredInfo    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU )
+{
+#if RWTH_SDC_DLT_B0036
+  if( pcCU->getSDCFlag(uiAbsPartIdx) )
+  {
+    decodeSDCPredMode(pcCU, uiAbsPartIdx, uiDepth);
+    return;
+  }
+#endif
+  
+  PartSize eMode = pcCU->getPartitionSize( uiAbsPartIdx );
+  
+  if( pcCU->isIntra( uiAbsPartIdx ) )                                 // If it is Intra mode, encode intra prediction mode.
+  {
+    if( eMode == SIZE_NxN )                                         // if it is NxN size, encode 4 intra directions.
+    {
+      UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+      // if it is NxN size, this size might be the smallest partition size.                                                         // if it is NxN size, this size might be the smallest partition size.
+      decodeIntraDirModeLuma( pcCU, uiAbsPartIdx,                  uiDepth+1 );
+      decodeIntraDirModeLuma( pcCU, uiAbsPartIdx + uiPartOffset,   uiDepth+1 );
+      decodeIntraDirModeLuma( pcCU, uiAbsPartIdx + uiPartOffset*2, uiDepth+1 );
+      decodeIntraDirModeLuma( pcCU, uiAbsPartIdx + uiPartOffset*3, uiDepth+1 );
+      decodeIntraDirModeChroma( pcCU, uiAbsPartIdx, uiDepth );
+    }
+    else                                                                // if it is not NxN size, encode 1 intra directions
+    {
+      decodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx, uiDepth );
+      decodeIntraDirModeChroma( pcCU, uiAbsPartIdx, uiDepth );
+    }
+  }
+  else                                                                // if it is Inter mode, encode motion vector and reference index
+  {
+    decodePUWise( pcCU, uiAbsPartIdx, uiDepth, pcSubCU );
+  }
+}
+
+/** Parse I_PCM information. 
+ * \param pcCU  pointer to CUpointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TDecEntropy::decodeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if(!pcCU->getSlice()->getSPS()->getUsePCM()
+    || pcCU->getWidth(uiAbsPartIdx) > (1<<pcCU->getSlice()->getSPS()->getPCMLog2MaxSize())
+    || pcCU->getWidth(uiAbsPartIdx) < (1<<pcCU->getSlice()->getSPS()->getPCMLog2MinSize()) )
+  {
+    return;
+  }
+  
+#if RWTH_SDC_DLT_B0036
+  if( pcCU->getSDCFlag(uiAbsPartIdx) )
+  {
+    return;
+  }
+#endif
+  
+  m_pcEntropyDecoderIf->parseIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraDirLumaAng( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraDirChroma( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** decode motion information for every PU block.
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param pcSubCU
+ * \returns Void
+ */
+Void TDecEntropy::decodePUWise( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU )
+{
+  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;
+
+#if CU_BASED_MRG_CAND_LIST
+#if H3D_IVMP
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+  for ( UInt ui = 0; ui < MRG_MAX_NUM_CANDS_MEM; ui++ )
+#else
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  for ( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+#endif
+  {
+    uhInterDirNeighbours[ui] = 0;
+  }
+  Int numValidMergeCand = 0;
+  bool isMerged = false;
+#endif
+
+  pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+  pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+  for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
+  {
+#if !CU_BASED_MRG_CAND_LIST
+#if H3D_IVMP
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+    Int numValidMergeCand = 0;
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS_MEM; ++ui )
+#else
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+    Int numValidMergeCand = 0;
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+#endif
+    {
+      uhInterDirNeighbours[ui] = 0;
+    }
+#endif
+    decodeMergeFlag( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      decodeMergeIndex( pcCU, uiPartIdx, uiSubPartIdx, ePartSize, uhInterDirNeighbours, cMvFieldNeighbours, uiDepth );
+#if CU_BASED_MRG_CAND_LIST
+      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 )
+        {
+          pcSubCU->getInterMergeCandidates( 0, 0, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+          isMerged = true;
+        }
+        pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth );
+      }
+      else
+      {
+        uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+      }
+#else
+      UInt uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
+#if MERL_VSP_C0152
+      Int iVSPIndexTrue[3] = {-1, -1, -1};
+      pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, iVSPIndexTrue, uiMergeIndex );
+
+#if HHI_MPI
+      if(pcCU->getTextureModeDepth( uiSubPartIdx ) == uiDepth)//MPI is used
+      {
+        TComDataCU *pcTextureCU = pcCU->getSlice()->getTexturePic()->getCU( pcCU->getAddr() );
+        UInt uiCurrPartNumb = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+        for( UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+        {
+          Int vspIdx = pcTextureCU->getVSPIndex( uiAbsPartIdx + ui);
+          pcCU->setVSPIndex( uiAbsPartIdx + ui, vspIdx);
+        }
+      }
+      else // MPI not used
+#endif
+      {
+        Int iVSPIdx = 0;
+        Int numVspIdx;
+        numVspIdx = 3;
+        for (Int i = 0; i < numVspIdx; i++)
+        {
+          if (iVSPIndexTrue[i] == uiMergeIndex)
+            {
+              iVSPIdx = i+1;
+              break;
+            }
+        }
+        pcCU->setVSPIndexSubParts( iVSPIdx, uiSubPartIdx, uiPartIdx, uiDepth );  //Initialize the VSP, may change later in get InterMergeCandidates()
+      }
+
+#else
+      pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+#endif
+#endif
+      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 )
+        {
+          pcCU->setMVPIdxSubParts( 0, RefPicList( uiRefListIdx ), uiSubPartIdx, uiPartIdx, uiDepth);
+          pcCU->setMVPNumSubParts( 0, RefPicList( uiRefListIdx ), uiSubPartIdx, uiPartIdx, uiDepth);
+          pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
+          pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
+
+        }
+      }
+    }
+    else
+    {
+      decodeInterDirPU( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {        
+        if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+        {
+          decodeRefFrmIdxPU( pcCU,    uiSubPartIdx,              uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+          decodeMvdPU      ( pcCU,    uiSubPartIdx,              uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+          decodeMVPIdxPU   ( pcSubCU, uiSubPartIdx-uiAbsPartIdx, uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+        }
+      }
+    }
+  }
+  return;
+}
+
+/** decode inter direction for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPartIdx 
+ * \returns Void
+ */
+Void TDecEntropy::decodeInterDirPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx )
+{
+  UInt uiInterDir;
+
+  if ( pcCU->getSlice()->isInterP() )
+  {
+    uiInterDir = 1;
+  }
+  else
+  {
+    m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx, uiDepth );
+  }
+
+  pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, uiPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeRefFrmIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getInterDir( uiAbsPartIdx ) != 3)
+  {
+    if(eRefList == REF_PIC_LIST_1)
+    {
+      return;
+    }
+
+    Int iRefFrmIdx = 0;
+    Int iRefFrmIdxTemp;
+    UInt uiInterDir;
+    RefPicList eRefListTemp;
+
+    PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+
+    if ( pcCU->getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 1 )
+    {
+      m_pcEntropyDecoderIf->parseRefFrmIdx( pcCU, iRefFrmIdx, uiAbsPartIdx, uiDepth, REF_PIC_LIST_C );
+    }
+    else
+    {
+      iRefFrmIdx=0;
+    }
+    uiInterDir = pcCU->getSlice()->getListIdFromIdxOfLC(iRefFrmIdx) + 1;
+    iRefFrmIdxTemp = pcCU->getSlice()->getRefIdxFromIdxOfLC(iRefFrmIdx);
+    eRefListTemp = (RefPicList)pcCU->getSlice()->getListIdFromIdxOfLC(iRefFrmIdx);
+
+    pcCU->getCUMvField( eRefListTemp )->setAllRefIdx( iRefFrmIdxTemp, ePartSize, uiAbsPartIdx, uiDepth, uiPartIdx );
+
+    pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, uiPartIdx, uiDepth );
+  }
+  else
+  {
+    Int iRefFrmIdx = 0;
+    Int iParseRefFrmIdx = pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList );
+
+    if ( pcCU->getSlice()->getNumRefIdx( eRefList ) > 1 && iParseRefFrmIdx )
+    {
+      m_pcEntropyDecoderIf->parseRefFrmIdx( pcCU, iRefFrmIdx, uiAbsPartIdx, uiDepth, eRefList );
+    }
+    else if ( !iParseRefFrmIdx )
+    {
+      iRefFrmIdx = NOT_VALID;
+    }
+    else
+    {
+      iRefFrmIdx = 0;
+    }
+
+    PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+    pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, ePartSize, uiAbsPartIdx, uiDepth, uiPartIdx );
+  }
+}
+
+/** decode motion vector difference for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPartIdx
+ * \param eRefList 
+ * \returns Void
+ */
+Void TDecEntropy::decodeMvdPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+  {
+    m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, uiPartIdx, uiDepth, eRefList );
+  }
+}
+
+Void TDecEntropy::decodeMVPIdxPU( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  Int iMVPIdx = -1;
+
+  TComMv cZeroMv( 0, 0 );
+  TComMv cMv     = cZeroMv;
+  Int    iRefIdx = -1;
+
+  TComCUMvField* pcSubCUMvField = pcSubCU->getCUMvField( eRefList );
+  AMVPInfo* pAMVPInfo = pcSubCUMvField->getAMVPInfo();
+
+  iRefIdx = pcSubCUMvField->getRefIdx(uiPartAddr);
+  cMv = cZeroMv;
+
+  if ( (pcSubCU->getInterDir(uiPartAddr) & ( 1 << eRefList )) && (pcSubCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+  {
+#if H3D_IVMP
+    const Int iNumAMVPCands = AMVP_MAX_NUM_CANDS + ( pcSubCU->getSlice()->getSPS()->getMultiviewMvPredMode() ? 1 : 0 );
+    m_pcEntropyDecoderIf->parseMVPIdx( iMVPIdx, iNumAMVPCands );
+#else
+    m_pcEntropyDecoderIf->parseMVPIdx( iMVPIdx );
+#endif
+  }
+#if H3D_IVMP
+  pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo, iMVPIdx);
+#else
+  pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo);
+#endif
+  pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, uiPartAddr, uiPartIdx, uiDepth);
+  pcSubCU->setMVPIdxSubParts( iMVPIdx, eRefList, uiPartAddr, uiPartIdx, uiDepth );
+  if ( iRefIdx >= 0 )
+  {
+    m_pcPrediction->getMvPredAMVP( pcSubCU, uiPartIdx, uiPartAddr, eRefList, iRefIdx, cMv);
+    cMv += pcSubCUMvField->getMvd( uiPartAddr );
+  }
+
+  PartSize ePartSize = pcSubCU->getPartitionSize( uiPartAddr );
+  pcSubCU->getCUMvField( eRefList )->setAllMv(cMv, ePartSize, uiPartAddr, 0, uiPartIdx);
+}
+
+Void TDecEntropy::xDecodeTransform( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt absTUPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, UInt uiInnerQuadIdx, UInt& uiYCbfFront3, UInt& uiUCbfFront3, UInt& uiVCbfFront3, Bool& bCodeDQP )
+{
+  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) )
+  {
+    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 > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx));
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    uiSubdiv = 1;
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    uiSubdiv = 0;
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    uiSubdiv = 0;
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, uiDepth );
+  }
+  
+  const UInt uiTrDepth = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+  
+  if( uiLog2TrafoSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    const Bool bFirstCbfOfCU = uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() || 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( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) )
+      {
+        if ( uiInnerQuadIdx == 3 && uiUCbfFront3 == 0 && uiLog2TrafoSize < pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+        {
+          uiUCbfFront3++;
+          pcCU->setCbfSubParts( 1 << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
+          //printf( " \nsave bits, U Cbf");
+        }
+        else
+        {
+          m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth, uiDepth );
+          uiUCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+        }
+      }
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) )
+      {
+        if ( uiInnerQuadIdx == 3 && uiVCbfFront3 == 0 && uiLog2TrafoSize < pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+        {
+          uiVCbfFront3++;
+          pcCU->setCbfSubParts( 1 << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
+          //printf( " \nsave bits, V Cbf");
+        }
+        else
+        {
+          m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth, uiDepth );
+          uiVCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+        }
+      }
+    }
+    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 );
+      if ( uiLog2TrafoSize == 2 )
+      {
+        uiUCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+        uiVCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+      }
+    }
+  }
+  
+  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 uiLumaTrMode, uiChromaTrMode;
+    pcCU->convertTransIdx( uiStartAbsPartIdx, uiTrDepth+1, uiLumaTrMode, uiChromaTrMode );
+    UInt uiYCbf = 0;
+    UInt uiUCbf = 0;
+    UInt uiVCbf = 0;
+    
+    UInt uiCurrentCbfY = 0;
+    UInt uiCurrentCbfU = 0;
+    UInt uiCurrentCbfV = 0;
+    
+    for( Int i = 0; i < 4; i++ )
+    {
+      UInt nsAddr = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, i, uiTrDepth+1 );
+      xDecodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, i, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV, bCodeDQP );
+      uiYCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode );
+      uiUCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiChromaTrMode );
+      uiVCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiChromaTrMode );
+      uiAbsPartIdx += uiQPartNum;
+      offsetLuma += size;  offsetChroma += (size>>2);
+    }
+    
+    uiYCbfFront3 += uiCurrentCbfY;
+    uiUCbfFront3 += uiCurrentCbfU;
+    uiVCbfFront3 += uiCurrentCbfV;
+    
+    pcCU->convertTransIdx( uiStartAbsPartIdx, uiTrDepth, uiLumaTrMode, uiChromaTrMode );
+    for( UInt ui = 0; ui < 4 * uiQPartNum; ++ui )
+    {
+      pcCU->getCbf( TEXT_LUMA     )[uiStartAbsPartIdx + ui] |= uiYCbf << uiLumaTrMode;
+      pcCU->getCbf( TEXT_CHROMA_U )[uiStartAbsPartIdx + ui] |= uiUCbf << uiChromaTrMode;
+      pcCU->getCbf( TEXT_CHROMA_V )[uiStartAbsPartIdx + ui] |= uiVCbf << uiChromaTrMode;
+    }
+  }
+  else
+  {
+    assert( uiDepth >= pcCU->getDepth( uiAbsPartIdx ) );
+    pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiDepth );
+    
+    {
+      DTRACE_CABAC_VL( g_nSymbolCounter++ );
+      DTRACE_CABAC_T( "\tTrIdx: abspart=" );
+      DTRACE_CABAC_V( uiAbsPartIdx );
+      DTRACE_CABAC_T( "\tdepth=" );
+      DTRACE_CABAC_V( uiDepth );
+      DTRACE_CABAC_T( "\ttrdepth=" );
+      DTRACE_CABAC_V( uiTrDepth );
+      DTRACE_CABAC_T( "\n" );
+    }
+    
+    UInt uiLumaTrMode, uiChromaTrMode;
+    pcCU->convertTransIdx( uiAbsPartIdx, uiTrDepth, uiLumaTrMode, uiChromaTrMode );
+    if(pcCU->getPredictionMode( uiAbsPartIdx ) == MODE_INTER && pcCU->useNonSquarePU( uiAbsPartIdx ) )
+    {
+      pcCU->setNSQTIdxSubParts( uiLog2TrafoSize, uiAbsPartIdx, absTUPartIdx, uiLumaTrMode );
+    }
+    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 << uiLumaTrMode, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      const UInt uiLog2CUSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - pcCU->getDepth( uiAbsPartIdx );
+      if ( pcCU->getPredictionMode( uiAbsPartIdx ) != MODE_INTRA && uiInnerQuadIdx == 3 && uiYCbfFront3 == 0 && uiUCbfFront3 == 0 && uiVCbfFront3 == 0
+          && ( uiLog2CUSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() + 1 || uiLog2TrafoSize < pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() ) )
+      {
+        pcCU->setCbfSubParts( 1 << uiLumaTrMode, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+        //printf( " \nsave bits, Y Cbf");
+        uiYCbfFront3++;    
+      }
+      else
+      {
+        m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode, uiDepth );
+        uiYCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode );
+      }
+    }
+    // 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
+      if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+      {
+        if ( bCodeDQP )
+        {
+          decodeQP( pcCU, m_bakAbsPartIdxCU);
+          bCodeDQP = false;
+        }
+      }
+    }
+    if( cbfY )
+    {
+      Int trWidth = width;
+      Int trHeight = height;
+      pcCU->getNSQTSize( uiTrIdx, uiAbsPartIdx, trWidth, trHeight );
+      m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffY()+offsetLuma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
+    }
+    if( uiLog2TrafoSize > 2 )
+    {
+      Int trWidth = width >> 1;
+      Int trHeight = height >> 1;
+      pcCU->getNSQTSize( uiTrIdx, uiAbsPartIdx, trWidth, trHeight );
+      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;
+        pcCU->getNSQTSize( uiTrIdx - 1, uiAbsPartIdx, trWidth, trHeight );
+        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 );
+        }
+      }
+    }
+    // transform_unit end
+  }
+}
+
+
+Void TDecEntropy::decodeQP          ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    m_pcEntropyDecoderIf->parseDeltaQP( pcCU, uiAbsPartIdx, pcCU->getDepth( uiAbsPartIdx ) );
+  }
+}
+
+
+/** 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;
+  UInt temp  = 0;
+  UInt temp1 = 0;
+  UInt temp2 = 0;
+  
+#if RWTH_SDC_DLT_B0036
+  if( pcCU->getSDCAvailable(uiAbsPartIdx) && pcCU->getSDCFlag( uiAbsPartIdx ) )
+  {
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+    assert( pcCU->getTransformIdx(uiAbsPartIdx) == 0 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA) == 1 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
+    
+    decodeSDCResidualData(pcCU, uiAbsPartIdx, uiDepth);
+    return;
+  }
+#endif
+  
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+  }
+  else
+  {
+    UInt uiQtRootCbf = 1;
+#if HHI_MPI
+    if( !(pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N &&
+          ( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 || uiDepth == pcCU->getTextureModeDepth( uiAbsPartIdx ) ) ) )
+#else
+    if( !( pcCU->getPartitionSize( uiAbsPartIdx) == SIZE_2Nx2N && pcCU->getMergeFlag( uiAbsPartIdx ) ) )
+#endif
+    {
+      m_pcEntropyDecoderIf->parseQtRootCbf( pcCU, uiAbsPartIdx, uiDepth, uiQtRootCbf );
+    }
+    if ( !uiQtRootCbf )
+    {
+      pcCU->setCbfSubParts( 0, 0, 0, uiAbsPartIdx, uiDepth );
+      pcCU->setTrIdxSubParts( 0 , uiAbsPartIdx, uiDepth );
+      pcCU->setNSQTIdxSubParts( uiAbsPartIdx, uiDepth );
+      return;
+    }
+    
+  }
+
+#if FIX_MPI_B0065
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getMergeIndex( uiAbsPartIdx ) == 0 && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N &&  pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1  )
+  {
+    TComDataCU *pcTextureCU = pcCU->getSlice()->getTexturePic()->getCU( pcCU->getAddr() );
+    if( uiDepth == pcTextureCU->getDepth(uiAbsPartIdx))
+    {
+      PartSize partSize = pcTextureCU->getPartitionSize(uiAbsPartIdx);
+      pcCU->setPartSizeSubParts( partSize, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setPartSizeSubParts( SIZE_NxN, uiAbsPartIdx, uiDepth );
+    }
+  }
+#endif
+
+  xDecodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, 0, temp, temp1, temp2, bCodeDQP );
+
+#if FIX_MPI_B0065
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getMergeIndex( uiAbsPartIdx ) == 0 && pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N &&  pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1 )
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );  
+  }
+#endif
+}
+
+#if RWTH_SDC_DLT_B0036
+Void TDecEntropy::decodeSDCPredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  
+  m_pcEntropyDecoderIf->parseSDCPredMode(pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  
+  m_pcEntropyDecoderIf->parseSDCFlag(pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeSDCResidualData( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  assert( pcCU->getSDCFlag(uiAbsPartIdx) );
+  
+  // number of segments depends on prediction mode for INTRA
+  UInt uiNumSegments = 2;
+  UInt uiLumaPredMode = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && (uiLumaPredMode == DC_IDX || uiLumaPredMode == PLANAR_IDX) )
+    uiNumSegments = 1;
+  
+  // decode residual data for each segment
+  for( UInt uiSeg = 0; uiSeg < uiNumSegments; uiSeg++ )
+    m_pcEntropyDecoderIf->parseSDCResidualData(pcCU, uiAbsPartIdx, uiDepth, uiSeg);
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecEntropy.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecEntropy.h	(revision 341)
@@ -0,0 +1,244 @@
+/* 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-2012, 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     TDecEntropy.h
+    \brief    entropy decoder class (header)
+*/
+
+#ifndef __TDECENTROPY__
+#define __TDECENTROPY__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComBitStream.h"
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComPrediction.h"
+#include "../TLibCommon/TComAdaptiveLoopFilter.h"
+#include "../TLibCommon/TComSampleAdaptiveOffset.h"
+
+class TDecSbac;
+class TDecCavlc;
+class SEImessages;
+class ParameterSetManagerDecoder;
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// entropy decoder pure class
+class TDecEntropyIf
+{
+public:
+  //  Virtual list for SBAC/CAVLC
+  virtual Void  resetEntropy          ( TComSlice* pcSlice )     = 0;
+  virtual Void  setBitstream          ( TComInputBitstream* p )  = 0;
+
+  virtual Void  decodeFlush()                                                                      = 0;
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  virtual Void  parseVPS                  ( TComVPS* pcVPS )                       = 0;
+#endif
+#if HHI_MPI || H3D_QTL
+  virtual Void  parseSPS                  ( TComSPS* pcSPS, Bool bIsDepth )                       = 0;
+#else
+  virtual Void  parseSPS                  ( TComSPS* pcSPS )                                      = 0;
+#endif
+  virtual Void  parsePPS                  ( TComPPS* pcPPS, ParameterSetManagerDecoder *parameterSet )                                      = 0;
+  virtual Void  parseAPS                  ( TComAPS* pAPS  )                                      = 0;
+  virtual void parseSEI(SEImessages&) = 0;
+
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  virtual Void parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet, bool isDepth)       = 0;
+#else
+  virtual Void parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet)       = 0;
+#endif
+
+  virtual Void  parseTerminatingBit       ( UInt& ruilsLast )                                     = 0;
+  
+#if H3D_IVMP
+  virtual Void parseMVPIdx        ( Int& riMVPIdx, Int iNumAMVPCands ) = 0;
+#else
+  virtual Void parseMVPIdx        ( Int& riMVPIdx ) = 0;
+#endif
+  
+public:
+  virtual Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#if LGE_ILLUCOMP_B0045
+  virtual Void parseICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#endif
+  virtual Void parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx ) = 0;
+  virtual Void parseMergeIndex    ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#if H3D_IVRP
+  virtual Void parseResPredFlag   ( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#endif
+  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, UInt uiDepth ) = 0;
+  virtual Void parseRefFrmIdx     ( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList ) = 0;
+  virtual Void parseMvd           ( TComDataCU* pcCU, UInt uiAbsPartAddr, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList ) = 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 parseQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf ) = 0;
+  
+  virtual Void parseDeltaQP       ( 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;
+
+  /// set slice granularity
+  virtual Void setSliceGranularity(Int iSliceGranularity) = 0;
+
+  /// get slice granularity
+  virtual Int  getSliceGranularity()                      = 0;
+
+  virtual Void readTileMarker   ( UInt& uiTileIdx, UInt uiBitsUsed ) = 0;
+  virtual Void updateContextTables( SliceType eSliceType, Int iQp ) = 0;
+  
+#if RWTH_SDC_DLT_B0036
+  virtual Void parseSDCFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseSDCPredMode     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseSDCResidualData     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPart ) = 0;
+#endif
+  
+  virtual ~TDecEntropyIf() {}
+};
+
+/// entropy decoder class
+class TDecEntropy
+{
+private:
+  TDecEntropyIf*  m_pcEntropyDecoderIf;
+  TComPrediction* m_pcPrediction;
+  UInt    m_uiBakAbsPartIdx;
+  UInt    m_uiBakChromaOffset;
+  UInt    m_bakAbsPartIdxCU;
+  
+public:
+  Void init (TComPrediction* p) {m_pcPrediction = p;}
+  Void decodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU );
+  Void decodeInterDirPU   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx );
+  Void decodeRefFrmIdxPU  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  Void decodeMvdPU        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  Void decodeMVPIdxPU     ( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  
+  Void    setEntropyDecoder           ( TDecEntropyIf* p );
+  Void    setBitstream                ( TComInputBitstream* p ) { m_pcEntropyDecoderIf->setBitstream(p);                    }
+  Void    resetEntropy                ( TComSlice* p)           { m_pcEntropyDecoderIf->resetEntropy(p);                    }
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void    decodeVPS                   ( TComVPS* pcVPS ) { m_pcEntropyDecoderIf->parseVPS(pcVPS); }
+#endif
+  
+#if HHI_MPI || H3D_QTL
+  Void    decodeSPS                   ( TComSPS* pcSPS, Bool bIsDepth ) { m_pcEntropyDecoderIf->parseSPS(pcSPS, bIsDepth); }
+#else
+  Void    decodeSPS                   ( TComSPS* pcSPS     )    { m_pcEntropyDecoderIf->parseSPS(pcSPS);                    }
+#endif
+  Void    decodePPS                   ( TComPPS* pcPPS, ParameterSetManagerDecoder *parameterSet    )    { m_pcEntropyDecoderIf->parsePPS(pcPPS, parameterSet);                    }
+  Void    decodeAPS                   ( TComAPS* pAPS      )    { m_pcEntropyDecoderIf->parseAPS(pAPS);}
+  void decodeSEI(SEImessages& seis) { m_pcEntropyDecoderIf->parseSEI(seis); }
+
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  Void    decodeSliceHeader           ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet, bool isDepth)  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice, parameterSetManager, alfCUCtrl, alfParamSet, isDepth);         }
+#else
+  Void    decodeSliceHeader           ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet)  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice, parameterSetManager, alfCUCtrl, alfParamSet);         }
+#endif
+
+  Void    decodeTerminatingBit        ( UInt& ruiIsLast )       { m_pcEntropyDecoderIf->parseTerminatingBit(ruiIsLast);     }
+  
+  TDecEntropyIf* getEntropyDecoder() { return m_pcEntropyDecoderIf; }
+  
+public:
+  Void decodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if LGE_ILLUCOMP_B0045
+  Void decodeICFlag            ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void decodeMergeFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void decodeMergeIndex        ( TComDataCU* pcSubCU, UInt uiPartIdx, UInt uiPartAddr, PartSize eCUMode, UChar* puhInterDirNeighbours, TComMvField* pcMvFieldNeighbours, UInt uiDepth );
+  Void decodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void decodeIPCMInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+
+  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 readTileMarker         ( UInt& uiTileIdx, UInt uiBitsUsed )  {  m_pcEntropyDecoderIf->readTileMarker( uiTileIdx, uiBitsUsed ); }
+  Void updateContextTables    ( SliceType eSliceType, Int iQp ) { m_pcEntropyDecoderIf->updateContextTables( eSliceType, iQp ); }
+  
+  
+private:
+  Void xDecodeTransform        ( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt absTUPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, UInt uiInnerQuadIdx, UInt& uiYCbfFront3, UInt& uiUCbfFront3, UInt& uiVCbfFront3, Bool& bCodeDQP );
+
+public:
+  Void decodeCoeff             ( TComDataCU* pcCU                 , UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
+  
+  // ALF-related
+
+  /// set slice granularity
+  Void setSliceGranularity (Int iSliceGranularity) {m_pcEntropyDecoderIf->setSliceGranularity(iSliceGranularity);}
+
+  Void decodeSaoParam         (SAOParam* saoParam);
+  void decodeSaoLcu(Int rx, Int ry, Int compIdx, SAOParam* saoParam, Bool &repeatedRow );
+  Void decodeSaoOneLcu(SaoLcuParam* saoLcuParam);
+
+  Void decodeFlush() { m_pcEntropyDecoderIf->decodeFlush(); }
+  
+#if RWTH_SDC_DLT_B0036
+  Void decodeSDCPredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeSDCResidualData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+
+};// END CLASS DEFINITION TDecEntropy
+
+//! \}
+
+#endif // __TDECENTROPY__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecGop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecGop.cpp	(revision 341)
@@ -0,0 +1,526 @@
+/* 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-2012, 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     TDecGop.cpp
+    \brief    GOP decoder class
+*/
+
+extern bool g_md5_mismatch; ///< top level flag to signal when there is a decode problem
+
+#include "TDecGop.h"
+#include "TDecCAVLC.h"
+#include "TDecSbac.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+#include "libmd5/MD5.h"
+#include "TLibCommon/SEI.h"
+
+#include <time.h>
+
+//! \ingroup TLibDecoder
+//! \{
+
+static void calcAndPrintMD5Status(TComPicYuv& pic, const SEImessages* seis);
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TDecGop::TDecGop()
+{
+  m_iGopSize = 0;
+  m_dDecTime = 0;
+  m_pcSbacDecoders = NULL;
+  m_pcBinCABACs = NULL;
+  m_first = true;
+}
+
+TDecGop::~TDecGop()
+{
+  
+}
+
+Void TDecGop::create()
+{
+  
+}
+
+
+Void TDecGop::destroy()
+{
+  m_alfParamSetPilot.releaseALFParam();
+}
+
+Void TDecGop::init( TDecEntropy*            pcEntropyDecoder, 
+                   TDecSbac*               pcSbacDecoder, 
+                   TDecBinCABAC*           pcBinCABAC,
+                   TDecCavlc*              pcCavlcDecoder, 
+                   TDecSlice*              pcSliceDecoder, 
+                   TComLoopFilter*         pcLoopFilter, 
+                   TComAdaptiveLoopFilter* pcAdaptiveLoopFilter 
+                   ,TComSampleAdaptiveOffset* pcSAO
+#if DEPTH_MAP_GENERATION
+                   ,TComDepthMapGenerator*  pcDepthMapGenerator
+#endif
+#if H3D_IVRP
+                  ,TComResidualGenerator*  pcResidualGenerator
+#endif
+                   )
+{
+  m_pcEntropyDecoder      = pcEntropyDecoder;
+  m_pcSbacDecoder         = pcSbacDecoder;
+  m_pcBinCABAC            = pcBinCABAC;
+  m_pcCavlcDecoder        = pcCavlcDecoder;
+  m_pcSliceDecoder        = pcSliceDecoder;
+  m_pcLoopFilter          = pcLoopFilter;
+  m_pcAdaptiveLoopFilter  = pcAdaptiveLoopFilter;
+  m_pcSAO  = pcSAO;
+#if DEPTH_MAP_GENERATION
+  m_pcDepthMapGenerator   = pcDepthMapGenerator;
+#endif
+#if H3D_IVRP
+  m_pcResidualGenerator   = pcResidualGenerator;
+#endif
+}
+
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+Void TDecGop::patchAlfLCUParams(ALFParam*** alfLCUParam, AlfParamSet* alfParamSet, Int firstLCUAddr)
+{
+  Int numLCUInWidth = alfParamSet->numLCUInWidth;
+  Int numLCU        = alfParamSet->numLCU;
+
+  Int rx, ry, pos, posUp;
+  std::vector<ALFParam*> storedFilters[NUM_ALF_COMPONENT];
+  storedFilters[ALF_Y].clear();
+  storedFilters[ALF_Cb].clear();
+  storedFilters[ALF_Cr].clear();
+
+  for(Int i=0; i< numLCU; i++)
+  {
+    rx     = (i+ firstLCUAddr)% numLCUInWidth;
+    ry     = (i+ firstLCUAddr)/ numLCUInWidth;
+    pos    = (ry*numLCUInWidth) + rx;
+    posUp  = pos-numLCUInWidth;
+
+    for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+    {
+      AlfUnitParam& alfUnitParam = alfParamSet->alfUnitParam[compIdx][i];
+      ALFParam&     alfFiltParam = *(alfLCUParam[compIdx][pos]);
+
+      switch( alfUnitParam.mergeType )
+      {
+      case ALF_MERGE_DISABLED:
+        {
+          if(alfUnitParam.isEnabled)
+          {
+            if(alfUnitParam.isNewFilt)
+            {
+              alfFiltParam = *alfUnitParam.alfFiltParam;
+              storedFilters[compIdx].push_back( &alfFiltParam );
+            }
+            else //stored filter
+            {
+              alfFiltParam = *(storedFilters[compIdx][alfUnitParam.storedFiltIdx]);
+              assert(alfFiltParam.alf_flag == 1);
+            }
+          }
+          else
+          {
+            alfFiltParam.alf_flag = 0;
+          }
+        }
+        break;
+      case ALF_MERGE_UP:
+        {
+          assert(posUp >= 0);
+          alfFiltParam = *(alfLCUParam[compIdx][posUp]);
+        }
+        break;
+      case ALF_MERGE_LEFT:
+        {
+          assert(pos-1 >= 0);
+          alfFiltParam = *(alfLCUParam[compIdx][pos-1]);
+        }
+        break;
+      case ALF_MERGE_FIRST:
+        {
+          alfFiltParam = *(alfLCUParam[compIdx][firstLCUAddr]);
+        }
+        break;
+      default:
+        {
+          printf("not a supported ALF merge type\n");
+          assert(0);
+          exit(-1);
+        }
+      }
+    } //compIdx
+  } //i (LCU)
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecGop::decompressGop(TComInputBitstream* pcBitstream, TComPic*& rpcPic, Bool bExecuteDeblockAndAlf)
+{
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+  // Table of extracted substreams.
+  // These must be deallocated AND their internal fifos, too.
+  TComInputBitstream **ppcSubstreams = NULL;
+
+  //-- For time output for each slice
+  long iBeforeTime = clock();
+  
+  UInt uiStartCUAddr   = pcSlice->getEntropySliceCurStartCUAddr();
+
+  if (!bExecuteDeblockAndAlf)
+  {
+    if(m_first)
+    {
+      m_uiILSliceCount = 0;
+      m_puiILSliceStartLCU = new UInt[(rpcPic->getNumCUsInFrame()* rpcPic->getNumPartInCU()) +1];
+      m_first = false;
+    }
+
+    UInt uiSliceStartCuAddr = pcSlice->getSliceCurStartCUAddr();
+    if(uiSliceStartCuAddr == uiStartCUAddr)
+    {
+      m_puiILSliceStartLCU[m_uiILSliceCount] = uiSliceStartCuAddr;
+      m_uiILSliceCount++;
+    }
+
+    m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
+    m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
+    
+    UInt uiNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+
+    //init each couple {EntropyDecoder, Substream}
+    UInt *puiSubstreamSizes = pcSlice->getSubstreamSizes();
+    ppcSubstreams    = new TComInputBitstream*[uiNumSubstreams];
+    m_pcSbacDecoders = new TDecSbac[uiNumSubstreams];
+    m_pcBinCABACs    = new TDecBinCABAC[uiNumSubstreams];
+    UInt uiBitsRead = pcBitstream->getByteLocation()<<3;
+    for ( UInt ui = 0 ; ui < uiNumSubstreams ; ui++ )
+    {
+      m_pcSbacDecoders[ui].init(&m_pcBinCABACs[ui]);
+      UInt uiSubstreamSizeBits = (ui+1 < uiNumSubstreams ? puiSubstreamSizes[ui] : pcBitstream->getNumBitsLeft());
+      ppcSubstreams[ui] = pcBitstream->extractSubstream(ui+1 < uiNumSubstreams ? puiSubstreamSizes[ui] : pcBitstream->getNumBitsLeft());
+      // update location information from where tile markers were extracted
+      {
+        UInt uiDestIdx       = 0;
+        for (UInt uiSrcIdx = 0; uiSrcIdx<pcBitstream->getTileMarkerLocationCount(); uiSrcIdx++)
+        {
+          UInt uiLocation = pcBitstream->getTileMarkerLocation(uiSrcIdx);
+          if ((uiBitsRead>>3)<=uiLocation  &&  uiLocation<((uiBitsRead+uiSubstreamSizeBits)>>3))
+          {
+            ppcSubstreams[ui]->setTileMarkerLocation( uiDestIdx, uiLocation - (uiBitsRead>>3) );
+            ppcSubstreams[ui]->setTileMarkerLocationCount( uiDestIdx+1 );
+            uiDestIdx++;
+          }
+        }
+        ppcSubstreams[ui]->setTileMarkerLocationCount( uiDestIdx );
+        uiBitsRead += uiSubstreamSizeBits;
+      }
+    }
+
+    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);
+
+    if(uiSliceStartCuAddr == uiStartCUAddr)
+    {
+      if(pcSlice->getSPS()->getUseALF())
+      {
+        if(pcSlice->getAlfEnabledFlag())
+        {
+          if(pcSlice->getSPS()->getUseALFCoefInSlice())
+          {
+            Int numSUinLCU    = 1<< (g_uiMaxCUDepth << 1); 
+            Int firstLCUAddr   = pcSlice->getSliceCurStartCUAddr() / numSUinLCU;  
+            patchAlfLCUParams(m_pcAdaptiveLoopFilter->getAlfLCUParam(), &m_alfParamSetPilot, firstLCUAddr);
+          }
+
+          if( !pcSlice->getSPS()->getUseALFCoefInSlice())
+          {
+          m_vAlfCUCtrlSlices.push_back(m_cAlfCUCtrlOneSlice);
+          }
+        }
+      }
+    }
+
+#if DEPTH_MAP_GENERATION
+    // init view component and predict virtual depth map
+    if( uiStartCUAddr == 0 )
+    {
+      m_pcDepthMapGenerator->initViewComponent( rpcPic );
+#if !H3D_NBDV
+      m_pcDepthMapGenerator->predictDepthMap  ( rpcPic );
+#endif
+#if H3D_IVRP
+      m_pcResidualGenerator->initViewComponent( rpcPic );
+#endif
+    }
+#endif
+
+#if H3D_NBDV
+    if(pcSlice->getViewId() && pcSlice->getSPS()->getMultiviewMvPredMode())
+    {
+      Int iColPoc = pcSlice->getRefPOC(RefPicList(pcSlice->getColDir()), pcSlice->getColRefIdx());
+      rpcPic->setRapbCheck(rpcPic->getDisCandRefPictures(iColPoc));
+    }
+#endif
+
+    m_pcSbacDecoders[0].load(m_pcSbacDecoder);
+    m_pcSliceDecoder->decompressSlice( pcBitstream, ppcSubstreams, rpcPic, m_pcSbacDecoder, m_pcSbacDecoders);
+    m_pcEntropyDecoder->setBitstream(  ppcSubstreams[uiNumSubstreams-1] );
+    if ( uiNumSubstreams > 1 )
+    {
+      // 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;
+  }
+  else
+  {
+#if H3D_IVRP
+    // set residual picture
+    m_pcResidualGenerator->setRecResidualPic( rpcPic );
+#endif
+#if DEPTH_MAP_GENERATION
+#if !H3D_NBDV
+    // update virtual depth map
+    m_pcDepthMapGenerator->updateDepthMap( rpcPic );
+#endif
+#endif
+    // deblocking filter
+    Bool bLFCrossTileBoundary = (pcSlice->getPPS()->getTileBehaviorControlPresentFlag() == 1)?
+                                (pcSlice->getPPS()->getLFCrossTileBoundaryFlag()):(pcSlice->getPPS()->getSPS()->getLFCrossTileBoundaryFlag());
+    if (pcSlice->getPPS()->getDeblockingFilterControlPresent())
+    {
+      if(pcSlice->getSPS()->getUseDF())
+      {
+        if(pcSlice->getInheritDblParamFromAPS())
+        {
+          pcSlice->setLoopFilterDisable(pcSlice->getAPS()->getLoopFilterDisable());
+          if (!pcSlice->getLoopFilterDisable())
+          {
+            pcSlice->setLoopFilterBetaOffset(pcSlice->getAPS()->getLoopFilterBetaOffset());
+            pcSlice->setLoopFilterTcOffset(pcSlice->getAPS()->getLoopFilterTcOffset());
+          }
+        }
+      }
+    }
+    m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresent(), pcSlice->getLoopFilterDisable(), pcSlice->getLoopFilterBetaOffset(), pcSlice->getLoopFilterTcOffset(), bLFCrossTileBoundary);
+    m_pcLoopFilter->loopFilterPic( rpcPic );
+
+    pcSlice = rpcPic->getSlice(0);
+    if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+    {
+      Int sliceGranularity = pcSlice->getPPS()->getSliceGranularity();
+      m_puiILSliceStartLCU[m_uiILSliceCount] = rpcPic->getNumCUsInFrame()* rpcPic->getNumPartInCU();
+      rpcPic->createNonDBFilterInfo(m_puiILSliceStartLCU, m_uiILSliceCount,sliceGranularity,pcSlice->getSPS()->getLFCrossSliceBoundaryFlag(),rpcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
+    }
+
+    if( pcSlice->getSPS()->getUseSAO() )
+    {
+      if(pcSlice->getSaoEnabledFlag())
+      {
+        if (pcSlice->getSaoInterleavingFlag())
+        {
+          pcSlice->getAPS()->setSaoInterleavingFlag(pcSlice->getSaoInterleavingFlag());
+          pcSlice->getAPS()->setSaoEnabled(pcSlice->getSaoEnabledFlag());
+          pcSlice->getAPS()->getSaoParam()->bSaoFlag[0] = pcSlice->getSaoEnabledFlag();
+          pcSlice->getAPS()->getSaoParam()->bSaoFlag[1] = pcSlice->getSaoEnabledFlagCb();
+          pcSlice->getAPS()->getSaoParam()->bSaoFlag[2] = pcSlice->getSaoEnabledFlagCr();
+        }
+        m_pcSAO->setSaoInterleavingFlag(pcSlice->getAPS()->getSaoInterleavingFlag());
+        m_pcSAO->createPicSaoInfo(rpcPic, m_uiILSliceCount);
+        m_pcSAO->SAOProcess(rpcPic, pcSlice->getAPS()->getSaoParam());  
+        m_pcAdaptiveLoopFilter->PCMLFDisableProcess(rpcPic);
+        m_pcSAO->destroyPicSaoInfo();
+      }
+    }
+
+    // adaptive loop filter
+    if( pcSlice->getSPS()->getUseALF() )
+    {
+      if( (pcSlice->getSPS()->getUseALFCoefInSlice())?(true):(pcSlice->getAlfEnabledFlag()))
+      {
+
+        if(!pcSlice->getSPS()->getUseALFCoefInSlice())
+        {
+          patchAlfLCUParams(m_pcAdaptiveLoopFilter->getAlfLCUParam(), pcSlice->getAPS()->getAlfParam());
+        }
+        m_pcAdaptiveLoopFilter->createPicAlfInfo(rpcPic, m_uiILSliceCount, pcSlice->getSliceQp());
+        m_pcAdaptiveLoopFilter->ALFProcess(rpcPic, m_vAlfCUCtrlSlices, pcSlice->getSPS()->getUseALFCoefInSlice());
+      m_pcAdaptiveLoopFilter->PCMLFDisableProcess(rpcPic);
+      m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
+      }
+      m_pcAdaptiveLoopFilter->resetLCUAlfInfo(); //reset all LCU ALFParam->alf_flag = 0
+    }
+    
+    if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+    {
+      rpcPic->destroyNonDBFilterInfo();
+    }
+
+ //   rpcPic->compressMotion(); 
+    Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+    if (!pcSlice->isReferenced()) c += 32;
+    
+    //-- For time output for each slice
+    printf("\n%s   View %2d POC %4d TId: %1d ( %c-SLICE, QP%3d ) ",
+          pcSlice->getIsDepth() ? "Depth  " : "Texture",
+          pcSlice->getViewId(),
+          pcSlice->getPOC(),
+          pcSlice->getTLayer(),
+          c,
+          pcSlice->getSliceQp() );
+
+    m_dDecTime += (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+    printf ("[DT %6.3f] ", m_dDecTime );
+    m_dDecTime  = 0;
+    
+    for (Int iRefList = 0; iRefList < 2; iRefList++)
+    {
+      printf ("[L%d ", iRefList);
+      for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
+      {
+        if( pcSlice->getViewId() != pcSlice->getRefViewId( RefPicList(iRefList), iRefIndex ) )
+        {
+          printf( "V%d ", pcSlice->getRefViewId( RefPicList(iRefList), iRefIndex ) );
+        }
+        else
+        {
+          printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
+        }
+      }
+      printf ("] ");
+    }
+    if(pcSlice->getNumRefIdx(REF_PIC_LIST_C)>0 && !pcSlice->getNoBackPredFlag())
+    {
+      printf ("[LC ");
+      for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(REF_PIC_LIST_C); iRefIndex++)
+      {
+        if( pcSlice->getViewId() != pcSlice->getRefViewId( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) )
+        {
+          printf( "V%d ", pcSlice->getRefViewId( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) );
+        }
+        else
+        {
+          printf ("%d ", pcSlice->getRefPOC((RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex)));
+        }
+      }
+      printf ("] ");
+    }
+
+    if (m_pictureDigestEnabled)
+    {
+      calcAndPrintMD5Status(*rpcPic->getPicYuvRec(), rpcPic->getSEIs());
+    }
+
+#if FIXED_ROUNDING_FRAME_MEMORY
+    rpcPic->getPicYuvRec()->xFixedRoundingPic();
+#endif
+
+    rpcPic->setOutputMark(true);
+    rpcPic->setReconMark(true);
+
+    rpcPic->setUsedForTMVP( true );
+
+    m_uiILSliceCount = 0;
+    m_vAlfCUCtrlSlices.clear();
+  }
+  fflush(stdout);
+}
+
+/**
+ * Calculate and print MD5 for pic, compare to picture_digest SEI if
+ * present in seis.  seis may be NULL.  MD5 is printed to stdout, in
+ * a manner suitable for the status line. Theformat is:
+ *  [MD5:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,(yyy)]
+ * Where, x..x is the md5
+ *        yyy has the following meanings:
+ *            OK          - calculated MD5 matches the SEI message
+ *            ***ERROR*** - calculated MD5 does not match the SEI message
+ *            unk         - no SEI message was available for comparison
+ */
+static void calcAndPrintMD5Status(TComPicYuv& pic, const SEImessages* seis)
+{
+  /* calculate MD5sum for entire reconstructed picture */
+  unsigned char recon_digest[16];
+  calcMD5(pic, recon_digest);
+
+  /* compare digest against received version */
+  const char* md5_ok = "(unk)";
+  bool md5_mismatch = false;
+
+  if (seis && seis->picture_digest)
+  {
+    md5_ok = "(OK)";
+    for (unsigned i = 0; i < 16; i++)
+    {
+      if (recon_digest[i] != seis->picture_digest->digest[i])
+      {
+        md5_ok = "(***ERROR***)";
+        md5_mismatch = true;
+      }
+    }
+  }
+
+  printf("[MD5:%s,%s] ", digestToString(recon_digest), md5_ok);
+  if (md5_mismatch)
+  {
+    g_md5_mismatch = true;
+    printf("[rxMD5:%s] ", digestToString(seis->picture_digest->digest));
+  }
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecGop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecGop.h	(revision 341)
@@ -0,0 +1,142 @@
+/* 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-2012, 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     TDecGop.h
+    \brief    GOP decoder class (header)
+*/
+
+#ifndef __TDECGOP__
+#define __TDECGOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComLoopFilter.h"
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComDepthMapGenerator.h"
+#include "../TLibCommon/TComResidualGenerator.h"
+
+#include "TDecEntropy.h"
+#include "TDecSlice.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP decoder class
+class TDecGop
+{
+private:
+  Int                   m_iGopSize;
+  TComList<TComPic*>    m_cListPic;         //  Dynamic buffer
+  
+  Bool m_first;
+  UInt m_uiILSliceCount;
+  UInt* m_puiILSliceStartLCU;
+  std::vector<AlfCUCtrlInfo> m_vAlfCUCtrlSlices;
+
+  //  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 DEPTH_MAP_GENERATION
+  TComDepthMapGenerator*  m_pcDepthMapGenerator;
+#endif
+#if H3D_IVRP
+  TComResidualGenerator*  m_pcResidualGenerator;
+#endif
+  
+  // Adaptive Loop filter
+  TComAdaptiveLoopFilter*       m_pcAdaptiveLoopFilter;
+  TComSampleAdaptiveOffset*     m_pcSAO;
+  Double                m_dDecTime;
+
+  bool m_pictureDigestEnabled; ///< if true, handle picture_digest SEI messages
+  AlfCUCtrlInfo       m_cAlfCUCtrlOneSlice;
+  AlfParamSet           m_alfParamSetPilot;
+
+public:
+  TDecGop();
+  virtual ~TDecGop();
+  
+  Void  init    ( TDecEntropy*            pcEntropyDecoder, 
+                 TDecSbac*               pcSbacDecoder, 
+                 TDecBinCABAC*           pcBinCABAC,
+                 TDecCavlc*              pcCavlcDecoder, 
+                 TDecSlice*              pcSliceDecoder, 
+                 TComLoopFilter*         pcLoopFilter, 
+                 TComAdaptiveLoopFilter* pcAdaptiveLoopFilter
+                 ,TComSampleAdaptiveOffset* pcSAO
+#if DEPTH_MAP_GENERATION
+                 ,TComDepthMapGenerator*  pcDepthMapGenerator
+#endif
+#if H3D_IVRP
+                ,TComResidualGenerator*  pcResidualGenerator
+#endif
+                 );
+  Void  create  ();
+  Void  destroy ();
+  Void  decompressGop(TComInputBitstream* pcBitstream, TComPic*& rpcPic, Bool bExecuteDeblockAndAlf );
+  Void  setGopSize( Int i) { m_iGopSize = i; }
+
+  void setPictureDigestEnabled(bool enabled) { m_pictureDigestEnabled = enabled; }
+  AlfCUCtrlInfo& getAlfCuCtrlParam() { return m_cAlfCUCtrlOneSlice; }
+  AlfParamSet& getAlfParamSet() {return m_alfParamSetPilot;}
+
+private:
+  Void patchAlfLCUParams(ALFParam*** alfLCUParam, AlfParamSet* alfParamSet, Int firstLCUAddr = 0);
+
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECGOP_H__29440B7A_7CC0_48C7_8DD5_1A531D3CED45__INCLUDED_)
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 341)
@@ -0,0 +1,2425 @@
+/* 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-2012, 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     TDecSbac.cpp
+    \brief    Context-adaptive entropy decoder class
+*/
+
+#include "TDecSbac.h"
+
+#if RWTH_SDC_DLT_B0036
+#define GetNumDepthValues()     (pcCU->getSlice()->getSPS()->getNumDepthValues())
+#define GetBitsPerDepthValue()  (pcCU->getSlice()->getSPS()->getBitsPerDepthValue())
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+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)
+#if LGE_ILLUCOMP_B0045
+, m_cCUICFlagSCModel          ( 1,             1,               NUM_IC_FLAG_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 H3D_IVRP
+, m_cResPredFlagSCModel       ( 1,             1,               NUM_RES_PRED_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_cCUAlfCtrlFlagSCModel     ( 1,             1,               NUM_ALF_CTRL_FLAG_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_cALFFlagSCModel           ( 1,             1,               NUM_ALF_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFUvlcSCModel           ( 1,             1,               NUM_ALF_UVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFSvlcSCModel           ( 1,             1,               NUM_ALF_SVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoFlagSCModel           ( 1,             1,               NUM_SAO_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoUvlcSCModel           ( 1,             1,               NUM_SAO_UVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoSvlcSCModel           ( 1,             1,               NUM_SAO_SVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeLeftSCModel      ( 1,             1,               NUM_SAO_MERGE_LEFT_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeUpSCModel        ( 1,             1,               NUM_SAO_MERGE_UP_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+, m_cDmmFlagSCModel           ( 1,             1,               NUM_DMM_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDmmModeSCModel           ( 1,             1,               NUM_DMM_MODE_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDmmDataSCModel           ( 1,             1,               NUM_DMM_DATA_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if LGE_EDGE_INTRA_A0070
+, m_cEdgeIntraSCModel         ( 1,             1,               NUM_EDGE_INTRA_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+#if LGE_EDGE_INTRA_DELTA_DC
+, m_cEdgeIntraDeltaDCSCModel  ( 1,             1,               NUM_EDGE_INTRA_DELTA_DC_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#endif
+#if RWTH_SDC_DLT_B0036
+, m_cSDCFlagSCModel             ( 1,             1,                 SDC_NUM_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCResidualFlagSCModel     ( 1,             2,  SDC_NUM_RESIDUAL_FLAG_CTX  , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCResidualSignFlagSCModel ( 1,             2,  SDC_NUM_SIGN_FLAG_CTX      , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCResidualSCModel         ( 1,             2,  SDC_NUM_RESIDUAL_CTX       , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCPredModeSCModel             ( 1,             3,                 SDC_NUM_PRED_MODE_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+{
+  assert( m_numContextModels <= MAX_NUM_CTX_MOD );
+  m_iSliceGranularity = 0;
+}
+
+TDecSbac::~TDecSbac()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+#if CABAC_INIT_FLAG
+Void TDecSbac::resetEntropy(TComSlice* pSlice)
+{
+  SliceType sliceType  = pSlice->getSliceType();
+  Int       qp         = pSlice->getSliceQp();
+
+  if (pSlice->getPPS()->getCabacInitPresentFlag() && pSlice->getCabacInitFlag())
+  {
+    switch (sliceType)
+    {
+    case P_SLICE:           // change initialization table to B_SLICE initialization
+      sliceType = B_SLICE; 
+      break;
+    case B_SLICE:           // change initialization table to P_SLICE initialization
+      sliceType = P_SLICE; 
+      break;
+    default     :           // should not occur
+      assert(0);
+    }
+  }
+
+#else
+Void TDecSbac::resetEntropywithQPandInitIDC (Int  qp, Int iID)
+{
+  SliceType sliceType = (SliceType)iID;
+#endif  
+
+  m_cCUSplitFlagSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SKIP_FLAG );
+#if LGE_ILLUCOMP_B0045
+  m_cCUICFlagSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUMergeFlagExtSCModel.initBuffer    ( sliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT );
+  m_cCUMergeIdxExtSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_MERGE_IDX_EXT );
+#if H3D_IVRP
+  m_cResPredFlagSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_RES_PRED_FLAG );
+#endif
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_ALF_CTRL_FLAG );
+  m_cCUPartSizeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PART_SIZE );
+  m_cCUAMPSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_CU_AMP_POS );
+  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_cALFFlagSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_ALF_SVLC );
+  m_cSaoFlagSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_SAO_FLAG );
+  m_cSaoUvlcSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_SAO_UVLC );
+  m_cSaoSvlcSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_SAO_SVLC );
+  m_cSaoMergeLeftSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+  m_cSaoMergeUpSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+
+  m_cCUTransSubdivFlagSCModel.initBuffer ( sliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+#if LGE_EDGE_INTRA_A0070
+  m_cEdgeIntraSCModel.initBuffer         ( sliceType, qp, (UChar*)INIT_EDGE_INTRA );
+#if LGE_EDGE_INTRA_DELTA_DC
+  m_cEdgeIntraDeltaDCSCModel.initBuffer  ( sliceType, qp, (UChar*)INIT_EDGE_INTRA_DELTA_DC );
+#endif
+#endif
+  m_uiLastDQpNonZero  = 0;
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  m_cDmmFlagSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_DMM_FLAG );
+  m_cDmmModeSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_DMM_MODE );
+  m_cDmmDataSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_DMM_DATA );
+#endif
+#if RWTH_SDC_DLT_B0036
+  m_cSDCFlagSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_SDC_FLAG );
+  m_cSDCResidualFlagSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_SDC_RESIDUAL );
+  m_cSDCResidualSignFlagSCModel.initBuffer  ( sliceType, qp, (UChar*)INIT_SDC_SIGN_FLAG );
+  m_cSDCPredModeSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_SDC_PRED_MODE );
+#endif
+  
+  // new structure
+  m_uiLastQp          = qp;
+  
+  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);
+  m_pcTDecBinIf->finish();  
+#if !OL_FLUSH_ALIGN
+  // Account for misaligned CABAC.
+  Int iCABACReadAhead = m_pcTDecBinIf->getBitsReadAhead();
+  iCABACReadAhead--;
+  Int iStreamBits = 8-m_pcBitstream->getNumBitsUntilByteAligned();
+  if (iCABACReadAhead >= iStreamBits)
+  {
+    // Misaligned CABAC has read into the 1st byte of the next tile.
+    // Back up a byte prior to alignment.
+    m_pcBitstream->backupByte();
+  }
+#endif
+  m_pcBitstream->readOutTrailingBits();
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+#if LGE_ILLUCOMP_B0045
+  m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT );
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT );
+#if H3D_IVRP
+  m_cResPredFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_RES_PRED_FLAG );
+#endif
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_ALF_CTRL_FLAG );
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  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_cALFFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_SVLC );
+  m_cSaoFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_FLAG );
+  m_cSaoUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_UVLC );
+  m_cSaoSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_SVLC );
+  m_cSaoMergeLeftSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+  m_cSaoMergeUpSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  m_cDmmFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_FLAG );
+  m_cDmmModeSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_MODE );
+  m_cDmmDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_DATA );
+#endif
+#if RWTH_SDC_DLT_B0036
+  m_cSDCFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
+  m_cSDCResidualFlagSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
+  m_cSDCResidualSignFlagSCModel.initBuffer  ( eSliceType, iQp, (UChar*)INIT_SDC_SIGN_FLAG );
+  m_cSDCPredModeSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_PRED_MODE );
+#endif
+
+  m_pcTDecBinIf->start();
+}
+
+Void TDecSbac::readTileMarker( UInt& uiTileIdx, UInt uiBitsUsed )
+{
+  UInt uiSymbol;
+  uiTileIdx = 0;
+  for (Int iShift=uiBitsUsed-1; iShift>=0; iShift--)
+  {
+    m_pcTDecBinIf->decodeBinEP ( uiSymbol );
+    if (uiSymbol)
+    {
+      uiTileIdx |= (1<<iShift);
+    }
+  }
+}
+
+Void TDecSbac::parseTerminatingBit( UInt& ruiBit )
+{
+  m_pcTDecBinIf->decodeBinTrm( ruiBit );
+}
+
+
+Void TDecSbac::xReadUnaryMaxSymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    ruiSymbol = 0;
+    return;
+  }
+  
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
+  
+  if( ruiSymbol == 0 || uiMaxSymbol == 1 )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCont;
+  
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] );
+    uiSymbol++;
+  }
+  while( uiCont && ( uiSymbol < uiMaxSymbol - 1 ) );
+  
+  if( uiCont && ( uiSymbol == uiMaxSymbol - 1 ) )
+  {
+    uiSymbol++;
+  }
+  
+  ruiSymbol = uiSymbol;
+}
+
+Void TDecSbac::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
+{
+  UInt uiSymbol = 0;
+  UInt uiBit = 1;
+  
+  while( uiBit )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiBit );
+    uiSymbol += uiBit << uiCount++;
+  }
+  
+  if ( --uiCount )
+  {
+    UInt bins;
+    m_pcTDecBinIf->decodeBinsEP( bins, uiCount );
+    uiSymbol += bins;
+  }
+  
+  ruiSymbol = uiSymbol;
+}
+
+Void TDecSbac::xReadUnarySymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset )
+{
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
+  
+  if( !ruiSymbol )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCont;
+  
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] );
+    uiSymbol++;
+  }
+  while( uiCont );
+  
+  ruiSymbol = uiSymbol;
+}
+
+/** Parsing of coeff_abs_level_minus3
+ * \param ruiSymbol reference to coeff_abs_level_minus3
+ * \param ruiGoRiceParam reference to Rice parameter
+ * \returns Void
+ */
+Void TDecSbac::xReadGoRiceExGolomb( UInt &ruiSymbol, UInt &ruiGoRiceParam )
+{
+  Bool bExGolomb    = false;
+  UInt uiCodeWord   = 0;
+  UInt uiQuotient   = 0;
+  UInt uiRemainder  = 0;
+  UInt uiMaxVlc     = g_auiGoRiceRange[ ruiGoRiceParam ];
+  UInt uiMaxPreLen  = g_auiGoRicePrefixLen[ ruiGoRiceParam ];
+
+  do
+  {
+    uiQuotient++;
+    m_pcTDecBinIf->decodeBinEP( uiCodeWord );
+  }
+  while( uiCodeWord && uiQuotient < uiMaxPreLen );
+
+  uiCodeWord  = 1 - uiCodeWord;
+  uiQuotient -= uiCodeWord;
+
+  if ( ruiGoRiceParam > 0 )
+  {
+    m_pcTDecBinIf->decodeBinsEP( uiRemainder, ruiGoRiceParam );    
+  }
+
+  ruiSymbol      = uiRemainder + ( uiQuotient << ruiGoRiceParam );
+  bExGolomb      = ruiSymbol == ( uiMaxVlc + 1 );
+
+  if( bExGolomb )
+  {
+    xReadEpExGolomb( uiCodeWord, 0 );
+    ruiSymbol += uiCodeWord;
+  }
+
+  ruiGoRiceParam = g_aauiGoRiceUpdate[ ruiGoRiceParam ][ min<UInt>( ruiSymbol, 23 ) ];
+
+  return;
+}
+
+
+/** Parse I_PCM information. 
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ *
+ * 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 )
+{
+  UInt uiSymbol;
+  Int numSubseqIPCM = 0;
+  Bool readPCMSampleFlag = false;
+
+  if(pcCU->getNumSucIPCM() > 0) 
+  {
+    readPCMSampleFlag = true;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBinTrm(uiSymbol);
+
+    if (uiSymbol)
+    {
+      readPCMSampleFlag = true;
+      m_pcTDecBinIf->decodeNumSubseqIPCM(numSubseqIPCM);
+      pcCU->setNumSucIPCM(numSubseqIPCM + 1);
+      m_pcTDecBinIf->decodePCMAlignBits();
+    }
+  }
+
+  if (readPCMSampleFlag == true)
+  {
+    Bool bIpcmFlag = true;
+
+
+    pcCU->setPartSizeSubParts  ( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts      ( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, 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;
+    }
+
+    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;
+    }
+
+    pcCU->setNumSucIPCM( pcCU->getNumSucIPCM() - 1);
+    if(pcCU->getNumSucIPCM() == 0)
+    {
+      m_pcTDecBinIf->resetBac();
+    }
+  }
+}
+
+/** parse skip flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parseSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tSkipFlag" );
+  DTRACE_CABAC_T( "\tuiCtxSkip: ");
+  DTRACE_CABAC_V( uiCtxSkip );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+  
+  if( uiSymbol )
+  {
+    pcCU->setPredModeSubParts( MODE_SKIP,  uiAbsPartIdx, uiDepth );
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setMergeFlagSubParts( true , uiAbsPartIdx, 0, uiDepth );
+  }
+}
+
+#if LGE_ILLUCOMP_B0045
+/** parse illumination compensation flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parseICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{ 
+  UInt uiSymbol = 0;
+  UInt uiCtxIC = pcCU->getCtxICFlag( uiAbsPartIdx );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUICFlagSCModel.get( 0, 0, uiCtxIC ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tICFlag" );
+  DTRACE_CABAC_T( "\tuiCtxIC: ");
+  DTRACE_CABAC_V( uiCtxIC );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+  
+  pcCU->setICFlagSubParts( uiSymbol ? true : false , uiAbsPartIdx, 0, uiDepth );
+}
+#endif
+
+
+/** parse merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPUIdx
+ * \returns Void
+ */
+Void TDecSbac::parseMergeFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
+  pcCU->setMergeFlagSubParts( uiSymbol ? true : false, uiAbsPartIdx, uiPUIdx, uiDepth );
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tMergeFlag: " );
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\tAddress: " );
+  DTRACE_CABAC_V( pcCU->getAddr() );
+  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
+  DTRACE_CABAC_V( uiAbsPartIdx );
+  DTRACE_CABAC_T( "\n" );
+}
+
+Void TDecSbac::parseMergeIndex ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiNumCand = MRG_MAX_NUM_CANDS;
+  UInt uiUnaryIdx = 0;
+  uiNumCand = pcCU->getSlice()->getMaxNumMergeCand();
+#if HHI_MPI
+  const Bool bMVIAvailable = pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE;
+  const UInt uiMviMergePos = bMVIAvailable ? HHI_MPI_MERGE_POS : uiNumCand;
+#endif
+  if ( uiNumCand > 1 )
+  {
+    for( ; uiUnaryIdx < uiNumCand - 1; ++uiUnaryIdx )
+    {
+      UInt uiSymbol = 0;
+      if ( uiUnaryIdx==0 )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) );
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinEP( uiSymbol );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+  }
+  ruiMergeIndex = uiUnaryIdx;
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseMergeIndex()" )
+  DTRACE_CABAC_T( "\tuiMRGIdx= " )
+  DTRACE_CABAC_V( ruiMergeIndex )
+  DTRACE_CABAC_T( "\n" )
+#if HHI_MPI
+  if( ruiMergeIndex > uiMviMergePos )
+  {
+    assert( bMVIAvailable );
+    ruiMergeIndex--;
+  }
+  else if( ruiMergeIndex == uiMviMergePos )
+  {
+    assert( bMVIAvailable );
+    pcCU->setTextureModeDepthSubParts( uiDepth, uiAbsPartIdx, uiDepth );
+  }
+#endif
+}
+
+#if H3D_IVRP
+Void
+TDecSbac::parseResPredFlag( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCtx    = pcCU->getCtxResPredFlag( uiAbsPartIdx );
+  UInt uiSymbol = 0;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cResPredFlagSCModel.get( 0, 0, uiCtx ) );
+  rbResPredFlag = ( uiSymbol != 0 );
+}
+#endif
+
+#if H3D_IVMP
+Void TDecSbac::parseMVPIdx      ( Int& riMVPIdx, Int iNumAMVPCands )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, m_cMVPIdxSCModel.get(0), 1, iNumAMVPCands-1);
+  riMVPIdx = uiSymbol;
+}
+#else
+Void TDecSbac::parseMVPIdx      ( Int& riMVPIdx )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, m_cMVPIdxSCModel.get(0), 1, AMVP_MAX_NUM_CANDS-1);
+  riMVPIdx = uiSymbol;
+}
+#endif
+
+Void TDecSbac::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+  {
+    pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+    return;
+  }
+  
+  UInt uiSymbol;
+
+#if H3D_QTL
+  Bool bParseSplitFlag    = true;
+
+  TComSPS *sps            = pcCU->getPic()->getSlice(0)->getSPS();
+  TComPic *pcTexture      = pcCU->getSlice()->getTexturePic();
+  Bool bDepthMapDetect    = (pcTexture != NULL);
+  Bool bIntraSliceDetect  = (pcCU->getSlice()->getSliceType() == I_SLICE);
+
+  Bool rapPic     = (pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA);
+  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTLPC())
+  {
+    TComDataCU *pcTextureCU = pcTexture->getCU(pcCU->getAddr());
+    assert(pcTextureCU->getDepth(uiAbsPartIdx) >= uiDepth);
+    bParseSplitFlag         = (pcTextureCU->getDepth(uiAbsPartIdx) > uiDepth);
+  }
+
+  if(bParseSplitFlag)
+  {
+#endif
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSplitFlagSCModel.get( 0, 0, pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ) ) );
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tSplitFlag\n" )
+#if H3D_QTL
+  }
+  else
+    uiSymbol = 0;
+#endif
+
+  pcCU->setDepthSubParts( uiDepth + uiSymbol, uiAbsPartIdx );
+  
+  return;
+}
+
+/** parse partition size
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parsePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol, uiMode = 0;
+  PartSize eMode;
+
+#if H3D_QTL
+  Bool bParsePartSize    = true;
+  TComSPS *sps           = pcCU->getPic()->getSlice(0)->getSPS();
+  TComPic *pcTexture     = pcCU->getSlice()->getTexturePic();
+  Bool bDepthMapDetect   = (pcTexture != NULL);
+  Bool bIntraSliceDetect = (pcCU->getSlice()->getSliceType() == I_SLICE);
+
+  Bool rapPic     = (pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA);
+  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTLPC())
+  {
+    TComDataCU *pcTextureCU = pcTexture->getCU(pcCU->getAddr());
+    assert(pcTextureCU->getDepth(uiAbsPartIdx) >= uiDepth);
+    if (pcTextureCU->getDepth(uiAbsPartIdx) == uiDepth && pcTextureCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN)
+    {
+      bParsePartSize = false;
+      eMode          = SIZE_2Nx2N;
+    }
+  }
+#endif
+  
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+#if H3D_QTL
+    if(bParsePartSize)
+    {
+#endif
+      uiSymbol = 1;
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      }
+      eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
+#if H3D_QTL
+    }
+#endif
+    UInt uiTrLevel = 0;    
+    UInt uiWidthInBit  = g_aucConvertToBit[pcCU->getWidth(uiAbsPartIdx)]+2;
+    UInt uiTrSizeInBit = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxTrSize()]+2;
+    uiTrLevel          = uiWidthInBit >= uiTrSizeInBit ? uiWidthInBit - uiTrSizeInBit : 0;
+    if( eMode == SIZE_NxN )
+    {
+      pcCU->setTrIdxSubParts( 1+uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setTrIdxSubParts( uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+  }
+  else
+  {
+#if H3D_QTL
+    if(bParsePartSize)
+    {
+#endif
+      UInt uiMaxNumBits = 2;
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getSlice()->getSPS()->getDisInter4x4() && (g_uiMaxCUWidth>>uiDepth) == 8 && (g_uiMaxCUHeight>>uiDepth) == 8 ) )
+      {
+        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 ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+      {
+        if (eMode == SIZE_2NxN)
+        {
+            m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          if (uiSymbol == 0)
+          {
+            m_pcTDecBinIf->decodeBinEP(uiSymbol);
+            eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+          }
+        }
+        else if (eMode == SIZE_Nx2N)
+        {
+          m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          if (uiSymbol == 0)
+          {
+            m_pcTDecBinIf->decodeBinEP(uiSymbol);
+            eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
+          }
+        }
+      }
+#if H3D_QTL
+    }
+#endif
+  }
+  pcCU->setPartSizeSubParts( eMode, uiAbsPartIdx, uiDepth );
+  pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+}
+
+/** parse prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parsePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( pcCU->getSlice()->isIntra() )
+  {
+    pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+    return;
+  }
+  
+  UInt uiSymbol;
+  Int  iPredMode = MODE_INTER;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+  iPredMode += uiSymbol;
+  pcCU->setPredModeSubParts( (PredMode)iPredMode, uiAbsPartIdx, uiDepth );
+}
+  
+Void TDecSbac::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  Int  intraPredMode;
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  UInt uiFlag = 0;
+  if( pcCU->getSlice()->getSPS()->getUseDMM() && (g_uiMaxCUWidth>>uiDepth) <= DMM_WEDGEMODEL_MAX_SIZE )
+  {
+    m_pcTDecBinIf->decodeBin( uiFlag, m_cDmmFlagSCModel.get(0, 0, 0) );
+  }
+  if( uiFlag )
+  {
+    UInt uiDMMode;
+
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmModeSCModel.get(0, 0, 0) ); uiDMMode  = uiSymbol;
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmModeSCModel.get(0, 0, 0) ); uiDMMode |= uiSymbol << 1;
+    if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && g_uiMaxCUWidth>>uiDepth > 4 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmModeSCModel.get(0, 0, 0) ); uiDMMode |= uiSymbol << 2;
+    }
+#else
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmModeSCModel.get(0, 0, 0) ); uiDMMode  = uiSymbol;
+    if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && g_uiMaxCUWidth>>uiDepth > 4 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmModeSCModel.get(0, 0, 0) ); uiDMMode |= uiSymbol << 1;
+    }
+#endif
+    intraPredMode = uiDMMode + NUM_INTRA_MODE;
+
+#if HHI_DMM_WEDGE_INTRA
+    if( intraPredMode == DMM_WEDGE_FULL_IDX )          { xParseWedgeFullInfo          ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( intraPredMode == DMM_WEDGE_FULL_D_IDX )        { xParseWedgeFullDeltaInfo     ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( intraPredMode == DMM_WEDGE_PREDDIR_IDX )       { xParseWedgePredDirInfo       ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( intraPredMode == DMM_WEDGE_PREDDIR_D_IDX )     { xParseWedgePredDirDeltaInfo  ( pcCU, uiAbsPartIdx, uiDepth ); }
+#endif
+#if HHI_DMM_PRED_TEX
+    if( intraPredMode == DMM_WEDGE_PREDTEX_D_IDX )     { xParseWedgePredTexDeltaInfo  ( pcCU, uiAbsPartIdx, uiDepth ); }
+#if LGE_DMM3_SIMP_C0044
+    if( intraPredMode == DMM_WEDGE_PREDTEX_IDX )       { xParseWedgePredTexInfo       ( pcCU, uiAbsPartIdx, uiDepth ); }
+#endif
+    if( intraPredMode == DMM_CONTOUR_PREDTEX_D_IDX )   { xParseContourPredTexDeltaInfo( pcCU, uiAbsPartIdx, uiDepth ); }
+#endif
+  }
+  else
+  {
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+    Bool bCodeEdgeIntra = false;
+    if( pcCU->getSlice()->getSPS()->isDepth() )
+    {
+      UInt uiPUWidth = pcCU->getWidth( uiAbsPartIdx ) >> (pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN ? 1 : 0);
+      if( uiPUWidth <= LGE_EDGE_INTRA_MAX_SIZE && uiPUWidth >= LGE_EDGE_INTRA_MIN_SIZE )
+        bCodeEdgeIntra = true;
+    }
+#endif
+
+    Int uiPreds[3] = {-1, -1, -1};
+    Int uiPredNum = pcCU->getIntraDirLumaPredictor(uiAbsPartIdx, uiPreds);  
+#if LGE_EDGE_INTRA_A0070
+    UInt uiCheckBit = 0;
+#endif
+
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 0) );
+
+    if ( uiSymbol )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiSymbol );
+      if (uiSymbol)
+      {
+        m_pcTDecBinIf->decodeBinEP( uiSymbol );
+        uiSymbol++;
+      }
+      intraPredMode = uiPreds[uiSymbol];
+    }
+    else
+    {
+      intraPredMode = 0;
+
+
+      m_pcTDecBinIf->decodeBinsEP( uiSymbol, 5 );
+#if LGE_EDGE_INTRA_A0070
+      if (bCodeEdgeIntra)
+      {
+        if (uiSymbol==31)
+        {
+          m_pcTDecBinIf->decodeBinsEP(uiCheckBit,1);
+          if (uiCheckBit)
+            uiSymbol = EDGE_INTRA_IDX;
+        }
+      }
+#endif
+      intraPredMode = uiSymbol;
+
+      //postponed sorting of MPMs (only in remaining branch)
+      if (uiPreds[0] > uiPreds[1])
+      { 
+        std::swap(uiPreds[0], uiPreds[1]); 
+      }
+      if (uiPreds[0] > uiPreds[2])
+      {
+        std::swap(uiPreds[0], uiPreds[2]);
+      }
+      if (uiPreds[1] > uiPreds[2])
+      {
+        std::swap(uiPreds[1], uiPreds[2]);
+      }
+#if LGE_EDGE_INTRA_A0070
+      if ( intraPredMode != EDGE_INTRA_IDX)
+      {
+#endif
+        for ( Int i = 0; i < uiPredNum; i++ )
+        {
+          intraPredMode += ( intraPredMode >= uiPreds[i] );
+        }
+#if LGE_EDGE_INTRA_A0070
+      }
+#endif
+    }
+
+#if LGE_EDGE_INTRA_A0070
+    if( intraPredMode == EDGE_INTRA_IDX )
+    {
+      xParseEdgeIntraInfo( pcCU, uiAbsPartIdx, uiDepth );
+#if LGE_EDGE_INTRA_DELTA_DC
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cEdgeIntraDeltaDCSCModel.get(0, 0, 0) );
+      if( uiSymbol )
+      {
+        intraPredMode = EDGE_INTRA_DELTA_IDX;
+        Int iDeltaDC0;
+        Int iDeltaDC1;
+
+        xReadExGolombLevel( (UInt &) iDeltaDC0, m_cEdgeIntraDeltaDCSCModel.get(0, 0, 1) );
+        if( iDeltaDC0 != 0 )
+        {
+          UInt uiSign;
+          m_pcTDecBinIf->decodeBinEP( uiSign );
+          if ( uiSign )
+          {
+            iDeltaDC0 = -iDeltaDC0;
+          }
+        }
+        xReadExGolombLevel( (UInt &) iDeltaDC1, m_cEdgeIntraDeltaDCSCModel.get(0, 0, 1) );
+        if( iDeltaDC1 != 0 )
+        {
+          UInt uiSign;
+          m_pcTDecBinIf->decodeBinEP( uiSign );
+          if ( uiSign )
+          {
+            iDeltaDC1 = -iDeltaDC1;
+          }
+        }
+
+        pcCU->setEdgeDeltaDC0( uiAbsPartIdx, iDeltaDC0 );
+        pcCU->setEdgeDeltaDC1( uiAbsPartIdx, iDeltaDC1 );
+      }
+#endif
+    }
+#endif
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  }
+#endif
+
+  pcCU->setLumaIntraDirSubParts( (UChar)intraPredMode, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecSbac::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+
+  if( uiSymbol == 0 )
+  {
+    uiSymbol = DM_CHROMA_IDX;
+  } 
+  else 
+  {
+    if( pcCU->getSlice()->getSPS()->getUseLMChroma() )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, 1 ) );
+    }
+    else
+    {
+      uiSymbol = 1;
+    }
+
+    if( uiSymbol == 0 )
+    {
+      uiSymbol = LM_CHROMA_IDX;
+    } 
+    else
+    {
+      UInt uiIPredMode;
+      m_pcTDecBinIf->decodeBinsEP( uiIPredMode, 2 );
+      UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
+      pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
+      uiSymbol = uiAllowedChromaDir[ uiIPredMode ];
+    }
+  }
+  pcCU->setChromIntraDirSubParts( uiSymbol, uiAbsPartIdx, uiDepth );
+  return;
+}
+
+Void TDecSbac::parseInterDir( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = pcCU->getCtxInterDir( uiAbsPartIdx );
+  ContextModel *pCtx = m_cCUInterDirSCModel.get( 0 );
+  m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + uiCtx ) );
+
+  if( uiSymbol )
+  {
+    uiSymbol = 2;
+  }
+
+  uiSymbol++;
+  ruiInterDir = uiSymbol;
+  return;
+}
+
+Void TDecSbac::parseRefFrmIdx( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+
+  if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C ) > 0 && eRefList==REF_PIC_LIST_C)
+  {
+    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+    m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+
+    if( uiSymbol )
+    {
+      xReadUnaryMaxSymbol( uiSymbol, pCtx + 1, 1, pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C )-2 );
+      uiSymbol++;
+    }
+    riRefFrmIdx = uiSymbol;
+  }
+  else
+  {
+    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+    m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+
+    if( uiSymbol )
+    {
+      xReadUnaryMaxSymbol( uiSymbol, pCtx + 1, 1, pcCU->getSlice()->getNumRefIdx( eRefList )-2 );
+      uiSymbol++;
+    }
+    riRefFrmIdx = uiSymbol;
+  }
+
+  return;
+}
+
+Void TDecSbac::parseMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+  UInt uiHorAbs;
+  UInt uiVerAbs;
+  UInt uiHorSign = 0;
+  UInt uiVerSign = 0;
+  ContextModel *pCtx = m_cCUMvdSCModel.get( 0 );
+
+  if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefList == REF_PIC_LIST_1 && pcCU->getInterDir(uiAbsPartIdx)==3)
+  {
+    uiHorAbs=0;
+    uiVerAbs=0;
+  }
+  else
+  {
+
+    m_pcTDecBinIf->decodeBin( uiHorAbs, *pCtx );
+    m_pcTDecBinIf->decodeBin( uiVerAbs, *pCtx );
+
+    const Bool bHorAbsGr0 = uiHorAbs != 0;
+    const Bool bVerAbsGr0 = uiVerAbs != 0;
+    pCtx++;
+
+    if( bHorAbsGr0 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+      uiHorAbs += uiSymbol;
+    }
+
+    if( bVerAbsGr0 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+      uiVerAbs += uiSymbol;
+    }
+
+    if( bHorAbsGr0 )
+    {
+      if( 2 == uiHorAbs )
+      {
+        xReadEpExGolomb( uiSymbol, 1 );
+        uiHorAbs += uiSymbol;
+      }
+
+      m_pcTDecBinIf->decodeBinEP( uiHorSign );
+    }
+
+    if( bVerAbsGr0 )
+    {
+      if( 2 == uiVerAbs )
+      {
+        xReadEpExGolomb( uiSymbol, 1 );
+        uiVerAbs += uiSymbol;
+      }
+
+      m_pcTDecBinIf->decodeBinEP( uiVerSign );
+    }
+
+  }
+
+  const TComMv cMv( uiHorSign ? -Int( uiHorAbs ): uiHorAbs, uiVerSign ? -Int( uiVerAbs ) : uiVerAbs );
+  pcCU->getCUMvField( eRefList )->setAllMvd( cMv, pcCU->getPartitionSize( uiAbsPartIdx ), uiAbsPartIdx, uiDepth, uiPartIdx );
+  return;
+}
+
+
+Void TDecSbac::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
+{
+  m_pcTDecBinIf->decodeBin( ruiSubdivFlag, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiLog2TransformBlockSize ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( ruiSubdivFlag )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiLog2TransformBlockSize )
+  DTRACE_CABAC_T( "\n" )
+}
+
+Void TDecSbac::parseQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = 0;
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtRootCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiSymbol )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+  
+  uiQtRootCbf = uiSymbol;
+}
+
+Void TDecSbac::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int qp;
+  UInt uiDQp;
+  Int  iDQp;
+  
+  m_pcTDecBinIf->decodeBin( uiDQp, m_cCUDeltaQpSCModel.get( 0, 0, 0 ) );
+  
+  if ( uiDQp == 0 )
+  {
+    qp = pcCU->getRefQP(uiAbsPartIdx);
+  }
+  else
+  {
+    UInt uiSign;
+    Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+    m_pcTDecBinIf->decodeBinEP(uiSign);
+
+    UInt uiMaxAbsDQpMinus1 = 24 + (qpBdOffsetY/2) + (uiSign);
+    UInt uiAbsDQpMinus1;
+    xReadUnaryMaxSymbol (uiAbsDQpMinus1,  &m_cCUDeltaQpSCModel.get( 0, 0, 1 ), 1, uiMaxAbsDQpMinus1);
+
+    iDQp = uiAbsDQpMinus1 + 1;
+
+    if(uiSign)
+    {
+      iDQp = -iDQp;
+    }
+
+    qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+qpBdOffsetY)) - qpBdOffsetY;
+  }
+  
+  UInt uiAbsQpCUPartIdx = (uiAbsPartIdx>>(8-(pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()<<1)))<<(8-(pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()<<1)) ;
+  UInt uiQpCUDepth =   min(uiDepth,pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()) ;
+  pcCU->setQPSubParts( qp, uiAbsQpCUPartIdx, uiQpCUDepth );
+}
+
+Void TDecSbac::parseQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = pcCU->getCtxQtCbf( uiAbsPartIdx, eType, uiTrDepth );
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA: eType, uiCtx ) );
+  
+  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" )
+  
+  pcCU->setCbfSubParts( uiSymbol << uiTrDepth, eType, uiAbsPartIdx, uiDepth );
+}
+
+/** Parse (X,Y) position of the last significant coefficient
+ * \param uiPosLastX reference to X component of last coefficient
+ * \param uiPosLastY reference to 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)
+ *
+ * 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 )
+{
+  UInt uiLast;
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType );
+
+  // posX
+  Int widthCtx = eTType ? 4 : width;
+  const UInt *puiCtxIdxX = g_uiLastCtx + ( g_aucConvertToBit[ widthCtx ] * ( g_aucConvertToBit[ widthCtx ] + 3 ) );
+  for( uiPosLastX = 0; uiPosLastX < g_uiGroupIdx[ width - 1 ]; uiPosLastX++ )
+  {
+    if ( eTType  )
+    {
+      m_pcTDecBinIf->decodeBin( uiLast, *( pCtxX + (uiPosLastX>>g_aucConvertToBit[ width ])  ) );
+    }
+    else
+    {
+      m_pcTDecBinIf->decodeBin( uiLast, *( pCtxX + puiCtxIdxX[ uiPosLastX ] ) );
+    }
+    if( !uiLast )
+    {
+      break;
+    }
+  }
+
+  // posY
+  Int heightCtx = eTType? 4 : height;
+  const UInt *puiCtxIdxY = g_uiLastCtx + ( g_aucConvertToBit[ heightCtx ] * ( g_aucConvertToBit[ heightCtx ] + 3 ) );
+  for( uiPosLastY = 0; uiPosLastY < g_uiGroupIdx[ height - 1 ]; uiPosLastY++ )
+  {
+    if (eTType)
+    {
+      m_pcTDecBinIf->decodeBin( uiLast, *( pCtxY + (uiPosLastY>>g_aucConvertToBit[ height ]) ) );
+    }
+    else
+    {
+      m_pcTDecBinIf->decodeBin( uiLast, *( pCtxY + puiCtxIdxY[ uiPosLastY ] ) );
+    }
+    if( !uiLast )
+    {
+      break;
+    }
+  }
+  if ( uiPosLastX > 3 )
+  {
+    UInt uiTemp  = 0;
+    UInt uiCount = ( uiPosLastX - 2 ) >> 1;
+    for ( Int i = uiCount - 1; i >= 0; i-- )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiLast );
+      uiTemp += uiLast << i;
+    }
+    uiPosLastX = g_uiMinInGroup[ uiPosLastX ] + uiTemp;
+  }
+  if ( uiPosLastY > 3 )
+  {
+    UInt uiTemp  = 0;
+    UInt uiCount = ( uiPosLastY - 2 ) >> 1;
+    for ( Int i = uiCount - 1; i >= 0; i-- )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiLast );
+      uiTemp += uiLast << i;
+    }
+    uiPosLastY = g_uiMinInGroup[ uiPosLastY ] + uiTemp;
+  }
+  
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosLastX, uiPosLastY );
+  }
+}
+
+Void TDecSbac::parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\twidth=" )
+  DTRACE_CABAC_V( uiWidth )
+  DTRACE_CABAC_T( "\theight=" )
+  DTRACE_CABAC_V( uiHeight )
+  DTRACE_CABAC_T( "\tdepth=" )
+  DTRACE_CABAC_V( uiDepth )
+  DTRACE_CABAC_T( "\tabspartidx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\ttoCU-X=" )
+  DTRACE_CABAC_V( pcCU->getCUPelX() )
+  DTRACE_CABAC_T( "\ttoCU-Y=" )
+  DTRACE_CABAC_V( pcCU->getCUPelY() )
+  DTRACE_CABAC_T( "\tCU-addr=" )
+  DTRACE_CABAC_V(  pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tinCU-X=" )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tinCU-Y=" )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tpredmode=" )
+  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
+  DTRACE_CABAC_T( "\n" )
+  
+  if( uiWidth > pcCU->getSlice()->getSPS()->getMaxTrSize() )
+  {
+    uiWidth  = pcCU->getSlice()->getSPS()->getMaxTrSize();
+    uiHeight = pcCU->getSlice()->getSPS()->getMaxTrSize();
+  }
+  
+  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));
+  int blockType = uiLog2BlockSize;
+  if (uiWidth != uiHeight)
+  {
+    uiScanIdx = SCAN_DIAG;
+    blockType = 4;
+  }
+  
+  //===== decode last significant =====
+  UInt uiPosLastX, uiPosLastY;
+  parseLastSignificantXY( uiPosLastX, uiPosLastY, uiWidth, uiHeight, eTType, uiScanIdx );
+  UInt uiBlkPosLast      = uiPosLastX + (uiPosLastY<<uiLog2BlockSize);
+  pcCoef[ uiBlkPosLast ] = 1;
+
+  //===== decode significance flags =====
+  UInt uiScanPosLast   = uiBlkPosLast;
+  if (uiScanIdx == SCAN_ZIGZAG)
+  {
+    // Map zigzag to diagonal scan
+    uiScanIdx = SCAN_DIAG;
+  }
+  const UInt * scan;
+  if (uiWidth == uiHeight)
+  {
+    scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize-1 ];
+  }
+  else
+  {
+    scan = g_sigScanNSQT[ uiLog2BlockSize - 2 ];
+  }
+  for( uiScanPosLast = 0; uiScanPosLast < uiMaxNumCoeffM1; uiScanPosLast++ )
+  {
+    UInt uiBlkPos = scan[ uiScanPosLast ];
+    if( uiBlkPosLast == uiBlkPos )
+    {
+      break;
+    }
+  }
+
+  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 uiNumOne                = 0;
+  UInt uiGoRiceParam           = 0;
+
+  UInt const tsig = pcCU->getSlice()->getPPS()->getTSIG();
+#if LOSSLESS_CODING
+  Bool beValid; 
+  if (pcCU->isLosslessCoded(uiAbsPartIdx))
+  {
+    beValid = false;
+  }
+  else 
+  {
+    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+  }
+#else
+  Bool beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+#endif
+  UInt absSum = 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;
+  if (uiWidth == uiHeight)
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0  ];    
+    if( uiLog2BlockSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlockSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+  else
+  {
+    scanCG = g_sigCGScanNSQT[ uiLog2BlockSize - 2 ];
+  }
+  Int  iScanPosSig             = (Int) uiScanPosLast;
+  for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
+  {
+    Int  iSubPos     = iSubSet << LOG2_SCAN_SET_SIZE;
+    uiGoRiceParam    = 0;
+    Int numNonZero = 0;
+    
+    Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE;
+
+    Int pos[SCAN_SET_SIZE];
+    if( iScanPosSig == (Int) uiScanPosLast )
+    {
+      lastNZPosInCG  = iScanPosSig;
+      firstNZPosInCG = iScanPosSig;
+      iScanPosSig--;
+      pos[ numNonZero ] = uiBlkPosLast;
+      numNonZero = 1;
+    }
+
+      // decode significant_coeffgroup_flag
+      Int iCGBlkPos = scanCG[ iSubSet ];
+      Int iCGPosY   = iCGBlkPos / uiNumBlkSide;
+      Int iCGPosX   = iCGBlkPos - (iCGPosY * uiNumBlkSide);
+      if( uiWidth == 8 && uiHeight == 8 && (uiScanIdx == SCAN_HOR || uiScanIdx == SCAN_VER) )
+      {
+        iCGPosY = (uiScanIdx == SCAN_HOR ? iCGBlkPos : 0);
+        iCGPosX = (uiScanIdx == SCAN_VER ? iCGBlkPos : 0);
+      }
+      if( iSubSet == iLastScanSet || iSubSet == 0)
+      {
+        uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+      }
+      else
+      {
+          UInt uiSigCoeffGroup;
+          UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiScanIdx, uiWidth, uiHeight );
+          m_pcTDecBinIf->decodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+          uiSigCoeffGroupFlag[ iCGBlkPos ] = uiSigCoeffGroup;
+      }
+
+      // decode significant_coeff_flag
+      UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig;
+      for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+      {
+        uiBlkPos  = scan[ iScanPosSig ];
+        uiPosY    = uiBlkPos >> uiLog2BlockSize;
+        uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+        uiSig     = 0;
+        
+        if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+        {
+          if( iScanPosSig > iSubPos || iSubSet == 0  || numNonZero )
+          {
+            uiCtxSig  = TComTrQuant::getSigCtxInc( pcCoef, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+            m_pcTDecBinIf->decodeBin( uiSig, baseCtx[ uiCtxSig ] );
+          }
+          else
+          {
+            uiSig = 1;
+          }
+        }
+        pcCoef[ uiBlkPos ] = uiSig;
+        if( uiSig )
+        {
+          pos[ numNonZero ] = uiBlkPos;
+          numNonZero ++;
+          if( lastNZPosInCG == -1 )
+          {
+            lastNZPosInCG = iScanPosSig;
+          }
+          firstNZPosInCG = iScanPosSig;
+        }
+      }
+
+    
+    if( numNonZero )
+    {
+      Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= (Int)tsig );
+      absSum = 0;
+
+      UInt c1 = 1;
+      UInt uiCtxSet    = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0;
+      UInt uiBin;
+      
+      if( uiNumOne > 0 )
+      {
+        uiCtxSet++;
+      }
+      
+      uiNumOne       >>= 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;   
+      Int numC1Flag = min(numNonZero, C1FLAG_NUMBER);
+      Int firstC2FlagIdx = -1;
+
+      for( Int idx = 0; idx < numC1Flag; idx++ )
+      {
+        m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[c1] );
+        if( uiBin == 1 )
+        {
+          c1 = 0;
+          if (firstC2FlagIdx == -1)
+          {
+            firstC2FlagIdx = idx;
+          }
+        }
+        else if( (c1 < 3) && (c1 > 0) )
+        {
+          c1++;
+        }
+        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;
+        if ( firstC2FlagIdx != -1)
+        {
+          m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[0] ); 
+          absCoeff[ firstC2FlagIdx ] = uiBin + 2;
+        }
+      }
+
+      UInt coeffSigns;
+      if ( signHidden && beValid )
+      {
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero-1 );
+        coeffSigns <<= 32 - (numNonZero-1);
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero );
+        coeffSigns <<= 32 - numNonZero;
+      }
+      
+      Int iFirstCoeff2 = 1;    
+      if (c1 == 0 || numNonZero > C1FLAG_NUMBER)
+      {
+        for( Int idx = 0; idx < numNonZero; idx++ )
+        {
+          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2) : 1;
+
+          if( absCoeff[ idx ] == baseLevel)
+          {
+            UInt uiLevel;
+            xReadGoRiceExGolomb( uiLevel, uiGoRiceParam );
+            absCoeff[ idx ] = uiLevel + baseLevel;
+          }
+
+          if(absCoeff[ idx ] >= 2)  
+          {
+            iFirstCoeff2 = 0;
+            uiNumOne++;
+          }
+        }
+      }
+
+      for( Int idx = 0; idx < numNonZero; idx++ )
+      {
+        Int blkPos = pos[ idx ];
+        // Signs applied later.
+        pcCoef[ blkPos ] = absCoeff[ idx ];
+        absSum += absCoeff[ idx ];
+
+        if ( idx == numNonZero-1 && signHidden && beValid )
+        {
+          // Infer sign of 1st element.
+          if (absSum&0x1)
+            pcCoef[ blkPos ] = -pcCoef[ blkPos ];
+        }
+        else
+        {
+          Int sign = static_cast<Int>( coeffSigns ) >> 31;
+          pcCoef[ blkPos ] = ( pcCoef[ blkPos ] ^ sign ) - sign;
+          coeffSigns <<= 1;
+        }
+      }
+    }
+    else
+    {
+      uiNumOne >>= 1;
+    }
+  }
+  
+  return;
+}
+
+
+Void TDecSbac::parseSaoUvlc (UInt& ruiVal)
+{
+  UInt uiCode;
+  Int  i;
+
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoUvlcSCModel.get( 0, 0, 0 ) );
+  if ( uiCode == 0 )
+  {
+    ruiVal = 0;
+    return;
+  }
+
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBin( uiCode, m_cSaoUvlcSCModel.get( 0, 0, 1 ) );
+    if ( uiCode == 0 ) break;
+    i++;
+  }
+
+  ruiVal = i;
+}
+
+Void TDecSbac::parseSaoSvlc (Int&  riVal)
+{
+  UInt uiCode;
+  Int  iSign;
+  Int  i;
+
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoSvlcSCModel.get( 0, 0, 0 ) );
+
+  if ( uiCode == 0 )
+  {
+    riVal = 0;
+    return;
+  }
+
+  // read sign
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoSvlcSCModel.get( 0, 0, 1 ) );
+
+  if ( uiCode == 0 )
+  {
+    iSign =  1;
+  }
+  else
+  {
+    iSign = -1;
+  }
+
+  // read magnitude
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBin( uiCode, m_cSaoSvlcSCModel.get( 0, 0, 2 ) );
+    if ( uiCode == 0 ) break;
+    i++;
+  }
+
+  riVal = i*iSign;
+}
+
+Void TDecSbac::parseSaoUflc (UInt&  riVal)
+{
+  UInt uiSymbol;
+  riVal = 0;
+  for (Int i=0;i<5;i++)
+  {
+    m_pcTDecBinIf->decodeBinEP ( uiSymbol );
+    if (uiSymbol)
+    {
+      riVal |= (1<<i);
+    }
+  }
+}
+Void TDecSbac::parseSaoMergeLeft (UInt&  ruiVal, UInt uiCompIdx)
+{
+  UInt uiCode;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeLeftSCModel.get( 0, 0, uiCompIdx ) );
+  ruiVal = (Int)uiCode;
+}
+
+Void TDecSbac::parseSaoMergeUp (UInt&  ruiVal)
+{
+  UInt uiCode;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeUpSCModel.get( 0, 0, 0 ) );
+  ruiVal = (Int)uiCode;
+}
+Void TDecSbac::parseSaoTypeIdx (UInt&  ruiVal)
+{
+  UInt uiCode;
+  Int  i;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  if ( uiCode == 0 )
+  {
+    ruiVal = 0;
+    return;
+  }
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 1 ) );
+    if ( uiCode == 0 ) break;
+    i++;
+  }
+  ruiVal = i;
+}
+
+inline Void copySaoOneLcuParam(SaoLcuParam* psDst,  SaoLcuParam* psSrc)
+{
+  Int i;
+  psDst->partIdx = psSrc->partIdx;
+  psDst->typeIdx    = psSrc->typeIdx;
+  if (psDst->typeIdx != -1)
+  {
+    if (psDst->typeIdx == SAO_BO)
+    {
+      psDst->bandPosition = psSrc->bandPosition ;
+    }
+    else
+    {
+      psDst->bandPosition = 0;
+    }
+    psDst->length  = psSrc->length;
+    for (i=0;i<psDst->length;i++)
+    {
+      psDst->offset[i] = psSrc->offset[i];
+    }
+  }
+  else
+  {
+    psDst->length  = 0;
+    for (i=0;i<SAO_BO_LEN;i++)
+    {
+      psDst->offset[i] = 0;
+    }
+  }
+}
+Void TDecSbac::parseSaoOffset(SaoLcuParam* psSaoLcuParam)
+{
+  UInt uiSymbol;
+  Int iSymbol;
+  static Int iTypeLength[MAX_NUM_SAO_TYPE] = {
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_BO_LEN
+  }; 
+
+  parseSaoTypeIdx(uiSymbol);
+  psSaoLcuParam->typeIdx = (Int)uiSymbol - 1;
+  if (uiSymbol)
+  {
+    psSaoLcuParam->length = iTypeLength[psSaoLcuParam->typeIdx];
+    if( psSaoLcuParam->typeIdx == SAO_BO )
+    {
+      // Parse Left Band Index
+      parseSaoUflc( uiSymbol );
+      psSaoLcuParam->bandPosition = uiSymbol;
+      for(Int i=0; i< psSaoLcuParam->length; i++)
+      {
+        parseSaoSvlc(iSymbol);
+        psSaoLcuParam->offset[i] = iSymbol;
+      }   
+    }
+    else if( psSaoLcuParam->typeIdx < 4 )
+    {
+      parseSaoUvlc(uiSymbol); psSaoLcuParam->offset[0] = uiSymbol;
+      parseSaoUvlc(uiSymbol); psSaoLcuParam->offset[1] = uiSymbol;
+      parseSaoUvlc(uiSymbol); psSaoLcuParam->offset[2] = -(Int)uiSymbol;
+      parseSaoUvlc(uiSymbol); psSaoLcuParam->offset[3] = -(Int)uiSymbol;
+    }
+  }
+  else
+  {
+    psSaoLcuParam->length = 0;
+  }
+}
+
+Void TDecSbac::parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Bool bLFCrossSliceBoundaryFlag)
+{
+  Int iAddr = pcCU->getAddr();
+  UInt uiSymbol;
+  for (Int iCompIdx=0; iCompIdx<3; iCompIdx++)
+  {
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag    = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag  = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].bandPosition   = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx        = -1;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[0]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[1]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[2]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[3]     = 0;
+
+    if (pSaoParam->bSaoFlag[iCompIdx])
+    {
+      if (rx>0 && iCUAddrInSlice!=0)
+      {
+        parseSaoMergeLeft(uiSymbol,iCompIdx); pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = (Int)uiSymbol;
+      }
+      else
+      {
+        pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = 0;
+      }
+
+      if (pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag==0)
+      {
+        if ((ry > 0) && (iCUAddrUpInSlice>0||bLFCrossSliceBoundaryFlag))
+        {
+          parseSaoMergeUp(uiSymbol);  pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = uiSymbol;
+        }
+        else
+        {
+          pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = 0;
+        }
+        if (!pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag)
+        {
+          parseSaoOffset(&(pSaoParam->saoLcuParam[iCompIdx][iAddr]));
+        }
+        else
+        {
+          copySaoOneLcuParam(&pSaoParam->saoLcuParam[iCompIdx][iAddr], &pSaoParam->saoLcuParam[iCompIdx][iAddr-pSaoParam->numCuInWidth]);
+        }
+      }
+      else
+      {
+        copySaoOneLcuParam(&pSaoParam->saoLcuParam[iCompIdx][iAddr],  &pSaoParam->saoLcuParam[iCompIdx][iAddr-1]);
+      }
+    }
+    else
+    {
+      pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx = -1;
+      pSaoParam->saoLcuParam[iCompIdx][iAddr].bandPosition = 0;
+    }
+  }
+}
+
+/**
+ - Initialize our contexts from the nominated source.
+ .
+ \param pSrc Contexts to be copied.
+ */
+Void TDecSbac::xCopyContextsFrom( TDecSbac* pSrc )
+{
+  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
+}
+
+Void TDecSbac::xCopyFrom( 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::decodeFlush ( )
+{
+  UInt uiBit;
+  m_pcTDecBinIf->decodeBinTrm(uiBit);
+  m_pcTDecBinIf->flush();
+
+}
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX || (LGE_EDGE_INTRA_A0070 && LGE_EDGE_INTRA_DELTA_DC)
+Void TDecSbac::xReadExGolombLevel( UInt& ruiSymbol, ContextModel& rcSCModel  )
+{
+  UInt uiSymbol;
+  UInt uiCount = 0;
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, rcSCModel );
+    uiCount++;
+  }
+  while( uiSymbol && ( uiCount != 13 ) );
+
+  ruiSymbol = uiCount - 1;
+
+  if( uiSymbol )
+  {
+    xReadEpExGolomb( uiSymbol, 0 );
+    ruiSymbol += uiSymbol + 1;
+  }
+
+  return;
+}
+#endif
+#if HHI_DMM_WEDGE_INTRA
+Void TDecSbac::xParseWedgeFullInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+  Int iBits = g_aucWedgeFullBitsListIdx[iIntraIdx];
+
+  UInt uiSymbol, uiTabIdx = 0;
+  for ( Int i = 0; i < iBits; i++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmDataSCModel.get(0, 0, 0) );
+    uiTabIdx += ( uiSymbol && i == 0 ) ? 1 : 0;
+    uiTabIdx += ( uiSymbol && i == 1 ) ? 2 : 0;
+    uiTabIdx += ( uiSymbol && i == 2 ) ? 4 : 0;
+    uiTabIdx += ( uiSymbol && i == 3 ) ? 8 : 0;
+    uiTabIdx += ( uiSymbol && i == 4 ) ? 16 : 0;
+    uiTabIdx += ( uiSymbol && i == 5 ) ? 32 : 0;
+    uiTabIdx += ( uiSymbol && i == 6 ) ? 64 : 0;
+    uiTabIdx += ( uiSymbol && i == 7 ) ? 128 : 0;
+    uiTabIdx += ( uiSymbol && i == 8 ) ? 256 : 0;
+    uiTabIdx += ( uiSymbol && i == 9 ) ? 512 : 0;
+    uiTabIdx += ( uiSymbol && i == 10 ) ? 1024 : 0;
+    uiTabIdx += ( uiSymbol && i == 11 ) ? 2048 : 0;
+    uiTabIdx += ( uiSymbol && i == 12 ) ? 4096 : 0;
+  }
+
+  pcCU->setWedgeFullTabIdxSubParts( uiTabIdx, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecSbac::xParseWedgeFullDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+  Int iBits = g_aucWedgeFullBitsListIdx[iIntraIdx];
+
+  UInt uiSymbol, uiTabIdx = 0;
+  for ( Int i = 0; i < iBits; i++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmDataSCModel.get(0, 0, 0) );
+    uiTabIdx += ( uiSymbol && i == 0 ) ? 1 : 0;
+    uiTabIdx += ( uiSymbol && i == 1 ) ? 2 : 0;
+    uiTabIdx += ( uiSymbol && i == 2 ) ? 4 : 0;
+    uiTabIdx += ( uiSymbol && i == 3 ) ? 8 : 0;
+    uiTabIdx += ( uiSymbol && i == 4 ) ? 16 : 0;
+    uiTabIdx += ( uiSymbol && i == 5 ) ? 32 : 0;
+    uiTabIdx += ( uiSymbol && i == 6 ) ? 64 : 0;
+    uiTabIdx += ( uiSymbol && i == 7 ) ? 128 : 0;
+    uiTabIdx += ( uiSymbol && i == 8 ) ? 256 : 0;
+    uiTabIdx += ( uiSymbol && i == 9 ) ? 512 : 0;
+    uiTabIdx += ( uiSymbol && i == 10 ) ? 1024 : 0;
+    uiTabIdx += ( uiSymbol && i == 11 ) ? 2048 : 0;
+    uiTabIdx += ( uiSymbol && i == 12 ) ? 4096 : 0;
+  }
+
+  pcCU->setWedgeFullTabIdxSubParts( uiTabIdx, uiAbsPartIdx, uiDepth );
+
+  UInt uiDC1, uiDC2;
+  xReadExGolombLevel( uiDC1, m_cDmmDataSCModel.get(0, 0, 1) );
+  Int iDC1 = uiDC1;
+  if ( uiDC1 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC1 = -iDC1;
+    }
+  }
+  xReadExGolombLevel( uiDC2, m_cDmmDataSCModel.get(0, 0, 1) );
+  Int iDC2 = uiDC2;
+  if ( uiDC2 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC2 = -iDC2;
+    }
+  }
+
+  pcCU->setWedgeFullDeltaDC1SubParts( iDC1, uiAbsPartIdx, uiDepth );
+  pcCU->setWedgeFullDeltaDC2SubParts( iDC2, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecSbac::xParseWedgePredDirInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( DMM_WEDGE_PREDDIR_DELTAEND_MAX > 0 )
+  {
+    UInt uiDeltaEnd = 0;
+    m_pcTDecBinIf->decodeBin( uiDeltaEnd, m_cDmmDataSCModel.get(0, 0, 2) );
+
+    Int iDeltaEnd;
+    if( uiDeltaEnd != 0 )
+    {
+      UInt uiAbsValMinus1;
+      UInt uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmDataSCModel.get(0, 0, 2) ); uiAbsValMinus1  = uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmDataSCModel.get(0, 0, 2) ); uiAbsValMinus1 |= uiSymbol << 1;
+      uiDeltaEnd = uiAbsValMinus1 + 1;
+
+      iDeltaEnd = uiDeltaEnd;
+      UInt uiSign;
+      m_pcTDecBinIf->decodeBinEP( uiSign );
+      if( uiSign )
+      {
+        iDeltaEnd = -iDeltaEnd;
+      }
+    }
+    else
+    {
+      iDeltaEnd = 0;
+    }
+    pcCU->setWedgePredDirDeltaEndSubParts( iDeltaEnd, uiAbsPartIdx, uiDepth );
+  }
+}
+
+Void TDecSbac::xParseWedgePredDirDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( DMM_WEDGE_PREDDIR_DELTAEND_MAX > 0 )
+  {
+    UInt uiDeltaEnd = 0;
+    m_pcTDecBinIf->decodeBin( uiDeltaEnd, m_cDmmDataSCModel.get(0, 0, 2) );
+
+    Int iDeltaEnd;
+    if( uiDeltaEnd != 0 )
+    {
+      UInt uiAbsValMinus1;
+      UInt uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmDataSCModel.get(0, 0, 2) ); uiAbsValMinus1  = uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmDataSCModel.get(0, 0, 2) ); uiAbsValMinus1 |= uiSymbol << 1;
+      uiDeltaEnd = uiAbsValMinus1 + 1;
+
+      iDeltaEnd = uiDeltaEnd;
+      UInt uiSign;
+      m_pcTDecBinIf->decodeBinEP( uiSign );
+      if( uiSign )
+      {
+        iDeltaEnd = -iDeltaEnd;
+      }
+    }
+    else
+    {
+      iDeltaEnd = 0;
+    }
+
+    pcCU->setWedgePredDirDeltaEndSubParts( iDeltaEnd, uiAbsPartIdx, uiDepth );
+  }
+
+  UInt uiDC1, uiDC2;
+  xReadExGolombLevel( uiDC1, m_cDmmDataSCModel.get(0, 0, 1) );
+  Int iDC1 = uiDC1;
+  if ( uiDC1 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC1 = -iDC1;
+    }
+  }
+  xReadExGolombLevel( uiDC2, m_cDmmDataSCModel.get(0, 0, 1) );
+  Int iDC2 = uiDC2;
+  if ( uiDC2 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC2 = -iDC2;
+    }
+  }
+
+  pcCU->setWedgePredDirDeltaDC1SubParts( iDC1, uiAbsPartIdx, uiDepth );
+  pcCU->setWedgePredDirDeltaDC2SubParts( iDC2, uiAbsPartIdx, uiDepth );
+}
+#endif
+#if HHI_DMM_PRED_TEX
+#if LGE_DMM3_SIMP_C0044
+Void TDecSbac::xParseWedgePredTexInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+  Int iBits = g_aucWedgeTexPredBitsListIdx[iIntraIdx];
+
+  UInt uiSymbol, uiTabIdx = 0;
+  for ( Int i = 0; i < iBits; i++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmmDataSCModel.get(0, 0, 3) );
+    uiTabIdx += ( uiSymbol && i == 0 ) ? 1 : 0;
+    uiTabIdx += ( uiSymbol && i == 1 ) ? 2 : 0;
+    uiTabIdx += ( uiSymbol && i == 2 ) ? 4 : 0;
+    uiTabIdx += ( uiSymbol && i == 3 ) ? 8 : 0;
+    uiTabIdx += ( uiSymbol && i == 4 ) ? 16 : 0;
+    uiTabIdx += ( uiSymbol && i == 5 ) ? 32 : 0;
+    uiTabIdx += ( uiSymbol && i == 6 ) ? 64 : 0;
+    uiTabIdx += ( uiSymbol && i == 7 ) ? 128 : 0;
+    uiTabIdx += ( uiSymbol && i == 8 ) ? 256 : 0;
+    uiTabIdx += ( uiSymbol && i == 9 ) ? 512 : 0;
+    uiTabIdx += ( uiSymbol && i == 10 ) ? 1024 : 0;
+  }
+
+  pcCU->setWedgePredTexIntraTabIdxSubParts( uiTabIdx, uiAbsPartIdx, uiDepth );
+}
+#endif
+
+Void TDecSbac::xParseWedgePredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+#if LGE_DMM3_SIMP_C0044
+  xParseWedgePredTexInfo( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+  UInt uiDC1, uiDC2;
+  xReadExGolombLevel( uiDC1, m_cDmmDataSCModel.get(0, 0, 1) );
+  Int iDC1 = uiDC1;
+  if ( uiDC1 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC1 = -iDC1;
+    }
+  }
+  xReadExGolombLevel( uiDC2, m_cDmmDataSCModel.get(0, 0, 1) );
+  Int iDC2 = uiDC2;
+  if ( uiDC2 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC2 = -iDC2;
+    }
+  }
+
+  pcCU->setWedgePredTexDeltaDC1SubParts( iDC1, uiAbsPartIdx, uiDepth );
+  pcCU->setWedgePredTexDeltaDC2SubParts( iDC2, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecSbac::xParseContourPredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiDC1, uiDC2;
+  xReadExGolombLevel( uiDC1, m_cDmmDataSCModel.get(0, 0, 1) );
+  Int iDC1 = uiDC1;
+  if ( uiDC1 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC1 = -iDC1;
+    }
+  }
+  xReadExGolombLevel( uiDC2, m_cDmmDataSCModel.get(0, 0, 1) );
+  Int iDC2 = uiDC2;
+  if ( uiDC2 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC2 = -iDC2;
+    }
+  }
+
+  pcCU->setContourPredTexDeltaDC1SubParts( iDC1, uiAbsPartIdx, uiDepth );
+  pcCU->setContourPredTexDeltaDC2SubParts( iDC2, uiAbsPartIdx, uiDepth );
+}
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+Void TDecSbac::xParseEdgeIntraInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol = 0;
+
+  // 1. Top(0) or Left(1)
+  UChar ucLeft;
+  m_pcTDecBinIf->decodeBinEP( uiSymbol );
+  ucLeft = uiSymbol;
+
+  // 2. Start position (lowest bit first)
+  UChar ucStart = 0;
+  for( UInt ui = 0; ui < 6 - uiDepth; ui++ )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiSymbol );
+    ucStart |= (uiSymbol << ui);
+  }
+
+  // 3. Number of edges
+  UChar ucMax = 0;
+  for( UInt ui = 0; ui < 7 - uiDepth; ui++ )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiSymbol );
+    ucMax |= (uiSymbol << ui);
+  }
+  ucMax++; // +1
+
+  // 4. Edges
+  UChar* pucSymbolList = (UChar*) xMalloc( UChar, 256 * LGE_EDGE_INTRA_MAX_EDGE_NUM_PER_4x4 );
+  UInt uiCtxEdgeIntra = pcCU->getCtxEdgeIntra( uiAbsPartIdx );
+  for( Int iPtr = 0; iPtr < ucMax; iPtr++ )
+  {
+    UChar ucEdge = 0;
+    UInt  uiReorderEdge = 0;
+    // Left-friendly direction
+    // 0 (   0deg) => 0
+    // 1 (  45deg) => 10
+    // 2 ( -45deg) => 110
+    // 3 (  90deg) => 1110
+    // 4 ( -90deg) => 11110
+    // 5 ( 135deg) => 111110
+    // 6 (-135deg) => 111111
+    // Right-friendly direction
+    // 0 (   0deg) => 0
+    // 1 ( -45deg) => 10
+    // 2 (  45deg) => 110
+    // 3 ( -90deg) => 1110
+    // 4 (  90deg) => 11110
+    // 5 (-135deg) => 111110
+    // 6 ( 135deg) => 111111
+    // refer to a paper "An efficient chain code with Huffman coding"
+    for( UInt ui = 0; ui < 6; ui++ )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cEdgeIntraSCModel.get( 0, 0, uiCtxEdgeIntra ) );
+      ucEdge <<= 1;
+      ucEdge |= uiSymbol;
+      if( uiSymbol == 0 )
+        break;
+    }
+
+    switch( ucEdge )
+    {
+    case 0 :  // "0"
+      uiReorderEdge = 0;
+      break;
+    case 2 :  // "10"
+      uiReorderEdge = 1;
+      break;
+    case 6 :  // "110"
+      uiReorderEdge = 2;
+      break;
+    case 14 : // "1110"
+      uiReorderEdge = 3;
+      break;
+    case 30 : // "11110"
+      uiReorderEdge = 4;
+      break;
+    case 62 : // "111110"
+      uiReorderEdge = 5;
+      break;
+    case 63 : // "111111"
+      uiReorderEdge = 6;
+      break;
+    default :
+      printf("parseIntraEdgeChain: error (unknown code %d)\n",ucEdge);
+      assert(false);
+      break;
+    }
+    pucSymbolList[iPtr] = uiReorderEdge;
+  }
+  /////////////////////
+  // Edge Reconstruction
+  Bool* pbRegion = pcCU->getEdgePartition( uiAbsPartIdx );
+  pcCU->reconPartition( uiAbsPartIdx, uiDepth, ucLeft == 1, ucStart, ucMax, pucSymbolList, pbRegion );
+  xFree( pucSymbolList );
+}
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+Void TDecSbac::parseSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  
+  UInt uiSymbol = 0;
+  UInt uiCtxSDCFlag = pcCU->getCtxSDCFlag( uiAbsPartIdx );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cSDCFlagSCModel.get( 0, 0, uiCtxSDCFlag ) );
+  
+  if( uiSymbol == 1 )
+  {
+    pcCU->setPartSizeSubParts(SIZE_2Nx2N, uiAbsPartIdx, uiDepth);
+    
+    pcCU->setSDCFlagSubParts( true, uiAbsPartIdx, 0, uiDepth);
+    pcCU->setTrIdxSubParts(0, uiAbsPartIdx, uiDepth);
+    pcCU->setCbfSubParts(1, 1, 1, uiAbsPartIdx, uiDepth);
+  }
+}
+
+Void TDecSbac::parseSDCPredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  
+  assert( pcCU->getSDCFlag(uiAbsPartIdx) );
+  
+  UInt uiCtx            = 0;
+  
+  UInt uiMPModeIdx      = 0;
+  
+  for(Int i=0; i<RWTH_SDC_NUM_PRED_MODES-1; i++)
+  {
+    UInt uiIsMostProb = 0;
+    m_pcTDecBinIf->decodeBin( uiIsMostProb, m_cSDCPredModeSCModel.get( 0, i, uiCtx ) );
+    
+    if ( uiIsMostProb == 1 )
+      break;
+    
+    // else: get next most probable pred mode
+    uiMPModeIdx = (uiMPModeIdx+1)%RWTH_SDC_NUM_PRED_MODES;
+  }
+  
+  Int intraPredMode = g_auiSDCPredModes[uiMPModeIdx];
+  
+#if HHI_DMM_WEDGE_INTRA
+  if( intraPredMode == DMM_WEDGE_FULL_IDX )          { xParseWedgeFullInfo          ( pcCU, uiAbsPartIdx, uiDepth ); }
+  if( intraPredMode == DMM_WEDGE_PREDDIR_IDX )       { xParseWedgePredDirInfo       ( pcCU, uiAbsPartIdx, uiDepth ); }
+#endif
+  
+  pcCU->setLumaIntraDirSubParts((UChar)intraPredMode, uiAbsPartIdx, uiDepth);
+}
+
+Void TDecSbac::parseSDCResidualData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSegment )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  assert( pcCU->getSDCFlag(uiAbsPartIdx) );
+  assert( uiSegment < 2 );
+  
+  UInt uiResidual = 0;
+  UInt uiBit      = 0;
+  UInt uiAbsIdx   = 0;
+  UInt uiSign     = 0;
+  Int  iIdx       = 0;
+  
+  UInt uiMaxResidualBits  = GetBitsPerDepthValue();
+  assert( uiMaxResidualBits <= g_uiBitDepth );
+  
+  m_pcTDecBinIf->decodeBin(uiResidual, m_cSDCResidualFlagSCModel.get( 0, uiSegment, 0 ) );
+  
+  if (uiResidual)
+  {
+    // decode residual sign bit
+    m_pcTDecBinIf->decodeBin(uiSign, m_cSDCResidualSignFlagSCModel.get( 0, uiSegment, 0 ) );
+    
+    // decode residual magnitude
+    for (Int i=0; i<uiMaxResidualBits; i++)
+    {
+      m_pcTDecBinIf->decodeBin(uiBit, m_cSDCResidualSCModel.get( 0, uiSegment, i ) );
+      uiAbsIdx |= uiBit << i;
+    }
+    
+    uiAbsIdx += 1;
+    iIdx =(Int)(uiSign ? -1 : 1)*uiAbsIdx;
+  }
+  
+  pcCU->setSDCSegmentDCOffset(iIdx, uiSegment, uiAbsPartIdx);
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSbac.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSbac.h	(revision 341)
@@ -0,0 +1,279 @@
+/* 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-2012, 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     TDecSbac.h
+    \brief    SBAC decoder class (header)
+*/
+
+#ifndef __TDECSBAC__
+#define __TDECSBAC__
+
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+
+#include "TDecEntropy.h"
+#include "TDecBinCoder.h"
+#include "TLibCommon/ContextTables.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/ContextModel3DBuffer.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class SEImessages;
+
+/// SBAC decoder class
+class TDecSbac : public TDecEntropyIf
+{
+public:
+  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 decodeFlush();
+
+#if CABAC_INIT_FLAG
+  Void  resetEntropy (TComSlice* pSlice );
+#else
+  Void  resetEntropywithQPandInitIDC ( Int  iQp, Int iID);
+  Void  resetEntropy                 ( Int  iQp, Int iID      ) { resetEntropywithQPandInitIDC(iQp, iID);                                      }
+  Void  resetEntropy                 ( TComSlice* pcSlice     ) { resetEntropywithQPandInitIDC(pcSlice->getSliceQp(), pcSlice->getCABACinitIDC());}
+#endif
+  Void  setBitstream              ( TComInputBitstream* p  ) { m_pcBitstream = p; m_pcTDecBinIf->init( p ); }
+  
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void  parseVPS                  ( TComVPS* pcVPS )  {}
+#endif
+#if HHI_MPI || H3D_QTL
+  Void  parseSPS                  ( TComSPS* pcSPS, Bool bIsDepth ) {}
+#else
+  Void  parseSPS                  ( TComSPS* pcSPS         ) {}
+#endif
+  Void  parsePPS                  ( TComPPS* pcPPS, ParameterSetManagerDecoder *parameterSet         ) {}
+  Void  parseAPS                  ( TComAPS* pAPS          ) {}
+  void parseSEI(SEImessages&) {}
+
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  Void  parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet, bool isDepth) {}
+#else
+  Void  parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, AlfCUCtrlInfo &alfCUCtrl, AlfParamSet& alfParamSet) {}
+#endif
+
+  Void  parseTerminatingBit       ( UInt& ruiBit );
+#if H3D_IVMP
+  Void  parseMVPIdx               ( Int& riMVPIdx, Int iNumAMVPCands );
+#else
+  Void  parseMVPIdx               ( Int& riMVPIdx          );
+#endif
+  
+  Void  parseSaoUvlc              ( UInt& ruiVal           );
+  Void  parseSaoSvlc              ( Int&  riVal            );
+  Void  parseSaoMergeLeft         ( UInt&  ruiVal, UInt uiCompIdx   );
+  Void  parseSaoMergeUp           ( UInt&  ruiVal  );
+  Void  parseSaoTypeIdx           ( UInt&  ruiVal  );
+  Void  parseSaoUflc              ( UInt& ruiVal           );
+  Void  parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Bool bLFCrossSliceBoundaryFlag);
+  Void  parseSaoOffset            (SaoLcuParam* psSaoLcuParam);
+  
+#if RWTH_SDC_DLT_B0036
+  Void parseSDCFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseSDCPredMode    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseSDCResidualData     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPart );
+#endif
+private:
+  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  xReadGoRiceExGolomb ( UInt &ruiSymbol, UInt &ruiGoRiceParam );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void  xReadExGolombLevel  ( UInt& ruiSymbol, ContextModel& rcSCModel  );
+#endif
+#if HHI_DMM_WEDGE_INTRA
+  Void xParseWedgeFullInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void xParseWedgeFullDeltaInfo     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void xParseWedgePredDirInfo       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void xParseWedgePredDirDeltaInfo  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if HHI_DMM_PRED_TEX
+#if LGE_DMM3_SIMP_C0044
+  Void xParseWedgePredTexInfo       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void xParseWedgePredTexDeltaInfo  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void xParseContourPredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  
+#if LGE_EDGE_INTRA_A0070
+  Void xParseEdgeIntraInfo ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  
+private:
+  TComInputBitstream* m_pcBitstream;
+  TDecBinIf*        m_pcTDecBinIf;
+  
+  Int           m_iSliceGranularity; //!< slice granularity
+
+public:
+  Void parseAlfCtrlFlag   ( UInt &ruiAlfCtrlFlag );
+
+  /// set slice granularity
+  Void setSliceGranularity(Int iSliceGranularity)  {m_iSliceGranularity = iSliceGranularity;}
+
+  /// get slice granularity
+  Int  getSliceGranularity()                       {return m_iSliceGranularity;             }
+
+  Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if LGE_ILLUCOMP_B0045
+  Void parseICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void parseMergeIndex    ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth );
+#if H3D_IVRP
+  Void parseResPredFlag   ( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  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, UInt uiDepth );
+  Void parseRefFrmIdx     ( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  Void parseMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList );
+  
+  Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
+  Void parseQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void parseQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf );
+  
+  Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  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 readTileMarker   ( UInt& uiTileIdx, UInt uiBitsUsed );
+  Void updateContextTables( SliceType eSliceType, Int iQp );
+
+  Void  parseScalingList ( TComScalingList* scalingList ) {}
+
+private:
+  UInt m_uiLastDQpNonZero;
+  UInt m_uiLastQp;
+  
+  ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
+  Int                  m_numContextModels;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+#if LGE_ILLUCOMP_B0045
+  ContextModel3DBuffer m_cCUICFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+#if H3D_IVRP
+  ContextModel3DBuffer m_cResPredFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUAlfCtrlFlagSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+  
+  ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
+  ContextModel3DBuffer m_cCUSigSCModel;
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+  
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+  
+  ContextModel3DBuffer m_cALFFlagSCModel;
+  ContextModel3DBuffer m_cALFUvlcSCModel;
+  ContextModel3DBuffer m_cALFSvlcSCModel;
+  ContextModel3DBuffer m_cCUAMPSCModel;
+  ContextModel3DBuffer m_cSaoFlagSCModel;
+  ContextModel3DBuffer m_cSaoUvlcSCModel;
+  ContextModel3DBuffer m_cSaoSvlcSCModel;
+  ContextModel3DBuffer m_cSaoMergeLeftSCModel;
+  ContextModel3DBuffer m_cSaoMergeUpSCModel;
+  ContextModel3DBuffer m_cSaoTypeIdxSCModel;
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  ContextModel3DBuffer m_cDmmFlagSCModel;
+  ContextModel3DBuffer m_cDmmModeSCModel;
+  ContextModel3DBuffer m_cDmmDataSCModel;
+#endif
+#if LGE_EDGE_INTRA_A0070
+  ContextModel3DBuffer m_cEdgeIntraSCModel;
+#if LGE_EDGE_INTRA_DELTA_DC
+  ContextModel3DBuffer m_cEdgeIntraDeltaDCSCModel;
+#endif
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  ContextModel3DBuffer m_cSDCFlagSCModel;
+  
+  ContextModel3DBuffer m_cSDCResidualFlagSCModel;
+  ContextModel3DBuffer m_cSDCResidualSignFlagSCModel;
+  ContextModel3DBuffer m_cSDCResidualSCModel;
+  
+  ContextModel3DBuffer m_cSDCPredModeSCModel;
+#endif
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECSBAC_H__CFCAAA19_8110_47F4_9A16_810C4B5499D5__INCLUDED_)
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 341)
@@ -0,0 +1,409 @@
+/* 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-2012, 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     TDecSlice.cpp
+    \brief    slice decoder class
+*/
+
+#include "TDecSlice.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+TDecSlice::TDecSlice()
+{
+  m_pcBufferSbacDecoders = NULL;
+  m_pcBufferBinCABACs    = NULL;
+  m_pcBufferLowLatSbacDecoders = NULL;
+  m_pcBufferLowLatBinCABACs    = NULL;
+}
+
+TDecSlice::~TDecSlice()
+{
+}
+
+Void TDecSlice::create( TComSlice* pcSlice, Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth )
+{
+}
+
+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;
+  }
+}
+
+Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcCuDecoder       = pcCuDecoder;
+}
+
+Void TDecSlice::decompressSlice(TComInputBitstream* pcBitstream, 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())->getEntropySliceCurStartCUAddr()/rpcPic->getNumPartInCU());
+  Int   iStartCUAddr = rpcPic->getPicSym()->getCUOrderMap(iStartCUEncOrder);
+
+  // decoder don't need prediction & residual frame buffer
+  rpcPic->setPicYuvPred( 0 );
+  rpcPic->setPicYuvResi( 0 );
+  
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( rpcPic->getPOC() );
+  DTRACE_CABAC_T( "\n" );
+
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+  UInt uiTilesAcross   = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+  UInt iSymbolMode    = pcSlice->getPPS()->getEntropyCodingMode();
+  Int  iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+
+  if( iSymbolMode )
+  {
+    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);
+    }
+  }  
+  if( iSymbolMode )
+  {
+    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;
+  UInt uiTileLCUY;
+  UInt uiTileWidth;
+  UInt uiTileHeight;
+  Int iNumSubstreamsPerTile = 1; // if independent.
+
+  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;
+    uiTileLCUY = uiTileStartLCU / uiWidthInLCUs;
+    uiTileWidth = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getTileWidth();
+    uiTileHeight = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getTileHeight();
+    uiCol     = iCUAddr % uiWidthInLCUs;
+    uiLin     = iCUAddr / uiWidthInLCUs;
+    // inherit from TR if necessary, select substream to use.
+    if( iSymbolMode && pcSlice->getPPS()->getNumSubstreams() > 1 )
+    {
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+        iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(iCUAddr)*iNumSubstreamsPerTile
+                      + uiLin%iNumSubstreamsPerTile;
+      }
+      else
+      {
+        // dependent tiles => substreams are "per frame".
+        uiSubStrm = uiLin % iNumSubstreams;
+      }
+      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 && uiCol == uiTileLCUX)
+      {
+        // 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)))
+             ))||
+             (true/*bEnforceEntropySliceRestriction*/ &&
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             ((pcCUTR->getSCUAddr()+uiMaxParts-1) < pcSlice->getEntropySliceCurStartCUAddr()) ||
+             ((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 ( iSymbolMode && 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())) // !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
+      {
+#if CABAC_INIT_FLAG
+        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() );
+#else
+        m_pcEntropyDecoder->updateContextTables( pcSlice->getSliceType(), pcSlice->getSliceQp() );
+#endif
+      }
+      
+      Bool bTileMarkerFoundFlag = false;
+      TComInputBitstream *pcTmpPtr;
+      pcTmpPtr = ppcSubstreams[uiSubStrm]; // for CABAC
+
+      for (UInt uiIdx=0; uiIdx<pcTmpPtr->getTileMarkerLocationCount(); uiIdx++)
+      {
+        if ( pcTmpPtr->getByteLocation() == (pcTmpPtr->getTileMarkerLocation( uiIdx )+2) )
+        {
+          bTileMarkerFoundFlag = true;
+          break;
+        }
+      }
+
+      if (bTileMarkerFoundFlag)
+      {
+        UInt uiTileIdx;
+        // Read tile index
+        m_pcEntropyDecoder->readTileMarker( uiTileIdx, rpcPic->getPicSym()->getBitsUsedByTileIdx() );
+      }
+    }
+
+
+
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+    if ( pcSlice->getSPS()->getUseSAO() && pcSlice->getSaoInterleavingFlag() && pcSlice->getSaoEnabledFlag() )
+    {
+      pcSlice->getAPS()->getSaoParam()->bSaoFlag[0] = pcSlice->getSaoEnabledFlag();
+      if (iCUAddr == iStartCUAddr)
+      {
+        pcSlice->getAPS()->getSaoParam()->bSaoFlag[1] = pcSlice->getSaoEnabledFlagCb();
+        pcSlice->getAPS()->getSaoParam()->bSaoFlag[2] = pcSlice->getSaoEnabledFlagCr();
+      }
+      Int numCuInWidth     = pcSlice->getAPS()->getSaoParam()->numCuInWidth;
+      Int cuAddrInSlice = iCUAddr - pcSlice->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU();
+      Int cuAddrUpInSlice  = cuAddrInSlice - numCuInWidth;
+      Int rx = iCUAddr % numCuInWidth;
+      Int ry = iCUAddr / numCuInWidth;
+      pcSbacDecoder->parseSaoOneLcuInterleaving(rx, ry, pcSlice->getAPS()->getSaoParam(),pcCU, cuAddrInSlice, cuAddrUpInSlice, pcSlice->getSPS()->getLFCrossSliceBoundaryFlag() );
+    }
+
+    m_pcCuDecoder->decodeCU     ( pcCU, uiIsLast );
+    m_pcCuDecoder->decompressCU ( pcCU );
+    
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+    if( iSymbolMode )
+    {
+      /*If at the end of a LCU line but not at the end of a substream, perform CABAC flush*/
+      if (!uiIsLast && pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        if ((uiCol == uiTileLCUX+uiTileWidth-1) && (uiLin+iNumSubstreamsPerTile < uiTileLCUY+uiTileHeight))
+        {
+          m_pcEntropyDecoder->decodeFlush();
+        }
+      }
+      pcSbacDecoders[uiSubStrm].load(pcSbacDecoder);
+
+      //Store probabilities of second LCU in line into buffer
+      if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiCol == uiTileLCUX+1))
+      {
+        m_pcBufferSbacDecoders[uiTileCol].loadContexts( &pcSbacDecoders[uiSubStrm] );
+      }
+
+    }
+  }
+
+}
+
+ParameterSetManagerDecoder::ParameterSetManagerDecoder()
+: m_spsBuffer(256)
+, m_ppsBuffer(16)
+, m_apsBuffer(64)
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046 
+, m_vpsBuffer(16)
+#endif
+{
+
+}
+
+ParameterSetManagerDecoder::~ParameterSetManagerDecoder()
+{
+
+}
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+TComVPS* ParameterSetManagerDecoder::getPrefetchedVPS  (Int vpsId)
+{
+  if (m_vpsBuffer.getPS(vpsId) != NULL )
+  {
+    return m_vpsBuffer.getPS(vpsId);
+  }
+  else
+  {
+    return getVPS(vpsId);
+  }
+}
+#endif
+
+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);
+  }
+}
+
+TComAPS* ParameterSetManagerDecoder::getPrefetchedAPS  (Int apsId)
+{
+  if (m_apsBuffer.getPS(apsId) != NULL )
+  {
+    return m_apsBuffer.getPS(apsId);
+  }
+  else
+  {
+    return getAPS(apsId);
+  }
+}
+
+Void     ParameterSetManagerDecoder::applyPrefetchedPS()
+{
+  m_apsMap.mergePSList(m_apsBuffer);
+  m_ppsMap.mergePSList(m_ppsBuffer);
+  m_spsMap.mergePSList(m_spsBuffer);
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  m_vpsMap.mergePSList(m_vpsBuffer);
+#endif
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSlice.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecSlice.h	(revision 341)
@@ -0,0 +1,117 @@
+/* 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-2012, 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     TDecSlice.h
+    \brief    slice decoder class (header)
+*/
+
+#ifndef __TDECSLICE__
+#define __TDECSLICE__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComPic.h"
+#include "TDecEntropy.h"
+#include "TDecCu.h"
+#include "TDecSbac.h"
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice decoder class
+class TDecSlice
+{
+private:
+  // access channel
+  TDecEntropy*    m_pcEntropyDecoder;
+  TDecCu*         m_pcCuDecoder;
+  UInt            m_uiCurrSliceIdx;
+
+  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;
+  
+public:
+  TDecSlice();
+  virtual ~TDecSlice();
+  
+  Void  init              ( TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder );
+  Void  create            ( TComSlice* pcSlice, Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
+  Void  destroy           ();
+  
+  Void  decompressSlice   ( TComInputBitstream* pcBitstream, TComInputBitstream** ppcSubstreams,   TComPic*& rpcPic, TDecSbac* pcSbacDecoder, TDecSbac* pcSbacDecoders );
+};
+
+
+class ParameterSetManagerDecoder:public ParameterSetManager
+{
+public:
+  ParameterSetManagerDecoder();
+  virtual ~ParameterSetManagerDecoder();
+
+  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     storePrefetchedAPS(TComAPS *aps)  { m_apsBuffer.storePS( aps->getAPSID(), aps); };
+  TComAPS* getPrefetchedAPS  (Int apsId);
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void     storePrefetchedVPS(TComVPS *vps)  { m_vpsBuffer.storePS( vps->getVPSId(), vps); };
+  TComVPS* getPrefetchedVPS  (Int vpsId);
+#endif
+  Void     applyPrefetchedPS();
+
+private:
+  ParameterSetMap<TComSPS> m_spsBuffer; 
+  ParameterSetMap<TComPPS> m_ppsBuffer; 
+  ParameterSetMap<TComAPS> m_apsBuffer; 
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046 
+  ParameterSetMap<TComVPS> m_vpsBuffer;
+#endif
+};
+
+
+//! \}
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecTop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecTop.cpp	(revision 341)
@@ -0,0 +1,1423 @@
+/* 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-2012, 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     TDecTop.cpp
+    \brief    decoder class
+*/
+
+#include "NALread.h"
+#include "../../App/TAppDecoder/TAppDecTop.h"
+#include "TDecTop.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+
+CamParsCollector::CamParsCollector()
+: m_bInitialized( false )
+{
+  m_aaiCodedOffset         = new Int* [ MAX_VIEW_NUM ];
+  m_aaiCodedScale          = new Int* [ MAX_VIEW_NUM ];
+  m_aiViewOrderIndex       = new Int  [ MAX_VIEW_NUM ];
+#if QC_MVHEVC_B0046
+  m_aiViewId               = new Int  [ MAX_VIEW_NUM ];
+#endif
+  m_aiViewReceived         = new Int  [ MAX_VIEW_NUM ];
+  for( UInt uiId = 0; uiId < MAX_VIEW_NUM; uiId++ )
+  {
+    m_aaiCodedOffset      [ uiId ] = new Int [ MAX_VIEW_NUM ];
+    m_aaiCodedScale       [ uiId ] = new Int [ MAX_VIEW_NUM ];
+  }
+
+#if MERL_VSP_C0152
+  xCreateLUTs( (UInt)MAX_VIEW_NUM, (UInt)MAX_VIEW_NUM, m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+  m_iLog2Precision   = LOG2_DISP_PREC_LUT;
+  m_uiBitDepthForLUT = 8; // fixed
+#endif
+}
+
+CamParsCollector::~CamParsCollector()
+{
+  for( UInt uiId = 0; uiId < MAX_VIEW_NUM; uiId++ )
+  {
+    delete [] m_aaiCodedOffset      [ uiId ];
+    delete [] m_aaiCodedScale       [ uiId ];
+  }
+  delete [] m_aaiCodedOffset;
+  delete [] m_aaiCodedScale;
+  delete [] m_aiViewOrderIndex;
+  delete [] m_aiViewReceived;
+
+#if MERL_VSP_C0152
+  xDeleteArray( m_adBaseViewShiftLUT, MAX_VIEW_NUM, MAX_VIEW_NUM, 2 );
+  xDeleteArray( m_aiBaseViewShiftLUT, MAX_VIEW_NUM, MAX_VIEW_NUM, 2 );
+#endif
+}
+
+Void
+CamParsCollector::init( FILE* pCodedScaleOffsetFile )
+{
+  m_bInitialized            = true;
+  m_pCodedScaleOffsetFile   = pCodedScaleOffsetFile;
+  m_uiCamParsCodedPrecision = 0;
+  m_bCamParsVaryOverTime    = false;
+  m_iLastViewId             = -1;
+  m_iLastPOC                = -1;
+  m_uiMaxViewId             = 0;
+}
+
+#if MERL_VSP_C0152
+Void
+CamParsCollector::xCreateLUTs( UInt uiNumberSourceViews, UInt uiNumberTargetViews, Double****& radLUT, Int****& raiLUT)
+{
+  //AOF( m_uiBitDepthForLUT == 8 );
+  //AOF(radLUT == NULL && raiLUT == NULL );
+
+  uiNumberSourceViews = Max( 1, uiNumberSourceViews );
+  uiNumberTargetViews = Max( 1, uiNumberTargetViews );
+
+  radLUT         = new Double***[ uiNumberSourceViews ];
+  raiLUT         = new Int   ***[ uiNumberSourceViews ];
+
+  for( UInt uiSourceView = 0; uiSourceView < uiNumberSourceViews; uiSourceView++ )
+  {
+    radLUT        [ uiSourceView ] = new Double**[ uiNumberTargetViews ];
+    raiLUT        [ uiSourceView ] = new Int   **[ uiNumberTargetViews ];
+
+    for( UInt uiTargetView = 0; uiTargetView < uiNumberTargetViews; uiTargetView++ )
+    {
+      radLUT        [ uiSourceView ][ uiTargetView ]      = new Double*[ 2 ];
+      radLUT        [ uiSourceView ][ uiTargetView ][ 0 ] = new Double [ 257 ];
+      radLUT        [ uiSourceView ][ uiTargetView ][ 1 ] = new Double [ 257 ];
+
+      raiLUT        [ uiSourceView ][ uiTargetView ]      = new Int*   [ 2 ];
+      raiLUT        [ uiSourceView ][ uiTargetView ][ 0 ] = new Int    [ 257 ];
+      raiLUT        [ uiSourceView ][ uiTargetView ][ 1 ] = new Int    [ 257 ];
+    }
+  }
+}
+
+Void 
+  CamParsCollector::xInitLUTs( UInt uiSourceView, UInt uiTargetView, Int iScale, Int iOffset, Double****& radLUT, Int****& raiLUT)
+{
+  Int     iLog2DivLuma   = m_uiBitDepthForLUT + m_uiCamParsCodedPrecision + 1 - m_iLog2Precision;   AOF( iLog2DivLuma > 0 );
+  Int     iLog2DivChroma = iLog2DivLuma + 1;
+
+  iOffset <<= m_uiBitDepthForLUT;
+
+  Double dScale  = (Double) iScale  / (( Double ) ( 1 << iLog2DivLuma ));
+  Double dOffset = (Double) iOffset / (( Double ) ( 1 << iLog2DivLuma ));
+
+  // offsets including rounding offsets
+  Int64 iOffsetLuma   = iOffset + ( ( 1 << iLog2DivLuma   ) >> 1 );
+  Int64 iOffsetChroma = iOffset + ( ( 1 << iLog2DivChroma ) >> 1 );
+
+
+  for( UInt uiDepthValue = 0; uiDepthValue < 256; uiDepthValue++ )
+  {
+
+    // real-valued look-up tables
+    Double  dShiftLuma      = ( (Double)uiDepthValue * dScale + dOffset ) * Double( 1 << m_iLog2Precision );
+    Double  dShiftChroma    = dShiftLuma / 2;
+    radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ uiDepthValue ] = dShiftLuma;
+    radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ uiDepthValue ] = dShiftChroma;
+
+    // integer-valued look-up tables
+    Int64   iTempScale      = (Int64)uiDepthValue * iScale;
+    Int64   iShiftLuma      = ( iTempScale + iOffsetLuma   ) >> iLog2DivLuma;
+    Int64   iShiftChroma    = ( iTempScale + iOffsetChroma ) >> iLog2DivChroma;
+    raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ uiDepthValue ] = (Int)iShiftLuma;
+    raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ uiDepthValue ] = (Int)iShiftChroma;
+
+    // maximum deviation
+    //dMaxDispDev     = Max( dMaxDispDev,    fabs( Double( (Int) iTestScale   ) - dShiftLuma * Double( 1 << iLog2DivLuma ) ) / Double( 1 << iLog2DivLuma ) );
+    //dMaxRndDispDvL  = Max( dMaxRndDispDvL, fabs( Double( (Int) iShiftLuma   ) - dShiftLuma   ) );
+    //dMaxRndDispDvC  = Max( dMaxRndDispDvC, fabs( Double( (Int) iShiftChroma ) - dShiftChroma ) );
+  }
+
+  radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 256 ] = radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 255 ];
+  radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 256 ] = radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 255 ];
+  raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 256 ] = raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 255 ];
+  raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 256 ] = raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 255 ];
+}
+#endif // end MERL_VSP_C0152
+
+Void
+CamParsCollector::uninit()
+{
+  m_bInitialized = false;
+}
+
+Void
+CamParsCollector::setSlice( TComSlice* pcSlice )
+{
+  if( pcSlice == 0 )
+  {
+    AOF( xIsComplete() );
+    if( m_bCamParsVaryOverTime || m_iLastPOC == 0 )
+    {
+      xOutput( m_iLastPOC );
+    }
+    return;
+  }
+
+  AOF( pcSlice->getSPS()->getViewId() < MAX_VIEW_NUM );
+#if !FCO_FIX  // Under flexible coding order, depth may need the camera parameters
+  if ( pcSlice->getSPS()->isDepth  () )
+  {
+    return;
+  }
+#endif
+  Bool  bFirstAU          = ( pcSlice->getPOC()               == 0 );
+  Bool  bFirstSliceInAU   = ( pcSlice->getPOC()               != Int ( m_iLastPOC ) );
+  Bool  bFirstSliceInView = ( pcSlice->getSPS()->getViewId()  != UInt( m_iLastViewId ) || bFirstSliceInAU );
+  AOT(  bFirstSliceInAU  &&   pcSlice->getSPS()->getViewId()  != 0 );
+#if FCO_FIX
+#else
+  AOT( !bFirstSliceInAU  &&   pcSlice->getSPS()->getViewId()   < UInt( m_iLastViewId ) );
+#endif
+  AOT( !bFirstSliceInAU  &&   pcSlice->getSPS()->getViewId()   > UInt( m_iLastViewId + 1 ) );
+  AOT( !bFirstAU         &&   pcSlice->getSPS()->getViewId()   > m_uiMaxViewId );
+  if ( !bFirstSliceInView )
+  {
+    if( m_bCamParsVaryOverTime ) // check consistency of slice parameters here
+    {
+      UInt uiViewId = pcSlice->getSPS()->getViewId();
+      for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+      {
+        AOF( m_aaiCodedScale [ uiBaseId ][ uiViewId ] == pcSlice->getCodedScale    () [ uiBaseId ] );
+        AOF( m_aaiCodedOffset[ uiBaseId ][ uiViewId ] == pcSlice->getCodedOffset   () [ uiBaseId ] );
+        AOF( m_aaiCodedScale [ uiViewId ][ uiBaseId ] == pcSlice->getInvCodedScale () [ uiBaseId ] );
+        AOF( m_aaiCodedOffset[ uiViewId ][ uiBaseId ] == pcSlice->getInvCodedOffset() [ uiBaseId ] );
+      }
+    }
+    return;
+  }
+
+  if( bFirstSliceInAU )
+  {
+    if( !bFirstAU )
+    {
+      AOF( xIsComplete() );
+      xOutput( m_iLastPOC );
+    }
+    ::memset( m_aiViewReceived, 0x00, MAX_VIEW_NUM * sizeof( Int ) );
+  }
+
+  UInt uiViewId                 = pcSlice->getSPS()->getViewId();
+  m_aiViewReceived[ uiViewId ]  = 1;
+  if( bFirstAU )
+  {
+    m_uiMaxViewId                     = Max( m_uiMaxViewId, uiViewId );
+    m_aiViewOrderIndex[ uiViewId ]    = pcSlice->getSPS()->getViewOrderIdx();
+    if( uiViewId == 1 )
+    {
+      m_uiCamParsCodedPrecision       = pcSlice->getSPS()->getCamParPrecision     ();
+      m_bCamParsVaryOverTime          = pcSlice->getSPS()->hasCamParInSliceHeader ();
+    }
+    else if( uiViewId > 1 )
+    {
+      AOF( m_uiCamParsCodedPrecision == pcSlice->getSPS()->getCamParPrecision     () );
+      AOF( m_bCamParsVaryOverTime    == pcSlice->getSPS()->hasCamParInSliceHeader () );
+    }
+    for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+    {
+      if( m_bCamParsVaryOverTime )
+      {
+        m_aaiCodedScale [ uiBaseId ][ uiViewId ]  = pcSlice->getCodedScale    () [ uiBaseId ];
+        m_aaiCodedOffset[ uiBaseId ][ uiViewId ]  = pcSlice->getCodedOffset   () [ uiBaseId ];
+        m_aaiCodedScale [ uiViewId ][ uiBaseId ]  = pcSlice->getInvCodedScale () [ uiBaseId ];
+        m_aaiCodedOffset[ uiViewId ][ uiBaseId ]  = pcSlice->getInvCodedOffset() [ uiBaseId ];
+#if MERL_VSP_C0152
+        xInitLUTs( uiBaseId, uiViewId, m_aaiCodedScale[ uiBaseId ][ uiViewId ], m_aaiCodedOffset[ uiBaseId ][ uiViewId ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT);
+        xInitLUTs( uiViewId, uiBaseId, m_aaiCodedScale[ uiViewId ][ uiBaseId ], m_aaiCodedOffset[ uiViewId ][ uiBaseId ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT);
+#endif
+      }
+      else
+      {
+        m_aaiCodedScale [ uiBaseId ][ uiViewId ]  = pcSlice->getSPS()->getCodedScale    () [ uiBaseId ];
+        m_aaiCodedOffset[ uiBaseId ][ uiViewId ]  = pcSlice->getSPS()->getCodedOffset   () [ uiBaseId ];
+        m_aaiCodedScale [ uiViewId ][ uiBaseId ]  = pcSlice->getSPS()->getInvCodedScale () [ uiBaseId ];
+        m_aaiCodedOffset[ uiViewId ][ uiBaseId ]  = pcSlice->getSPS()->getInvCodedOffset() [ uiBaseId ];
+#if MERL_VSP_C0152
+        xInitLUTs( uiBaseId, uiViewId, m_aaiCodedScale[ uiBaseId ][ uiViewId ], m_aaiCodedOffset[ uiBaseId ][ uiViewId ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+        xInitLUTs( uiViewId, uiBaseId, m_aaiCodedScale[ uiViewId ][ uiBaseId ], m_aaiCodedOffset[ uiViewId ][ uiBaseId ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+#endif
+      }
+    }
+  }
+  else
+  {
+    AOF( m_aiViewOrderIndex[ uiViewId ] == pcSlice->getSPS()->getViewOrderIdx() );
+    if( m_bCamParsVaryOverTime )
+    {
+      for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+      {
+        m_aaiCodedScale [ uiBaseId ][ uiViewId ]  = pcSlice->getCodedScale    () [ uiBaseId ];
+        m_aaiCodedOffset[ uiBaseId ][ uiViewId ]  = pcSlice->getCodedOffset   () [ uiBaseId ];
+        m_aaiCodedScale [ uiViewId ][ uiBaseId ]  = pcSlice->getInvCodedScale () [ uiBaseId ];
+        m_aaiCodedOffset[ uiViewId ][ uiBaseId ]  = pcSlice->getInvCodedOffset() [ uiBaseId ];
+#if MERL_VSP_C0152
+        xInitLUTs( uiBaseId, uiViewId, m_aaiCodedScale[ uiBaseId ][ uiViewId ], m_aaiCodedOffset[ uiBaseId ][ uiViewId ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+        xInitLUTs( uiViewId, uiBaseId, m_aaiCodedScale[ uiViewId ][ uiBaseId ], m_aaiCodedOffset[ uiViewId ][ uiBaseId ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+#endif
+      }
+    }
+  }
+  m_iLastViewId = (Int)pcSlice->getSPS()->getViewId();
+  m_iLastPOC    = (Int)pcSlice->getPOC();
+}
+
+Bool
+CamParsCollector::xIsComplete()
+{
+  for( UInt uiView = 0; uiView <= m_uiMaxViewId; uiView++ )
+  {
+    if( m_aiViewReceived[ uiView ] == 0 )
+    {
+      return false;
+    }
+  }
+  return true;
+}
+
+Void
+CamParsCollector::xOutput( Int iPOC )
+{
+  if( m_pCodedScaleOffsetFile )
+  {
+    if( iPOC == 0 )
+    {
+      fprintf( m_pCodedScaleOffsetFile, "#     ViewId ViewOrderIdx\n" );
+      fprintf( m_pCodedScaleOffsetFile, "#----------- ------------\n" );
+      for( UInt uiViewId = 0; uiViewId <= m_uiMaxViewId; uiViewId++ )
+      {
+        fprintf( m_pCodedScaleOffsetFile, "%12d %12d\n", uiViewId, m_aiViewOrderIndex[ uiViewId ] );
+      }
+      fprintf( m_pCodedScaleOffsetFile, "\n\n");
+      fprintf( m_pCodedScaleOffsetFile, "# StartFrame     EndFrame   TargetView     BaseView   CodedScale  CodedOffset    Precision\n" );
+      fprintf( m_pCodedScaleOffsetFile, "#----------- ------------ ------------ ------------ ------------ ------------ ------------\n" );
+    }
+    if( iPOC == 0 || m_bCamParsVaryOverTime )
+    {
+      Int iS = iPOC;
+      Int iE = ( m_bCamParsVaryOverTime ? iPOC : ~( 1 << 31 ) );
+      for( UInt uiViewId = 0; uiViewId <= m_uiMaxViewId; uiViewId++ )
+      {
+        for( UInt uiBaseId = 0; uiBaseId <= m_uiMaxViewId; uiBaseId++ )
+        {
+          if( uiViewId != uiBaseId )
+          {
+            fprintf( m_pCodedScaleOffsetFile, "%12d %12d %12d %12d %12d %12d %12d\n",
+              iS, iE, uiViewId, uiBaseId, m_aaiCodedScale[ uiBaseId ][ uiViewId ], m_aaiCodedOffset[ uiBaseId ][ uiViewId ], m_uiCamParsCodedPrecision );
+          }
+        }
+      }
+    }
+  }
+}
+
+TDecTop::TDecTop()
+: m_SEIs(0)
+, m_tAppDecTop( NULL )
+, m_nalUnitTypeBaseView( NAL_UNIT_INVALID )
+{
+  m_pcPic = 0;
+  m_iGopSize      = 0;
+  m_bGopSizeSet   = false;
+  m_iMaxRefPicNum = 0;
+  m_uiValidPS = 0;
+#if ENC_DEC_TRACE
+  if(!g_hTrace) g_hTrace = fopen( "TraceDec.txt", "wb" );
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#endif
+  m_bRefreshPending = 0;
+  m_pocCRA = 0;
+  m_pocRandomAccess = MAX_INT;          
+  m_prevPOC                = MAX_INT;
+  m_bFirstSliceInPicture    = true;
+  m_bFirstSliceInSequence   = true;
+  m_pcCamParsCollector = 0;
+#if QC_MVHEVC_B0046
+  m_bFirstNal                  = false;
+#endif
+}
+
+TDecTop::~TDecTop()
+{
+#if ENC_DEC_TRACE
+  if(g_hTrace) fclose( g_hTrace );
+  g_hTrace=NULL;
+#endif
+}
+
+Void TDecTop::create()
+{
+  m_cGopDecoder.create();
+  m_apcSlicePilot = new TComSlice;
+  m_uiSliceIdx = m_uiLastSliceIdx = 0;
+}
+
+Void TDecTop::destroy()
+{
+  m_cGopDecoder.destroy();
+  
+  delete m_apcSlicePilot;
+  m_apcSlicePilot = NULL;
+  
+  m_cSliceDecoder.destroy();
+  m_tAppDecTop = NULL;
+
+#if DEPTH_MAP_GENERATION
+  m_cDepthMapGenerator.destroy();
+#endif
+#if H3D_IVRP
+  m_cResidualGenerator.destroy();
+#endif
+
+}
+
+Void TDecTop::init( TAppDecTop* pcTAppDecTop, Bool bFirstInstance )
+{
+  // initialize ROM
+  if( bFirstInstance )
+  {
+  initROM();
+  }
+  m_cGopDecoder.init( &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cAdaptiveLoopFilter, &m_cSAO
+#if DEPTH_MAP_GENERATION
+                    , &m_cDepthMapGenerator
+#endif
+#if H3D_IVRP
+                    , &m_cResidualGenerator
+#endif
+    );
+  m_cSliceDecoder.init( &m_cEntropyDecoder, &m_cCuDecoder );
+  m_cEntropyDecoder.init(&m_cPrediction);
+  m_tAppDecTop = pcTAppDecTop;
+#if DEPTH_MAP_GENERATION
+#if VIDYO_VPS_INTEGRATION
+  m_cDepthMapGenerator.init( &m_cPrediction, m_tAppDecTop->getVPSAccess(), m_tAppDecTop->getSPSAccess(), m_tAppDecTop->getAUPicAccess() );
+#else
+  m_cDepthMapGenerator.init( &m_cPrediction, m_tAppDecTop->getSPSAccess(), m_tAppDecTop->getAUPicAccess() );
+#endif
+#endif
+#if H3D_IVRP
+  m_cResidualGenerator.init( &m_cTrQuant, &m_cDepthMapGenerator );
+#endif
+}
+
+Void TDecTop::deletePicBuffer ( )
+{
+  TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
+  Int iSize = Int( m_cListPic.size() );
+  
+  for (Int i = 0; i < iSize; i++ )
+  {
+    if( *iterPic )
+    {
+      TComPic* pcPic = *(iterPic++);
+      pcPic->destroy();
+    
+      delete pcPic;
+      pcPic = NULL;
+    }
+  }
+  
+  // destroy ALF temporary buffers
+  m_cAdaptiveLoopFilter.destroy();
+
+  m_cSAO.destroy();
+  
+  m_cLoopFilter.        destroy();
+  
+  // destroy ROM
+  if(m_viewId == 0 && m_isDepth == false)
+  {
+    destroyROM();
+  }
+}
+
+#if H3D_IVRP
+Void
+TDecTop::deleteExtraPicBuffers( Int iPoc )
+{
+  TComPic*                      pcPic = 0;
+  TComList<TComPic*>::iterator  cIter = m_cListPic.begin();
+  TComList<TComPic*>::iterator  cEnd  = m_cListPic.end  ();
+  for( ; cIter != cEnd; cIter++ )
+  {
+    if( (*cIter)->getPOC() == iPoc )
+    {
+      pcPic = *cIter;
+      break;
+    }
+  }
+  //AOF( pcPic );
+  if ( pcPic )
+  {
+    pcPic->removeResidualBuffer   ();
+  }
+}
+#endif
+
+
+Void
+TDecTop::compressMotion( Int iPoc )
+{
+  TComPic*                      pcPic = 0;
+  TComList<TComPic*>::iterator  cIter = m_cListPic.begin();
+  TComList<TComPic*>::iterator  cEnd  = m_cListPic.end  ();
+  for( ; cIter != cEnd; cIter++ )
+  {
+    if( (*cIter)->getPOC() == iPoc )
+    {
+      pcPic = *cIter;
+      break;
+    }
+  }
+//  AOF( pcPic );
+  if ( pcPic )
+  {
+    pcPic->compressMotion();
+  }
+}
+
+Void TDecTop::xUpdateGopSize (TComSlice* pcSlice)
+{
+  if ( !pcSlice->isIntra() && !m_bGopSizeSet)
+  {
+    m_iGopSize    = pcSlice->getPOC();
+    m_bGopSizeSet = true;
+    
+    m_cGopDecoder.setGopSize(m_iGopSize);
+  }
+}
+
+Void TDecTop::xGetNewPicBuffer ( TComSlice* pcSlice, TComPic*& rpcPic )
+{
+  xUpdateGopSize(pcSlice);
+  
+  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer())+pcSlice->getSPS()->getNumReorderPics(pcSlice->getTLayer()) + 1; // +1 to have space for the picture currently being decoded
+
+#if DEPTH_MAP_GENERATION
+  UInt uiPdm                  = ( pcSlice->getSPS()->getViewId() ? pcSlice->getSPS()->getPredDepthMapGeneration() : m_tAppDecTop->getSPSAccess()->getPdm() );
+  Bool bNeedPrdDepthMapBuffer = ( !pcSlice->getSPS()->isDepth() && uiPdm > 0 );
+#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, true);
+    
+#if DEPTH_MAP_GENERATION
+    if( bNeedPrdDepthMapBuffer )
+    {
+      rpcPic->addPrdDepthMapBuffer( PDM_SUB_SAMP_EXP_X(uiPdm), PDM_SUB_SAMP_EXP_Y(uiPdm) );
+    }
+#endif
+    
+    m_cListPic.pushBack( rpcPic );
+    
+    return;
+  }
+  
+  Bool bBufferIsAvailable = false;
+  TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
+  while (iterPic != m_cListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if ( rpcPic->getReconMark() == false && rpcPic->getOutputMark() == false)
+    {
+      rpcPic->setOutputMark(false);
+      bBufferIsAvailable = true;
+      break;
+    }
+
+    if ( rpcPic->getSlice( 0 )->isReferenced() == false  && rpcPic->getOutputMark() == false)
+    {
+      rpcPic->setOutputMark(false);
+      rpcPic->setReconMark( false );
+      rpcPic->getPicYuvRec()->setBorderExtension( false );
+      bBufferIsAvailable = true;
+      break;
+    }
+  }
+  
+  if ( !bBufferIsAvailable )
+  {
+    //There is no room for this picture, either because of faulty encoder or dropped NAL. Extend the buffer.
+    m_iMaxRefPicNum++;
+    rpcPic = new TComPic();
+    m_cListPic.pushBack( rpcPic );
+  }
+  rpcPic->destroy();  
+  rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, true);
+#if DEPTH_MAP_GENERATION
+  if( bNeedPrdDepthMapBuffer && !rpcPic->getPredDepthMap() )
+  {
+    rpcPic->addPrdDepthMapBuffer( PDM_SUB_SAMP_EXP_X(uiPdm), PDM_SUB_SAMP_EXP_Y(uiPdm) );
+  }
+#endif
+}
+
+Void TDecTop::executeDeblockAndAlf(UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, Int& iSkipFrame, Int& iPOCLastDisplay)
+{
+  if (!m_pcPic)
+  {
+    /* nothing to deblock */
+    return;
+  }
+  
+  TComPic*&   pcPic         = m_pcPic;
+
+  // Execute Deblock and ALF only + Cleanup
+
+  m_cGopDecoder.decompressGop(NULL, pcPic, true);
+
+  TComSlice::sortPicList( m_cListPic ); // sorting for application output
+  ruiPOC              = pcPic->getSlice(m_uiSliceIdx-1)->getPOC();
+  rpcListPic          = &m_cListPic;  
+  m_cCuDecoder.destroy();        
+  m_bFirstSliceInPicture  = true;
+
+  return;
+}
+
+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();
+  cFillSlice.initTiles();
+  TComPic *cFillPic;
+  xGetNewPicBuffer(&cFillSlice,cFillPic);
+  cFillPic->getSlice(0)->setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
+  cFillPic->getSlice(0)->setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+  cFillPic->getSlice(0)->initSlice();
+  cFillPic->getSlice(0)->initTiles();
+
+  
+  
+  TComList<TComPic*>::iterator iterPic = m_cListPic.begin();
+  Int closestPoc = 1000000;
+  while ( iterPic != m_cListPic.end())
+  {
+    TComPic * rpcPic = *(iterPic++);
+    if(abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)<closestPoc&&abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)!=0&&rpcPic->getPicSym()->getSlice(0)->getPOC()!=m_apcSlicePilot->getPOC())
+    {
+      closestPoc=abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc);
+    }
+  }
+  iterPic = m_cListPic.begin();
+  while ( iterPic != m_cListPic.end())
+  {
+    TComPic *rpcPic = *(iterPic++);
+    if(abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)==closestPoc&&rpcPic->getPicSym()->getSlice(0)->getPOC()!=m_apcSlicePilot->getPOC())
+    {
+      printf("copying picture %d to %d (%d)\n",rpcPic->getPicSym()->getSlice(0)->getPOC() ,iLostPoc,m_apcSlicePilot->getPOC());
+      rpcPic->getPicYuvRec()->copyToPic(cFillPic->getPicYuvRec());
+      break;
+    }
+  }
+  cFillPic->setCurrSliceIdx(0);
+  for(Int i=0; i<cFillPic->getNumCUsInFrame(); i++) 
+  {
+    cFillPic->getCU(i)->initCU(cFillPic,i);
+  }
+  cFillPic->getSlice(0)->setReferenced(true);
+  cFillPic->getSlice(0)->setPOC(iLostPoc);
+  cFillPic->setReconMark(true);
+  cFillPic->setOutputMark(true);
+  if(m_pocRandomAccess == MAX_INT)
+  {
+    m_pocRandomAccess = iLostPoc;
+  }
+}
+
+
+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 VIDYO_VPS_INTEGRATION
+  TComVPS *vps = m_parameterSetManagerDecoder.getVPS(sps->getVPSId());
+  assert (vps != 0);
+#if !QC_REM_IDV_B0046
+  if( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )
+#else
+  if( (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA) && !sps->getViewId() )
+#endif
+    // VPS can only be activated on IDR or CRA...
+    getTAppDecTop()->getVPSAccess()->setActiveVPSId( sps->getVPSId() );
+#endif
+  m_apcSlicePilot->setPPS(pps);
+  m_apcSlicePilot->setSPS(sps);
+#if QC_MVHEVC_B0046
+  TComVPS *vps = m_parameterSetManagerDecoder.getVPS(sps->getVPSId());
+#endif
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  m_apcSlicePilot->setVPS(vps);
+#endif
+  pps->setSPS(sps);
+
+  if(sps->getUseSAO() || sps->getUseALF()|| sps->getScalingListFlag() || sps->getUseDF())
+  {
+    m_apcSlicePilot->setAPS( m_parameterSetManagerDecoder.getAPS(m_apcSlicePilot->getAPSId())  );
+  }
+  pps->setMinCuDQPSize( sps->getMaxCUWidth() >> ( pps->getMaxCuDQPDepth()) );
+
+  for (Int i = 0; i < sps->getMaxCUDepth() - 1; i++)
+  {
+    sps->setAMPAcc( i, sps->getUseAMP() );
+  }
+
+  for (Int i = sps->getMaxCUDepth() - 1; i < sps->getMaxCUDepth(); i++)
+  {
+    sps->setAMPAcc( i, 0 );
+  }
+
+  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  m_cLoopFilter.        create( g_uiMaxCUDepth );
+}
+
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay )
+{
+  TComPic*&   pcPic         = m_pcPic;
+  m_apcSlicePilot->initSlice();
+
+  //!!!KS: DIRTY HACK
+  m_apcSlicePilot->setPPSId(0);
+  m_apcSlicePilot->setPPS(m_parameterSetManagerDecoder.getPrefetchedPPS(0));
+  m_apcSlicePilot->setSPS(m_parameterSetManagerDecoder.getPrefetchedSPS(0));
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+#if QC_MVHEVC_B0046
+  m_apcSlicePilot->setIsDepth(false);
+#endif
+  m_apcSlicePilot->setVPS(m_parameterSetManagerDecoder.getPrefetchedVPS(0));
+#endif
+  m_apcSlicePilot->initTiles();
+#if QC_MVHEVC_B0046
+  m_apcSlicePilot->setViewId( nalu.m_layerId );
+  m_apcSlicePilot->setViewId( nalu.m_layerId );
+  m_apcSlicePilot->setViewOrderIdx(m_apcSlicePilot->getVPS()->getViewId(nalu.m_layerId), nalu.m_layerId);
+  Int iNumDirectRef = m_apcSlicePilot->getVPS()->getNumDirectRefLayer(nalu.m_layerId);
+  m_apcSlicePilot->getSPS()->setNumberOfUsableInterViewRefs(iNumDirectRef);
+  for(Int iNumIvRef = 0; iNumIvRef < iNumDirectRef; iNumIvRef ++)
+  {
+    Int iDeltaLayerId = m_apcSlicePilot->getVPS()->getDirectRefLayerId( nalu.m_layerId, iNumIvRef);
+    m_apcSlicePilot->getSPS()->setUsableInterViewRef(iNumIvRef, (iDeltaLayerId-nalu.m_layerId));
+  }
+#endif
+  if (m_bFirstSliceInPicture)
+  {
+    m_uiSliceIdx     = 0;
+    m_uiLastSliceIdx = 0;
+  }
+  m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
+  if (!m_bFirstSliceInPicture)
+  {
+    m_apcSlicePilot->copySliceInfo( pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
+  }
+
+  m_apcSlicePilot->setNalUnitType(nalu.m_nalUnitType);
+  if( m_bFirstSliceInPicture )
+  {
+#if QC_MVHEVC_B0046
+    if( nalu.m_layerId == 0 ) { m_nalUnitTypeBaseView = nalu.m_nalUnitType; }
+    else                     { m_nalUnitTypeBaseView = m_tAppDecTop->getTDecTop( 0, 0 )->getNalUnitTypeBaseView(); }
+#else
+#if VIDYO_VPS_INTEGRATION
+    if( m_apcSlicePilot->getVPS()->getViewId(nalu.m_layerId) == 0 ) { m_nalUnitTypeBaseView = nalu.m_nalUnitType; }
+    else { m_nalUnitTypeBaseView = m_tAppDecTop->getTDecTop( 0, m_apcSlicePilot->getVPS()->getDepthFlag(nalu.m_layerId) )->getNalUnitTypeBaseView(); }
+#else
+    if( nalu.m_viewId == 0 ) { m_nalUnitTypeBaseView = nalu.m_nalUnitType; }
+    else                     { m_nalUnitTypeBaseView = m_tAppDecTop->getTDecTop( 0, nalu.m_isDepth )->getNalUnitTypeBaseView(); }
+#endif
+#endif
+    m_apcSlicePilot->setNalUnitTypeBaseViewMvc( m_nalUnitTypeBaseView );
+  }
+
+  m_apcSlicePilot->setReferenced(nalu.m_nalRefFlag);
+  m_apcSlicePilot->setTLayerInfo(nalu.m_temporalId);
+
+  // ALF CU parameters should be part of the slice header -> needs to be fixed 
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder, m_cGopDecoder.getAlfCuCtrlParam(), m_cGopDecoder.getAlfParamSet(),m_apcSlicePilot->getVPS()->getDepthFlag(nalu.m_layerId));
+#else
+  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder, m_cGopDecoder.getAlfCuCtrlParam(), m_cGopDecoder.getAlfParamSet());
+#endif
+  // byte align
+  {
+    Int numBitsForByteAlignment = nalu.m_Bitstream->getNumBitsUntilByteAligned();
+    if ( numBitsForByteAlignment > 0 )
+    {
+      UInt bitsForByteAlignment;
+      nalu.m_Bitstream->read( numBitsForByteAlignment, bitsForByteAlignment );
+      assert( bitsForByteAlignment == ( ( 1 << numBitsForByteAlignment ) - 1 ) );
+    }
+  }
+
+  // exit when a new picture is found
+  if (m_apcSlicePilot->isNextSlice() && m_apcSlicePilot->getPOC()!=m_prevPOC && !m_bFirstSliceInSequence)
+  {
+    if (m_prevPOC >= m_pocRandomAccess)
+    {
+      m_prevPOC = m_apcSlicePilot->getPOC();
+      return true;
+    }
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+  // actual decoding starts here
+  xActivateParameterSets();
+  m_apcSlicePilot->initTiles();
+
+  if (m_apcSlicePilot->isNextSlice()) 
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+  m_bFirstSliceInSequence = false;
+  if (m_apcSlicePilot->isNextSlice())
+  {
+    // Skip pictures due to random access
+    if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
+    {
+      return false;
+    }
+  }
+  //detect lost reference picture and insert copy of earlier frame.
+  while(m_apcSlicePilot->checkThatAllRefPicsAreAvailable(m_cListPic, m_apcSlicePilot->getRPS(), true, m_pocRandomAccess) > 0)
+  {
+    xCreateLostPicture(m_apcSlicePilot->checkThatAllRefPicsAreAvailable(m_cListPic, m_apcSlicePilot->getRPS(), false)-1);
+  }
+  if (m_bFirstSliceInPicture)
+  {
+    // Buffer initialize for prediction.
+    m_cPrediction.initTempBuff();
+    m_apcSlicePilot->applyReferencePictureSet(m_cListPic, m_apcSlicePilot->getRPS());
+    //  Get a new picture buffer
+    xGetNewPicBuffer (m_apcSlicePilot, pcPic);
+
+#if INTER_VIEW_VECTOR_SCALING_C0115
+    pcPic->setViewOrderIdx( m_apcSlicePilot->getVPS()->getViewOrderIdx(nalu.m_layerId) );    // will be changed to view_id
+#endif
+    /* transfer any SEI messages that have been received to the picture */
+    pcPic->setSEIs(m_SEIs);
+    m_SEIs = NULL;
+
+    // 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( m_apcSlicePilot, m_apcSlicePilot->getSPS()->getPicWidthInLumaSamples(), m_apcSlicePilot->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#if DEPTH_MAP_GENERATION
+    UInt uiPdm = ( m_apcSlicePilot->getSPS()->getViewId() ? m_apcSlicePilot->getSPS()->getPredDepthMapGeneration() : m_tAppDecTop->getSPSAccess()->getPdm() );
+    m_cDepthMapGenerator.create( true, m_apcSlicePilot->getSPS()->getPicWidthInLumaSamples(), m_apcSlicePilot->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiBitDepth + g_uiBitIncrement, PDM_SUB_SAMP_EXP_X(uiPdm), PDM_SUB_SAMP_EXP_Y(uiPdm) );
+    TComDepthMapGenerator* pcDMG0 = m_tAppDecTop->getDecTop0()->getDepthMapGenerator();
+    if( m_apcSlicePilot->getSPS()->getViewId() == 1 && ( pcDMG0->getSubSampExpX() != PDM_SUB_SAMP_EXP_X(uiPdm) || pcDMG0->getSubSampExpY() != PDM_SUB_SAMP_EXP_Y(uiPdm) ) )
+    {
+      pcDMG0->create( true, m_apcSlicePilot->getSPS()->getPicWidthInLumaSamples(), m_apcSlicePilot->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiBitDepth + g_uiBitIncrement, PDM_SUB_SAMP_EXP_X(uiPdm), PDM_SUB_SAMP_EXP_Y(uiPdm) );
+    }
+#endif
+#if H3D_IVRP
+    m_cResidualGenerator.create( true, m_apcSlicePilot->getSPS()->getPicWidthInLumaSamples(), m_apcSlicePilot->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiBitDepth + g_uiBitIncrement );
+#endif
+  }
+
+  //  Set picture slice pointer
+  TComSlice*  pcSlice = m_apcSlicePilot;
+  Bool bNextSlice     = pcSlice->isNextSlice();
+
+  UInt uiCummulativeTileWidth;
+  UInt uiCummulativeTileHeight;
+  UInt i, j, p;
+
+
+  if( pcSlice->getPPS()->getColumnRowInfoPresent() == 1 )
+  {
+    //set NumColumnsMins1 and NumRowsMinus1
+    pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
+    pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
+
+    //create the TComTileArray
+    pcPic->getPicSym()->xCreateTComTileArray();
+
+    if( pcSlice->getPPS()->getUniformSpacingIdr() == 1)
+    {
+      //set the width for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+      {
+        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
+        {
+          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
+            setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
+            - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
+        }
+      }
+
+      //set the height for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+      {
+        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
+        {
+          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
+            setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
+            - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
+        }
+      }
+    }
+    else
+    {
+      //set the width for each tile
+      for(j=0; j < pcSlice->getPPS()->getNumRowsMinus1()+1; j++)
+      {
+        uiCummulativeTileWidth = 0;
+        for(i=0; i < pcSlice->getPPS()->getNumColumnsMinus1(); i++)
+        {
+          pcPic->getPicSym()->getTComTile(j * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + i)->setTileWidth( pcSlice->getPPS()->getColumnWidth(i) );
+          uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(i);
+        }
+        pcPic->getPicSym()->getTComTile(j * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + i)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
+      }
+
+      //set the height for each tile
+      for(j=0; j < pcSlice->getPPS()->getNumColumnsMinus1()+1; j++)
+      {
+        uiCummulativeTileHeight = 0;
+        for(i=0; i < pcSlice->getPPS()->getNumRowsMinus1(); i++)
+        { 
+          pcPic->getPicSym()->getTComTile(i * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcSlice->getPPS()->getRowHeight(i) );
+          uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(i);
+        }
+        pcPic->getPicSym()->getTComTile(i * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
+      }
+    }
+  }
+  else
+  {
+    //set NumColumnsMins1 and NumRowsMinus1
+    pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getSPS()->getNumColumnsMinus1() );
+    pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getSPS()->getNumRowsMinus1() );
+
+    //create the TComTileArray
+    pcPic->getPicSym()->xCreateTComTileArray();
+
+    //automatically set the column and row boundary if UniformSpacingIdr = 1
+    if( pcSlice->getSPS()->getUniformSpacingIdr() == 1 )
+    {
+      //set the width for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+      {
+        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
+        {
+          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
+            setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
+            - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
+        }
+      }
+
+      //set the height for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+      {
+        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
+        {
+          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
+            setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
+            - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
+        }
+      }
+    }
+    else
+    {
+      //set the width for each tile
+      for(j=0; j < pcSlice->getSPS()->getNumRowsMinus1()+1; j++)
+      {
+        uiCummulativeTileWidth = 0;
+        for(i=0; i < pcSlice->getSPS()->getNumColumnsMinus1(); i++)
+        {
+          pcPic->getPicSym()->getTComTile(j * (pcSlice->getSPS()->getNumColumnsMinus1()+1) + i)->setTileWidth( pcSlice->getSPS()->getColumnWidth(i) );
+          uiCummulativeTileWidth += pcSlice->getSPS()->getColumnWidth(i);
+        }
+        pcPic->getPicSym()->getTComTile(j * (pcSlice->getSPS()->getNumColumnsMinus1()+1) + i)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
+      }
+
+      //set the height for each tile
+      for(j=0; j < pcSlice->getSPS()->getNumColumnsMinus1()+1; j++)
+      {
+        uiCummulativeTileHeight = 0;
+        for(i=0; i < pcSlice->getSPS()->getNumRowsMinus1(); i++)
+        { 
+          pcPic->getPicSym()->getTComTile(i * (pcSlice->getSPS()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcSlice->getSPS()->getRowHeight(i) );
+          uiCummulativeTileHeight += pcSlice->getSPS()->getRowHeight(i);
+        }
+        pcPic->getPicSym()->getTComTile(i * (pcSlice->getSPS()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
+      }
+    }
+  }
+
+  pcPic->getPicSym()->xInitTiles();
+
+  //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 entropy slice into encoding order
+  pcSlice->setEntropySliceCurStartCUAddr( pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getEntropySliceCurStartCUAddr()) );
+  pcSlice->setEntropySliceCurEndCUAddr( pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getEntropySliceCurEndCUAddr()) );
+  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 (bNextSlice)
+  {
+    pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_cListPic); 
+
+    if ( !pcSlice->getPPS()->getEnableTMVPFlag() && pcPic->getTLayer() == 0 )
+    {
+      pcSlice->decodingMarkingForNoTMVP( m_cListPic, pcSlice->getPOC() );
+    }
+
+    // Set reference list 
+#if !QC_MVHEVC_B0046
+#if VIDYO_VPS_INTEGRATION
+    pcSlice->setViewId( pcSlice->getVPS()->getViewId(nalu.m_layerId) );
+    pcSlice->setIsDepth( pcSlice->getVPS()->getDepthFlag(nalu.m_layerId) );
+#else
+    pcSlice->setViewId(m_viewId);
+    pcSlice->setIsDepth(m_isDepth);
+#endif
+#endif
+
+#if INTER_VIEW_VECTOR_SCALING_C0115
+#if VIDYO_VPS_INTEGRATION
+    pcSlice->setViewOrderIdx( pcSlice->getVPS()->getViewOrderIdx(nalu.m_layerId) );        // will be changed to view_id
+#else
+    pcSlice->setViewOrderIdx( pcPic->getViewOrderIdx() );
+#endif
+#endif
+
+#if INTER_VIEW_VECTOR_SCALING_C0115
+    pcSlice->setIVScalingFlag( pcSlice->getVPS()->getIVScalingFlag());
+#endif
+
+    assert( m_tAppDecTop != NULL );
+    TComPic * const pcTexturePic = m_isDepth ? m_tAppDecTop->getPicFromView(  m_viewId, pcSlice->getPOC(), false ) : NULL;
+
+#if FLEX_CODING_ORDER_M23723
+    if (pcTexturePic != NULL)
+    {
+      assert( !m_isDepth || pcTexturePic != NULL );
+      pcSlice->setTexturePic( pcTexturePic );
+    }
+#else
+    assert( !m_isDepth || pcTexturePic != NULL );
+    pcSlice->setTexturePic( pcTexturePic );
+#endif
+
+
+    std::vector<TComPic*> apcInterViewRefPics = m_tAppDecTop->getInterViewRefPics( m_viewId, pcSlice->getPOC(), m_isDepth, pcSlice->getSPS() );
+    pcSlice->setRefPicListMvc( m_cListPic, apcInterViewRefPics );
+
+    // For generalized B
+    // note: maybe not existed case (always L0 is copied to L1 if L1 is empty)
+    if (pcSlice->isInterB() && pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0)
+    {
+      Int iNumRefIdx = pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+      pcSlice->setNumRefIdx        ( REF_PIC_LIST_1, iNumRefIdx );
+
+      for (Int iRefIdx = 0; iRefIdx < iNumRefIdx; iRefIdx++)
+      {
+        pcSlice->setRefPic(pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx), REF_PIC_LIST_1, iRefIdx);
+      }
+    }
+    if (pcSlice->isInterB())
+    {
+      Bool bLowDelay = true;
+      Int  iCurrPOC  = pcSlice->getPOC();
+      Int iRefIdx = 0;
+
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+
+      pcSlice->setCheckLDC(bLowDelay);            
+    }
+
+    //---------------
+    pcSlice->setRefPOCnViewListsMvc();
+
+    if(!pcSlice->getRefPicListModificationFlagLC())
+    {
+      pcSlice->generateCombinedList();
+    }
+
+#if !FIX_LGE_WP_FOR_3D_C0223
+    if( pcSlice->getRefPicListCombinationFlag() && pcSlice->getPPS()->getWPBiPredIdc()==1 && pcSlice->getSliceType()==B_SLICE )
+    {
+      pcSlice->setWpParamforLC();
+    }
+#endif
+    pcSlice->setNoBackPredFlag( false );
+    if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
+    {
+      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
+      {
+        pcSlice->setNoBackPredFlag( true );
+        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
+        {
+          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+          {
+            pcSlice->setNoBackPredFlag( false );
+            break;
+          }
+        }
+      }
+    }
+  }
+
+  pcPic->setCurrSliceIdx(m_uiSliceIdx);
+  if(pcSlice->getSPS()->getScalingListFlag())
+  {
+    if(pcSlice->getAPS()->getScalingListEnabled())
+    {
+      pcSlice->setScalingList ( pcSlice->getAPS()->getScalingList()  );
+      if(pcSlice->getScalingList()->getScalingListPresentFlag())
+      {
+        pcSlice->setDefaultScalingList();
+      }
+      m_cTrQuant.setScalingListDec(pcSlice->getScalingList());
+    }
+    m_cTrQuant.setUseScalingList(true);
+  }
+  else
+  {
+    m_cTrQuant.setFlatScalingList();
+    m_cTrQuant.setUseScalingList(false);
+  }
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( m_parameterSetManagerDecoder.getPrefetchedSPS(0)->getUseDMM() && g_aacWedgeLists.empty() )
+  {
+    initWedgeLists();
+  }
+#endif
+
+#if FCO_DVP_REFINE_C0132_C0170
+  if(m_bFirstSliceInPicture)
+  {
+    pcPic->setDepthCoded(false);
+
+    if(m_viewId != 0)
+    {
+      if( m_isDepth == 0)
+      {
+        TComPic * recDepthMapBuffer;
+        recDepthMapBuffer = m_tAppDecTop->getPicFromView( m_viewId, pcSlice->getPOC(), true );
+        pcPic->setRecDepthMap(recDepthMapBuffer);
+
+        if(recDepthMapBuffer != NULL)
+        {
+          pcPic->setDepthCoded(true);
+        }
+      }
+    }
+  }
+#endif
+
+
+#if MERL_VSP_C0152 // set BW LUT 
+  if( m_pcCamParsCollector ) // Initialize the LUT elements 
+  {
+    m_pcCamParsCollector->setSlice( pcSlice );
+  }
+  if( pcSlice->getViewId() !=0 )
+  {
+    TComPic* pcBaseTxtPic = m_tAppDecTop->getPicFromView(  0, pcSlice->getPOC(), false );  // get base view reconstructed texture
+    TComPic* pcBaseDepthPic = m_tAppDecTop->getPicFromView(  0, pcSlice->getPOC(), true ); // get base view reconstructed depth
+     pcSlice->setRefPicBaseTxt(pcBaseTxtPic);
+     pcSlice->setRefPicBaseDepth(pcBaseDepthPic);
+  }
+  getTAppDecTop()->setBWVSPLUT( pcSlice, pcSlice->getViewId(),  pcSlice->getPOC() ); // get the LUT for backward warping
+#endif
+
+  //  Decode a picture
+  m_cGopDecoder.decompressGop(nalu.m_Bitstream, pcPic, false);
+
+#if QC_IV_AS_LT_B0046
+  std::vector<TComPic*> apcInterViewRefPics = m_tAppDecTop->getInterViewRefPics( m_viewId, pcSlice->getPOC(), m_isDepth, pcSlice->getSPS() );
+  for( Int k = 0; k < apcInterViewRefPics.size(); k++ )
+  {
+    TComPic*  pcPicIv = apcInterViewRefPics[k];
+    pcPicIv->setIsLongTerm( 0 );
+  }
+#endif
+  if( m_pcCamParsCollector )
+  {
+    m_pcCamParsCollector->setSlice( pcSlice );
+  }
+
+  m_bFirstSliceInPicture = false;
+  m_uiSliceIdx++;
+
+  return false;
+}
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+Void TDecTop::xDecodeVPS()
+{
+  TComVPS* vps = new TComVPS();
+  
+  m_cEntropyDecoder.decodeVPS( vps );
+  m_parameterSetManagerDecoder.storePrefetchedVPS(vps);  
+#if !QC_MVHEVC_B0046
+  getTAppDecTop()->getVPSAccess()->addVPS( vps );
+#endif
+}
+#endif
+
+Void TDecTop::xDecodeSPS()
+{
+  TComSPS* sps = new TComSPS();
+  TComRPSList* rps = new TComRPSList();
+  sps->setRPSList(rps);
+#if HHI_MPI || H3D_QTL
+  m_cEntropyDecoder.decodeSPS( sps, m_isDepth );
+#else
+  m_cEntropyDecoder.decodeSPS( sps );
+#endif
+  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
+  m_cAdaptiveLoopFilter.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+}
+
+Void TDecTop::xDecodePPS()
+{
+  TComPPS* pps = new TComPPS();
+  m_cEntropyDecoder.decodePPS( pps, &m_parameterSetManagerDecoder );
+  m_parameterSetManagerDecoder.storePrefetchedPPS( pps );
+
+  //!!!KS: Activate parameter sets for parsing APS (unless dependency is resolved)
+  m_apcSlicePilot->setPPSId(pps->getPPSId());
+  xActivateParameterSets();
+  m_apcSlicePilot->initTiles();
+}
+
+Void TDecTop::xDecodeAPS()
+{
+  TComAPS  *aps = new TComAPS();
+  allocAPS (aps);
+  decodeAPS(aps);
+  m_parameterSetManagerDecoder.storePrefetchedAPS(aps);
+}
+
+Void TDecTop::xDecodeSEI()
+{
+  m_SEIs = new SEImessages;
+  m_cEntropyDecoder.decodeSEI(*m_SEIs);
+}
+
+Bool TDecTop::decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay)
+{
+  // Initialize entropy decoder
+  m_cEntropyDecoder.setEntropyDecoder (&m_cCavlcDecoder);
+  m_cEntropyDecoder.setBitstream      (nalu.m_Bitstream);
+
+  switch (nalu.m_nalUnitType)
+  {
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+    case NAL_UNIT_VPS:
+      xDecodeVPS();
+      return false;
+#endif
+    case NAL_UNIT_SPS:
+      xDecodeSPS();
+      return false;
+
+    case NAL_UNIT_PPS:
+      xDecodePPS();
+      return false;
+    case NAL_UNIT_APS:
+      xDecodeAPS();
+      return false;
+
+    case NAL_UNIT_SEI:
+      xDecodeSEI();
+      return false;
+
+    case NAL_UNIT_CODED_SLICE:
+    case NAL_UNIT_CODED_SLICE_IDR:
+#if !QC_REM_IDV_B0046
+    case NAL_UNIT_CODED_SLICE_IDV:
+#endif
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_TLA:
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay);
+      break;
+    default:
+      assert (1);
+  }
+
+  return false;
+}
+
+#if QC_MVHEVC_B0046
+Void TDecTop::xCopyVPS( TComVPS* pVPSV0 )
+{
+  m_parameterSetManagerDecoder.storePrefetchedVPS(pVPSV0);  
+}
+
+Void TDecTop::xCopySPS( TComSPS* pSPSV0 )
+{
+  TComSPS* sps = new TComSPS();
+  sps = pSPSV0;
+  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
+  m_cAdaptiveLoopFilter.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+}
+
+Void TDecTop::xCopyPPS(TComPPS* pPPSV0 )
+{
+  m_parameterSetManagerDecoder.storePrefetchedPPS( pPPSV0 );
+
+  //!!!KS: Activate parameter sets for parsing APS (unless dependency is resolved)
+  m_apcSlicePilot->setPPSId(pPPSV0->getPPSId());
+  xActivateParameterSets();
+  m_apcSlicePilot->initTiles();
+}
+#endif
+/** Function for checking if picture should be skipped because of random access
+ * \param iSkipFrame skip frame counter
+ * \param iPOCLastDisplay POC of last picture displayed
+ * \returns true if the picture shold be skipped in the random access.
+ * This function checks the skipping of pictures in the case of -s option random access.
+ * All pictures prior to the random access point indicated by the counter iSkipFrame are skipped.
+ * It also checks the type of Nal unit type at the random access point.
+ * If the random access point is CRA, pictures with POC equal to or greater than the CRA POC are decoded.
+ * If the random access point is IDR all pictures after the random access point are decoded.
+ * If the random access point is not IDR or CRA, 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 random 
+ * access point there is no guarantee that the decoder will not crash.
+ */
+Bool TDecTop::isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay)
+{
+  if (iSkipFrame) 
+  {
+    iSkipFrame--;   // decrement the counter
+    return true;
+  }
+  else if (m_pocRandomAccess == MAX_INT) // start of random access point, m_pocRandomAccess has not been set yet.
+  {
+    if( m_apcSlicePilot->getNalUnitTypeBaseViewMvc() == NAL_UNIT_CODED_SLICE_CRA )
+    {
+      m_pocRandomAccess = m_apcSlicePilot->getPOC(); // set the POC random access since we need to skip the reordered pictures in CRA.
+    }
+    else if( m_apcSlicePilot->getNalUnitTypeBaseViewMvc() == NAL_UNIT_CODED_SLICE_IDR )
+    {
+      m_pocRandomAccess = 0; // no need to skip the reordered pictures in IDR, they are decodable.
+    }
+    else 
+    {
+      static bool warningMessage = false;
+      if(!warningMessage)
+      {
+        printf("\nWarning: this is not a valid random access point and the data is discarded until the first CRA picture");
+        warningMessage = true;
+      }
+      return true;
+    }
+  }
+  else if (m_apcSlicePilot->getPOC() < m_pocRandomAccess)  // skip the reordered pictures if necessary
+  {
+    iPOCLastDisplay++;
+    return true;
+  }
+  // if we reach here, then the picture is not skipped.
+  return false; 
+}
+
+Void TDecTop::allocAPS (TComAPS* pAPS)
+{
+  // we don't know the SPS before it has been activated. These fields could exist
+  // depending on the corresponding flags in the APS, but SAO/ALF allocation functions will
+  // have to be moved for that
+  pAPS->createScalingList();
+  pAPS->createSaoParam();
+  m_cSAO.allocSaoParam(pAPS->getSaoParam());
+  pAPS->createAlfParam();
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecTop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibDecoder/TDecTop.h	(revision 341)
@@ -0,0 +1,300 @@
+/* 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-2012, 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     TDecTop.h
+    \brief    decoder class (header)
+*/
+
+#ifndef __TDECTOP__
+#define __TDECTOP__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComDepthMapGenerator.h"
+#include "TLibCommon/SEI.h"
+
+#include "TDecGop.h"
+#include "TDecEntropy.h"
+#include "TDecSbac.h"
+#include "TDecCAVLC.h"
+
+struct InputNALUnit;
+
+//! \ingroup TLibDecoder
+//! \{
+
+#define APS_RESERVED_BUFFER_SIZE 2 //!< must be equal to or larger than 2 to handle bitstream parsing
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TAppDecTop;
+
+class CamParsCollector
+{
+public:
+  CamParsCollector  ();
+  ~CamParsCollector ();
+
+  Void  init        ( FILE* pCodedScaleOffsetFile );
+  Void  uninit      ();
+  Void  setSlice    ( TComSlice* pcSlice );
+
+  Bool  isInitialized() const { return m_bInitialized; }
+
+#if MERL_VSP_C0152
+  Int**** getBaseViewShiftLUTI()  { return m_aiBaseViewShiftLUT;   }
+#endif
+private:
+  Bool  xIsComplete ();
+  Void  xOutput     ( Int iPOC );
+
+private:
+  Bool    m_bInitialized;
+  FILE*   m_pCodedScaleOffsetFile;
+
+  Int**   m_aaiCodedOffset;
+  Int**   m_aaiCodedScale;
+  Int*    m_aiViewOrderIndex;
+#if QC_MVHEVC_B0046
+  Int*    m_aiViewId;
+#endif
+  Int*    m_aiViewReceived;
+  UInt    m_uiCamParsCodedPrecision;
+  Bool    m_bCamParsVaryOverTime;
+  Int     m_iLastViewId;
+  Int     m_iLastPOC;
+  UInt    m_uiMaxViewId;
+
+#if MERL_VSP_C0152
+  UInt    m_uiBitDepthForLUT;
+  UInt    m_iLog2Precision;
+  UInt    m_uiInputBitDepth;
+  // look-up tables
+  Double****   m_adBaseViewShiftLUT;       ///< Disparity LUT
+  Int****      m_aiBaseViewShiftLUT;       ///< Disparity LUT
+  Void xCreateLUTs( UInt uiNumberSourceViews, UInt uiNumberTargetViews, Double****& radLUT, Int****& raiLUT);
+  Void xInitLUTs( UInt uiSourceView, UInt uiTargetView, Int iScale, Int iOffset, Double****& radLUT, Int****& raiLUT);
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize1, UInt uiSize2, UInt uiSize3 );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize1, UInt uiSize2 );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize );
+#endif
+
+};
+
+#if MERL_VSP_C0152
+template <class T>
+Void CamParsCollector::xDeleteArray( T*& rpt, UInt uiSize1, UInt uiSize2, UInt uiSize3 )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize1; uiK++ )
+    {
+      for( UInt uiL = 0; uiL < uiSize2; uiL++ )
+      {
+        for( UInt uiM = 0; uiM < uiSize3; uiM++ )
+        {
+          delete[] rpt[ uiK ][ uiL ][ uiM ];
+        }
+        delete[] rpt[ uiK ][ uiL ];
+      }
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+template <class T>
+Void CamParsCollector::xDeleteArray( T*& rpt, UInt uiSize1, UInt uiSize2 )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize1; uiK++ )
+    {
+      for( UInt uiL = 0; uiL < uiSize2; uiL++ )
+      {
+        delete[] rpt[ uiK ][ uiL ];
+      }
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+template <class T>
+Void CamParsCollector::xDeleteArray( T*& rpt, UInt uiSize )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize; uiK++ )
+    {
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+#endif
+
+/// decoder class
+class TDecTop
+{
+private:
+  Int                     m_iGopSize;
+  Bool                    m_bGopSizeSet;
+  int                     m_iMaxRefPicNum;
+  
+  Bool                    m_bRefreshPending;    ///< refresh pending flag
+  Int                     m_pocCRA;            ///< POC number of the latest CRA picture
+  Int                     m_pocRandomAccess;   ///< POC number of the random access point (the first IDR or CRA picture)
+
+  UInt                    m_uiValidPS;
+  TComList<TComPic*>      m_cListPic;         //  Dynamic buffer
+  ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
+  TComRPSList             m_RPSList;
+  TComSlice*              m_apcSlicePilot;
+  
+  SEImessages *m_SEIs; ///< "all" SEI messages.  If not NULL, we own the object.
+
+  // functional classes
+  TComPrediction          m_cPrediction;
+  TComTrQuant             m_cTrQuant;
+  TDecGop                 m_cGopDecoder;
+  TDecSlice               m_cSliceDecoder;
+  TDecCu                  m_cCuDecoder;
+  TDecEntropy             m_cEntropyDecoder;
+  TDecCavlc               m_cCavlcDecoder;
+  TDecSbac                m_cSbacDecoder;
+  TDecBinCABAC            m_cBinCABAC;
+  TComLoopFilter          m_cLoopFilter;
+  TComAdaptiveLoopFilter  m_cAdaptiveLoopFilter;
+  TComSampleAdaptiveOffset m_cSAO;
+
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator   m_cDepthMapGenerator;
+#endif
+#if H3D_IVRP
+  TComResidualGenerator   m_cResidualGenerator;
+#endif
+
+  Bool isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay);
+  TComPic*                m_pcPic;
+  UInt                    m_uiSliceIdx;
+  UInt                    m_uiLastSliceIdx;
+  Int                     m_prevPOC;
+  Bool                    m_bFirstSliceInPicture;
+  Bool                    m_bFirstSliceInSequence;
+
+  Int                     m_viewId;
+  Bool                    m_isDepth;
+  TAppDecTop*             m_tAppDecTop;
+  CamParsCollector*       m_pcCamParsCollector;
+  NalUnitType             m_nalUnitTypeBaseView;  
+
+public:
+  TDecTop();
+  virtual ~TDecTop();
+  
+  Void  create  ();
+  Void  destroy ();
+
+  void setPictureDigestEnabled(bool enabled) { m_cGopDecoder.setPictureDigestEnabled(enabled); }
+  
+  Void  init( TAppDecTop* pcTAppDecTop, Bool bFirstInstance );
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay);
+  
+  Void  deletePicBuffer();
+#if QC_MVHEVC_B0046
+  Void      xCopySPS( TComSPS* pSPSV0);
+  Void      xCopyPPS( TComPPS* pPPSV0);
+  Void      xCopyVPS( TComVPS* pVPSV0);
+#endif
+#if H3D_IVRP
+  Void      deleteExtraPicBuffers   ( Int iPoc );
+#endif
+  Void  compressMotion       ( Int iPoc );
+
+  Void executeDeblockAndAlf(UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, Int& iSkipFrame,  Int& iPOCLastDisplay);
+
+  Void setViewId(Int viewId)      { m_viewId = viewId;}
+  Int  getViewId()                { return m_viewId  ;}
+  Void setIsDepth( Bool isDepth ) { m_isDepth = isDepth; }
+
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator*  getDepthMapGenerator  () { return &m_cDepthMapGenerator; }
+#endif
+
+  Void setCamParsCollector( CamParsCollector* pcCamParsCollector ) { m_pcCamParsCollector = pcCamParsCollector; }
+
+  TComList<TComPic*>* getListPic()                              { return &m_cListPic; }
+  Void                setTAppDecTop( TAppDecTop* pcTAppDecTop ) { m_tAppDecTop = pcTAppDecTop; }
+  TAppDecTop*         getTAppDecTop()                           { return  m_tAppDecTop; }
+  NalUnitType         getNalUnitTypeBaseView()                  { return m_nalUnitTypeBaseView; }
+#if QC_MVHEVC_B0046
+  bool                m_bFirstNal; //used to copy SPS, PPS, VPS
+  ParameterSetManagerDecoder* xGetParaSetDec ()        {return  &m_parameterSetManagerDecoder;}
+#endif
+
+protected:
+  Void  xGetNewPicBuffer  (TComSlice* pcSlice, TComPic*& rpcPic);
+  Void  xUpdateGopSize    (TComSlice* pcSlice);
+  Void  xCreateLostPicture (Int iLostPOC);
+
+  Void      decodeAPS( TComAPS* cAPS) { m_cEntropyDecoder.decodeAPS(cAPS); };
+  Void      xActivateParameterSets();
+  Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay);
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void      xDecodeVPS();
+#endif
+  Void      xDecodeSPS();
+  Void      xDecodePPS();
+  Void      xDecodeAPS();
+  Void      xDecodeSEI();
+
+  Void      allocAPS (TComAPS* pAPS); //!< memory allocation for APS
+};// END CLASS DEFINITION TDecTop
+
+
+//! \}
+
+#endif // __TDECTOP__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 341)
@@ -0,0 +1,86 @@
+/* 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-2012, 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
+
+#include <ostream>
+#include "TLibCommon/AccessUnit.h"
+#include "NALwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/**
+ * write all NALunits in au to bytestream out in a manner satisfying
+ * AnnexB of AVC.  NALunits are written in the order they are found in au.
+ * the zero_byte word is appended to:
+ *  - the initial startcode in the access unit,
+ *  - any SPS/PPS nal units
+ */
+static std::vector<unsigned> writeAnnexB(std::ostream& out, const AccessUnit& au)
+{
+  std::vector<unsigned> annexBsizes;
+
+  for (AccessUnit::const_iterator it = au.begin(); it != au.end(); it++)
+  {
+    const NALUnitEBSP& nalu = **it;
+    unsigned size = 0; /* size of annexB unit in bytes */
+
+    static const char start_code_prefix[] = {0,0,0,1};
+    if (it == au.begin() || nalu.m_nalUnitType == NAL_UNIT_SPS || nalu.m_nalUnitType == NAL_UNIT_PPS)
+    {
+      /* From AVC, When any of the following conditions are fulfilled, the
+       * zero_byte syntax element shall be present:
+       *  - the nal_unit_type within the nal_unit() is equal to 7 (sequence
+       *    parameter set) or 8 (picture parameter set),
+       *  - the byte stream NAL unit syntax structure contains the first NAL
+       *    unit of an access unit in decoding order, as specified by subclause
+       *    7.4.1.2.3.
+       */
+      out.write(start_code_prefix, 4);
+      size += 4;
+    }
+    else
+    {
+      out.write(start_code_prefix+1, 3);
+      size += 3;
+    }
+    out << nalu.m_nalUnitData.str();
+    size += unsigned(nalu.m_nalUnitData.str().size());
+
+    annexBsizes.push_back(size);
+  }
+
+  return annexBsizes;
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/NALwrite.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/NALwrite.cpp	(revision 341)
@@ -0,0 +1,197 @@
+/* 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-2012, 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 <vector>
+#include <algorithm>
+#include <ostream>
+
+#include "TLibCommon/NAL.h"
+#include "TLibCommon/TComBitStream.h"
+#include "NALwrite.h"
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+static const char emulation_prevention_three_byte[] = {3};
+
+/**
+ * write nalu to bytestream out, performing RBSP anti startcode
+ * emulation as required.  nalu.m_RBSPayload must be byte aligned.
+ */
+void write(ostream& out, OutputNALUnit& nalu)
+{
+  TComOutputBitstream bsNALUHeader;
+
+  bsNALUHeader.write(0,1); // forbidden_zero_flag
+  bsNALUHeader.write(nalu.m_nalRefFlag? 1 : 0, 1); // nal_ref_flag
+  bsNALUHeader.write(nalu.m_nalUnitType, 6);          // nal_unit_type
+
+#if QC_MVHEVC_B0046
+  bsNALUHeader.write(nalu.m_layerId,        5); // when nal_ref_flag is signalled, 5 bits here. otherwise, 6 bits
+  bsNALUHeader.write(nalu.m_temporalId + 1, 3); // temporal_id
+#else
+#if VIDYO_VPS_INTEGRATION
+  bsNALUHeader.write(nalu.m_temporalId, 3); // temporal_id
+  bsNALUHeader.write(nalu.m_layerId + 1, 5); // layer_id_plus1
+#else
+  bsNALUHeader.write(nalu.m_temporalId, 3); // temporal_id
+ // bsNALUHeader.write(1, 5); // reserved_one_5bits
+  bsNALUHeader.write(nalu.m_viewId+1,4); 
+  bsNALUHeader.write(nalu.m_isDepth,1);
+#endif
+#endif 
+  out.write(bsNALUHeader.getByteStream(), bsNALUHeader.getByteStreamLength());
+
+  /* write out rsbp_byte's, inserting any required
+   * emulation_prevention_three_byte's */
+  /* 7.4.1 ...
+   * emulation_prevention_three_byte is a byte equal to 0x03. When an
+   * emulation_prevention_three_byte is present in the NAL unit, it shall be
+   * discarded by the decoding process.
+   * The last byte of the NAL unit shall not be equal to 0x00.
+   * Within the NAL unit, the following three-byte sequences shall not occur at
+   * any byte-aligned position:
+   *  - 0x000000
+   *  - 0x000001
+   *  - 0x000002
+   * Within the NAL unit, any four-byte sequence that starts with 0x000003
+   * other than the following sequences shall not occur at any byte-aligned
+   * position:
+   *  - 0x00000300
+   *  - 0x00000301
+   *  - 0x00000302
+   *  - 0x00000303
+   */
+  vector<uint8_t>& rbsp   = nalu.m_Bitstream.getFIFO();
+  UInt uiTileMarkerCount  = nalu.m_Bitstream.getTileMarkerLocationCount();
+
+  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);
+
+    UInt uiDistance = (UInt)(found - rbsp.begin());
+    for ( UInt uiMrkrIdx = 0; uiMrkrIdx < uiTileMarkerCount ; uiMrkrIdx++ )
+    {    
+      UInt uiByteLocation   = nalu.m_Bitstream.getTileMarkerLocation( uiMrkrIdx );
+      if (found != rbsp.end() && uiByteLocation > (uiDistance - 2) )
+      {
+        nalu.m_Bitstream.setTileMarkerLocation( uiMrkrIdx, uiByteLocation+1 );
+      }
+    }
+    it = found;
+    if (found != rbsp.end())
+    {
+      it = rbsp.insert(found, emulation_prevention_three_byte[0]);
+    }
+  }
+
+  // Insert tile markers
+  TComOutputBitstream cTileMarker;
+  UInt uiMarker = 0x000002;
+  cTileMarker.write(uiMarker, 24);
+  for ( UInt uiInsertIdx   = 0; uiInsertIdx < uiTileMarkerCount ; uiInsertIdx++ )
+  {
+    UInt uiByteLocation   = nalu.m_Bitstream.getTileMarkerLocation( uiInsertIdx );
+    nalu.m_Bitstream.insertAt( cTileMarker, uiByteLocation ); // 0x000002
+
+    // update tile marker byte locations of yet to be written markers
+    for ( UInt uiUpdateLOCIdx = uiInsertIdx+1; uiUpdateLOCIdx < uiTileMarkerCount; uiUpdateLOCIdx++ )
+    {
+      UInt uiLocation = nalu.m_Bitstream.getTileMarkerLocation( uiUpdateLOCIdx );
+      nalu.m_Bitstream.setTileMarkerLocation( uiUpdateLOCIdx, uiLocation + 3 );
+    }
+  }
+  out.write((char*)&(*rbsp.begin()), rbsp.end() - rbsp.begin());
+
+
+  /* 7.4.1.1
+   * ... when the last byte of the RBSP data is equal to 0x00 (which can
+   * only occur when the RBSP ends in a cabac_zero_word), a final byte equal
+   * to 0x03 is appended to the end of the data.
+   */
+  if (rbsp.back() == 0x00)
+  {
+    out.write(emulation_prevention_three_byte, 1);
+  }
+}
+
+/**
+ * Write rbsp_trailing_bits to bs causing it to become byte-aligned
+ */
+void writeRBSPTrailingBits(TComOutputBitstream& bs)
+{
+  bs.write( 1, 1 );
+  bs.writeAlignZero();
+}
+
+#if !QC_MVHEVC_B0046
+/**
+ * Copy NALU from naluSrc to naluDest
+ */
+void copyNaluData(OutputNALUnit& naluDest, const OutputNALUnit& naluSrc)
+{
+  naluDest.m_nalUnitType = naluSrc.m_nalUnitType;
+  naluDest.m_nalRefFlag  = naluSrc.m_nalRefFlag;
+#if !VIDYO_VPS_INTEGRATION
+  naluDest.m_viewId      = naluSrc.m_viewId;
+  naluDest.m_isDepth     = naluSrc.m_isDepth;
+#endif
+  naluDest.m_temporalId  = naluSrc.m_temporalId;
+#if VIDYO_VPS_INTEGRATION
+  naluDest.m_layerId = naluSrc.m_layerId;
+#else
+  
+#endif
+  naluDest.m_Bitstream   = naluSrc.m_Bitstream;
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/NALwrite.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/NALwrite.h	(revision 341)
@@ -0,0 +1,101 @@
+/* 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-2012, 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
+
+#include <ostream>
+
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/NAL.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/**
+ * A convenience wrapper to NALUnit that also provides a
+ * bitstream object.
+ */
+struct OutputNALUnit : public NALUnit
+{
+  /**
+   * construct an OutputNALunit structure with given header values and
+   * storage for a bitstream.  Upon construction the NALunit header is
+   * written to the bitstream.
+   */
+  OutputNALUnit(
+    NalUnitType nalUnitType,
+    Bool nalRefFlag,
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+    unsigned layerId,
+#else
+    Int viewId,
+    Bool isDepth,
+#endif
+    unsigned temporalID = 0)
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  : NALUnit(nalUnitType, nalRefFlag, layerId, temporalID)
+#else
+  : NALUnit(nalUnitType, nalRefFlag, viewId, isDepth, temporalID)
+#endif
+  , m_Bitstream()
+  {}
+
+  OutputNALUnit(const NALUnit& src)
+  {
+    m_Bitstream.clear();
+    static_cast<NALUnit*>(this)->operator=(src);
+  }
+
+  OutputNALUnit& operator=(const NALUnit& src)
+  {
+    m_Bitstream.clear();
+    static_cast<NALUnit*>(this)->operator=(src);
+    return *this;
+  }
+
+  TComOutputBitstream m_Bitstream;
+};
+
+void write(std::ostream& out, OutputNALUnit& nalu);
+void writeRBSPTrailingBits(TComOutputBitstream& bs);
+
+inline NALUnitEBSP::NALUnitEBSP(OutputNALUnit& nalu)
+  : NALUnit(nalu)
+{
+  write(m_nalUnitData, nalu);
+}
+
+void copyNaluData(OutputNALUnit& naluDest, const OutputNALUnit& naluSrc);
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 341)
@@ -0,0 +1,117 @@
+/* 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-2012, 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/TComBitCounter.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/SEI.h"
+#include "SEIwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+static void writeSEIuserDataUnregistered(TComBitIf& bs, const SEIuserDataUnregistered &sei);
+static void writeSEIpictureDigest(TComBitIf& bs, const SEIpictureDigest& sei);
+
+void writeSEIpayloadData(TComBitIf& bs, const SEI& sei)
+{
+  switch (sei.payloadType())
+  {
+  case SEI::USER_DATA_UNREGISTERED:
+    writeSEIuserDataUnregistered(bs, *static_cast<const SEIuserDataUnregistered*>(&sei));
+    break;
+  case SEI::PICTURE_DIGEST:
+    writeSEIpictureDigest(bs, *static_cast<const SEIpictureDigest*>(&sei));
+    break;
+  default:
+    assert(!"Unhandled SEI message");
+  }
+}
+
+/**
+ * marshal a single SEI message sei, storing the marshalled representation
+ * in bitstream bs.
+ */
+void writeSEImessage(TComBitIf& bs, const SEI& sei)
+{
+  /* calculate how large the payload data is */
+  /* TODO: this would be far nicer if it used vectored buffers */
+  TComBitCounter bs_count;
+  bs_count.resetBits();
+  writeSEIpayloadData(bs_count, sei);
+  unsigned payload_data_num_bits = bs_count.getNumberOfWrittenBits();
+  assert(0 == payload_data_num_bits % 8);
+
+  unsigned payloadType = sei.payloadType();
+  for (; payloadType >= 0xff; payloadType -= 0xff)
+    bs.write(0xff, 8);
+  bs.write(payloadType, 8);
+
+  unsigned payloadSize = payload_data_num_bits/8;
+  for (; payloadSize >= 0xff; payloadSize -= 0xff)
+    bs.write(0xff, 8);
+  bs.write(payloadSize, 8);
+
+  /* payloadData */
+  writeSEIpayloadData(bs, sei);
+}
+
+/**
+ * marshal a user_data_unregistered SEI message sei, storing the marshalled
+ * representation in bitstream bs.
+ */
+static void writeSEIuserDataUnregistered(TComBitIf& bs, const SEIuserDataUnregistered &sei)
+{
+  for (unsigned i = 0; i < 16; i++)
+  {
+    bs.write(sei.uuid_iso_iec_11578[i], 8);
+  }
+
+  for (unsigned i = 0; i < sei.userDataLength; i++)
+  {
+    bs.write(sei.userData[i], 8);
+  }
+}
+
+/**
+ * marshal a picture_digest SEI message, storing the marshalled
+ * representation in bitstream bs.
+ */
+static void writeSEIpictureDigest(TComBitIf& bs, const SEIpictureDigest& sei)
+{
+  bs.write(sei.method, 8);
+  for (unsigned i = 0; i < 16; i++)
+  {
+    bs.write(sei.digest[i], 8);
+  }
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/SEIwrite.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/SEIwrite.h	(revision 341)
@@ -0,0 +1,44 @@
+/* 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-2012, 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
+
+class TComBitIf;
+class SEI;
+
+//! \ingroup TLibEncoder
+//! \{
+
+void writeSEImessage(TComBitIf& bs, const SEI& sei);
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp	(revision 341)
@@ -0,0 +1,4744 @@
+/* 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-2012, 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     TEncAdaptiveLoopFilter.cpp
+ \brief    estimation part of adaptive loop filter class
+ */
+#include "TEncAdaptiveLoopFilter.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+#define ALF_NUM_OF_REDESIGN 1
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+const Int TEncAdaptiveLoopFilter::m_alfNumPartsInRowTab[5] =
+{
+  1,      //level 0
+  2,      //level 1
+  4,      //level 2
+  8,      //level 3
+  16      //level 4
+};
+
+const Int TEncAdaptiveLoopFilter::m_alfNumPartsLevelTab[5] =
+{
+  1,      //level 0
+  4,      //level 1
+  16,     //level 2
+  64,     //level 3
+  256     //level 4
+};
+
+const Int TEncAdaptiveLoopFilter::m_alfNumCulPartsLevelTab[5] =
+{
+  1,    //level 0
+  5,    //level 1
+  21,   //level 2
+  85,   //level 3
+  341,  //level 4
+};
+// ====================================================================================================================
+// Constructor / destructor
+// ====================================================================================================================
+
+///AlfCorrData
+AlfCorrData::AlfCorrData()
+{
+  this->componentID = -1;
+  this->ECorr  = NULL;
+  this->yCorr  = NULL;
+  this->pixAcc = NULL;
+}
+
+AlfCorrData::AlfCorrData(Int cIdx)
+{
+  const Int numCoef = ALF_MAX_NUM_COEF;
+  const Int maxNumGroups = NO_VAR_BINS;
+
+  Int numGroups = (cIdx == ALF_Y)?(maxNumGroups):(1);
+
+  this->componentID = cIdx;
+
+  this->ECorr = new Double**[numGroups];
+  this->yCorr = new Double*[numGroups];
+  this->pixAcc = new Double[numGroups];
+  for(Int g= 0; g< numGroups; g++)
+  {
+    this->yCorr[g] = new Double[numCoef];
+    for(Int j=0; j< numCoef; j++)
+    {
+      this->yCorr[g][j] = 0;
+    }
+
+    this->ECorr[g] = new Double*[numCoef];
+    for(Int i=0; i< numCoef; i++)
+    {
+      this->ECorr[g][i] = new Double[numCoef];
+      for(Int j=0; j< numCoef; j++)
+      {
+        this->ECorr[g][i][j] = 0;
+      }
+    }
+    this->pixAcc[g] = 0;  
+  }
+}
+
+AlfCorrData::~AlfCorrData()
+{
+  if(this->componentID >=0)
+  {
+    const Int numCoef = ALF_MAX_NUM_COEF;
+    const Int maxNumGroups = NO_VAR_BINS;
+
+    Int numGroups = (this->componentID == ALF_Y)?(maxNumGroups):(1);
+
+    for(Int g= 0; g< numGroups; g++)
+    {
+      for(Int i=0; i< numCoef; i++)
+      {
+        delete[] this->ECorr[g][i];
+      }
+      delete[] this->ECorr[g];
+      delete[] this->yCorr[g];
+    }
+    delete[] this->ECorr;
+    delete[] this->yCorr;
+    delete[] this->pixAcc;
+  }
+
+}
+
+AlfCorrData& AlfCorrData::operator += (const AlfCorrData& src)
+{
+  if(this->componentID >=0)
+  {
+    const Int numCoef = ALF_MAX_NUM_COEF;
+    const Int maxNumGroups = NO_VAR_BINS;
+
+    Int numGroups = (this->componentID == ALF_Y)?(maxNumGroups):(1);
+    for(Int g=0; g< numGroups; g++)
+    {
+      this->pixAcc[g] += src.pixAcc[g];
+
+      for(Int j=0; j< numCoef; j++)
+      {
+        this->yCorr[g][j] += src.yCorr[g][j];
+        for(Int i=0; i< numCoef; i++)
+        {
+          this->ECorr[g][j][i] += src.ECorr[g][j][i];
+        }
+      }
+    }
+  }
+
+  return *this;
+}
+
+
+Void AlfCorrData::reset()
+{
+  if(this->componentID >=0)
+  {
+    const Int numCoef = ALF_MAX_NUM_COEF;
+    const Int maxNumGroups = NO_VAR_BINS;
+
+    Int numGroups = (this->componentID == ALF_Y)?(maxNumGroups):(1);
+    for(Int g=0; g< numGroups; g++)
+    {
+      this->pixAcc[g] = 0;
+
+      for(Int j=0; j< numCoef; j++)
+      {
+        this->yCorr[g][j] = 0;
+        for(Int i=0; i< numCoef; i++)
+        {
+          this->ECorr[g][j][i] = 0;
+        }
+      }
+
+
+    }
+  }
+
+}
+
+Void AlfCorrData::mergeFrom(const AlfCorrData& src, Int* mergeTable, Bool doPixAccMerge)
+{
+  assert(componentID == src.componentID);
+
+  reset();
+
+  const Int numCoef = ALF_MAX_NUM_COEF;
+
+  Double **srcE, **dstE;
+  Double *srcy, *dsty;
+
+  switch(componentID)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      srcE = src.ECorr  [0];
+      dstE = this->ECorr[0];
+
+      srcy  = src.yCorr[0];
+      dsty  = this->yCorr[0];
+
+      for(Int j=0; j< numCoef; j++)
+      {
+        for(Int i=0; i< numCoef; i++)
+        {
+          dstE[j][i] += srcE[j][i];
+        }
+
+        dsty[j] += srcy[j];
+      }
+      if(doPixAccMerge)
+      {
+        this->pixAcc[0] = src.pixAcc[0];
+      }
+    }
+    break;
+  case ALF_Y:
+    {
+      Int maxFilterSetSize = (Int)NO_VAR_BINS;
+      for (Int varInd=0; varInd< maxFilterSetSize; varInd++)
+      {
+        Int filtIdx = (mergeTable == NULL)?(0):(mergeTable[varInd]);
+        srcE = src.ECorr  [varInd];
+        dstE = this->ECorr[ filtIdx ];
+        srcy  = src.yCorr[varInd];
+        dsty  = this->yCorr[ filtIdx ];
+        for(Int j=0; j< numCoef; j++)
+        {
+          for(Int i=0; i< numCoef; i++)
+          {
+            dstE[j][i] += srcE[j][i];
+          }
+          dsty[j] += srcy[j];
+        }
+        if(doPixAccMerge)
+        {
+          this->pixAcc[filtIdx] += src.pixAcc[varInd];
+        }
+      }
+    }
+    break;
+  default:
+    {
+      printf("not a legal component ID\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+///AlfPicQTPart
+AlfPicQTPart::AlfPicQTPart()
+{
+  componentID = -1;
+  alfUnitParam = NULL; 
+  alfCorr = NULL;
+}
+
+AlfPicQTPart::~AlfPicQTPart()
+{
+  if(alfUnitParam != NULL)
+  {
+    if(alfUnitParam->alfFiltParam != NULL)
+    {
+      delete alfUnitParam->alfFiltParam;
+      alfUnitParam->alfFiltParam = NULL;
+    }
+    delete alfUnitParam;
+    alfUnitParam = NULL;
+  }
+  if(alfCorr != NULL)
+  {
+    delete alfCorr;
+    alfCorr = NULL;
+  }
+}
+
+AlfPicQTPart& AlfPicQTPart::operator= (const AlfPicQTPart& src)
+{
+  componentID = src.componentID;
+  partCUXS    = src.partCUXS;
+  partCUYS    = src.partCUYS;
+  partCUXE    = src.partCUXE;
+  partCUYE    = src.partCUYE;
+  partIdx     = src.partIdx;
+  partLevel   = src.partLevel;
+  partCol     = src.partCol;
+  partRow     = src.partRow;
+  for(Int i=0; i<4; i++)
+  {
+    childPartIdx[i] = src.childPartIdx[i];
+  }
+  parentPartIdx = src.parentPartIdx;
+
+  isBottomLevel = src.isBottomLevel;
+  isSplit       = src.isSplit;
+
+  isProcessed   = src.isProcessed;
+  splitMinCost  = src.splitMinCost;
+  splitMinDist  = src.splitMinDist;
+  splitMinRate  = src.splitMinRate;
+  selfMinCost   = src.selfMinCost;
+  selfMinDist   = src.selfMinDist;
+  selfMinRate   = src.selfMinRate;
+
+  numFilterBudget = src.numFilterBudget;
+
+  if(src.alfUnitParam != NULL)
+  {
+    if(alfUnitParam == NULL)
+    {
+      //create alfUnitparam
+      alfUnitParam = new AlfUnitParam;
+      alfUnitParam->alfFiltParam = new ALFParam(componentID);
+    }
+    //assign from src
+    alfUnitParam->mergeType = src.alfUnitParam->mergeType;
+    alfUnitParam->isEnabled = src.alfUnitParam->isEnabled;
+    alfUnitParam->isNewFilt = src.alfUnitParam->isNewFilt;
+    alfUnitParam->storedFiltIdx = src.alfUnitParam->storedFiltIdx;
+    *(alfUnitParam->alfFiltParam) = *(src.alfUnitParam->alfFiltParam);   
+  }
+  else
+  {
+    printf("source quad-tree partition info is not complete\n");
+    assert(0);
+    exit(-1);
+  }
+
+  if(src.alfCorr != NULL)
+  {
+    if(alfCorr == NULL)
+    {
+      alfCorr = new AlfCorrData(componentID);
+    }
+    alfCorr->reset();
+    (*alfCorr) += (*(src.alfCorr));
+  }
+  else
+  {
+    printf("source quad-tree partition info is not complete\n");
+    assert(0);
+    exit(-1);
+  }
+  return *this;
+}
+
+
+TEncAdaptiveLoopFilter::TEncAdaptiveLoopFilter()
+{
+  m_pcEntropyCoder = NULL;
+  m_pcPicYuvBest = NULL;
+  m_pcPicYuvTmp = NULL;
+
+  m_iALFMaxNumberFilters = NO_FILTERS;
+
+  m_bAlfCUCtrlEnabled = false;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** convert Level Row Col to Idx
+ * \param   level,  row,  col
+ */
+Int TEncAdaptiveLoopFilter::convertLevelRowCol2Idx(Int level, Int row, Int col)
+{
+  Int idx;
+  if (level == 0)
+  {
+    idx = 0;
+  }
+  else if (level == 1)
+  {
+    idx = 1 + row*2 + col;
+  }
+  else if (level == 2)
+  {
+    idx = 5 + row*4 + col;
+  }
+  else if (level == 3)
+  {
+    idx = 21 + row*8 + col;
+  }
+  else // (level == 4)
+  {
+    idx = 85 + row*16 + col;
+  }
+  return idx;
+}
+
+/** convert quadtree Idx to Level, Row, and Col
+ * \param  idx,  *level,  *row,  *col
+ */
+Void TEncAdaptiveLoopFilter::convertIdx2LevelRowCol(Int idx, Int *level, Int *row, Int *col)
+{
+  if (idx == 0)
+  {
+    *level = 0;
+    *row = 0;
+    *col = 0;
+  }
+  else if (idx>=1 && idx<=4)
+  {
+    *level = 1;
+    *row = (idx-1) / 2;
+    *col = (idx-1) % 2;
+  }
+  else if (idx>=5 && idx<=20)
+  {
+    *level = 2;
+    *row = (idx-5) / 4;
+    *col = (idx-5) % 4;
+  }
+  else if (idx>=21 && idx<=84)
+  {
+    *level = 3;
+    *row = (idx-21) / 8;
+    *col = (idx-21) % 8;
+  }
+  else // (idx>=85 && idx<=340)
+  {
+    *level = 4;
+    *row = (idx-85) / 16;
+    *col = (idx-85) % 16;
+  }
+}
+
+/** Initial picture quad-tree
+ * \param [in] isPicBasedEncode picture quad-tree encoding is enabled or disabled
+ */
+Void TEncAdaptiveLoopFilter::initPicQuadTreePartition(Bool isPicBasedEncode)
+{
+  if (!isPicBasedEncode)
+  {
+    return;
+  }
+  
+  Int maxDepthInWidth   = (Int)(logf((float)(m_numLCUInPicWidth     ))/logf(2.0));
+  Int maxDepthInHeight  = (Int)(logf((float)(m_numLCUInPicHeight    ))/logf(2.0));
+  Int maxDepthInFilters = (Int)(logf((float)(m_iALFMaxNumberFilters ))/logf(2.0));
+  m_alfPQTMaxDepth = (maxDepthInWidth  > maxDepthInHeight ) ? maxDepthInHeight  : maxDepthInWidth ;
+  m_alfPQTMaxDepth = (m_alfPQTMaxDepth > maxDepthInFilters) ? maxDepthInFilters : m_alfPQTMaxDepth ;
+
+  for (Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    m_alfPQTPart[compIdx] = new AlfPicQTPart [ m_alfNumCulPartsLevelTab[m_alfPQTMaxDepth] ];
+    for (Int i = 0; i < m_alfNumCulPartsLevelTab[m_alfPQTMaxDepth]; i++ )
+    {
+      m_alfPQTPart[compIdx][i].alfCorr = new AlfCorrData(compIdx);
+      m_alfPQTPart[compIdx][i].alfUnitParam = new AlfUnitParam;
+      m_alfPQTPart[compIdx][i].alfUnitParam->alfFiltParam = new ALFParam(compIdx);
+    }
+
+  }
+  creatPQTPart(0, 0, 0, -1, 0, m_numLCUInPicWidth-1, 0, m_numLCUInPicHeight-1); 
+}
+
+/** Reset picture quad-tree variables
+ */
+Void TEncAdaptiveLoopFilter::resetPQTPart()
+{
+  Int compIdx, i;
+
+  for (compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    for (i = 0; i < m_alfNumCulPartsLevelTab[m_alfPQTMaxDepth]; i++ )
+    {
+      m_alfPQTPart[compIdx][i].isProcessed  = false;
+      m_alfPQTPart[compIdx][i].selfMinCost  = MAX_DOUBLE;
+      m_alfPQTPart[compIdx][i].splitMinCost = MAX_DOUBLE;      
+      //reset correlations
+      m_alfPQTPart[compIdx][i].alfCorr->reset();
+      //reset ALF unit param
+      m_alfPQTPart[compIdx][i].alfUnitParam->mergeType = ALF_MERGE_DISABLED;
+      m_alfPQTPart[compIdx][i].alfUnitParam->isEnabled = false;
+      m_alfPQTPart[compIdx][i].alfUnitParam->alfFiltParam->alf_flag = 0;
+    }
+  }
+}
+
+/** create picture quad-tree
+ * \param [in] partLevel quad-tree level
+ * \param [in] partRow row position at partLevel
+ * \param [in] partCol column position at partLevel
+ * \param [in] parentPartIdx parent partition index
+ * \param [in] partCUXS starting LCU X position
+ * \param [in] partCUXE ending LCU X position
+ * \param [in] partCUYS starting LCU Y position
+ * \param [in] partCUYE ending LCU Y position
+ */
+Void TEncAdaptiveLoopFilter::creatPQTPart(Int partLevel, Int partRow, Int partCol, Int parentPartIdx, Int partCUXS, Int partCUXE, Int partCUYS, Int partCUYE)
+{
+  Int partIdx = convertLevelRowCol2Idx(partLevel, partRow, partCol);
+
+  AlfPicQTPart *alfOnePartY, *alfOnePartCb, *alfOnePartCr;
+
+  alfOnePartY  = &(m_alfPQTPart[ALF_Y ][partIdx]);
+  alfOnePartCb = &(m_alfPQTPart[ALF_Cb][partIdx]);
+  alfOnePartCr = &(m_alfPQTPart[ALF_Cr][partIdx]);
+
+  // Y, Cb, Cr
+  alfOnePartY->partIdx   = alfOnePartCb->partIdx   = alfOnePartCr->partIdx   = partIdx;
+  alfOnePartY->partCol   = alfOnePartCb->partCol   = alfOnePartCr->partCol   = partCol;
+  alfOnePartY->partRow   = alfOnePartCb->partRow   = alfOnePartCr->partRow   = partRow;
+  alfOnePartY->partLevel = alfOnePartCb->partLevel = alfOnePartCr->partLevel = partLevel;
+
+  alfOnePartY->partCUXS  = alfOnePartCb->partCUXS  = alfOnePartCr->partCUXS  = partCUXS;  
+  alfOnePartY->partCUXE  = alfOnePartCb->partCUXE  = alfOnePartCr->partCUXE  = partCUXE;
+  alfOnePartY->partCUYS  = alfOnePartCb->partCUYS  = alfOnePartCr->partCUYS  = partCUYS;
+  alfOnePartY->partCUYE  = alfOnePartCb->partCUYE  = alfOnePartCr->partCUYE  = partCUYE;
+
+  alfOnePartY->parentPartIdx = alfOnePartCb->parentPartIdx = alfOnePartCr->parentPartIdx = parentPartIdx;  
+  alfOnePartY->isSplit       = alfOnePartCb->isSplit       = alfOnePartCr->isSplit       = false;
+
+#if LCUALF_FILTER_BUDGET_CONTROL_ENC
+  alfOnePartY->numFilterBudget = alfOnePartCb->numFilterBudget = alfOnePartCr->numFilterBudget = m_iALFMaxNumberFilters/m_alfNumPartsLevelTab[partLevel];
+#else
+  alfOnePartY->numFilterBudget = alfOnePartCb->numFilterBudget = alfOnePartCr->numFilterBudget = NO_VAR_BINS;
+#endif
+
+  alfOnePartY->componentID  = ALF_Y;
+  alfOnePartCb->componentID = ALF_Cb;
+  alfOnePartCr->componentID = ALF_Cr;
+
+  if (alfOnePartY->partLevel != m_alfPQTMaxDepth)
+  {
+    alfOnePartY->isBottomLevel = alfOnePartCb->isBottomLevel = alfOnePartCr->isBottomLevel = false;
+
+    Int downLevel    = partLevel + 1;
+    Int downRowStart = partRow << 1;
+    Int downColStart = partCol << 1;
+
+    Int downRowIdx, downColIdx;
+    Int numCULeft, numCUTop;
+    Int downStartCUX, downStartCUY, downEndCUX, downEndCUY;
+
+    numCULeft = (partCUXE - partCUXS + 1) >> 1 ;
+    numCUTop  = (partCUYE - partCUYS + 1) >> 1 ;
+
+    // ChildPart00
+    downStartCUX = partCUXS;
+    downEndCUX   = downStartCUX + numCULeft - 1;
+    downStartCUY = partCUYS;
+    downEndCUY   = downStartCUY + numCUTop  - 1;
+    downRowIdx   = downRowStart + 0;
+    downColIdx   = downColStart + 0;
+
+    alfOnePartY->childPartIdx[0] = alfOnePartCb->childPartIdx[0] = alfOnePartCr->childPartIdx[0] = convertLevelRowCol2Idx(downLevel, downRowIdx, downColIdx);
+    creatPQTPart(downLevel, downRowIdx, downColIdx, partIdx, downStartCUX, downEndCUX, downStartCUY, downEndCUY);
+
+    // ChildPart01
+    downStartCUX = partCUXS + numCULeft;
+    downEndCUX   = partCUXE;
+    downStartCUY = partCUYS;
+    downEndCUY   = downStartCUY + numCUTop  - 1;
+    downRowIdx   = downRowStart + 0;
+    downColIdx   = downColStart + 1;
+
+    alfOnePartY->childPartIdx[1] = alfOnePartCb->childPartIdx[1] = alfOnePartCr->childPartIdx[1] = convertLevelRowCol2Idx(downLevel, downRowIdx, downColIdx);
+    creatPQTPart(downLevel, downRowIdx, downColIdx, partIdx, downStartCUX, downEndCUX, downStartCUY, downEndCUY);
+
+    // ChildPart10
+    downStartCUX = partCUXS;
+    downEndCUX   = downStartCUX + numCULeft - 1;
+    downStartCUY = partCUYS + numCUTop;
+    downEndCUY   = partCUYE;
+    downRowIdx   = downRowStart + 1;
+    downColIdx   = downColStart + 0;
+
+    alfOnePartY->childPartIdx[2] = alfOnePartCb->childPartIdx[2] = alfOnePartCr->childPartIdx[2] = convertLevelRowCol2Idx(downLevel, downRowIdx, downColIdx);
+    creatPQTPart(downLevel, downRowIdx, downColIdx, partIdx, downStartCUX, downEndCUX, downStartCUY, downEndCUY);
+
+    // ChildPart11
+    downStartCUX = partCUXS + numCULeft;
+    downEndCUX   = partCUXE;
+    downStartCUY = partCUYS + numCUTop;
+    downEndCUY   = partCUYE;
+    downRowIdx   = downRowStart + 1;
+    downColIdx   = downColStart + 1;
+
+    alfOnePartY->childPartIdx[3] = alfOnePartCb->childPartIdx[3] = alfOnePartCr->childPartIdx[3] = convertLevelRowCol2Idx(downLevel, downRowIdx, downColIdx);
+    creatPQTPart(downLevel, downRowIdx, downColIdx, partIdx, downStartCUX, downEndCUX, downStartCUY, downEndCUY);
+  }
+  else
+  {
+    alfOnePartY->isBottomLevel = alfOnePartCb->isBottomLevel = alfOnePartCr->isBottomLevel = true;
+
+    alfOnePartY->childPartIdx[0] = alfOnePartCb->childPartIdx[0] = alfOnePartCr->childPartIdx[0] = -1;
+    alfOnePartY->childPartIdx[1] = alfOnePartCb->childPartIdx[1] = alfOnePartCr->childPartIdx[1] = -1;
+    alfOnePartY->childPartIdx[2] = alfOnePartCb->childPartIdx[2] = alfOnePartCr->childPartIdx[2] = -1;
+    alfOnePartY->childPartIdx[3] = alfOnePartCb->childPartIdx[3] = alfOnePartCr->childPartIdx[3] = -1;
+  }
+}
+
+/** create global buffers for ALF encoding
+ */
+Void TEncAdaptiveLoopFilter::createAlfGlobalBuffers()
+{
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    m_alfPicFiltUnits[compIdx] = new AlfUnitParam[m_uiNumCUsInFrame];
+    m_alfCorr[compIdx] = new AlfCorrData*[m_uiNumCUsInFrame];
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      m_alfCorr[compIdx][n]= new AlfCorrData(compIdx);
+      m_alfCorr[compIdx][n]->reset();
+    }
+
+    m_alfCorrMerged[compIdx] = new AlfCorrData(compIdx);
+
+  }
+
+
+  const Int numCoef = (Int)ALF_MAX_NUM_COEF;
+
+  for(Int i=0; i< (Int)NO_VAR_BINS; i++)
+  {
+    m_coeffNoFilter[i] = new Int[numCoef];
+  }
+
+  m_numSlicesDataInOneLCU = new Int[m_uiNumCUsInFrame];
+
+}
+
+/** destroy ALF global buffers
+ * This function is used to destroy the global ALF encoder buffers
+ */
+Void TEncAdaptiveLoopFilter::destroyAlfGlobalBuffers()
+{
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    delete[] m_alfPicFiltUnits[compIdx];
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      delete m_alfCorr[compIdx][n];
+    }
+
+    delete[] m_alfCorr[compIdx];
+    m_alfCorr[compIdx] = NULL;
+
+    delete m_alfCorrMerged[compIdx];
+  }
+
+  //const Int numCoef = (Int)ALF_MAX_NUM_COEF;
+
+  for(Int i=0; i< (Int)NO_VAR_BINS; i++)
+  {
+    delete[] m_coeffNoFilter[i];
+  }
+
+  delete[] m_numSlicesDataInOneLCU;
+
+}
+
+/** initialize ALF encoder at picture level
+ * \param [in] isAlfParamInSlice ALF parameters are coded in slice (true) or APS (false)
+ * \param [in] isPicBasedEncode picture-based encoding (true) or LCU-based encoding (false)
+ * \param [in] numSlices number of slices in current picture
+ * \param [in, out] alfParams ALF parameter set
+ * \param [in, out] alfCUCtrlParam ALF CU-on/off control parameters
+ */
+Void TEncAdaptiveLoopFilter::initALFEnc(Bool isAlfParamInSlice, Bool isPicBasedEncode, Int numSlices, AlfParamSet* & alfParams, std::vector<AlfCUCtrlInfo>* & alfCUCtrlParam)
+{
+  m_picBasedALFEncode = isPicBasedEncode;
+
+  if(isAlfParamInSlice) 
+  {
+    alfParams = new AlfParamSet[m_uiNumSlicesInPic];
+    Int numLCUs = m_uiNumCUsInFrame;
+
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      numLCUs = (Int)(m_pcPic->getOneSliceCUDataForNDBFilter(s).size());
+      alfParams[s].create(m_numLCUInPicWidth,m_numLCUInPicHeight, numLCUs );
+      alfParams[s].createALFParam();
+    }
+    alfCUCtrlParam = NULL; 
+  }
+  else //ALF parameter in APS
+  {
+    alfParams = NULL; //ALF parameters are handled by APS
+    alfCUCtrlParam = new std::vector<AlfCUCtrlInfo>;
+    alfCUCtrlParam->resize(numSlices);
+  }
+
+  resetPicAlfUnit();
+
+  if(m_picBasedALFEncode)
+  {
+    resetPQTPart();  
+  }
+
+  const Int numCoef = (Int)ALF_MAX_NUM_COEF;
+#if LCUALF_QP_DEPENDENT_BITS
+  Int numBitShift = getAlfPrecisionBit( m_alfQP ); 
+#else
+  Int numBitShift = (Int)ALF_NUM_BIT_SHIFT;
+#endif
+  for(Int i=0; i< (Int)NO_VAR_BINS; i++)
+  {
+    ::memset(&(m_coeffNoFilter[i][0]), 0, sizeof(Int)*numCoef);
+    m_coeffNoFilter[i][numCoef-1] = (1 << numBitShift);
+  }
+
+}
+
+/** Uninitialize ALF encoder at picture level
+ * \param [in, out] alfParams ALF parameter set
+ * \param [in, out] alfCUCtrlParam ALF CU-on/off control parameters
+ */
+Void TEncAdaptiveLoopFilter::uninitALFEnc(AlfParamSet* & alfParams, std::vector<AlfCUCtrlInfo>* & alfCUCtrlParam)
+{
+  if(alfParams != NULL)
+  {
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      alfParams[s].releaseALFParam();
+    }
+    delete[] alfParams;
+    alfParams = NULL;
+  }
+
+  if(alfCUCtrlParam != NULL)
+  {
+    delete alfCUCtrlParam;
+    alfCUCtrlParam = NULL;
+  }
+}
+
+/** reset ALF unit parameters in current picture
+ */
+Void TEncAdaptiveLoopFilter::resetPicAlfUnit()
+{
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    for(Int i=0; i< m_uiNumCUsInFrame; i++)
+    {
+      AlfUnitParam& alfUnit = m_alfPicFiltUnits[compIdx][i];
+      alfUnit.mergeType = ALF_MERGE_DISABLED;
+      alfUnit.isEnabled = false;
+      alfUnit.isNewFilt = true;
+      alfUnit.alfFiltParam = m_alfFiltInfo[compIdx][i];
+
+      alfUnit.alfFiltParam->alf_flag = 0;
+    }
+  }
+}
+
+/**
+ \param pcPic           picture (TComPic) pointer
+ \param pcEntropyCoder  entropy coder class
+ */
+Void TEncAdaptiveLoopFilter::startALFEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder )
+{
+  m_pcEntropyCoder = pcEntropyCoder;
+  xCreateTmpAlfCtrlFlags();
+  
+  Int iWidth = pcPic->getPicYuvOrg()->getWidth();
+  Int iHeight = pcPic->getPicYuvOrg()->getHeight();
+  
+  m_pcPicYuvTmp = new TComPicYuv();
+  m_pcPicYuvTmp->createLuma(iWidth, iHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+  m_pcPicYuvBest = pcPic->getPicYuvPred();
+  initMatrix_int(&m_filterCoeffSymQuant, NO_VAR_BINS, ALF_MAX_NUM_COEF); 
+  initMatrix_Pel(&m_maskImg, m_img_height, m_img_width);
+  initMatrix_double(&m_E_temp, MAX_SQR_FILT_LENGTH, MAX_SQR_FILT_LENGTH);//
+  m_y_temp = (double *) calloc(MAX_SQR_FILT_LENGTH, sizeof(double));//
+  initMatrix3D_double(&m_E_merged, NO_VAR_BINS, MAX_SQR_FILT_LENGTH, MAX_SQR_FILT_LENGTH);//
+  initMatrix_double(&m_y_merged, NO_VAR_BINS, MAX_SQR_FILT_LENGTH); //
+  m_pixAcc_merged = (double *) calloc(NO_VAR_BINS, sizeof(double));//
+  m_filterCoeffQuantMod = (int *) calloc(ALF_MAX_NUM_COEF, sizeof(int));//
+  m_filterCoeff = (double *) calloc(ALF_MAX_NUM_COEF, sizeof(double));//
+  m_filterCoeffQuant = (int *) calloc(ALF_MAX_NUM_COEF, sizeof(int));//
+  initMatrix_int(&m_diffFilterCoeffQuant, NO_VAR_BINS, ALF_MAX_NUM_COEF);//
+  initMatrix_int(&m_FilterCoeffQuantTemp, NO_VAR_BINS, ALF_MAX_NUM_COEF);//
+
+  m_tempALFp = new ALFParam(ALF_Y);
+}
+
+Void TEncAdaptiveLoopFilter::endALFEnc()
+{
+  xDestroyTmpAlfCtrlFlags();
+  
+  m_pcPicYuvTmp->destroyLuma();
+  delete m_pcPicYuvTmp;
+  m_pcPicYuvTmp = NULL;
+  m_pcPic = NULL;
+  m_pcEntropyCoder = NULL;
+  destroyMatrix_int(m_filterCoeffSymQuant);
+  destroyMatrix_Pel(m_maskImg);
+  destroyMatrix3D_double(m_E_merged, NO_VAR_BINS);
+  destroyMatrix_double(m_y_merged);
+  destroyMatrix_double(m_E_temp);
+  free(m_pixAcc_merged);
+  
+  free(m_filterCoeffQuantMod);
+  free(m_y_temp);
+  
+  free(m_filterCoeff);
+  free(m_filterCoeffQuant);
+  destroyMatrix_int(m_diffFilterCoeffQuant);
+  destroyMatrix_int(m_FilterCoeffQuantTemp);
+  
+  delete m_tempALFp;
+}
+
+
+/** Assign output ALF parameters
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in, out] alfCtrlParam ALF CU-on/off control parameters
+ */
+Void TEncAdaptiveLoopFilter::assignALFEncoderParam(AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam)
+{
+  //assign CU control parameters
+  if(m_bAlfCUCtrlEnabled)
+  {
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      (*alfCtrlParam)[s]= m_vBestAlfCUCtrlParam[s];
+    }
+  }
+
+  //assign RDO results to alfParamSet
+  if(m_alfCoefInSlice)
+  {
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      if(!m_pcPic->getValidSlice(s))
+      {
+        continue;
+      }
+
+      if( m_bestAlfParamSet[s].isEnabled[ALF_Y] || m_bestAlfParamSet[s].isEnabled[ALF_Cb] || m_bestAlfParamSet[s].isEnabled[ALF_Cr])
+      {
+        m_bestAlfParamSet[s].isEnabled[ALF_Y] = true;
+      }
+
+      copyAlfParamSet(&(alfParamSet[s]), &(m_bestAlfParamSet[s]));
+    }
+  }
+  else
+  {
+    if( m_bestAlfParamSet->isEnabled[ALF_Y] || m_bestAlfParamSet->isEnabled[ALF_Cb] || m_bestAlfParamSet->isEnabled[ALF_Cr])
+    {
+      m_bestAlfParamSet->isEnabled[ALF_Y] = true;
+    }
+
+    copyAlfParamSet(alfParamSet, m_bestAlfParamSet);
+  }
+
+  if(m_alfCoefInSlice)
+  {
+    delete[] m_bestAlfParamSet;
+  }
+  else
+  {
+    delete m_bestAlfParamSet;
+  }
+}
+
+/** initialize ALF encoder configurations
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in, out] alfCtrlParam ALF CU-on/off control parameters
+ */
+Void TEncAdaptiveLoopFilter::initALFEncoderParam(AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam)
+{
+  //reset BA index map 
+  memset(&m_varImg[0][0], 0, sizeof(Pel)*(m_img_height*m_img_width));
+
+  //reset mask
+  for(Int y=0; y< m_img_height; y++)
+  {
+    for(Int x=0; x< m_img_width; x++)
+    {
+      m_maskImg[y][x] = 1;
+    }
+  }
+  //get last valid slice index
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    if(m_pcPic->getValidSlice(s))
+    {
+      m_lastSliceIdx = s;
+    }
+  }
+  //reset alf CU control flags
+  m_bAlfCUCtrlEnabled = (alfCtrlParam != NULL)?true:false;
+  if(m_bAlfCUCtrlEnabled)
+  {
+    m_vBestAlfCUCtrlParam.resize(m_uiNumSlicesInPic);
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      m_vBestAlfCUCtrlParam[s].reset();
+    }
+  }
+  else
+  {
+    m_vBestAlfCUCtrlParam.clear();
+  }
+  //get number slices in each LCU
+  if(m_uiNumSlicesInPic == 1 || m_iSGDepth == 0)
+  {
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      m_numSlicesDataInOneLCU[n] = 1;
+    }
+  }
+  else
+  {
+    Int count;
+    Int prevSliceID = -1;
+
+    for(Int n=0; n< m_uiNumCUsInFrame; n++)
+    {
+      std::vector<NDBFBlockInfo>& vNDBFBlock = *(m_pcPic->getCU(n)->getNDBFilterBlocks());
+
+      count = 0;
+
+      for(Int i=0; i< (Int)vNDBFBlock.size(); i++)
+      {
+        if(vNDBFBlock[i].sliceID != prevSliceID)
+        {
+          prevSliceID = vNDBFBlock[i].sliceID;
+          count++;
+        }
+      }
+
+      m_numSlicesDataInOneLCU[n] = count;
+    }
+  }
+  //set redesign number
+  if(m_iALFEncodePassReduction)
+  {
+    m_iALFNumOfRedesign = 0;
+  }
+  else
+  {
+    m_iALFNumOfRedesign = ALF_NUM_OF_REDESIGN;
+  }
+
+  //initialize m_bestAlfParamSet
+  if(m_alfCoefInSlice)
+  {
+    m_bestAlfParamSet = new AlfParamSet[m_uiNumSlicesInPic];
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      m_bestAlfParamSet[s].create( alfParamSet[s].numLCUInWidth, alfParamSet[s].numLCUInHeight, alfParamSet[s].numLCU);
+    }
+  }
+  else
+  {
+    m_bestAlfParamSet = new AlfParamSet;
+    m_bestAlfParamSet->create( alfParamSet->numLCUInWidth, alfParamSet->numLCUInHeight, alfParamSet->numLCU);
+  }
+
+}
+
+/** copy ALF parameter set
+ * \param [out] dst destination ALF parameter set
+ * \param [in] src source ALF parameter set
+ */
+Void TEncAdaptiveLoopFilter::copyAlfParamSet(AlfParamSet* dst, AlfParamSet* src)
+{
+  dst->numLCU = src->numLCU;
+  dst->numLCUInWidth = src->numLCUInWidth;
+  dst->numLCUInHeight = src->numLCUInHeight;
+
+  for(Int compIdx =0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    dst->isEnabled[compIdx] = src->isEnabled[compIdx];
+    dst->isUniParam[compIdx] = src->isUniParam[compIdx];
+
+    for(Int n=0; n< src->numLCU; n++)
+    {
+      dst->alfUnitParam[compIdx][n].isEnabled = src->alfUnitParam[compIdx][n].isEnabled;
+      dst->alfUnitParam[compIdx][n].isNewFilt = src->alfUnitParam[compIdx][n].isNewFilt;
+      dst->alfUnitParam[compIdx][n].mergeType = src->alfUnitParam[compIdx][n].mergeType;
+      dst->alfUnitParam[compIdx][n].storedFiltIdx = src->alfUnitParam[compIdx][n].storedFiltIdx;
+      *(dst->alfUnitParam[compIdx][n].alfFiltParam) = *(src->alfUnitParam[compIdx][n].alfFiltParam);
+    }
+  }
+}
+
+
+/** ALF encoding process top function
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in, out] alfCtrlParam ALF CU-on/off control parameters
+ * \param [in] dLambdaLuma lambda value for luma RDO
+ * \param [in] dLambdaChroma lambda value for chroma RDO
+ */
+#if ALF_CHROMA_LAMBDA
+#if HHI_INTERVIEW_SKIP
+Void TEncAdaptiveLoopFilter::ALFProcess( AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam, Double lambdaLuma, Double lambdaChroma, Bool bInterviewSkip)
+#else
+Void TEncAdaptiveLoopFilter::ALFProcess( AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam, Double lambdaLuma, Double lambdaChroma)
+#endif
+#else
+#if HHI_INTERVIEW_SKIP
+#else
+Void TEncAdaptiveLoopFilter::ALFProcess( AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam, Double lambda)
+#endif
+#endif
+{
+#if ALF_CHROMA_LAMBDA
+  m_dLambdaLuma   = lambdaLuma;
+  m_dLambdaChroma = lambdaChroma;
+#else
+  m_dLambdaLuma   = lambda;
+  m_dLambdaChroma = lambda;
+#endif
+  TComPicYuv* yuvOrg    = m_pcPic->getPicYuvOrg();
+  TComPicYuv* yuvRec    = m_pcPic->getPicYuvRec();
+  TComPicYuv* yuvExtRec = m_pcTempPicYuv;
+#if HHI_INTERVIEW_SKIP
+  TComPicYuv* pUsedPelMap = NULL;
+  if( bInterviewSkip )
+  {
+    pUsedPelMap = m_pcPic->getUsedPelsMap();
+  }
+#endif
+
+  //picture boundary padding
+  yuvRec->copyToPic(yuvExtRec);
+  yuvExtRec->setBorderExtension( false );
+  yuvExtRec->extendPicBorder   ();
+
+  //initialize encoder parameters
+  initALFEncoderParam(alfParamSet, alfCtrlParam);
+
+  //get LCU statistics
+  getStatistics(yuvOrg, yuvExtRec);
+
+  //decide ALF parameters
+#if HHI_INTERVIEW_SKIP
+  decideParameters(yuvOrg, yuvExtRec, yuvRec, pUsedPelMap, m_bestAlfParamSet, alfCtrlParam);
+#else
+  decideParameters(yuvOrg, yuvExtRec, yuvRec, m_bestAlfParamSet, alfCtrlParam);
+#endif
+
+  //assign best parameters
+  assignALFEncoderParam(alfParamSet, alfCtrlParam);
+}
+
+/** Check if the current LCU can be merged with neighboring LCU
+ * \param [in] compIdx luma/chroma component index
+ * \param [out] alfUnitPic ALF unit parameters for all LCUs in picture
+ */
+Void TEncAdaptiveLoopFilter::checkMerge(Int compIdx, AlfUnitParam* alfUnitPic)
+{
+  AlfUnitParam *alfUnitLeft, *alfUnitUp;
+
+  for(Int n=0; n< m_uiNumCUsInFrame; n++)
+  {
+    Int lcuPosX = (Int)(n % m_numLCUInPicWidth);
+    Int lcuPosY = (Int)(n / m_numLCUInPicWidth);
+
+    AlfUnitParam& alfUnitCur = alfUnitPic[n];
+
+    //check merge left
+    if( lcuPosX != 0)
+    {
+      alfUnitLeft = &(alfUnitPic[n - 1]);
+      if(alfUnitCur == *alfUnitLeft)
+      {
+        alfUnitCur.mergeType = ALF_MERGE_LEFT;
+        alfUnitCur.isEnabled = alfUnitLeft->isEnabled;
+        alfUnitCur.isNewFilt = alfUnitLeft->isNewFilt;
+        alfUnitCur.storedFiltIdx = alfUnitLeft->storedFiltIdx;
+        *(alfUnitCur.alfFiltParam) = *(alfUnitLeft->alfFiltParam);
+        continue;
+      }
+    }
+
+    //check merge up
+    if(lcuPosY !=0 )
+    {
+      alfUnitUp = &(alfUnitPic[n - m_numLCUInPicWidth]);
+      if(alfUnitCur == *alfUnitUp)
+      {
+        alfUnitCur.mergeType = ALF_MERGE_UP;
+        alfUnitCur.isEnabled = alfUnitUp->isEnabled;
+        alfUnitCur.isNewFilt = alfUnitUp->isNewFilt;
+        alfUnitCur.storedFiltIdx = alfUnitUp->storedFiltIdx;
+        *(alfUnitCur.alfFiltParam) = *(alfUnitUp->alfFiltParam);
+        continue;
+      }
+    }
+  }
+
+}
+
+/** Transfer ALF unit parameters for LCUs to to-be-coded ALF parameter set
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfUnitPic ALF unit parameters for all LCUs in picture
+ * \param [out] alfParamSet to-be-coded ALF parameter set
+ */
+Void TEncAdaptiveLoopFilter::transferToAlfParamSet(Int compIdx, AlfUnitParam* alfUnitPic, AlfParamSet* & alfParamSet)
+{
+
+  Int countFiltOffLCU = 0, countNewFilts = 0;
+
+  AlfUnitParam* alfUnitParams = alfParamSet->alfUnitParam[compIdx];
+  for(Int n=0; n< m_uiNumCUsInFrame; n++)
+  {
+    alfUnitParams[n] = alfUnitPic[n];
+
+
+    if(alfUnitParams[n].alfFiltParam->alf_flag == 0)
+    {
+      countFiltOffLCU++;
+    }
+    else
+    {
+      Bool isNewFiltInSlice =   (alfUnitParams[n].mergeType == ALF_MERGE_DISABLED && alfUnitParams[n].isEnabled && alfUnitParams[n].isNewFilt);
+      if( isNewFiltInSlice )
+      {
+        countNewFilts++;
+      }
+    }
+  }
+
+  //slice-level parameters
+  AlfUnitParam* firstAlfUnitInSlice = &(alfUnitParams[0]);
+  if( countFiltOffLCU == m_uiNumCUsInFrame ) //number of filter-off LCU is equal to the number of LCUs in slice
+  {
+    alfParamSet->isEnabled [compIdx] = false;    
+    alfParamSet->isUniParam[compIdx] = true; //uni-param, all off
+    assert(firstAlfUnitInSlice->alfFiltParam->alf_flag == 0);
+  }
+  else
+  {
+    alfParamSet->isEnabled[compIdx] = true;
+    if( countNewFilts == 1 && firstAlfUnitInSlice->alfFiltParam->alf_flag != 0 && countFiltOffLCU == 0)
+    {
+      alfParamSet->isUniParam[compIdx] = true;
+    }
+    else
+    {
+      alfParamSet->isUniParam[compIdx] = false;
+    }
+  }
+
+}
+
+/** Disable all ALF unit parameters in current component
+ * \param [in] compIdx luma/chroma component index
+ * \param [out] alfParamSet to-be-coded ALF parameter set
+ * \param [in] alfUnitPic ALF unit parameters for all LCUs in picture
+ */
+Void TEncAdaptiveLoopFilter::disableComponentAlfParam(Int compIdx, AlfParamSet* alfParamSet, AlfUnitParam* alfUnitPic)
+{
+  alfParamSet->isEnabled [compIdx] = false;
+  alfParamSet->isUniParam[compIdx] = true; //all off
+
+  for(Int lcuPos = 0; lcuPos < m_uiNumCUsInFrame; lcuPos++)
+  {
+    AlfUnitParam& alfunitParam = alfUnitPic[lcuPos];
+
+    alfunitParam.mergeType = ALF_MERGE_DISABLED; 
+    alfunitParam.isEnabled = false; 
+    alfunitParam.isNewFilt = false; 
+    alfunitParam.storedFiltIdx = -1;
+    alfunitParam.alfFiltParam->alf_flag = 0;
+  }
+
+  //check merge-up and merge-left
+  checkMerge(compIdx, alfUnitPic);
+
+  //transfer to AlfParamSet
+  transferToAlfParamSet(compIdx, alfUnitPic, alfParamSet);
+
+}
+
+/** Picture-based encoding
+ * \param [out] alfParamSet to-be-coded ALF parameter set
+ * \param [in, out] alfPicQTPart picture quad-tree partition
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] pOrg picture buffer for original picture
+ * \param [in] pDec picture buffer for un-filtered picture
+ * \param [out] pRest picture buffer for filtered picture
+ * \param [in] stride stride size for 1-D picture memory
+ * \param [in, out] alfCorrLCUs correlation values for LCUs
+ */
+#if HHI_INTERVIEW_SKIP
+Void TEncAdaptiveLoopFilter::executePicBasedModeDecision(AlfParamSet* alfParamSet
+                                                        , AlfPicQTPart* alfPicQTPart
+                                                        , Int compIdx
+                                                        , Pel* pOrg, Pel* pDec, Pel* pRest, Pel* pUsed, Int stride, Int formatShift
+                                                        , AlfCorrData** alfCorrLCUs
+                                                        )
+#else
+Void TEncAdaptiveLoopFilter::executePicBasedModeDecision(AlfParamSet* alfParamSet
+                                                        , AlfPicQTPart* alfPicQTPart
+                                                        , Int compIdx
+                                                        , Pel* pOrg, Pel* pDec, Pel* pRest, Int stride, Int formatShift
+                                                        , AlfCorrData** alfCorrLCUs
+                                                        )
+#endif
+{
+  if(compIdx != ALF_Y)
+  {
+    if(!alfParamSet->isEnabled[ALF_Y])
+    {
+      disableComponentAlfParam(compIdx, alfParamSet, m_alfPicFiltUnits[compIdx]);
+      return;
+    }
+  }
+
+  Int picWidth = (m_img_width >> formatShift);
+  Int picHeight= (m_img_height >> formatShift);
+
+  Int64  minDist = 0;
+  Int64  minRate = 0;
+  Double minCost = 0;
+
+  decideQTPartition(alfPicQTPart, alfCorrLCUs, 0, 0, minCost, minDist, minRate);
+
+  //patch quad-tree decision to m_alfPicFiltUnits (m_alfFiltInfo[compIdx])
+  patchAlfUnitParams(alfPicQTPart, 0, m_alfPicFiltUnits[compIdx]);
+
+  //check merge-up and merge-left
+  checkMerge(compIdx, m_alfPicFiltUnits[compIdx]);
+
+  //transfer to AlfParamSet
+  transferToAlfParamSet(compIdx, m_alfPicFiltUnits[compIdx], alfParamSet);
+
+  //reconstruction
+  recALF(compIdx, m_alfFiltInfo[compIdx], pDec, pRest, stride, formatShift, NULL, false);
+
+  Double lambda = (compIdx == ALF_Y)?(m_dLambdaLuma):(m_dLambdaChroma);
+
+
+  std::vector<AlfCUCtrlInfo> alfCUCtrlParamTemp(m_vBestAlfCUCtrlParam); 
+  minRate = calculateAlfParamSetRateRDO(compIdx, alfParamSet, &alfCUCtrlParamTemp);
+#if HHI_INTERVIEW_SKIP
+  minDist = xCalcSSD(pOrg, pRest, pUsed, picWidth, picHeight, stride);
+#else
+  minDist = xCalcSSD(pOrg, pRest, picWidth, picHeight, stride);
+#endif
+  minCost = (Double)minDist + lambda*((Double)minRate);
+
+  //block on/off control
+  if(compIdx == ALF_Y && m_bAlfCUCtrlEnabled)
+  {
+#if HHI_INTERVIEW_SKIP
+    decideBlockControl(pOrg, pDec, pRest, pUsed, stride, alfPicQTPart, alfParamSet, minRate, minDist, minCost);
+#else
+    decideBlockControl(pOrg, pDec, pRest, stride, alfPicQTPart, alfParamSet, minRate, minDist, minCost);  
+#endif
+  }
+
+  //get filter-off distortion, rate, cost
+  AlfParamSet alfParamSetOff;
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    alfCUCtrlParamTemp[s].reset();
+  }
+  alfParamSetOff.isEnabled[compIdx] = false;
+  alfParamSetOff.isUniParam[compIdx] = true;
+#if HHI_INTERVIEW_SKIP
+  Int64  offDist = xCalcSSD(pOrg, pDec, pUsed, picWidth, picHeight, stride);
+#else
+  Int64  offDist = xCalcSSD(pOrg, pDec, picWidth, picHeight, stride);
+#endif
+  Int64  offRate = calculateAlfParamSetRateRDO(compIdx, &alfParamSetOff, &alfCUCtrlParamTemp);
+  Double offCost = (Double)offDist + lambda*((Double)offRate);
+
+  if(offCost < minCost  )
+  {
+    //revert to filter-off results
+    Pel* pelSrc = pDec;
+    Pel* pelDst = pRest;
+    for(Int y=0; y< picHeight; y++)
+    {
+      ::memcpy(pelDst, pelSrc, sizeof(Pel)*picWidth);
+      pelSrc += stride;
+      pelDst += stride;
+    }
+
+    alfParamSet->isEnabled[compIdx] = false;
+    alfParamSet->isUniParam[compIdx] = true; //all filter-off
+  }
+
+}
+
+/** copy picture quadtree infromation
+ * \param [out] alfPicQTPartDest destination part in picture quad tree
+ * \param [in ] alfPicQTPartSrc source part in picture quad tree
+ */
+Void TEncAdaptiveLoopFilter::copyPicQT(AlfPicQTPart* alfPicQTPartDest, AlfPicQTPart* alfPicQTPartSrc)
+{
+  for (Int i=0; i< m_alfNumCulPartsLevelTab[m_alfPQTMaxDepth]; i++)
+  {
+    alfPicQTPartDest[i] = alfPicQTPartSrc[i];
+  }
+}
+
+/** copy pixel values for one rectangular region
+ * \param [out] imgDest destination part in picture quad tree
+ * \param [in ] imgSrc source part in picture quad tree
+ * \param [in ] stride source part in picture quad tree
+ * \param [in ] yPos starting y position
+ * \param [in ] height region height
+ * \param [in ] xPos starting x position
+ * \param [in ] width region width
+ */
+Void TEncAdaptiveLoopFilter::copyPixelsInOneRegion(Pel* imgDest, Pel* imgSrc, Int stride, Int yPos, Int height, Int xPos, Int width)
+{
+  Int offset = (yPos*stride) + xPos;
+  Pel *imgDestLine = imgDest + offset;
+  Pel *imgSrcLine  = imgSrc  + offset;
+
+  for (Int j=0; j<height; j++)
+  {
+    ::memcpy(imgDestLine, imgSrcLine, sizeof(Pel)*width);
+    imgDestLine += stride;
+    imgSrcLine  += stride;
+  }
+}
+
+/** Re-design ALF parameters for picture quad-tree partitions
+ * \param [out] alfPicQTPart picture quad-tree partition information
+ * \param [in ] partIdx partition index
+ * \param [in ] partLevel partition level
+ */
+Void TEncAdaptiveLoopFilter::reDesignQT(AlfPicQTPart *alfPicQTPart, Int partIdx, Int partLevel)
+{
+  AlfPicQTPart *alfPicQTOnePart = &(alfPicQTPart[partIdx]);  
+  Int nextPartLevel = partLevel + 1;
+
+  if (!alfPicQTOnePart->isSplit)
+  {
+    if (alfPicQTOnePart->alfUnitParam->alfFiltParam->alf_flag)
+    {
+      executeModeDecisionOnePart(alfPicQTPart, m_alfCorr[ALF_Y], partIdx, partLevel) ;     
+    }
+  }
+  else
+  {
+    for (Int i=0; i<4; i++)
+    {
+      reDesignQT(alfPicQTPart, alfPicQTOnePart->childPartIdx[i], nextPartLevel);
+    }
+  }  
+}
+
+/** CU-on/off control decision
+ * \param [in ] imgOrg picture buffer for original picture
+ * \param [in ] imgDec picture buffer for un-filtered picture
+ * \param [in ] imgRest picture buffer for filtered picture
+ * \param [in ] stride buffer stride size for 1-D picture memory
+ * \param [in, out] alfPicQTPart picture quad-tree partition information
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in, out ] minRate minimum rate
+ * \param [in, out ] minDist minimum distortion
+ * \param [in, out ] minCost minimum RD cost
+ */
+#if HHI_INTERVIEW_SKIP
+Void TEncAdaptiveLoopFilter::decideBlockControl(Pel* imgOrg, Pel* imgDec, Pel* imgRest, Pel* imgUsed, Int stride, AlfPicQTPart* alfPicQTPart, AlfParamSet* & alfParamSet, Int64 &minRate, Int64 &minDist, Double &minCost)
+#else
+Void TEncAdaptiveLoopFilter::decideBlockControl(Pel* imgOrg, Pel* imgDec, Pel* imgRest, Int stride, AlfPicQTPart* alfPicQTPart, AlfParamSet* & alfParamSet, Int64 &minRate, Int64 &minDist, Double &minCost)
+#endif
+{
+  Int    rate, ctrlDepth;
+  Double cost;
+  UInt64 dist;
+  Bool isChanged = false;
+  Pel *imgYtemp = getPicBuf(m_pcPicYuvTmp, ALF_Y);
+  Pel *imgYBest = getPicBuf(m_pcPicYuvBest, ALF_Y);
+  std::vector<AlfCUCtrlInfo> vAlfCUCtrlParamTemp(m_vBestAlfCUCtrlParam);  
+
+  AlfPicQTPart *alfPicQTPartNoCtrl = new AlfPicQTPart [ m_alfNumCulPartsLevelTab[m_alfPQTMaxDepth] ];
+  AlfPicQTPart *alfPicQTPartBest   = new AlfPicQTPart [ m_alfNumCulPartsLevelTab[m_alfPQTMaxDepth] ];
+
+  // backup data of PQT without block on/off
+  copyPicQT(alfPicQTPartNoCtrl, alfPicQTPart);
+
+  for (ctrlDepth=0; ctrlDepth<4; ctrlDepth++)
+  {        
+    // Restore data from PQT without block on/off
+    copyPixelsInOneRegion(imgYtemp, imgRest, stride, 0, m_img_height, 0, m_img_width);
+    copyPicQT(alfPicQTPart, alfPicQTPartNoCtrl);
+
+    for (Int reDesignRun=0; reDesignRun <= m_iALFNumOfRedesign; reDesignRun++)
+    {
+      // re-design filter
+      if (reDesignRun > 0)
+      {
+        // re-gather statistics
+        getOneCompStatistics(m_alfCorr[ALF_Y], ALF_Y, imgOrg, imgDec, stride, 0, true);
+
+        // reDesign in each QT partition
+        reDesignQT(alfPicQTPart, 0, 0);
+
+        //patch quad-tree decision to m_alfPicFiltUnits (m_alfFiltInfo[compIdx])
+        patchAlfUnitParams(alfPicQTPart, 0, m_alfPicFiltUnits[ALF_Y]);
+
+        //reconstruction
+        copyPixelsInOneRegion(imgYtemp, imgDec, stride, 0, m_img_height, 0, m_img_width);
+        recALF(ALF_Y, m_alfFiltInfo[ALF_Y], imgDec, imgYtemp, stride, 0, NULL, false);
+      }
+
+      // Gest distortion and decide on/off, Pel should be changed to TComPicYUV
+#if HHI_INTERVIEW_SKIP
+      setCUAlfCtrlFlags((UInt)ctrlDepth, imgOrg, imgDec, imgYtemp, imgUsed, stride, dist, vAlfCUCtrlParamTemp);
+#else
+      setCUAlfCtrlFlags((UInt)ctrlDepth, imgOrg, imgDec, imgYtemp, stride, dist, vAlfCUCtrlParamTemp);   
+#endif
+
+      //patch quad-tree decision to m_alfPicFiltUnits (m_alfFiltInfo[compIdx])
+      patchAlfUnitParams(alfPicQTPart, 0, m_alfPicFiltUnits[ALF_Y]);
+
+      //check merge-up and merge-left
+      checkMerge(ALF_Y, m_alfPicFiltUnits[ALF_Y]);
+
+      //transfer to AlfParamSet
+      transferToAlfParamSet(ALF_Y, m_alfPicFiltUnits[ALF_Y], alfParamSet);
+
+      rate = calculateAlfParamSetRateRDO(ALF_Y, alfParamSet, &vAlfCUCtrlParamTemp);
+      cost = (Double)dist + m_dLambdaLuma * ((Double)rate);
+
+      if (cost < minCost)
+      {
+        isChanged     = true;
+        minCost       = cost;
+        minDist       = (Int64) dist;
+        minRate       = rate;
+
+        m_vBestAlfCUCtrlParam = vAlfCUCtrlParamTemp;
+        copyPixelsInOneRegion(imgYBest, imgYtemp, stride, 0, m_img_height, 0, m_img_width);
+
+        copyPicQT(alfPicQTPartBest, alfPicQTPart);
+        xCopyTmpAlfCtrlFlagsFrom();
+      }
+
+    }
+  }
+
+  if (isChanged == true)
+  {
+    copyPicQT(alfPicQTPart, alfPicQTPartBest);
+    xCopyTmpAlfCtrlFlagsTo();
+
+    copyPixelsInOneRegion(imgRest, imgYBest, stride, 0, m_img_height, 0, m_img_width);
+    xCopyDecToRestCUs(imgDec, imgRest, stride);
+  }
+  else
+  {
+    copyPicQT(alfPicQTPart, alfPicQTPartNoCtrl);
+  }
+
+  //patch quad-tree decision to m_alfPicFiltUnits (m_alfFiltInfo[compIdx])
+  patchAlfUnitParams(alfPicQTPart, 0, m_alfPicFiltUnits[ALF_Y]);
+
+  //check merge-up and merge-left
+  checkMerge(ALF_Y, m_alfPicFiltUnits[ALF_Y]);
+
+  //transfer to AlfParamSet
+  transferToAlfParamSet(ALF_Y, m_alfPicFiltUnits[ALF_Y], alfParamSet);
+
+  delete [] alfPicQTPartNoCtrl;
+  alfPicQTPartNoCtrl = NULL;
+
+  delete [] alfPicQTPartBest;
+  alfPicQTPartBest = NULL;
+}
+
+/** Copy ALF unit parameters from quad-tree partition to LCUs
+ * \param [in] alfPicQTPart picture quad-tree partition information
+ * \param [in] partIdx partition index
+ * \param [out] alfUnitPic ALF unit parameters for LCUs
+ */
+Void TEncAdaptiveLoopFilter::patchAlfUnitParams(AlfPicQTPart* alfPicQTPart, Int partIdx, AlfUnitParam* alfUnitPic)
+{
+  AlfPicQTPart* alfQTPart = &(alfPicQTPart[partIdx]);
+  //Int compIdx = alfQTPart->componentID;
+
+  if(alfQTPart->isSplit == false)
+  {
+    AlfUnitParam* alfpartParam = alfQTPart->alfUnitParam;
+
+    Int lcuPos;
+    for(Int lcuPosY = alfQTPart->partCUYS; lcuPosY <= alfQTPart->partCUYE; lcuPosY++)
+    {
+      for(Int lcuPosX = alfQTPart->partCUXS; lcuPosX <= alfQTPart->partCUXE; lcuPosX++)
+      {
+        lcuPos = lcuPosY*m_numLCUInPicWidth + lcuPosX;
+        AlfUnitParam& alfunitParam = alfUnitPic[lcuPos];
+
+        alfunitParam.mergeType = alfpartParam->mergeType; 
+        alfunitParam.isEnabled = alfpartParam->isEnabled; 
+        alfunitParam.isNewFilt = alfpartParam->isNewFilt; 
+        alfunitParam.storedFiltIdx = alfpartParam->storedFiltIdx; //not used
+        *(alfunitParam.alfFiltParam) = *(alfpartParam->alfFiltParam);
+      }
+    }
+  }
+  else
+  {
+    for(Int i=0; i< 4; i++)
+    {
+      patchAlfUnitParams(alfPicQTPart, alfQTPart->childPartIdx[i], alfUnitPic);      
+    }
+  }
+}
+
+/** Decide picture quad-tree partition
+ * \param [in, out] alfPicQTPart picture quad-tree partition information
+ * \param [in, out] alfPicLCUCorr correlations for LCUs
+ * \param [int] partIdx partition index
+ * \param [int] partLevel partition level
+ * \param [in, out] cost cost for one partition
+ * \param [in, out] dist distortion for one partition
+ * \param [in, out] rate bitrate for one partition
+ */
+Void TEncAdaptiveLoopFilter::decideQTPartition(AlfPicQTPart* alfPicQTPart, AlfCorrData** alfPicLCUCorr, Int partIdx, Int partLevel, Double &cost, Int64 &dist, Int64 &rate)
+{
+  AlfPicQTPart* alfPicQTOnePart = &(alfPicQTPart[partIdx]);
+  Int nextPartLevel = partLevel + 1;
+  Int childPartIdx;
+  Double splitCost = 0;
+  Int64  splitRate = 0;
+  Int64  splitDist = 0;  
+
+  if (!alfPicQTOnePart->isProcessed)
+  {
+    executeModeDecisionOnePart(alfPicQTPart, alfPicLCUCorr, partIdx, partLevel);
+
+    alfPicQTOnePart->isProcessed = true;
+  }
+
+  if (!alfPicQTOnePart->isBottomLevel) 
+  {    
+    for (Int i=0; i<4; i++)
+    {      
+      childPartIdx = alfPicQTOnePart->childPartIdx[i];
+      decideQTPartition(alfPicQTPart, alfPicLCUCorr, childPartIdx, nextPartLevel, splitCost, splitDist, splitRate);      
+    }
+
+    alfPicQTOnePart->splitMinCost = splitCost;
+    alfPicQTOnePart->splitMinDist = splitDist;
+    alfPicQTOnePart->splitMinRate = splitRate;
+
+    if (alfPicQTOnePart->splitMinCost < alfPicQTOnePart->selfMinCost)
+    {
+      alfPicQTOnePart->isSplit = true;
+    }
+    else
+    { 
+      alfPicQTOnePart->isSplit = false; 
+    }
+  }
+  else
+  {
+    alfPicQTOnePart->isSplit = false;
+    alfPicQTOnePart->splitMinCost = alfPicQTOnePart->selfMinCost;
+    alfPicQTOnePart->splitMinDist = alfPicQTOnePart->selfMinDist;
+    alfPicQTOnePart->splitMinRate = alfPicQTOnePart->selfMinRate;
+  }
+
+  if (alfPicQTOnePart->isSplit)
+  {
+    cost += alfPicQTOnePart->splitMinCost;
+    rate += alfPicQTOnePart->splitMinRate;
+    dist += alfPicQTOnePart->splitMinDist;
+  }
+  else
+  {
+    cost += alfPicQTOnePart->selfMinCost;
+    rate += alfPicQTOnePart->selfMinRate;
+    dist += alfPicQTOnePart->selfMinDist;
+  }
+
+}
+
+/** Mode decision process for one picture quad-tree partition
+ * \param [in, out] alfPicQTPart picture quad-tree partition information
+ * \param [in, out] alfPicLCUCorr correlations for LCUs
+ * \param [int] partIdx partition index
+ * \param [int] partLevel partition level
+ */
+Void TEncAdaptiveLoopFilter::executeModeDecisionOnePart(AlfPicQTPart *alfPicQTPart, AlfCorrData** alfPicLCUCorr, Int partIdx, Int partLevel)
+{
+  AlfPicQTPart* alfQTPart = &(alfPicQTPart[partIdx]);
+  Int compIdx = alfQTPart->componentID;
+  Double lambda = (compIdx == ALF_Y)?(m_dLambdaLuma):(m_dLambdaChroma);
+
+  //gather correlations
+  alfQTPart->alfCorr->reset();
+  for(Int lcuPosY = alfQTPart->partCUYS; lcuPosY <= alfQTPart->partCUYE; lcuPosY++)
+  {
+    for(Int lcuPosX = alfQTPart->partCUXS; lcuPosX <= alfQTPart->partCUXE; lcuPosX++)
+    {
+      *(alfQTPart->alfCorr) +=  *(alfPicLCUCorr[lcuPosY*m_numLCUInPicWidth + lcuPosX]);
+    }
+  }
+
+  //test filter on
+  AlfUnitParam* alfPartUnitParam = alfQTPart->alfUnitParam;
+  alfPartUnitParam->mergeType = ALF_MERGE_DISABLED;
+  alfPartUnitParam->isEnabled = true;
+  alfPartUnitParam->isNewFilt = true;
+  alfPartUnitParam->storedFiltIdx = -1;
+  alfPartUnitParam->alfFiltParam->alf_flag = 1;
+  deriveFilterInfo(compIdx, alfQTPart->alfCorr, alfPartUnitParam->alfFiltParam, alfQTPart->numFilterBudget);
+
+  alfQTPart->selfMinDist = estimateFilterDistortion(compIdx, alfQTPart->alfCorr, m_filterCoeffSym, alfPartUnitParam->alfFiltParam->filters_per_group, m_varIndTab);
+  alfQTPart->selfMinRate = calculateAlfUnitRateRDO(alfPartUnitParam);
+  alfQTPart->selfMinCost = (Double)(alfQTPart->selfMinDist) + lambda*((Double)(alfQTPart->selfMinRate));
+  
+  alfQTPart->selfMinCost +=  ((lambda* 1.5)* ((Double)( (alfQTPart->partCUYE - alfQTPart->partCUYS+ 1)*(alfQTPart->partCUXE - alfQTPart->partCUXS +1) )));  //RDCO
+  
+
+  //test filter off
+  AlfUnitParam alfUnitParamTemp(*(alfQTPart->alfUnitParam));
+  alfUnitParamTemp.mergeType = ALF_MERGE_DISABLED;
+  alfUnitParamTemp.isEnabled = false;
+  Int64  dist = estimateFilterDistortion(compIdx, alfQTPart->alfCorr);
+  Int64  rate = calculateAlfUnitRateRDO(&alfUnitParamTemp);
+  Double cost = (Double)dist + lambda*((Double)rate);
+  if(cost < alfQTPart->selfMinCost)
+  {
+    alfQTPart->selfMinCost = cost;
+    alfQTPart->selfMinDist = dist;
+    alfQTPart->selfMinRate = rate;
+    *(alfQTPart->alfUnitParam) = alfUnitParamTemp;
+
+    alfQTPart->alfUnitParam->alfFiltParam->alf_flag = 0;
+  }
+
+}
+
+/** Derive filter coefficients
+ * \param [in, out] alfPicQTPart picture quad-tree partition information
+ * \param [in, out] alfPicLCUCorr correlations for LCUs
+ * \param [int] partIdx partition index
+ * \param [int] partLevel partition level
+ */
+Void TEncAdaptiveLoopFilter::deriveFilterInfo(Int compIdx, AlfCorrData* alfCorr, ALFParam* alfFiltParam, Int maxNumFilters)
+{
+  const Int filtNo = 0; 
+  const Int numCoeff = ALF_MAX_NUM_COEF;
+
+  switch(compIdx)
+  {
+  case ALF_Y:
+    {       
+      Int lambdaForMerge = ((Int) m_dLambdaLuma) * (1<<(2*g_uiBitIncrement));
+      Int numFilters;
+
+      ::memset(m_varIndTab, 0, sizeof(Int)*NO_VAR_BINS);
+
+      xfindBestFilterVarPred(alfCorr->yCorr, alfCorr->ECorr, alfCorr->pixAcc, m_filterCoeffSym, m_filterCoeffSymQuant, filtNo, &numFilters, m_varIndTab, NULL, m_varImg, m_maskImg, NULL, lambdaForMerge, maxNumFilters);
+      xcodeFiltCoeff(m_filterCoeffSymQuant, filtNo, m_varIndTab, numFilters, alfFiltParam);
+    }
+    break;
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      static Double coef[ALF_MAX_NUM_COEF];
+
+      alfFiltParam->filters_per_group = 1;
+
+      gnsSolveByChol(alfCorr->ECorr[0], alfCorr->yCorr[0], coef, numCoeff);
+      xQuantFilterCoef(coef, m_filterCoeffSym[0], filtNo, g_uiBitDepth + g_uiBitIncrement);
+      ::memcpy(alfFiltParam->coeffmulti[0], m_filterCoeffSym[0], sizeof(Int)*numCoeff);
+      predictALFCoeffChroma(alfFiltParam->coeffmulti[0]);
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+
+}
+
+/** Estimate rate-distortion cost for ALF parameter set
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfParamSet ALF parameter set
+ * \param [in] alfCUCtrlParam CU-on/off control parameters
+ */
+Int TEncAdaptiveLoopFilter::calculateAlfParamSetRateRDO(Int compIdx, AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCUCtrlParam)
+{
+  Int rate = 0;
+
+  m_pcEntropyCoder->resetEntropy();
+  m_pcEntropyCoder->resetBits();
+
+
+  m_pcEntropyCoder->encodeAlfParamSet(alfParamSet, m_numLCUInPicWidth, m_uiNumCUsInFrame, 0, true, compIdx, compIdx);
+
+  if(m_bAlfCUCtrlEnabled)
+  {
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      m_pcEntropyCoder->encodeAlfCtrlParam( (*alfCUCtrlParam)[s], m_uiNumCUsInFrame);      
+    }
+  }
+
+  rate = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+  return rate;
+}
+
+/** Estimate rate-distortion cost for ALF unit parameters
+ * \param [in] alfUnitParam ALF unit parameters
+ * \param [in] numStoredFilters number of stored filter (set)
+ */
+Int TEncAdaptiveLoopFilter::calculateAlfUnitRateRDO(AlfUnitParam* alfUnitParam, Int numStoredFilters)
+{
+  Int rate = 0;
+
+  if(alfUnitParam->mergeType != ALF_MERGE_LEFT)
+  {
+    m_pcEntropyCoder->resetEntropy();
+    m_pcEntropyCoder->resetBits();
+
+    m_pcEntropyCoder->encodeAlfFlag( (alfUnitParam->mergeType == ALF_MERGE_UP)?1:0);
+
+    if(alfUnitParam->mergeType != ALF_MERGE_UP)
+    {
+      m_pcEntropyCoder->encodeAlfFlag( (alfUnitParam->isEnabled)?1:0);
+
+      if(alfUnitParam->isEnabled)
+      {
+        if(numStoredFilters > 0)
+        {
+          m_pcEntropyCoder->encodeAlfFlag( (alfUnitParam->isNewFilt)?1:0);
+        }
+
+        if(!(alfUnitParam->isNewFilt) && numStoredFilters > 0)
+        {
+          m_pcEntropyCoder->encodeAlfStoredFilterSetIdx(alfUnitParam->storedFiltIdx, numStoredFilters);
+        }
+        else
+        {
+          m_pcEntropyCoder->encodeAlfParam(alfUnitParam->alfFiltParam);
+        }
+
+      }
+    }
+    rate = m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+  return rate;
+}
+
+/** Estimate filtering distortion
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfCorr correlations
+ * \param [in] coeffSet filter coefficients
+ * \param [in] filterSetSize number of filter set
+ * \param [in] mergeTable merge table of filter set (only for luma BA)
+ * \param [in] doPixAccMerge calculate pixel squared value (true) or not (false)
+ */
+Int64 TEncAdaptiveLoopFilter::estimateFilterDistortion(Int compIdx, AlfCorrData* alfCorr, Int** coeffSet, Int filterSetSize, Int* mergeTable, Bool doPixAccMerge)
+{
+  const Int numCoeff = (Int)ALF_MAX_NUM_COEF;
+  AlfCorrData* alfMerged = m_alfCorrMerged[compIdx];
+
+  alfMerged->mergeFrom(*alfCorr, mergeTable, doPixAccMerge);
+
+  Int**     coeff = (coeffSet == NULL)?(m_coeffNoFilter):(coeffSet);
+  Int64     iDist = 0;
+  for(Int f=0; f< filterSetSize; f++)
+  {
+    iDist += xFastFiltDistEstimation(alfMerged->ECorr[f], alfMerged->yCorr[f], coeff[f], numCoeff);
+  }
+  return iDist;
+}
+
+/** Mode decision for ALF unit in LCU-based encoding
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfUnitPic ALF unit parmeters for LCUs in picture
+ * \param [in] lcuIdx LCU index (order) in slice
+ * \param [in] lcuPos LCU position in picture
+ * \param [in] numLCUWidth number of width in LCU
+ * \param [in, out] alfUnitParams ALF unit parameters for LCUs in slice
+ * \param [in] alfCorr correlations
+ * \param [in] storedFilters stored-filter buffer
+ * \param [in] maxNumFilter constraint for number of filters
+ * \param [in] lambda lagrangian multiplier for RDO
+ * \param [in] isLeftUnitAvailable left ALF unit available (true) or not (false)
+ * \param [in] isUpUnitAvailable upper ALF unit available (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::decideLCUALFUnitParam(Int compIdx, AlfUnitParam* alfUnitPic, Int lcuIdx, Int lcuPos, Int numLCUWidth, AlfUnitParam* alfUnitParams, AlfCorrData* alfCorr, std::vector<ALFParam*>& storedFilters, Int maxNumFilter, Double lambda, Bool isLeftUnitAvailable, Bool isUpUnitAvailable)
+{
+  Int    numSliceDataInCurrLCU = m_numSlicesDataInOneLCU[lcuPos];
+  Int    budgetNumFilters = (Int)(maxNumFilter/numSliceDataInCurrLCU);
+  Int    numStoredFilters = (Int)storedFilters.size();
+  Double cost, minCost = MAX_DOUBLE;
+  Int64  dist;
+  Int    rate;
+
+  AlfUnitParam& alfUnitParamCurr = alfUnitParams[lcuIdx];
+
+  ///--- new filter mode test ---
+  AlfUnitParam alfUnitParamTemp(alfUnitParamCurr);
+  alfUnitParamTemp.mergeType = ALF_MERGE_DISABLED;
+  alfUnitParamTemp.isEnabled = true;
+  alfUnitParamTemp.isNewFilt = true;
+  alfUnitParamTemp.storedFiltIdx = -1;
+  deriveFilterInfo(compIdx, alfCorr, alfUnitParamTemp.alfFiltParam, budgetNumFilters);
+
+  dist = estimateFilterDistortion(compIdx, alfCorr, m_filterCoeffSym, alfUnitParamTemp.alfFiltParam->filters_per_group, m_varIndTab);
+  rate = calculateAlfUnitRateRDO(&alfUnitParamTemp, numStoredFilters);
+  cost = (Double)dist + lambda*((Double)rate);
+  if(cost < minCost)
+  {
+    minCost = cost;
+    alfUnitParamCurr = alfUnitParamTemp;
+
+    alfUnitParamCurr.alfFiltParam->alf_flag = 1;
+  }
+
+  if(numSliceDataInCurrLCU == 1)
+  {
+    if(numStoredFilters > 0)
+    {
+      ///--- stored filter mode test ---//
+      alfUnitParamTemp = alfUnitParamCurr;
+
+      alfUnitParamTemp.mergeType = ALF_MERGE_DISABLED;
+      alfUnitParamTemp.isEnabled = true;
+      alfUnitParamTemp.isNewFilt = false;
+
+      for(Int i=0; i< numStoredFilters; i++)
+      {
+        ALFParam* storedALFParam = storedFilters[i];
+
+        alfUnitParamTemp.storedFiltIdx = i;
+        alfUnitParamTemp.alfFiltParam  = storedALFParam;
+
+        assert(storedALFParam->alf_flag == 1);
+
+        reconstructCoefInfo(compIdx, storedALFParam, m_filterCoeffSym, m_varIndTab);
+
+        dist = estimateFilterDistortion(compIdx, alfCorr, m_filterCoeffSym, alfUnitParamTemp.alfFiltParam->filters_per_group, m_varIndTab);
+        rate = calculateAlfUnitRateRDO(&alfUnitParamTemp, numStoredFilters);
+        cost = (Double)dist + lambda*((Double)rate);
+
+        if(cost < minCost)
+        {
+          minCost = cost;
+          alfUnitParamCurr = alfUnitParamTemp;
+        }
+      }
+    }
+
+    /// merge-up test
+    if(isUpUnitAvailable)
+    {
+      Int addrUp = lcuPos - m_numLCUInPicWidth;
+      AlfUnitParam& alfUnitParamUp = alfUnitPic[addrUp];
+
+      if(alfUnitParamUp.alfFiltParam->alf_flag == 1)
+      {
+        alfUnitParamTemp = alfUnitParamUp;
+        alfUnitParamTemp.mergeType    = ALF_MERGE_UP;
+
+        reconstructCoefInfo(compIdx, alfUnitParamTemp.alfFiltParam, m_filterCoeffSym, m_varIndTab);
+        dist = estimateFilterDistortion(compIdx, alfCorr, m_filterCoeffSym, alfUnitParamTemp.alfFiltParam->filters_per_group, m_varIndTab);
+        rate = calculateAlfUnitRateRDO(&alfUnitParamTemp, numStoredFilters);
+        cost = (Double)dist + lambda*((Double)rate);
+
+        if(cost < minCost)
+        {
+          minCost = cost;
+
+          alfUnitParamCurr = alfUnitParamTemp;
+        }
+
+      }
+
+    } //upper unit available
+
+
+    /// merge-left test
+    if(isLeftUnitAvailable)
+    {
+      Int addrLeft = lcuPos - 1;
+      AlfUnitParam& alfUnitParamLeft = alfUnitPic[addrLeft];
+
+      if(alfUnitParamLeft.alfFiltParam->alf_flag == 1)
+      {
+        alfUnitParamTemp = alfUnitParamLeft;
+        alfUnitParamTemp.mergeType    = ALF_MERGE_LEFT;
+
+        reconstructCoefInfo(compIdx, alfUnitParamTemp.alfFiltParam, m_filterCoeffSym, m_varIndTab);
+        dist = estimateFilterDistortion(compIdx, alfCorr, m_filterCoeffSym, alfUnitParamTemp.alfFiltParam->filters_per_group, m_varIndTab);
+        rate = calculateAlfUnitRateRDO(&alfUnitParamTemp, numStoredFilters);
+        cost = (Double)dist + lambda*((Double)rate);
+
+        if(cost < minCost)
+        {
+          minCost = cost;
+
+          alfUnitParamCurr = alfUnitParamTemp;
+        }
+
+      }
+
+    } //left unit available
+
+  }
+}
+
+/** Choose the best ALF unit parameters when filter is not enabled.
+ * \param [out] alfFiltOffParam ALF unit parameters for filter-off case
+ * \param [in] lcuPos LCU position in picture
+ * \param [in] alfUnitPic ALF unit parmeters for LCUs in picture
+ * \param [in] isLeftUnitAvailable left ALF unit available (true) or not (false)
+ * \param [in] isUpUnitAvailable upper ALF unit available (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::getFiltOffAlfUnitParam(AlfUnitParam* alfFiltOffParam, Int lcuPos, AlfUnitParam* alfUnitPic, Bool isLeftUnitAvailable, Bool isUpUnitAvailable)
+{
+  Int    numSliceDataInCurrLCU = m_numSlicesDataInOneLCU[lcuPos];
+
+  if(numSliceDataInCurrLCU == 1)
+  {
+    if(isLeftUnitAvailable)
+    {
+      Int addrLeft = lcuPos - 1;
+      AlfUnitParam& alfUnitParamLeft = alfUnitPic[addrLeft];
+
+      if(alfUnitParamLeft.alfFiltParam->alf_flag == 0)
+      {
+        alfFiltOffParam->mergeType    = ALF_MERGE_LEFT;
+        alfFiltOffParam->isEnabled    = false;
+        alfFiltOffParam->alfFiltParam = alfUnitParamLeft.alfFiltParam;
+
+        return;
+      }
+    }
+
+    if(isUpUnitAvailable)
+    {
+      Int addrUp = lcuPos - m_numLCUInPicWidth;
+      AlfUnitParam& alfUnitParamUp = alfUnitPic[addrUp];
+
+      if(alfUnitParamUp.alfFiltParam->alf_flag == 0)
+      {
+        alfFiltOffParam->mergeType    = ALF_MERGE_UP;
+        alfFiltOffParam->isEnabled    = false;
+        alfFiltOffParam->alfFiltParam = alfUnitParamUp.alfFiltParam;
+
+        return;
+      }
+
+    }
+  }
+
+
+  alfFiltOffParam->mergeType = ALF_MERGE_DISABLED;
+  alfFiltOffParam->isEnabled = false;
+  alfFiltOffParam->alfFiltParam = alfUnitPic[lcuPos].alfFiltParam;
+
+  return;
+}
+
+/** Calculate distortion for ALF LCU
+ * \param [in] skipLCUBottomLines true for considering skipping bottom LCU lines
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfLCUInfo ALF LCU information
+ * \param [in] picSrc source picture buffer
+ * \param [in] picCmp to-be-compared picture buffer
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ * \return the distortion
+ */
+#if HHI_INTERVIEW_SKIP
+Int64 TEncAdaptiveLoopFilter::calcAlfLCUDist(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo& alfLCUInfo, Pel* picSrc, Pel* picCmp, Pel* picUsed, Int stride, Int formatShift)
+#else
+Int64 TEncAdaptiveLoopFilter::calcAlfLCUDist(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo& alfLCUInfo, Pel* picSrc, Pel* picCmp, Int stride, Int formatShift)
+#endif
+{
+  Int64 dist = 0;  
+  Int  posOffset, ypos, xpos, height, width;
+  Pel* pelCmp;
+  Pel* pelSrc;
+#if HHI_INTERVIEW_SKIP
+  Pel* pelUsed = NULL ;
+#endif
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+  Int endypos;
+  Bool notSkipLinesBelowVB = true;
+  Int lcuAddr = alfLCUInfo.pcCU->getAddr();
+  if(skipLCUBottomLines)
+  {
+    if(lcuAddr + m_numLCUInPicWidth < m_uiNumCUsInFrame)
+    {
+      notSkipLinesBelowVB = false;
+    }
+  }
+#endif
+
+  switch(compIdx)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      for(Int n=0; n< alfLCUInfo.numSGU; n++)
+      {
+        ypos    = (Int)(alfLCUInfo[n].posY   >> formatShift);
+        xpos    = (Int)(alfLCUInfo[n].posX   >> formatShift);
+        height  = (Int)(alfLCUInfo[n].height >> formatShift);
+        width   = (Int)(alfLCUInfo[n].width  >> formatShift);
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+        if(!notSkipLinesBelowVB )
+        {
+          endypos = ypos+ height -1;
+          Int iLineVBPos = m_lcuHeightChroma - 2;
+          Int yEndLineInLCU = endypos % m_lcuHeightChroma;
+          height = (yEndLineInLCU >= iLineVBPos) ? (height - 2) : height ; 
+        }
+#endif
+
+        posOffset = (ypos * stride) + xpos;
+        pelCmp    = picCmp + posOffset;    
+        pelSrc    = picSrc + posOffset;    
+
+
+#if HHI_INTERVIEW_SKIP
+        if( picUsed)
+        {
+          pelUsed   = picUsed+ posOffset;
+        }
+        dist  += xCalcSSD( pelSrc, pelCmp,  pelUsed, width, height, stride );
+#else
+        dist  += xCalcSSD( pelSrc, pelCmp,  width, height, stride );
+#endif
+      }
+
+    }
+    break;
+  case ALF_Y:
+    {
+      for(Int n=0; n< alfLCUInfo.numSGU; n++)
+      {
+        ypos    = (Int)(alfLCUInfo[n].posY);
+        xpos    = (Int)(alfLCUInfo[n].posX);
+        height  = (Int)(alfLCUInfo[n].height);
+        width   = (Int)(alfLCUInfo[n].width);
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+        if(!notSkipLinesBelowVB)
+        {
+          endypos = ypos+ height -1;
+          Int iLineVBPos = m_lcuHeight - 4;
+          Int yEndLineInLCU = endypos % m_lcuHeight;
+          height = (yEndLineInLCU >= iLineVBPos) ? (height - 4) : height ; 
+        }
+#endif
+
+        posOffset = (ypos * stride) + xpos;
+        pelCmp    = picCmp + posOffset;    
+        pelSrc    = picSrc + posOffset;    
+
+#if HHI_INTERVIEW_SKIP
+        if( picUsed )
+        {
+          pelUsed   = picUsed+ posOffset;
+        }
+        dist  += xCalcSSD( pelSrc, pelCmp,  pelUsed, width, height, stride );
+#else
+        dist  += xCalcSSD( pelSrc, pelCmp,  width, height, stride );
+#endif
+      }
+
+    }
+    break;
+  default:
+    {
+      printf("not a legal component ID for ALF \n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+  return dist;
+}
+
+/** Copy one ALF LCU region
+ * \param [in] alfLCUInfo ALF LCU information
+ * \param [out] picDst to-be-compared picture buffer
+ * \param [in] picSrc source picture buffer
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ */
+Void TEncAdaptiveLoopFilter::copyOneAlfLCU(AlfLCUInfo& alfLCUInfo, Pel* picDst, Pel* picSrc, Int stride, Int formatShift)
+{
+  Int posOffset, ypos, xpos, height, width;
+  Pel* pelDst;
+  Pel* pelSrc;
+
+  for(Int n=0; n< alfLCUInfo.numSGU; n++)
+  {
+    ypos    = (Int)(alfLCUInfo[n].posY   >> formatShift);
+    xpos    = (Int)(alfLCUInfo[n].posX   >> formatShift);
+    height  = (Int)(alfLCUInfo[n].height >> formatShift);
+    width   = (Int)(alfLCUInfo[n].width  >> formatShift);
+
+    posOffset  = ( ypos * stride)+ xpos;
+    pelDst   = picDst  + posOffset;    
+    pelSrc   = picSrc  + posOffset;    
+
+    for(Int j=0; j< height; j++)
+    {
+      ::memcpy(pelDst, pelSrc, sizeof(Pel)*width);
+      pelDst += stride;
+      pelSrc += stride;
+    }
+  }
+
+}
+
+/** Reconstruct ALF LCU pixels
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] alfLCUInfo ALF LCU information
+ * \param [in] alfUnitParam ALF unit parameters
+ * \param [in] picDec picture buffer for un-filtered picture 
+ * \param [out] picRest picture buffer for reconstructed picture
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ */
+Void TEncAdaptiveLoopFilter::reconstructOneAlfLCU(Int compIdx, AlfLCUInfo& alfLCUInfo, AlfUnitParam* alfUnitParam, Pel* picDec, Pel* picRest, Int stride, Int formatShift)
+{
+  ALFParam* alfParam = alfUnitParam->alfFiltParam;
+  Int ypos, xpos, height, width;
+
+  if( alfUnitParam->isEnabled)
+  {
+    assert(alfParam->alf_flag == 1);
+
+    //reconstruct ALF coefficients & related parameters 
+    reconstructCoefInfo(compIdx, alfParam, m_filterCoeffSym, m_varIndTab);
+
+    //filtering process
+    for(Int n=0; n< alfLCUInfo.numSGU; n++)
+    {
+      ypos    = (Int)(alfLCUInfo[n].posY   >> formatShift);
+      xpos    = (Int)(alfLCUInfo[n].posX   >> formatShift);
+      height  = (Int)(alfLCUInfo[n].height >> formatShift);
+      width   = (Int)(alfLCUInfo[n].width  >> formatShift);
+
+      filterOneCompRegion(picRest, picDec, stride, (compIdx!=ALF_Y), ypos, ypos+height, xpos, xpos+width, m_filterCoeffSym, m_varIndTab, m_varImg);
+    }
+  }
+  else
+  {
+    copyOneAlfLCU(alfLCUInfo, picRest, picDec, stride, formatShift);
+  }
+}
+
+/** LCU-based mode decision
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] pOrg picture buffer for original picture
+ * \param [in] pDec picture buffer for un-filtered picture 
+ * \param [out] pRest picture buffer for reconstructed picture
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ * \param [in] alfCorrLCUs correlations for LCUs
+ */
+#if HHI_INTERVIEW_SKIP
+Void TEncAdaptiveLoopFilter::executeLCUBasedModeDecision(AlfParamSet* alfParamSet
+                                                        ,Int compIdx, Pel* pOrg, Pel* pDec, Pel* pRest, Pel* pUsed, Int stride, Int formatShift
+                                                        ,AlfCorrData** alfCorrLCUs
+                                                        )
+#else
+Void TEncAdaptiveLoopFilter::executeLCUBasedModeDecision(AlfParamSet* alfParamSet
+                                                        ,Int compIdx, Pel* pOrg, Pel* pDec, Pel* pRest, Int stride, Int formatShift
+                                                        ,AlfCorrData** alfCorrLCUs
+                                                        )
+#endif
+{
+  Double lambda = (compIdx == ALF_Y)?(m_dLambdaLuma):(m_dLambdaChroma);
+  static Int* isProcessed = NULL;
+
+  AlfUnitParam* alfUnitPic = m_alfPicFiltUnits[compIdx];
+
+  Int64  distEnc, distOff;
+  Int    rateEnc, rateOff;
+  Double costEnc, costOff;
+  Bool isLeftUnitAvailable, isUpUnitAvailable;
+
+  isProcessed = new Int[m_uiNumCUsInFrame];
+  ::memset(isProcessed, 0, sizeof(Int)*m_uiNumCUsInFrame);
+
+#if LCUALF_FILTER_BUDGET_CONTROL_ENC
+  Int numProcessedLCU = 0;
+  m_alfFiltBudgetPerLcu = (Double)(m_iALFMaxNumberFilters) / (Double)(m_uiNumCUsInFrame);
+  m_alfUsedFilterNum = 0;
+#endif
+
+  for(Int s=0; s<= m_lastSliceIdx; s++)
+  {
+    if(!m_pcPic->getValidSlice(s))
+    {
+      continue;
+    }
+    Bool isAcrossSlice = (m_alfCoefInSlice)?(!m_isNonCrossSlice):(true);
+    Int  numLCUWidth   = alfParamSet[s].numLCUInWidth;
+
+    AlfUnitParam* alfSliceUnitParams = alfParamSet[s].alfUnitParam[compIdx];
+    std::vector<ALFParam*> storedFilters;
+    storedFilters.clear(); //reset stored filter buffer at the slice beginning
+
+    Int u =0; //counter for LCU index in slice
+    Int countFiltOffLCU = 0; //counter for number of LCU with filter-off mode
+    Int countNewFilts = 0; //counter for number of LCU with new filter inside slice
+
+    Int numTilesInSlice = (Int)m_pvpSliceTileAlfLCU[s].size();
+    for(Int t=0; t< numTilesInSlice; t++)
+    {
+      std::vector<AlfLCUInfo*> & vpAlfLCU = m_pvpSliceTileAlfLCU[s][t];
+      Pel* pSrc = pDec;
+
+      if(m_bUseNonCrossALF)
+      {
+        pSrc = getPicBuf(m_pcSliceYuvTmp, compIdx);
+        copyRegion(vpAlfLCU, pSrc, pDec, stride, formatShift);
+        extendRegionBorder(vpAlfLCU, pSrc, stride, formatShift);
+      }
+
+      Int numLCUs = (Int)vpAlfLCU.size();
+      for(Int n=0; n< numLCUs; n++)
+      {
+        AlfLCUInfo*   alfLCU       = vpAlfLCU[n];                  //ALF LCU information
+        TComDataCU*   pcCU         = alfLCU->pcCU;
+        Int           addr         = pcCU->getAddr();              //real LCU addr
+        AlfUnitParam* alfUnitParam = &(alfSliceUnitParams[u]);
+
+        if(isProcessed[addr] == 0)
+        {
+          Int           maxNumFilter = (Int)NO_VAR_BINS;   
+
+#if LCUALF_FILTER_BUDGET_CONTROL_ENC
+          Bool          isOutOfFilterBudget = true;
+          Double        usedFiltBudget = (numProcessedLCU == 0) ? 0.0 : (Double)m_alfUsedFilterNum / (Double)(numProcessedLCU);
+          if ( (m_alfFiltBudgetPerLcu >= usedFiltBudget) && (m_alfUsedFilterNum < m_iALFMaxNumberFilters) )
+          {
+            isOutOfFilterBudget = false;
+            Int leftNumFilt = m_iALFMaxNumberFilters - m_alfUsedFilterNum;
+            Int avgNumFilt  = leftNumFilt / (m_uiNumCUsInFrame - numProcessedLCU) + 1 ;
+            maxNumFilter = (leftNumFilt < avgNumFilt) ? leftNumFilt : avgNumFilt ;
+          }
+#endif
+
+          AlfCorrData*  alfCorr      = alfCorrLCUs[addr];            //ALF LCU correlation
+          alfUnitParam->alfFiltParam = alfUnitPic[addr].alfFiltParam;
+
+          //mode decision 
+          isLeftUnitAvailable = (   (addr % m_numLCUInPicWidth != 0) && (u != 0));
+          isUpUnitAvailable   = (((Int)(addr/m_numLCUInPicWidth) > 0) && ( ( (u - numLCUWidth) >= 0) || isAcrossSlice ));
+
+          decideLCUALFUnitParam(compIdx, alfUnitPic, u, addr, numLCUWidth, alfSliceUnitParams, alfCorr, storedFilters, maxNumFilter, lambda, isLeftUnitAvailable, isUpUnitAvailable);
+          reconstructOneAlfLCU(compIdx, *alfLCU, alfUnitParam, pSrc, pRest, stride, formatShift);
+#if HHI_INTERVIEW_SKIP
+          distEnc = calcAlfLCUDist(!m_picBasedALFEncode, compIdx, *alfLCU, pOrg, pRest, pUsed, stride, formatShift);
+#else
+          distEnc = calcAlfLCUDist(!m_picBasedALFEncode, compIdx, *alfLCU, pOrg, pRest, stride, formatShift);
+#endif
+          rateEnc = calculateAlfUnitRateRDO(alfUnitParam, (Int)storedFilters.size());
+          costEnc = (Double)distEnc + lambda*((Double)rateEnc);
+          costEnc += ((lambda* 1.5)*1.0);  //RDCO
+
+          //v.s. filter off case
+          AlfUnitParam alfUnitParamOff;
+          getFiltOffAlfUnitParam(&alfUnitParamOff, addr, alfUnitPic, isLeftUnitAvailable, isUpUnitAvailable);
+#if HHI_INTERVIEW_SKIP
+          distOff = calcAlfLCUDist(!m_picBasedALFEncode, compIdx, *alfLCU, pOrg, pSrc, pUsed, stride, formatShift);
+#else
+          distOff = calcAlfLCUDist(!m_picBasedALFEncode, compIdx, *alfLCU, pOrg, pSrc, stride, formatShift);
+#endif
+          rateOff = calculateAlfUnitRateRDO(&alfUnitParamOff, (Int)storedFilters.size());
+          costOff = (Double)distOff + lambda*((Double)rateOff);
+
+#if LCUALF_FILTER_BUDGET_CONTROL_ENC
+          if( (costOff < costEnc)  ||  isOutOfFilterBudget)
+#else
+          if( costOff < costEnc)
+#endif
+          {
+            //filter off. set alf_flag = 0, copy pDest to pRest
+            *alfUnitParam = alfUnitParamOff;
+            alfUnitParam->alfFiltParam->alf_flag = 0;
+            copyOneAlfLCU(*alfLCU, pRest, pSrc, stride, formatShift);
+          }
+
+          if(alfUnitParam->mergeType == ALF_MERGE_DISABLED)
+          {
+            if(alfUnitParam->isEnabled)
+            {
+              if(alfUnitParam->isNewFilt)
+              {
+                //update stored filter buffer
+                storedFilters.push_back(alfUnitParam->alfFiltParam);
+                assert(alfUnitParam->alfFiltParam->alf_flag == 1);
+              }
+            }
+          }
+
+          alfUnitPic[addr] = *alfUnitParam;
+
+          isProcessed[addr] = 1;
+
+#if LCUALF_FILTER_BUDGET_CONTROL_ENC
+          numProcessedLCU++;
+          if(alfUnitParam->mergeType == ALF_MERGE_DISABLED && alfUnitParam->isEnabled && alfUnitParam->isNewFilt)
+          {
+            m_alfUsedFilterNum += alfUnitParam->alfFiltParam->filters_per_group;
+          }
+#endif
+        }
+        else
+        {
+          //keep the ALF parameters in LCU are the same
+          *alfUnitParam = alfUnitPic[addr];
+          reconstructOneAlfLCU(compIdx, *alfLCU, alfUnitParam, pSrc, pRest, stride, formatShift);
+
+#if LCUALF_FILTER_BUDGET_CONTROL_ENC
+          if(alfUnitParam->mergeType == ALF_MERGE_DISABLED && alfUnitParam->isEnabled && alfUnitParam->isNewFilt)
+          {
+            m_alfUsedFilterNum += alfUnitParam->alfFiltParam->filters_per_group;
+          }
+#endif
+        }
+
+        if(alfUnitParam->alfFiltParam->alf_flag == 0)
+        {
+          countFiltOffLCU++;
+        }
+        else
+        {
+          Bool isNewFiltInSlice =   (alfUnitParam->mergeType == ALF_MERGE_DISABLED && alfUnitParam->isEnabled && alfUnitParam->isNewFilt);
+          Bool isMergeAcrossSlice = ( alfUnitParam->mergeType == ALF_MERGE_UP && (u-numLCUWidth < 0) );
+
+          if( isNewFiltInSlice || isMergeAcrossSlice )
+          {
+            countNewFilts++;
+          }
+        }
+
+        u++;      
+
+      } //LCU
+    } //tile
+
+
+    //slice-level parameters
+    AlfUnitParam* firstAlfUnitInSlice = &(alfSliceUnitParams[0]);
+    if( countFiltOffLCU == u ) //number of filter-off LCU is equal to the number of LCUs in slice
+    {
+      alfParamSet[s].isEnabled [compIdx] = false;    
+      alfParamSet[s].isUniParam[compIdx] = true; //uni-param, all off
+      assert(firstAlfUnitInSlice->alfFiltParam->alf_flag == 0);
+    }
+    else
+    {
+      alfParamSet[s].isEnabled[compIdx] = true;
+      if( countNewFilts == 1 && firstAlfUnitInSlice->alfFiltParam->alf_flag != 0 && countFiltOffLCU == 0 )
+      {
+        alfParamSet[s].isUniParam[compIdx] = true;
+      }
+      else
+      {
+        alfParamSet[s].isUniParam[compIdx] = false;
+      }
+    }
+  } //slice
+
+
+  delete[] isProcessed;
+  isProcessed = NULL;
+}
+
+
+/** Decide ALF parameter set for luma/chroma components (top function) 
+ * \param [in] pPicOrg picture buffer for original picture
+ * \param [in] pPicDec picture buffer for un-filtered picture 
+ * \param [out] pPicRest picture buffer for reconstructed picture
+ * \param [in, out] alfParamSet ALF parameter set
+ * \param [in, out] alfCtrlParam ALF CU-on/off control parameters
+ */
+#if HHI_INTERVIEW_SKIP
+Void TEncAdaptiveLoopFilter::decideParameters(TComPicYuv* pPicOrg, TComPicYuv* pPicDec, TComPicYuv* pPicRest, TComPicYuv* pUsedPelMap
+                                            , AlfParamSet* alfParamSet
+                                            , std::vector<AlfCUCtrlInfo>* alfCtrlParam)
+#else
+Void TEncAdaptiveLoopFilter::decideParameters(TComPicYuv* pPicOrg, TComPicYuv* pPicDec, TComPicYuv* pPicRest
+                                            , AlfParamSet* alfParamSet
+                                            , std::vector<AlfCUCtrlInfo>* alfCtrlParam)
+#endif
+{
+  static Int lumaStride        = pPicOrg->getStride();
+  static Int chromaStride      = pPicOrg->getCStride();
+
+  Pel *pOrg, *pDec, *pRest;
+  Int stride, formatShift;
+#if HHI_INTERVIEW_SKIP
+  Pel *pUsed = NULL ;
+#endif
+
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    pOrg        = getPicBuf(pPicOrg, compIdx);
+    pDec        = getPicBuf(pPicDec, compIdx);
+    pRest       = getPicBuf(pPicRest, compIdx);
+#if HHI_INTERVIEW_SKIP
+    if( pUsedPelMap )
+    {
+      pUsed        = getPicBuf(pUsedPelMap, compIdx);
+    }
+#endif
+    stride      = (compIdx == ALF_Y)?(lumaStride):(chromaStride);
+    formatShift = (compIdx == ALF_Y)?(0):(1);
+
+    AlfCorrData** alfCorrComp     = m_alfCorr[compIdx];
+
+    if(!m_picBasedALFEncode) //lcu-based optimization
+    {
+#if HHI_INTERVIEW_SKIP
+      executeLCUBasedModeDecision(alfParamSet, compIdx, pOrg, pDec, pRest, pUsed, stride, formatShift, alfCorrComp);
+#else
+      executeLCUBasedModeDecision(alfParamSet, compIdx, pOrg, pDec, pRest, stride, formatShift, alfCorrComp);
+#endif
+    }
+    else //picture-based optimization
+    {
+      AlfPicQTPart* alfPicQTPart = m_alfPQTPart[compIdx];
+#if HHI_INTERVIEW_SKIP
+      executePicBasedModeDecision(alfParamSet, alfPicQTPart, compIdx, pOrg, pDec, pRest, pUsed, stride, formatShift, alfCorrComp);
+#else
+      executePicBasedModeDecision(alfParamSet, alfPicQTPart, compIdx, pOrg, pDec, pRest, stride, formatShift, alfCorrComp);
+#endif
+    }  
+
+  } //component
+
+}
+
+/** Gather correlations for all LCUs in picture
+ * \param [in] pPicOrg picture buffer for original picture
+ * \param [in] pPicDec picture buffer for un-filtered picture 
+ */
+Void TEncAdaptiveLoopFilter::getStatistics(TComPicYuv* pPicOrg, TComPicYuv* pPicDec)
+{
+  Int lumaStride   = pPicOrg->getStride();
+  Int chromaStride = pPicOrg->getCStride();
+  const  Int chromaFormatShift = 1;
+
+  //calculate BA index
+  calcOneRegionVar(m_varImg, getPicBuf(pPicDec, ALF_Y), lumaStride, false, 0, m_img_height, 0, m_img_width);
+  for(Int compIdx = 0; compIdx < NUM_ALF_COMPONENT; compIdx++)
+  {
+    AlfCorrData** alfCorrComp = m_alfCorr[compIdx];
+    Int          formatShift = (compIdx == ALF_Y)?(0):(chromaFormatShift);
+    Int          stride      = (compIdx == ALF_Y)?(lumaStride):(chromaStride);
+
+    getOneCompStatistics(alfCorrComp, compIdx, getPicBuf(pPicOrg, compIdx), getPicBuf(pPicDec, compIdx), stride, formatShift, false);
+  } 
+}
+
+/** Gather correlations for all LCUs of one luma/chroma component in picture
+ * \param [out] alfCorrComp correlations for LCUs
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] imgOrg picture buffer for original picture
+ * \param [in] imgDec picture buffer for un-filtered picture 
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ * \param [in] isRedesignPhase at re-design filter stage (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::getOneCompStatistics(AlfCorrData** alfCorrComp, Int compIdx, Pel* imgOrg, Pel* imgDec, Int stride, Int formatShift, Bool isRedesignPhase)
+{
+
+  // initialize to zero
+  for(Int n=0; n< m_uiNumCUsInFrame; n++)
+  {
+    alfCorrComp[n]->reset();
+  }
+
+  for(Int s=0; s<= m_lastSliceIdx; s++)
+  {
+    if(!m_pcPic->getValidSlice(s))
+    {
+      continue;
+    }
+    Int numTilesInSlice = (Int)m_pvpSliceTileAlfLCU[s].size();
+    for(Int t=0; t< numTilesInSlice; t++)
+    {
+      std::vector<AlfLCUInfo*> & vpAlfLCU = m_pvpSliceTileAlfLCU[s][t];
+      Pel* pSrc = imgDec;
+
+      if(m_bUseNonCrossALF)
+      {
+        pSrc = getPicBuf(m_pcSliceYuvTmp, compIdx);
+        copyRegion(vpAlfLCU, pSrc, imgDec, stride, formatShift);
+        extendRegionBorder(vpAlfLCU, pSrc, stride, formatShift);
+      }
+
+      Int numLCUs = (Int)vpAlfLCU.size();
+      for(Int n=0; n< numLCUs; n++)
+      {
+        AlfLCUInfo* alfLCU = vpAlfLCU[n];
+        Int addr = alfLCU->pcCU->getAddr();
+        getStatisticsOneLCU(!m_picBasedALFEncode, compIdx, alfLCU, alfCorrComp[addr], imgOrg, pSrc, stride, formatShift, isRedesignPhase);
+      } //LCU
+    } //tile
+  } //slice
+
+}
+
+/** Gather correlations for one LCU
+ * \param [out] alfCorrComp correlations for LCUs
+ * \param [in] compIdx luma/chroma component index
+ * \param [in] imgOrg picture buffer for original picture
+ * \param [in] imgDec picture buffer for un-filtered picture 
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] formatShift 0 for luma and 1 for chroma (4:2:0)
+ * \param [in] isRedesignPhase at re-design filter stage (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::getStatisticsOneLCU(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo* alfLCU, AlfCorrData* alfCorr, Pel* pPicOrg, Pel* pPicSrc, Int stride, Int formatShift, Bool isRedesignPhase)
+{
+  Int numBlocks = alfLCU->numSGU;
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+  Int  lcuAddr = alfLCU->pcCU->getAddr();
+  Bool notSkipLinesBelowVB = true;
+  Int  endypos;
+#endif
+  Bool isLastBlock;
+  Int ypos, xpos, height, width;
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+  if(skipLCUBottomLines)
+  {
+    if(lcuAddr + m_numLCUInPicWidth < m_uiNumCUsInFrame)
+    {
+      notSkipLinesBelowVB = false;
+    }
+  }
+#endif
+
+  switch(compIdx)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      for(Int n=0; n< numBlocks; n++)
+      {
+        isLastBlock = (n== numBlocks-1);
+        NDBFBlockInfo& AlfSGU = (*alfLCU)[n];
+
+        ypos   = (Int)(AlfSGU.posY  >> formatShift);
+        xpos   = (Int)(AlfSGU.posX  >> formatShift);
+        height = (Int)(AlfSGU.height>> formatShift);
+        width  = (Int)(AlfSGU.width >> formatShift);
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+        if(!notSkipLinesBelowVB )
+        {
+          endypos = ypos+ height -1;
+          Int iLineVBPos = m_lcuHeightChroma - 2;
+          Int yEndLineInLCU = endypos % m_lcuHeightChroma;
+          height = (yEndLineInLCU >= iLineVBPos) ? (height - 2) : height ; 
+        }
+#endif
+
+        calcCorrOneCompRegionChma(pPicOrg, pPicSrc, stride, ypos, xpos, height, width, alfCorr->ECorr[0], alfCorr->yCorr[0], isLastBlock);
+      }
+    }
+    break;
+  case ALF_Y:
+    {
+      Bool forceCollection = true;
+
+      if(isRedesignPhase)
+      {
+        Int numValidPels = 0;
+        for(Int n=0; n< numBlocks; n++)
+        {
+          NDBFBlockInfo& AlfSGU = (*alfLCU)[n];
+
+          ypos   = (Int)(AlfSGU.posY  );
+          xpos   = (Int)(AlfSGU.posX  );
+          height = (Int)(AlfSGU.height);
+          width  = (Int)(AlfSGU.width );
+
+          for (Int y = ypos; y < ypos+ height; y++)
+          {
+            for (Int x = xpos; x < xpos + width; x++)
+            {
+              if (m_maskImg[y][x] == 1)
+              {
+                numValidPels++;
+              }
+            }
+          }
+        }
+
+        if(numValidPels > 0)
+        {
+          forceCollection = false;
+        }
+      }
+
+      for(Int n=0; n< numBlocks; n++)
+      {
+        isLastBlock = (n== numBlocks-1);
+        NDBFBlockInfo& AlfSGU = (*alfLCU)[n];
+
+        ypos   = (Int)(AlfSGU.posY  );
+        xpos   = (Int)(AlfSGU.posX  );
+        height = (Int)(AlfSGU.height);
+        width  = (Int)(AlfSGU.width );
+
+#if LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER
+        endypos = ypos+ height -1;
+        if(!notSkipLinesBelowVB)
+        {
+          Int iLineVBPos = m_lcuHeight - 4;
+          Int yEndLineInLCU = endypos % m_lcuHeight;
+          height = (yEndLineInLCU >= iLineVBPos) ? (height - 4) : height ; 
+        }
+#endif
+
+        calcCorrOneCompRegionLuma(pPicOrg, pPicSrc, stride, ypos, xpos, height, width, alfCorr->ECorr, alfCorr->yCorr, alfCorr->pixAcc, forceCollection, isLastBlock);
+      }
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component index for ALF\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+
+/** Gather correlations for one region for chroma component
+ * \param [in] imgOrg picture buffer for original picture
+ * \param [in] imgPad picture buffer for un-filtered picture 
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] yPos region starting y position
+ * \param [in] xPos region starting x position
+ * \param [in] height region height
+ * \param [in] width region width
+ * \param [out] eCorr auto-correlation matrix
+ * \param [out] yCorr cross-correlation array
+ * \param [in] isSymmCopyBlockMatrix symmetrically copy correlation values in eCorr (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::calcCorrOneCompRegionChma(Pel* imgOrg, Pel* imgPad, Int stride 
+                                                     , Int yPos, Int xPos, Int height, Int width
+                                                     , Double **eCorr, Double *yCorr, Bool isSymmCopyBlockMatrix
+                                                      )
+{
+  Int yPosEnd = yPos + height;
+  Int xPosEnd = xPos + width;
+  Int N = ALF_MAX_NUM_COEF; //m_sqrFiltLengthTab[0];
+
+  Int imgHeightChroma = m_img_height>>1;
+
+  Int yLineInLCU, paddingLine;
+  Int ELocal[ALF_MAX_NUM_COEF];
+  Pel *imgPad1, *imgPad2, *imgPad3, *imgPad4, *imgPad5, *imgPad6;
+  Int i, j, k, l, yLocal;
+
+  imgPad += (yPos*stride);
+  imgOrg += (yPos*stride);
+
+  for (i= yPos; i< yPosEnd; i++)
+  {
+    yLineInLCU = i % m_lcuHeightChroma;
+
+    if (yLineInLCU==0 && i>0)
+    {
+      paddingLine = yLineInLCU + 2 ;
+      imgPad1 = imgPad + stride;
+      imgPad2 = imgPad - stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;;
+    }
+    else if (yLineInLCU < m_lineIdxPadBotChroma || i-yLineInLCU+m_lcuHeightChroma >= imgHeightChroma )
+    {
+      imgPad1 = imgPad + stride;
+      imgPad2 = imgPad - stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = imgPad + 3*stride;
+      imgPad6 = imgPad - 3*stride;
+    }
+    else if (yLineInLCU < m_lineIdxPadTopChroma)
+    {
+      paddingLine = - yLineInLCU + m_lineIdxPadTopChroma - 1;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + min(paddingLine, 1)*stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + min(paddingLine, 2)*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + min(paddingLine, 3)*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - 3*stride;
+    }
+    else
+    {
+      paddingLine = yLineInLCU - m_lineIdxPadTopChroma ;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - min(paddingLine, 1)*stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + 2*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - min(paddingLine, 2)*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;
+    }
+
+    for (j= xPos; j< xPosEnd; j++)
+    {
+      memset(ELocal, 0, N*sizeof(Int));
+
+      ELocal[0] = (imgPad5[j] + imgPad6[j]);
+
+      ELocal[1] = (imgPad3[j] + imgPad4[j]);
+
+      ELocal[2] = (imgPad1[j-1] + imgPad2[j+1]);
+      ELocal[3] = (imgPad1[j  ] + imgPad2[j  ]);
+      ELocal[4] = (imgPad1[j+1] + imgPad2[j-1]);
+
+      ELocal[5] = (imgPad[j+4] + imgPad[j-4]);
+      ELocal[6] = (imgPad[j+3] + imgPad[j-3]);
+      ELocal[7] = (imgPad[j+2] + imgPad[j-2]);
+      ELocal[8] = (imgPad[j+1] + imgPad[j-1]);
+      ELocal[9] = (imgPad[j  ]);
+
+      yLocal= (Int)imgOrg[j];
+
+      for(k=0; k<N; k++)
+      {
+        eCorr[k][k] += ELocal[k]*ELocal[k];
+        for(l=k+1; l<N; l++)
+        {
+          eCorr[k][l] += ELocal[k]*ELocal[l];
+        }
+
+        yCorr[k] += yLocal*ELocal[k];
+      }
+    }
+
+    imgPad+= stride;
+    imgOrg+= stride;
+  }
+
+  if(isSymmCopyBlockMatrix)
+  {
+    for(j=0; j<N-1; j++)
+    {
+      for(i=j+1; i<N; i++)
+      {
+        eCorr[i][j] = eCorr[j][i];
+      }
+    }
+  }
+}
+
+/** Gather correlations for one region for luma component
+ * \param [in] imgOrg picture buffer for original picture
+ * \param [in] imgPad picture buffer for un-filtered picture 
+ * \param [in] stride buffer stride size for 1-D pictrue memory
+ * \param [in] yPos region starting y position
+ * \param [in] xPos region starting x position
+ * \param [in] height region height
+ * \param [in] width region width
+ * \param [out] eCorr auto-correlation matrix
+ * \param [out] yCorr cross-correlation array
+ * \param [out] pixAcc pixel squared value
+ * \param [in] isforceCollection all pixel are used for correlation calculation (true) or not (false)
+ * \param [in] isSymmCopyBlockMatrix symmetrically copy correlation values in eCorr (true) or not (false)
+ */
+Void TEncAdaptiveLoopFilter::calcCorrOneCompRegionLuma(Pel* imgOrg, Pel* imgPad, Int stride
+                                                      ,Int yPos, Int xPos, Int height, Int width
+                                                      ,Double ***eCorr, Double **yCorr, Double *pixAcc
+                                                      ,Bool isforceCollection, Bool isSymmCopyBlockMatrix
+                                                      )
+{
+  Int yPosEnd = yPos + height;
+  Int xPosEnd = xPos + width;
+  Int yLineInLCU;
+  Int paddingLine ;
+  Int N = ALF_MAX_NUM_COEF; //m_sqrFiltLengthTab[0];
+
+  Int ELocal[ALF_MAX_NUM_COEF];
+  Pel *imgPad1, *imgPad2, *imgPad3, *imgPad4, *imgPad5, *imgPad6;
+  Int i, j, k, l, yLocal, varInd;
+  Double **E;
+  Double *yy;
+
+  imgPad += (yPos*stride);
+  imgOrg += (yPos*stride);
+
+  for (i= yPos; i< yPosEnd; i++)
+  {
+    yLineInLCU = i % m_lcuHeight;
+
+    if (yLineInLCU<m_lineIdxPadBot || i-yLineInLCU+m_lcuHeight >= m_img_height)
+    {
+      imgPad1 = imgPad + stride;
+      imgPad2 = imgPad - stride;
+      imgPad3 = imgPad + 2*stride;
+      imgPad4 = imgPad - 2*stride;
+      imgPad5 = imgPad + 3*stride;
+      imgPad6 = imgPad - 3*stride;
+    }
+    else if (yLineInLCU<m_lineIdxPadTop)
+    {
+      paddingLine = - yLineInLCU + m_lineIdxPadTop - 1;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + min(paddingLine, 1)*stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + min(paddingLine, 2)*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - 2*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + min(paddingLine, 3)*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - 3*stride;
+    }
+    else
+    {
+      paddingLine = yLineInLCU - m_lineIdxPadTop;
+      imgPad1 = (paddingLine < 1) ? imgPad : imgPad + stride;
+      imgPad2 = (paddingLine < 1) ? imgPad : imgPad - min(paddingLine, 1)*stride;
+      imgPad3 = (paddingLine < 2) ? imgPad : imgPad + 2*stride;
+      imgPad4 = (paddingLine < 2) ? imgPad : imgPad - min(paddingLine, 2)*stride;
+      imgPad5 = (paddingLine < 3) ? imgPad : imgPad + 3*stride;
+      imgPad6 = (paddingLine < 3) ? imgPad : imgPad - min(paddingLine, 3)*stride;
+    }         
+
+    for (j= xPos; j< xPosEnd; j++)
+    {
+      if ( m_maskImg[i][j] || isforceCollection )
+      {
+        varInd = m_varImg[i/VAR_SIZE_H][j/VAR_SIZE_W];
+        memset(ELocal, 0, N*sizeof(Int));
+
+        ELocal[0] = (imgPad5[j] + imgPad6[j]);
+        ELocal[1] = (imgPad3[j] + imgPad4[j]);
+
+        ELocal[2] = (imgPad1[j-1] + imgPad2[j+1]);
+        ELocal[3] = (imgPad1[j  ] + imgPad2[j  ]);
+        ELocal[4] = (imgPad1[j+1] + imgPad2[j-1]);
+
+        ELocal[5] = (imgPad[j+4] + imgPad[j-4]);
+        ELocal[6] = (imgPad[j+3] + imgPad[j-3]);
+        ELocal[7] = (imgPad[j+2] + imgPad[j-2]);
+        ELocal[8] = (imgPad[j+1] + imgPad[j-1]);
+        ELocal[9] = (imgPad[j  ]);
+
+        yLocal= imgOrg[j];
+        pixAcc[varInd] += (yLocal*yLocal);
+        E  = eCorr[varInd];
+        yy = yCorr[varInd];
+
+        for (k=0; k<N; k++)
+        {
+          for (l=k; l<N; l++)
+          {
+            E[k][l]+=(double)(ELocal[k]*ELocal[l]);
+          }
+          yy[k]+=(double)(ELocal[k]*yLocal);
+        }
+      }
+    }
+    imgPad += stride;
+    imgOrg += stride;
+  }
+
+  if(isSymmCopyBlockMatrix)
+  {
+    for (varInd=0; varInd<NO_VAR_BINS; varInd++)
+    {
+      E = eCorr[varInd];
+      for (k=1; k<N; k++)
+      {
+        for (l=0; l<k; l++)
+        {
+          E[k][l] = E[l][k];
+        }
+      }
+    }
+  }
+
+}
+
+
+/** 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.
+ */
+Void TEncAdaptiveLoopFilter::PCMLFDisableProcess (TComPic* pcPic)
+{
+  xPCMRestoration(pcPic);
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+Void TEncAdaptiveLoopFilter::xCreateTmpAlfCtrlFlags()
+{
+  for( UInt uiCUAddr = 0; uiCUAddr < m_pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( uiCUAddr );
+    pcCU->createTmpAlfCtrlFlag();
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xDestroyTmpAlfCtrlFlags()
+{
+  for( UInt uiCUAddr = 0; uiCUAddr < m_pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( uiCUAddr );
+    pcCU->destroyTmpAlfCtrlFlag();
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xCopyTmpAlfCtrlFlagsTo()
+{
+  for( UInt uiCUAddr = 0; uiCUAddr < m_pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( uiCUAddr );
+    pcCU->copyAlfCtrlFlagFromTmp();
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xCopyTmpAlfCtrlFlagsFrom()
+{
+  for( UInt uiCUAddr = 0; uiCUAddr < m_pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( uiCUAddr );
+    pcCU->copyAlfCtrlFlagToTmp();
+  }
+}
+
+/** Encode ALF CU control flags
+ */
+Void TEncAdaptiveLoopFilter::xEncodeCUAlfCtrlFlags(std::vector<AlfCUCtrlInfo> &vAlfCUCtrlParam)
+{
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    if(!m_pcPic->getValidSlice(s))
+    {
+      continue;
+    }
+
+    AlfCUCtrlInfo& rCUCtrlInfo = vAlfCUCtrlParam[s];
+    if(rCUCtrlInfo.cu_control_flag == 1)
+    {
+      for(Int i=0; i< (Int)rCUCtrlInfo.alf_cu_flag.size(); i++)
+      {
+        m_pcEntropyCoder->encodeAlfCtrlFlag(rCUCtrlInfo.alf_cu_flag[i]);
+      }
+    }
+  }
+}
+Void TEncAdaptiveLoopFilter::xEncodeCUAlfCtrlFlag(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  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;
+  
+#if AD_HOCS_SLICES  
+  if( ( uiRPelX >= pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#else  
+  if( ( uiRPelX >= pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#endif  
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( m_pcPic->getNumPartInCU() >> (uiDepth<<1) )>>2;
+    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] ];
+      
+#if AD_HOCS_SLICES      
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#else
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#endif      
+        xEncodeCUAlfCtrlFlag(pcCU, uiAbsPartIdx, uiDepth+1);
+    }
+    return;
+  }
+  
+  m_pcEntropyCoder->encodeAlfCtrlFlag(pcCU, uiAbsPartIdx);
+}
+
+#if IBDI_DISTORTION
+#if HHI_INTERVIEW_SKIP
+UInt64 TEncAdaptiveLoopFilter::xCalcSSD(Pel* pOrg, Pel* pCmp, Pel* pUsed, Int iWidth, Int iHeight, Int iStride )
+{
+  UInt64 uiSSD = 0;
+  Int x, y;
+
+  Int iShift = g_uiBitIncrement;
+  Int iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int iTemp;
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      if ( pUsed ) // interview skipped
+      {
+        if( pUsed[x] )
+        {
+      iTemp = ((pOrg[x]+iOffset)>>iShift) - ((pCmp[x]+iOffset)>>iShift); uiSSD += iTemp * iTemp;
+        }
+      }
+      else         // no interview skip
+      {
+          iTemp = ((pOrg[x]+iOffset)>>iShift) - ((pCmp[x]+iOffset)>>iShift); uiSSD += iTemp * iTemp;
+      }
+    }
+    pOrg += iStride;
+    pCmp += iStride;
+    if(pUsed)
+    {
+      pUsed+= iStride;
+    }
+  }
+
+  return uiSSD;;
+}
+#else
+UInt64 TEncAdaptiveLoopFilter::xCalcSSD(Pel* pOrg, Pel* pCmp, Int iWidth, Int iHeight, Int iStride )
+{
+  UInt64 uiSSD = 0;
+  Int x, y;
+  
+  Int iShift = g_uiBitIncrement;
+  Int iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0;
+  Int iTemp;
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iTemp = ((pOrg[x]+iOffset)>>iShift) - ((pCmp[x]+iOffset)>>iShift); uiSSD += iTemp * iTemp;
+    }
+    pOrg += iStride;
+    pCmp += iStride;
+  }
+
+  return uiSSD;;
+}
+#endif
+#else
+#if HHI_INTERVIEW_SKIP
+UInt64 TEncAdaptiveLoopFilter::xCalcSSD(Pel* pOrg, Pel* pCmp, Pel* pUsed, Int iWidth, Int iHeight, Int iStride )
+{
+  UInt64 uiSSD = 0;
+  Int x, y;
+
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int iTemp =0 ;
+
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      if ( pUsed ) // interview skipped
+      {
+        if( pUsed[x] )
+        {
+          iTemp = pOrg[x] - pCmp[x]; uiSSD += ( iTemp * iTemp ) >> uiShift;
+        }
+      }
+      else         // no interview skip
+      {
+          iTemp = pOrg[x] - pCmp[x]; uiSSD += ( iTemp * iTemp ) >> uiShift;
+      }
+    }
+    pOrg += iStride;
+    pCmp += iStride;
+    if(pUsed)
+    {
+      pUsed+= iStride;
+    }
+  }
+
+  return uiSSD;;
+}
+#else
+UInt64 TEncAdaptiveLoopFilter::xCalcSSD(Pel* pOrg, Pel* pCmp, Int iWidth, Int iHeight, Int iStride )
+{
+  UInt64 uiSSD = 0;
+  Int x, y;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int iTemp;
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iTemp = pOrg[x] - pCmp[x]; uiSSD += ( iTemp * iTemp ) >> uiShift;
+    }
+    pOrg += iStride;
+    pCmp += iStride;
+  }
+  
+  return uiSSD;;
+}
+#endif
+#endif
+
+Int TEncAdaptiveLoopFilter::xGauss(Double **a, Int N)
+{
+  Int i, j, k;
+  Double t;
+  
+  for(k=0; k<N; k++)
+  {
+    if (a[k][k] <0.000001)
+    {
+      return 1;
+    }
+  }
+  
+  for(k=0; k<N-1; k++)
+  {
+    for(i=k+1;i<N; i++)
+    {
+      t=a[i][k]/a[k][k];
+      for(j=k+1; j<=N; j++)
+      {
+        a[i][j] -= t * a[k][j];
+        if(i==j && fabs(a[i][j])<0.000001) return 1;
+      }
+    }
+  }
+  for(i=N-1; i>=0; i--)
+  {
+    t = a[i][N];
+    for(j=i+1; j<N; j++)
+    {
+      t -= a[i][j] * a[j][N];
+    }
+    a[i][N] = t / a[i][i];
+  }
+  return 0;
+}
+
+Void TEncAdaptiveLoopFilter::xFilterCoefQuickSort( Double *coef_data, Int *coef_num, Int upper, Int lower )
+{
+  Double mid, tmp_data;
+  Int i, j, tmp_num;
+  
+  i = upper;
+  j = lower;
+  mid = coef_data[(lower+upper)>>1];
+  do
+  {
+    while( coef_data[i] < mid ) i++;
+    while( mid < coef_data[j] ) j--;
+    if( i <= j )
+    {
+      tmp_data = coef_data[i];
+      tmp_num  = coef_num[i];
+      coef_data[i] = coef_data[j];
+      coef_num[i]  = coef_num[j];
+      coef_data[j] = tmp_data;
+      coef_num[j]  = tmp_num;
+      i++;
+      j--;
+    }
+  } while( i <= j );
+  if ( upper < j ) 
+  {
+    xFilterCoefQuickSort(coef_data, coef_num, upper, j);
+  }
+  if ( i < lower ) 
+  {
+    xFilterCoefQuickSort(coef_data, coef_num, i, lower);
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xQuantFilterCoef(Double* h, Int* qh, Int tap, int bit_depth)
+{
+  Int i, N;
+  Int max_value, min_value;
+  Double dbl_total_gain;
+  Int total_gain, q_total_gain;
+  Int upper, lower;
+  Double *dh;
+  Int    *nc;
+  const Int    *pFiltMag;
+#if LCUALF_QP_DEPENDENT_BITS
+  Int alfPrecisionBit = getAlfPrecisionBit( m_alfQP );
+#endif
+
+  N = m_sqrFiltLengthTab[tap];
+  pFiltMag = weightsShape1Sym;
+
+  dh = new Double[N];
+  nc = new Int[N];
+  
+#if LCUALF_QP_DEPENDENT_BITS  
+  max_value =   (1<<(1+alfPrecisionBit))-1;
+  min_value = 0-(1<<(1+alfPrecisionBit));
+#else
+  max_value =   (1<<(1+ALF_NUM_BIT_SHIFT))-1;
+  min_value = 0-(1<<(1+ALF_NUM_BIT_SHIFT));
+#endif
+
+  dbl_total_gain=0.0;
+  q_total_gain=0;
+  for(i=0; i<N; i++)
+  {
+    if(h[i]>=0.0)
+    {
+#if LCUALF_QP_DEPENDENT_BITS
+      qh[i] =  (Int)( h[i]*(1<<alfPrecisionBit)+0.5);
+#else
+      qh[i] =  (Int)( h[i]*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+#endif
+    }
+    else
+    {
+#if LCUALF_QP_DEPENDENT_BITS
+      qh[i] = -(Int)(-h[i]*(1<<alfPrecisionBit)+0.5);
+#else
+      qh[i] = -(Int)(-h[i]*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+#endif
+    }
+
+#if LCUALF_QP_DEPENDENT_BITS
+    dh[i] = (Double)qh[i]/(Double)(1<<alfPrecisionBit) - h[i];
+#else
+    dh[i] = (Double)qh[i]/(Double)(1<<ALF_NUM_BIT_SHIFT) - h[i];
+#endif
+    dh[i]*=pFiltMag[i];
+    dbl_total_gain += h[i]*pFiltMag[i];
+    q_total_gain   += qh[i]*pFiltMag[i];
+    nc[i] = i;
+  }
+  
+  // modification of quantized filter coefficients
+#if LCUALF_QP_DEPENDENT_BITS
+  total_gain = (Int)(dbl_total_gain*(1<<alfPrecisionBit)+0.5);
+#else
+  total_gain = (Int)(dbl_total_gain*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+#endif  
+  if( q_total_gain != total_gain )
+  {
+    xFilterCoefQuickSort(dh, nc, 0, N-1);
+    if( q_total_gain > total_gain )
+    {
+      upper = N-1;
+      while( q_total_gain > total_gain+1 )
+      {
+        i = nc[upper%N];
+        qh[i]--;
+        q_total_gain -= pFiltMag[i];
+        upper--;
+      }
+      if( q_total_gain == total_gain+1 )
+      {
+        if(dh[N-1]>0)
+        {
+          qh[N-1]--;
+        }
+        else
+        {
+          i=nc[upper%N];
+          qh[i]--;
+          qh[N-1]++;
+        }
+      }
+    }
+    else if( q_total_gain < total_gain )
+    {
+      lower = 0;
+      while( q_total_gain < total_gain-1 )
+      {
+        i=nc[lower%N];
+        qh[i]++;
+        q_total_gain += pFiltMag[i];
+        lower++;
+      }
+      if( q_total_gain == total_gain-1 )
+      {
+        if(dh[N-1]<0)
+        {
+          qh[N-1]++;
+        }
+        else
+        {
+          i=nc[lower%N];
+          qh[i]++;
+          qh[N-1]--;
+        }
+      }
+    }
+  }
+  
+  // set of filter coefficients
+  for(i=0; i<N; i++)
+  {
+    qh[i] = max(min_value,min(max_value, qh[i]));
+  }
+
+  checkFilterCoeffValue(qh, N, true);
+
+  delete[] dh;
+  dh = NULL;
+  
+  delete[] nc;
+  nc = NULL;
+}
+/** Restore the not-filtered pixels
+ * \param [in] imgDec picture buffer before filtering
+ * \param [out] imgRest picture buffer after filtering
+ * \param [in] stride stride size for 1-D picture memory
+ */
+Void TEncAdaptiveLoopFilter::xCopyDecToRestCUs(Pel* imgDec, Pel* imgRest, Int stride)
+{
+
+  if(m_uiNumSlicesInPic > 1)
+  {
+    Pel* pPicDecLuma  = imgDec;
+    Pel* pPicRestLuma = imgRest;
+    UInt SUWidth      = m_pcPic->getMinCUWidth();
+    UInt SUHeight     = m_pcPic->getMinCUHeight();
+
+    UInt startSU, endSU, LCUX, LCUY, currSU, LPelX, TPelY;
+    UInt posOffset;
+    Pel *pDec, *pRest;
+
+    for(Int s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      if(!m_pcPic->getValidSlice(s))
+      {
+        continue;
+      }
+      std::vector< AlfLCUInfo* >&  vpSliceAlfLCU = m_pvpAlfLCU[s]; 
+      for(Int i=0; i< vpSliceAlfLCU.size(); i++)
+      {
+        AlfLCUInfo& rAlfLCU    = *(vpSliceAlfLCU[i]);
+        TComDataCU* pcCU       = rAlfLCU.pcCU;
+        startSU                = rAlfLCU.startSU;
+        endSU                  = rAlfLCU.endSU;
+        LCUX                 = pcCU->getCUPelX();
+        LCUY                 = pcCU->getCUPelY();
+
+        for(currSU= startSU; currSU<= endSU; currSU++)
+        {
+          LPelX   = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+          TPelY   = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+          if( !( LPelX < m_img_width )  || !( TPelY < m_img_height )  )
+          {
+            continue;
+          }
+          if(!pcCU->getAlfCtrlFlag(currSU))
+          {
+            posOffset = TPelY*stride + LPelX;
+            pDec = pPicDecLuma + posOffset;
+            pRest= pPicRestLuma+ posOffset;
+            for(Int y=0; y< SUHeight; y++)
+            {
+              ::memcpy(pRest, pDec, sizeof(Pel)*SUWidth);
+              pDec += stride;
+              pRest+= stride;
+            }
+          }
+        }
+      }
+    }
+    return;
+  }
+
+  for( UInt uiCUAddr = 0; uiCUAddr < m_pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( uiCUAddr );
+    xCopyDecToRestCU(pcCU, 0, 0, imgDec, imgRest, stride);
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xCopyDecToRestCU(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Pel* imgDec, Pel* imgRest, Int stride)
+{
+  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;
+  
+  if( ( uiRPelX >= pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( m_pcPic->getNumPartInCU() >> (uiDepth<<1) )>>2;
+    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] ];
+      
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )      
+        xCopyDecToRestCU(pcCU, uiAbsPartIdx, uiDepth+1, imgDec, imgRest, stride);
+    }
+    return;
+  }
+  
+  if (!pcCU->getAlfCtrlFlag(uiAbsPartIdx))
+  {
+    Int iWidth = pcCU->getWidth(uiAbsPartIdx);
+    Int iHeight = pcCU->getHeight(uiAbsPartIdx);
+    copyPixelsInOneRegion(imgRest, imgDec, stride, (Int)uiTPelY, iHeight, (Int)uiLPelX, iWidth);
+  }
+}
+
+double TEncAdaptiveLoopFilter::xfindBestCoeffCodMethod(int **filterCoeffSymQuant, int filter_shape, int sqrFiltLength, int filters_per_fr, double errorForce0CoeffTab[NO_VAR_BINS][2], 
+  double lambda)
+{
+  Int coeffBits, i;
+  Double error=0, lagrangian;
+  coeffBits = xsendAllFiltersPPPred(filterCoeffSymQuant, filter_shape, sqrFiltLength, filters_per_fr, 
+    0, m_tempALFp);
+  for(i=0;i<filters_per_fr;i++)
+  {
+    error += errorForce0CoeffTab[i][1];
+  }
+  lagrangian = error + lambda * coeffBits;
+  return (lagrangian);
+}
+
+/** Predict ALF luma filter coefficients. Centre coefficient is always predicted. Determines if left neighbour should be predicted.
+ */
+Void TEncAdaptiveLoopFilter::predictALFCoeffLumaEnc(ALFParam* pcAlfParam, Int **pfilterCoeffSym, Int filter_shape)
+{
+#if LCUALF_QP_DEPENDENT_BITS
+  Int alfPrecisionBit = getAlfPrecisionBit( m_alfQP );
+#endif
+  Int sum, coeffPred, ind;
+  const Int* pFiltMag = NULL;
+  pFiltMag = weightsTabShapes[filter_shape];
+  for(ind = 0; ind < pcAlfParam->filters_per_group; ++ind)
+  {
+    sum = 0;
+    for(Int i = 0; i < pcAlfParam->num_coeff-2; i++)
+    {
+      sum +=  pFiltMag[i]*pfilterCoeffSym[ind][i];
+    }
+
+    if((pcAlfParam->predMethod==0)|(ind==0))
+    {
+#if LCUALF_QP_DEPENDENT_BITS
+      coeffPred = ((1<<alfPrecisionBit)-sum) >> 2;
+#else
+      coeffPred = ((1<<ALF_NUM_BIT_SHIFT)-sum) >> 2;
+#endif
+    }
+    else
+    {
+      coeffPred = (0-sum) >> 2;
+    }
+    if(abs(pfilterCoeffSym[ind][pcAlfParam->num_coeff-2]-coeffPred) < abs(pfilterCoeffSym[ind][pcAlfParam->num_coeff-2]))
+    {
+      pcAlfParam->nbSPred[ind] = 0; 
+    }
+    else
+    {
+      pcAlfParam->nbSPred[ind] = 1; 
+      coeffPred = 0;
+    }
+    sum += pFiltMag[pcAlfParam->num_coeff-2]*pfilterCoeffSym[ind][pcAlfParam->num_coeff-2];
+    pfilterCoeffSym[ind][pcAlfParam->num_coeff-2] -= coeffPred; 
+    if((pcAlfParam->predMethod==0)|(ind==0))
+    {
+#if LCUALF_QP_DEPENDENT_BITS
+      coeffPred = (1<<alfPrecisionBit)-sum;
+#else
+      coeffPred = (1<<ALF_NUM_BIT_SHIFT)-sum;
+#endif
+    }
+    else
+    {
+      coeffPred = -sum;
+    }
+    pfilterCoeffSym[ind][pcAlfParam->num_coeff-1] -= coeffPred;
+  }
+}
+
+Int TEncAdaptiveLoopFilter::xsendAllFiltersPPPred(int **FilterCoeffQuant, int fl, int sqrFiltLength, 
+                                                  int filters_per_group, int createBistream, ALFParam* ALFp)
+{
+  int ind, bit_ct = 0, bit_ct0 = 0, i;
+  int predMethod = 0;
+  int force0 = 0;
+  Int64 Newbit_ct;
+  
+  for(ind = 0; ind < filters_per_group; ind++)
+  {
+    for(i = 0; i < sqrFiltLength; i++)
+    {
+      m_FilterCoeffQuantTemp[ind][i]=FilterCoeffQuant[ind][i];
+    }
+  }
+  ALFp->filters_per_group = filters_per_group;
+  ALFp->predMethod = 0;
+  ALFp->num_coeff = sqrFiltLength;
+  predictALFCoeffLumaEnc(ALFp, m_FilterCoeffQuantTemp, fl);
+  Int nbFlagIntra[16];
+  for(ind = 0; ind < filters_per_group; ind++)
+  {
+    nbFlagIntra[ind] = ALFp->nbSPred[ind];
+  }
+  bit_ct0 = xcodeFilterCoeff(m_FilterCoeffQuantTemp, fl, sqrFiltLength, filters_per_group, 0);
+  for(ind = 0; ind < filters_per_group; ++ind)
+  {
+    if(ind == 0)
+    {
+      for(i = 0; i < sqrFiltLength; i++)
+        m_diffFilterCoeffQuant[ind][i] = FilterCoeffQuant[ind][i];
+    }
+    else
+    {
+      for(i = 0; i < sqrFiltLength; i++)
+        m_diffFilterCoeffQuant[ind][i] = FilterCoeffQuant[ind][i] - FilterCoeffQuant[ind-1][i];
+    }
+  }
+  ALFp->predMethod = 1;
+  predictALFCoeffLumaEnc(ALFp, m_diffFilterCoeffQuant, fl);
+  
+  if(xcodeFilterCoeff(m_diffFilterCoeffQuant, fl, sqrFiltLength, filters_per_group, 0) >= bit_ct0)
+  {
+    predMethod = 0;  
+    if(filters_per_group > 1)
+    {
+      bit_ct += lengthPredFlags(force0, predMethod, NULL, 0, createBistream);
+    }
+    bit_ct += xcodeFilterCoeff(m_FilterCoeffQuantTemp, fl, sqrFiltLength, filters_per_group, createBistream);
+  }
+  else
+  {
+    predMethod = 1;
+    if(filters_per_group > 1)
+    {
+      bit_ct += lengthPredFlags(force0, predMethod, NULL, 0, createBistream);
+    }
+    bit_ct += xcodeFilterCoeff(m_diffFilterCoeffQuant, fl, sqrFiltLength, filters_per_group, createBistream);
+  }
+  ALFp->filters_per_group = filters_per_group;
+  ALFp->predMethod = predMethod;
+  ALFp->num_coeff = sqrFiltLength;
+  ALFp->filter_shape = fl;
+  for(ind = 0; ind < filters_per_group; ++ind)
+  {
+    for(i = 0; i < sqrFiltLength; i++)
+    {
+      if (predMethod) ALFp->coeffmulti[ind][i] = m_diffFilterCoeffQuant[ind][i];
+      else 
+      {
+        ALFp->coeffmulti[ind][i] = m_FilterCoeffQuantTemp[ind][i];
+      }
+    }
+    if(predMethod==0)
+    {
+      ALFp->nbSPred[ind] = nbFlagIntra[ind];
+    }
+  }
+  m_pcEntropyCoder->codeFiltCountBit(ALFp, &Newbit_ct);
+  
+  //  return(bit_ct);
+  return ((Int)Newbit_ct);
+}
+
+Int TEncAdaptiveLoopFilter::xcodeAuxInfo(int filters_per_fr, int varIndTab[NO_VAR_BINS], int filter_shape, ALFParam* ALFp)
+{
+  int i, filterPattern[NO_VAR_BINS], startSecondFilter=0, bitCt=0;
+  Int64 NewbitCt;
+
+  //send realfiltNo (tap related)
+  ALFp->filter_shape = filter_shape;
+
+  // decide startSecondFilter and filterPattern
+  memset(filterPattern, 0, NO_VAR_BINS * sizeof(int)); 
+  if(filters_per_fr > 1)
+  {
+    for(i = 1; i < NO_VAR_BINS; ++i)
+    {
+      if(varIndTab[i] != varIndTab[i-1])
+      {
+        filterPattern[i] = 1;
+        startSecondFilter = i;
+      }
+    }
+  }
+  memcpy (ALFp->filterPattern, filterPattern, NO_VAR_BINS * sizeof(int));
+  ALFp->startSecondFilter = startSecondFilter;
+
+  assert(filters_per_fr>0);
+  m_pcEntropyCoder->codeAuxCountBit(ALFp, &NewbitCt);
+
+  bitCt = (int) NewbitCt;
+  return(bitCt);
+}
+
+Int   TEncAdaptiveLoopFilter::xcodeFilterCoeff(int **pDiffQFilterCoeffIntPP, int fl, int sqrFiltLength, 
+                                               int filters_per_group, int createBitstream)
+{
+  int i, k, kMin, kStart, minBits, ind, scanPos, maxScanVal, coeffVal, len = 0,
+    *pDepthInt=NULL, kMinTab[MAX_SCAN_VAL], bitsCoeffScan[MAX_SCAN_VAL][MAX_EXP_GOLOMB],
+  minKStart, minBitsKStart, bitsKStart;
+  Int minScanVal = MIN_SCAN_POS_CROSS;
+  pDepthInt = pDepthIntTabShapes[fl];
+  
+  maxScanVal = 0;
+  for(i = 0; i < sqrFiltLength; i++)
+  {
+    maxScanVal = max(maxScanVal, pDepthInt[i]);
+  }
+  
+  // vlc for all
+  memset(bitsCoeffScan, 0, MAX_SCAN_VAL * MAX_EXP_GOLOMB * sizeof(int));
+  for(ind=0; ind<filters_per_group; ++ind)
+  {
+    for(i = 0; i < sqrFiltLength; i++)
+    {     
+      scanPos=pDepthInt[i]-1;
+      coeffVal=abs(pDiffQFilterCoeffIntPP[ind][i]);
+      for (k=1; k<15; k++)
+      {
+        bitsCoeffScan[scanPos][k]+=lengthGolomb(coeffVal, k);
+      }
+    }
+  }
+  
+  minBitsKStart = 0;
+  minKStart = -1;
+  for(k = 1; k < 8; k++)
+  { 
+    bitsKStart = 0; 
+    kStart = k;
+    for(scanPos = minScanVal; scanPos < maxScanVal; scanPos++)
+    {
+      kMin = kStart; 
+      minBits = bitsCoeffScan[scanPos][kMin];
+      
+      if(bitsCoeffScan[scanPos][kStart+1] < minBits)
+      {
+        kMin = kStart + 1; 
+        minBits = bitsCoeffScan[scanPos][kMin];
+      }
+      kStart = kMin;
+      bitsKStart += minBits;
+    }
+    if((bitsKStart < minBitsKStart) || (k == 1))
+    {
+      minBitsKStart = bitsKStart;
+      minKStart = k;
+    }
+  }
+  
+  kStart = minKStart; 
+  for(scanPos = minScanVal; scanPos < maxScanVal; scanPos++)
+  {
+    kMin = kStart; 
+    minBits = bitsCoeffScan[scanPos][kMin];
+    
+    if(bitsCoeffScan[scanPos][kStart+1] < minBits)
+    {
+      kMin = kStart + 1; 
+      minBits = bitsCoeffScan[scanPos][kMin];
+    }
+    
+    kMinTab[scanPos] = kMin;
+    kStart = kMin;
+  }
+  
+  // Coding parameters
+  //  len += lengthFilterCodingParams(minKStart, maxScanVal, kMinTab, createBitstream);
+  if (filters_per_group == 1)
+  {
+    len += lengthFilterCoeffs(sqrFiltLength, filters_per_group, pDepthInt, pDiffQFilterCoeffIntPP, 
+      kTableTabShapes[ALF_CROSS9x7_SQUARE3x3], createBitstream);
+  }
+  else
+  {
+  len += (3 + maxScanVal);
+  
+  // Filter coefficients
+  len += lengthFilterCoeffs(sqrFiltLength, filters_per_group, pDepthInt, pDiffQFilterCoeffIntPP, 
+                            kMinTab, createBitstream);
+  }
+
+  return len;
+}
+
+Int TEncAdaptiveLoopFilter::lengthGolomb(int coeffVal, int k)
+{
+  int m = 2 << (k - 1);
+  int q = coeffVal / m;
+  if(coeffVal != 0)
+  {
+    return(q + 2 + k);
+  }
+  else
+  {
+    return(q + 1 + k);
+  }
+}
+
+Int TEncAdaptiveLoopFilter::lengthPredFlags(int force0, int predMethod, int codedVarBins[NO_VAR_BINS], 
+                                            int filters_per_group, int createBitstream)
+{
+  int bit_cnt = 0;
+  
+  if(force0)
+  {
+    bit_cnt = 2 + filters_per_group;
+  }
+  else
+  {
+    bit_cnt = 2;
+  }
+  return bit_cnt;
+  
+}
+//important
+Int TEncAdaptiveLoopFilter::lengthFilterCoeffs(int sqrFiltLength, int filters_per_group, int pDepthInt[], 
+                                               int **FilterCoeff, int kMinTab[], int createBitstream)
+{
+  int ind, scanPos, i;
+  int bit_cnt = 0;
+  
+  for(ind = 0; ind < filters_per_group; ++ind)
+  {
+    for(i = 0; i < sqrFiltLength; i++)
+    {
+      scanPos = pDepthInt[i] - 1;
+      Int k = (filters_per_group == 1) ? kMinTab[i] : kMinTab[scanPos];
+      bit_cnt += lengthGolomb(abs(FilterCoeff[ind][i]), k);
+    }
+  }
+  return bit_cnt;
+}
+
+
+Void TEncAdaptiveLoopFilter::xfindBestFilterVarPred(double **ySym, double ***ESym, double *pixAcc, Int **filterCoeffSym, Int **filterCoeffSymQuant, Int filter_shape, Int *filters_per_fr_best, Int varIndTab[], Pel **imgY_rec, Pel **varImg, Pel **maskImg, Pel **imgY_pad, double lambda_val, Int numMaxFilters)
+{
+  Int filters_per_fr, firstFilt, interval[NO_VAR_BINS][2], intervalBest[NO_VAR_BINS][2];
+  int i;
+  double  lagrangian, lagrangianMin;
+  int sqrFiltLength;
+  int *weights;
+  Int coeffBits;
+  double errorForce0CoeffTab[NO_VAR_BINS][2];
+  
+  sqrFiltLength= m_sqrFiltLengthTab[filter_shape] ;
+  weights = weightsTabShapes[filter_shape];
+
+  // zero all variables 
+  memset(varIndTab,0,sizeof(int)*NO_VAR_BINS);
+
+  for(i = 0; i < NO_VAR_BINS; i++)
+  {
+    memset(filterCoeffSym[i],0,sizeof(int)*ALF_MAX_NUM_COEF);
+    memset(filterCoeffSymQuant[i],0,sizeof(int)*ALF_MAX_NUM_COEF);
+  }
+
+  firstFilt=1;  lagrangianMin=0;
+  filters_per_fr=NO_FILTERS;
+
+  while(filters_per_fr>=1)
+  {
+    mergeFiltersGreedy(ySym, ESym, pixAcc, interval, sqrFiltLength, filters_per_fr);
+    findFilterCoeff(ESym, ySym, pixAcc, filterCoeffSym, filterCoeffSymQuant, interval,
+      varIndTab, sqrFiltLength, filters_per_fr, weights, errorForce0CoeffTab);
+
+    lagrangian=xfindBestCoeffCodMethod(filterCoeffSymQuant, filter_shape, sqrFiltLength, filters_per_fr, errorForce0CoeffTab, lambda_val);
+    if (lagrangian<lagrangianMin || firstFilt==1 || filters_per_fr == numMaxFilters)
+    {
+      firstFilt=0;
+      lagrangianMin=lagrangian;
+
+      (*filters_per_fr_best)=filters_per_fr;
+      memcpy(intervalBest, interval, NO_VAR_BINS*2*sizeof(int));
+    }
+    filters_per_fr--;
+  }
+  findFilterCoeff(ESym, ySym, pixAcc, filterCoeffSym, filterCoeffSymQuant, intervalBest,
+    varIndTab, sqrFiltLength, (*filters_per_fr_best), weights, errorForce0CoeffTab);
+
+
+  xfindBestCoeffCodMethod(filterCoeffSymQuant, filter_shape, sqrFiltLength, (*filters_per_fr_best), errorForce0CoeffTab, lambda_val);
+  coeffBits = xcodeAuxInfo((*filters_per_fr_best), varIndTab, filter_shape, m_tempALFp);
+  coeffBits += xsendAllFiltersPPPred(filterCoeffSymQuant, filter_shape, sqrFiltLength, (*filters_per_fr_best), 0, m_tempALFp);
+
+  if( *filters_per_fr_best == 1)
+  {
+    ::memset(varIndTab, 0, sizeof(Int)*NO_VAR_BINS);
+  }
+}
+
+
+/** code filter coefficients
+ * \param filterCoeffSymQuant filter coefficients buffer
+ * \param filtNo filter No.
+ * \param varIndTab[] merge index information
+ * \param filters_per_fr_best the number of filters used in this picture
+ * \param frNo 
+ * \param ALFp ALF parameters
+ * \returns bitrate
+ */
+UInt TEncAdaptiveLoopFilter::xcodeFiltCoeff(Int **filterCoeffSymQuant, Int filter_shape, Int varIndTab[], Int filters_per_fr_best, ALFParam* ALFp)
+{
+  Int coeffBits;   
+  Int sqrFiltLength = m_sqrFiltLengthTab[filter_shape] ; 
+
+  ALFp->filters_per_group = filters_per_fr_best;
+
+  coeffBits = xcodeAuxInfo(filters_per_fr_best, varIndTab, filter_shape, ALFp);
+
+
+  ALFp->predMethod = 0;
+  ALFp->num_coeff = sqrFiltLength;
+  ALFp->filter_shape=filter_shape;
+
+  if (filters_per_fr_best <= 1)
+  {
+    ALFp->predMethod = 0;
+  }
+
+  coeffBits += xsendAllFiltersPPPred(filterCoeffSymQuant, filter_shape, sqrFiltLength, 
+    filters_per_fr_best, 1, ALFp);
+
+  return (UInt)coeffBits;
+}
+
+Void TEncAdaptiveLoopFilter::getCtrlFlagsFromCU(AlfLCUInfo* pcAlfLCU, std::vector<UInt> *pvFlags, Int alfDepth, UInt maxNumSUInLCU)
+{
+  const UInt startSU               = pcAlfLCU->startSU;
+  const UInt endSU                 = pcAlfLCU->endSU;
+  const Bool bAllSUsInLCUInSameSlice = pcAlfLCU->bAllSUsInLCUInSameSlice;
+
+  TComDataCU* pcCU = pcAlfLCU->pcCU;
+  UInt  currSU, CUDepth, setDepth, ctrlNumSU;
+
+  currSU = startSU;
+
+  if(bAllSUsInLCUInSameSlice)
+  {
+    while(currSU < maxNumSUInLCU)
+    {
+      //depth of this CU
+      CUDepth = pcCU->getDepth(currSU);
+
+      //choose the min. depth for ALF
+      setDepth   = (alfDepth < CUDepth)?(alfDepth):(CUDepth);
+      ctrlNumSU = maxNumSUInLCU >> (setDepth << 1);
+
+      pvFlags->push_back(pcCU->getAlfCtrlFlag(currSU));
+      currSU += ctrlNumSU;
+    }
+
+    return;
+  }
+
+
+  const UInt  LCUX = pcCU->getCUPelX();
+  const UInt  LCUY = pcCU->getCUPelY();
+
+  Bool  bFirst, bValidCU;
+  UInt  idx, LPelXSU, TPelYSU;
+
+  bFirst= true;
+  while(currSU <= endSU)
+  {
+    //check picture boundary
+    while(!( LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ] < m_img_width  ) || 
+          !( LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ] < m_img_height )
+      )
+    {
+      currSU++;
+
+      if(currSU >= maxNumSUInLCU || currSU > endSU)
+      {
+        break;
+      }
+    }
+
+    if(currSU >= maxNumSUInLCU || currSU > endSU)
+    {
+      break;
+    }
+
+    //depth of this CU
+    CUDepth = pcCU->getDepth(currSU);
+
+    //choose the min. depth for ALF
+    setDepth   = (alfDepth < CUDepth)?(alfDepth):(CUDepth);
+    ctrlNumSU = maxNumSUInLCU >> (setDepth << 1);
+
+    if(bFirst)
+    {
+      if(currSU !=0 )
+      {
+        currSU = ((UInt)(currSU/ctrlNumSU))* ctrlNumSU;
+      }
+      bFirst = false;
+    }
+
+    bValidCU = false;
+    for(idx = currSU; idx < currSU + ctrlNumSU; idx++)
+    {
+      if(idx < startSU || idx > endSU)
+      {
+        continue;
+      }
+
+      LPelXSU   = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[idx] ];
+      TPelYSU   = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[idx] ];
+
+      if( !( LPelXSU < m_img_width )  || !( TPelYSU < m_img_height )  )
+      {
+        continue;
+      }
+
+      bValidCU = true;
+    }
+
+    if(bValidCU)
+    {
+      pvFlags->push_back(pcCU->getAlfCtrlFlag(currSU));
+    }
+
+    currSU += ctrlNumSU;
+  }
+}
+
+
+/** set ALF CU control flags
+ * \param [in] uiAlfCtrlDepth ALF CU control depth
+ * \param [in] pcPicOrg picture of original signal
+ * \param [in] pcPicDec picture before filtering
+ * \param [in] pcPicRest picture after filtering
+ * \param [out] ruiDist distortion after CU control
+ * \param [in,out]vAlfCUCtrlParam ALF CU control parameters 
+ */
+#if HHI_INTERVIEW_SKIP
+Void TEncAdaptiveLoopFilter::setCUAlfCtrlFlags(UInt uiAlfCtrlDepth, Pel* imgOrg, Pel* imgDec, Pel* imgRest, Pel* imgUsed, Int stride, UInt64& ruiDist, std::vector<AlfCUCtrlInfo>& vAlfCUCtrlParam)
+#else
+Void TEncAdaptiveLoopFilter::setCUAlfCtrlFlags(UInt uiAlfCtrlDepth, Pel* imgOrg, Pel* imgDec, Pel* imgRest, Int stride, UInt64& ruiDist, std::vector<AlfCUCtrlInfo>& vAlfCUCtrlParam)
+#endif
+{
+  ruiDist = 0;
+  std::vector<UInt> uiFlags;
+
+  //initial
+  for(Int s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    vAlfCUCtrlParam[s].cu_control_flag = 1;
+    vAlfCUCtrlParam[s].alf_max_depth   = uiAlfCtrlDepth;
+
+    vAlfCUCtrlParam[s].alf_cu_flag.reserve(m_uiNumCUsInFrame << ((g_uiMaxCUDepth-1)*2));
+    vAlfCUCtrlParam[s].alf_cu_flag.resize(0);
+  }
+
+  //LCU-based on/off control
+  for( UInt CUAddr = 0; CUAddr < m_pcPic->getNumCUsInFrame() ; CUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( CUAddr );
+#if HHI_INTERVIEW_SKIP
+    setCUAlfCtrlFlag(pcCU, 0, 0, uiAlfCtrlDepth, imgOrg, imgDec, imgRest, imgUsed, stride, ruiDist, vAlfCUCtrlParam[0].alf_cu_flag);
+#else
+    setCUAlfCtrlFlag(pcCU, 0, 0, uiAlfCtrlDepth, imgOrg, imgDec, imgRest, stride, ruiDist, vAlfCUCtrlParam[0].alf_cu_flag);
+#endif
+  }
+  vAlfCUCtrlParam[0].num_alf_cu_flag = (UInt)(vAlfCUCtrlParam[0].alf_cu_flag.size());
+
+
+  if(m_uiNumSlicesInPic > 1)
+  {
+    //reset the first slice on/off flags
+    vAlfCUCtrlParam[0].alf_cu_flag.resize(0);
+
+    //distribute on/off flags to slices
+    std::vector<UInt> vCtrlFlags;
+    vCtrlFlags.reserve(1 << ((g_uiMaxCUDepth-1)*2));
+
+    for(Int s=0; s < m_uiNumSlicesInPic; s++)
+    {
+      if(!m_pcPic->getValidSlice(s))
+      {
+        continue;
+      }
+      std::vector< AlfLCUInfo* >& vpAlfLCU = m_pvpAlfLCU[s];
+      for(Int i=0; i< vpAlfLCU.size(); i++)
+      {
+        //get on/off flags for one LCU
+        vCtrlFlags.resize(0);
+        getCtrlFlagsFromCU(vpAlfLCU[i], &vCtrlFlags, (Int)uiAlfCtrlDepth, m_pcPic->getNumPartInCU());
+
+        for(Int k=0; k< vCtrlFlags.size(); k++)
+        {
+          vAlfCUCtrlParam[s].alf_cu_flag.push_back( vCtrlFlags[k]);
+        }
+      } //i (LCU)
+      vAlfCUCtrlParam[s].num_alf_cu_flag = (UInt)(vAlfCUCtrlParam[s].alf_cu_flag.size());
+    } //s (Slice)
+  }
+}
+
+#if HHI_INTERVIEW_SKIP
+Void TEncAdaptiveLoopFilter::setCUAlfCtrlFlag(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiAlfCtrlDepth, Pel* imgOrg, Pel* imgDec, Pel* imgRest, Pel* imgUsed, Int stride, UInt64& ruiDist, std::vector<UInt>& vCUCtrlFlag)
+#else
+Void TEncAdaptiveLoopFilter::setCUAlfCtrlFlag(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiAlfCtrlDepth, Pel* imgOrg, Pel* imgDec, Pel* imgRest, Int stride, UInt64& ruiDist, std::vector<UInt>& vCUCtrlFlag)
+#endif
+{
+  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;
+  
+  if( ( uiRPelX >= pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( m_pcPic->getNumPartInCU() >> (uiDepth<<1) )>>2;
+    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] ];
+      
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#if HHI_INTERVIEW_SKIP
+        setCUAlfCtrlFlag(pcCU, uiAbsPartIdx, uiDepth+1, uiAlfCtrlDepth, imgOrg, imgDec, imgRest, imgUsed, stride, ruiDist, vCUCtrlFlag);
+#else
+        setCUAlfCtrlFlag(pcCU, uiAbsPartIdx, uiDepth+1, uiAlfCtrlDepth, imgOrg, imgDec, imgRest, stride, ruiDist, vCUCtrlFlag);
+#endif
+    }
+    return;
+  }
+  
+  if( uiDepth > uiAlfCtrlDepth && !pcCU->isFirstAbsZorderIdxInDepth(uiAbsPartIdx, uiAlfCtrlDepth))
+  {
+    return;
+  }
+  UInt64 uiRecSSD = 0;
+  UInt64 uiFiltSSD = 0;
+  
+  Int iWidth;
+  Int iHeight;
+  UInt uiSetDepth;
+  
+  if (uiDepth > uiAlfCtrlDepth && pcCU->isFirstAbsZorderIdxInDepth(uiAbsPartIdx, uiAlfCtrlDepth))
+  {
+    iWidth = g_uiMaxCUWidth >> uiAlfCtrlDepth;
+    iHeight = g_uiMaxCUHeight >> uiAlfCtrlDepth;
+    
+    uiRPelX   = uiLPelX + iWidth  - 1;
+    uiBPelY   = uiTPelY + iHeight - 1;
+
+    if( uiRPelX >= pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() )
+    {
+      iWidth = pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() - uiLPelX;
+    }
+    
+    if( uiBPelY >= pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() )
+    {
+      iHeight = pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() - uiTPelY;
+    }
+    
+    uiSetDepth = uiAlfCtrlDepth;
+  }
+  else
+  {
+    iWidth = pcCU->getWidth(uiAbsPartIdx);
+    iHeight = pcCU->getHeight(uiAbsPartIdx);
+    uiSetDepth = uiDepth;
+  }
+  
+  Int  offset = uiTPelY*stride + uiLPelX;
+  Pel* pOrg  = imgOrg  + offset;
+  Pel* pRec  = imgDec  + offset;
+  Pel* pFilt = imgRest + offset;
+
+#if HHI_INTERVIEW_SKIP
+  Pel* pUsed = NULL ;
+  if( imgUsed )
+  {
+    pUsed = imgUsed + offset;
+  }
+  uiRecSSD  += xCalcSSD( pOrg, pRec,  pUsed, iWidth, iHeight, stride );
+  uiFiltSSD += xCalcSSD( pOrg, pFilt, pUsed, iWidth, iHeight, stride );
+#else
+  uiRecSSD  += xCalcSSD( pOrg, pRec,  iWidth, iHeight, stride );
+  uiFiltSSD += xCalcSSD( pOrg, pFilt, iWidth, iHeight, stride );
+#endif
+  if (uiFiltSSD < uiRecSSD)
+  {
+    ruiDist += uiFiltSSD;
+    pcCU->setAlfCtrlFlagSubParts(1, uiAbsPartIdx, uiSetDepth);
+    vCUCtrlFlag.push_back(1);
+
+    for (int i=uiTPelY ;i<=min(uiBPelY,(unsigned int)(m_img_height-1))  ;i++)
+    {
+      for (int j=uiLPelX ;j<=min(uiRPelX,(unsigned int)(m_img_width-1)) ;j++)
+      { 
+        m_maskImg[i][j]=1;
+      }
+    }
+  }
+  else
+  {
+    ruiDist += uiRecSSD;
+    pcCU->setAlfCtrlFlagSubParts(0, uiAbsPartIdx, uiSetDepth);
+    vCUCtrlFlag.push_back(0);
+    for (int i=uiTPelY ;i<=min(uiBPelY,(unsigned int)(m_img_height-1))  ;i++)
+    {
+      for (int j=uiLPelX ;j<=min(uiRPelX,(unsigned int)(m_img_width-1)) ;j++)
+      { 
+        m_maskImg[i][j]=0;
+      }
+    }
+  }
+}
+
+
+#define ROUND(a)  (((a) < 0)? (int)((a) - 0.5) : (int)((a) + 0.5))
+#define REG              0.0001
+#define REG_SQR          0.0000001
+
+//Find filter coeff related
+Int TEncAdaptiveLoopFilter::gnsCholeskyDec(Double **inpMatr, Double outMatr[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], Int noEq)
+{ 
+  Int i, j, k;     /* Looping Variables */
+  Double scale;       /* scaling factor for each row */
+  Double invDiag[ALF_MAX_NUM_COEF];  /* Vector of the inverse of diagonal entries of outMatr */
+  
+  //  Cholesky decomposition starts
+  
+  for(i = 0; i < noEq; i++)
+  {
+    for(j = i; j < noEq; j++)
+    {
+      /* Compute the scaling factor */
+      scale = inpMatr[i][j];
+      if ( i > 0) 
+      {
+        for( k = i - 1 ; k >= 0 ; k--)
+        {
+          scale -= outMatr[k][j] * outMatr[k][i];
+        }
+      }
+      /* Compute i'th row of outMatr */
+      if(i == j)
+      {
+        if(scale <= REG_SQR ) // if(scale <= 0 )  /* If inpMatr is singular */
+        {
+          return 0;
+        }
+        else
+        {
+           /* Normal operation */
+           invDiag[i] =  1.0 / (outMatr[i][i] = sqrt(scale));
+        }
+      }
+      else
+      {
+        outMatr[i][j] = scale * invDiag[i]; /* Upper triangular part          */
+        outMatr[j][i] = 0.0;              /* Lower triangular part set to 0 */
+      }                    
+    }
+  }
+  return 1; /* Signal that Cholesky factorization is successfully performed */
+}
+
+
+Void TEncAdaptiveLoopFilter::gnsTransposeBacksubstitution(Double U[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], Double rhs[], Double x[], Int order)
+{
+  Int i,j;              /* Looping variables */
+  Double sum;              /* Holds backsubstitution from already handled rows */
+  
+  /* Backsubstitution starts */
+  x[0] = rhs[0] / U[0][0];               /* First row of U'                   */
+  for (i = 1; i < order; i++)
+  {         /* For the rows 1..order-1           */
+    
+    for (j = 0, sum = 0.0; j < i; j++) /* Backsubst already solved unknowns */
+    {
+      sum += x[j] * U[j][i];
+    }
+    x[i] = (rhs[i] - sum) / U[i][i];       /* i'th component of solution vect.  */
+  }
+}
+
+Void  TEncAdaptiveLoopFilter::gnsBacksubstitution(Double R[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], Double z[ALF_MAX_NUM_COEF], Int R_size, Double A[MAX_SQR_FILT_LENGTH])
+{
+  Int i, j;
+  Double sum;
+  
+  R_size--;
+  
+  A[R_size] = z[R_size] / R[R_size][R_size];
+  
+  for (i = R_size-1; i >= 0; i--)
+  {
+    for (j = i + 1, sum = 0.0; j <= R_size; j++)
+    {
+      sum += R[i][j] * A[j];
+    }
+    
+    A[i] = (z[i] - sum) / R[i][i];
+  }
+}
+
+
+Int TEncAdaptiveLoopFilter::gnsSolveByChol(Double **LHS, Double *rhs, Double *x, Int noEq)
+{
+  assert(noEq > 0);
+
+  Double aux[ALF_MAX_NUM_COEF];     /* Auxiliary vector */
+  Double U[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF];    /* Upper triangular Cholesky factor of LHS */
+  Int  i, singular;          /* Looping variable */
+  
+  /* The equation to be solved is LHSx = rhs */
+  
+  /* Compute upper triangular U such that U'*U = LHS */
+  if(gnsCholeskyDec(LHS, U, noEq)) /* If Cholesky decomposition has been successful */
+  {
+    singular = 1;
+    /* Now, the equation is  U'*U*x = rhs, where U is upper triangular
+     * Solve U'*aux = rhs for aux
+     */
+    gnsTransposeBacksubstitution(U, rhs, aux, noEq);         
+    
+    /* The equation is now U*x = aux, solve it for x (new motion coefficients) */
+    gnsBacksubstitution(U, aux, noEq, x);   
+    
+  }
+  else /* LHS was singular */ 
+  {
+    singular = 0;
+    
+    /* Regularize LHS */
+    for(i=0; i < noEq; i++)
+    {
+      LHS[i][i] += REG;
+    }
+    /* Compute upper triangular U such that U'*U = regularized LHS */
+    singular = gnsCholeskyDec(LHS, U, noEq);
+    if ( singular == 1 )
+    {
+      /* Solve  U'*aux = rhs for aux */  
+      gnsTransposeBacksubstitution(U, rhs, aux, noEq);   
+      
+      /* Solve U*x = aux for x */
+      gnsBacksubstitution(U, aux, noEq, x);      
+    }
+    else
+    {
+      x[0] = 1.0;
+      for (i = 1; i < noEq; i++ )
+      {
+        x[i] = 0.0;
+      }
+    }
+  }  
+  return singular;
+}
+
+Void TEncAdaptiveLoopFilter::add_A(Double **Amerged, Double ***A, Int start, Int stop, Int size)
+{ 
+  Int i, j, ind;          /* Looping variable */
+  
+  for (i = 0; i < size; i++)
+  {
+    for (j = 0; j < size; j++)
+    {
+      Amerged[i][j] = 0;
+      for (ind = start; ind <= stop; ind++)
+      {
+        Amerged[i][j] += A[ind][i][j];
+      }
+    }
+  }
+}
+
+Void TEncAdaptiveLoopFilter::add_b(Double *bmerged, Double **b, Int start, Int stop, Int size)
+{ 
+  Int i, ind;          /* Looping variable */
+  
+  for (i = 0; i < size; i++)
+  {
+    bmerged[i] = 0;
+    for (ind = start; ind <= stop; ind++)
+    {
+      bmerged[i] += b[ind][i];
+    }
+  }
+}
+
+Double TEncAdaptiveLoopFilter::calculateErrorCoeffProvided(Double **A, Double *b, Double *c, Int size)
+{
+  Int i, j;
+  Double error, sum = 0;
+  
+  error = 0;
+  for (i = 0; i < size; i++)   //diagonal
+  {
+    sum = 0;
+    for (j = i + 1; j < size; j++)
+    {
+      sum += (A[j][i] + A[i][j]) * c[j];
+    }
+    error += (A[i][i] * c[i] + sum - 2 * b[i]) * c[i];
+  }
+  
+  return error;
+}
+
+Double TEncAdaptiveLoopFilter::calculateErrorAbs(Double **A, Double *b, Double y, Int size)
+{
+  Int i;
+  Double error, sum;
+  Double c[ALF_MAX_NUM_COEF];
+  
+  gnsSolveByChol(A, b, c, size);
+  
+  sum = 0;
+  for (i = 0; i < size; i++)
+  {
+    sum += c[i] * b[i];
+  }
+  error = y - sum;
+  
+  return error;
+}
+
+Double TEncAdaptiveLoopFilter::mergeFiltersGreedy(Double **yGlobalSeq, Double ***EGlobalSeq, Double *pixAccGlobalSeq, Int intervalBest[NO_VAR_BINS][2], Int sqrFiltLength, Int noIntervals)
+{
+  Int first, ind, ind1, ind2, i, j, bestToMerge ;
+  Double error, error1, error2, errorMin;
+  static Double pixAcc_temp, error_tab[NO_VAR_BINS],error_comb_tab[NO_VAR_BINS];
+  static Int indexList[NO_VAR_BINS], available[NO_VAR_BINS], noRemaining;
+  if (noIntervals == NO_FILTERS)
+  {
+    noRemaining = NO_VAR_BINS;
+    for (ind=0; ind<NO_VAR_BINS; ind++)
+    {
+      indexList[ind] = ind; 
+      available[ind] = 1;
+      m_pixAcc_merged[ind] = pixAccGlobalSeq[ind];
+      memcpy(m_y_merged[ind], yGlobalSeq[ind], sizeof(Double)*sqrFiltLength);
+      for (i=0; i < sqrFiltLength; i++)
+      {
+        memcpy(m_E_merged[ind][i], EGlobalSeq[ind][i], sizeof(Double)*sqrFiltLength);
+      }
+    }
+  }
+  // Try merging different matrices
+  if (noIntervals == NO_FILTERS)
+  {
+    for (ind = 0; ind < NO_VAR_BINS; ind++)
+    {
+      error_tab[ind] = calculateErrorAbs(m_E_merged[ind], m_y_merged[ind], m_pixAcc_merged[ind], sqrFiltLength);
+    }
+    for (ind = 0; ind < NO_VAR_BINS - 1; ind++)
+    {
+      ind1 = indexList[ind];
+      ind2 = indexList[ind+1];
+      
+      error1 = error_tab[ind1];
+      error2 = error_tab[ind2];
+      
+      pixAcc_temp = m_pixAcc_merged[ind1] + m_pixAcc_merged[ind2];
+      for (i = 0; i < sqrFiltLength; i++)
+      {
+        m_y_temp[i] = m_y_merged[ind1][i] + m_y_merged[ind2][i];
+        for (j = 0; j < sqrFiltLength; j++)
+        {
+          m_E_temp[i][j] = m_E_merged[ind1][i][j] + m_E_merged[ind2][i][j];
+        }
+      }
+      error_comb_tab[ind1] = calculateErrorAbs(m_E_temp, m_y_temp, pixAcc_temp, sqrFiltLength) - error1 - error2;
+    }
+  }
+  while (noRemaining > noIntervals)
+  {
+    errorMin = 0; 
+    first = 1;
+    bestToMerge = 0;
+    for (ind = 0; ind < noRemaining - 1; ind++)
+    {
+      error = error_comb_tab[indexList[ind]];
+      if ((error < errorMin || first == 1))
+      {
+        errorMin = error;
+        bestToMerge = ind;
+        first = 0;
+      }
+    }
+    ind1 = indexList[bestToMerge];
+    ind2 = indexList[bestToMerge+1];
+    m_pixAcc_merged[ind1] += m_pixAcc_merged[ind2];
+    for (i = 0; i < sqrFiltLength; i++)
+    {
+      m_y_merged[ind1][i] += m_y_merged[ind2][i];
+      for (j = 0; j < sqrFiltLength; j++)
+      {
+        m_E_merged[ind1][i][j] += m_E_merged[ind2][i][j];
+      }
+    }
+    available[ind2] = 0;
+    
+    //update error tables
+    error_tab[ind1] = error_comb_tab[ind1] + error_tab[ind1] + error_tab[ind2];
+    if (indexList[bestToMerge] > 0)
+    {
+      ind1 = indexList[bestToMerge-1];
+      ind2 = indexList[bestToMerge];
+      error1 = error_tab[ind1];
+      error2 = error_tab[ind2];
+      pixAcc_temp = m_pixAcc_merged[ind1] + m_pixAcc_merged[ind2];
+      for (i = 0; i < sqrFiltLength; i++)
+      {
+        m_y_temp[i] = m_y_merged[ind1][i] + m_y_merged[ind2][i];
+        for (j = 0; j < sqrFiltLength; j++)
+        {
+          m_E_temp[i][j] = m_E_merged[ind1][i][j] + m_E_merged[ind2][i][j];
+        }
+      }
+      error_comb_tab[ind1] = calculateErrorAbs(m_E_temp, m_y_temp, pixAcc_temp, sqrFiltLength) - error1 - error2;
+    }
+    if (indexList[bestToMerge+1] < NO_VAR_BINS - 1)
+    {
+      ind1 = indexList[bestToMerge];
+      ind2 = indexList[bestToMerge+2];
+      error1 = error_tab[ind1];
+      error2 = error_tab[ind2];
+      pixAcc_temp = m_pixAcc_merged[ind1] + m_pixAcc_merged[ind2];
+      for (i=0; i<sqrFiltLength; i++)
+      {
+        m_y_temp[i] = m_y_merged[ind1][i] + m_y_merged[ind2][i];
+        for (j=0; j < sqrFiltLength; j++)
+        {
+          m_E_temp[i][j] = m_E_merged[ind1][i][j] + m_E_merged[ind2][i][j];
+        }
+      }
+      error_comb_tab[ind1] = calculateErrorAbs(m_E_temp, m_y_temp, pixAcc_temp, sqrFiltLength) - error1 - error2;
+    }
+    
+    ind=0;
+    for (i = 0; i < NO_VAR_BINS; i++)
+    {
+      if (available[i] == 1)
+      {
+        indexList[ind] = i;
+        ind++;
+      }
+    }
+    noRemaining--;
+  }
+  
+  errorMin = 0;
+  for (ind = 0; ind < noIntervals; ind++)
+  {
+    errorMin += error_tab[indexList[ind]];
+  }
+  
+  for (ind = 0; ind < noIntervals - 1; ind++)
+  {
+    intervalBest[ind][0] = indexList[ind]; 
+    intervalBest[ind][1] = indexList[ind+1] - 1;
+  }
+  
+  intervalBest[noIntervals-1][0] = indexList[noIntervals-1]; 
+  intervalBest[noIntervals-1][1] = NO_VAR_BINS-1;
+  
+  return(errorMin);
+}
+
+Void TEncAdaptiveLoopFilter::roundFiltCoeff(Int *FilterCoeffQuan, Double *FilterCoeff, Int sqrFiltLength, Int factor)
+{
+  Int i;
+  Double diff; 
+  Int diffInt, sign; 
+  
+  for(i = 0; i < sqrFiltLength; i++)
+  {
+    sign = (FilterCoeff[i] > 0)? 1 : -1; 
+    diff = FilterCoeff[i] * sign; 
+    diffInt = (Int)(diff * (Double)factor + 0.5); 
+    FilterCoeffQuan[i] = diffInt * sign;
+  }
+}
+
+Double TEncAdaptiveLoopFilter::QuantizeIntegerFilterPP(Double *filterCoeff, Int *filterCoeffQuant, Double **E, Double *y, Int sqrFiltLength, Int *weights)
+{
+  double error;
+#if LCUALF_QP_DEPENDENT_BITS
+  Int factor = (1<<(getAlfPrecisionBit(m_alfQP)));
+#else
+  Int factor = (1<<  ((Int)ALF_NUM_BIT_SHIFT)  );
+#endif
+  Int i;
+  int quantCoeffSum, minInd, targetCoeffSumInt, k, diff;
+  double targetCoeffSum, errMin;
+  
+  gnsSolveByChol(E, y, filterCoeff, sqrFiltLength);
+  targetCoeffSum=0;
+  for (i=0; i<sqrFiltLength; i++)
+  {
+    targetCoeffSum+=(weights[i]*filterCoeff[i]*factor);
+  }
+  targetCoeffSumInt=ROUND(targetCoeffSum);
+  roundFiltCoeff(filterCoeffQuant, filterCoeff, sqrFiltLength, factor);
+  quantCoeffSum=0;
+  for (i=0; i<sqrFiltLength; i++)
+  {
+    quantCoeffSum+=weights[i]*filterCoeffQuant[i];
+  }
+  
+  int count=0;
+  while(quantCoeffSum!=targetCoeffSumInt && count < 10)
+  {
+    if (quantCoeffSum>targetCoeffSumInt)
+    {
+      diff=quantCoeffSum-targetCoeffSumInt;
+      errMin=0; minInd=-1;
+      for (k=0; k<sqrFiltLength; k++)
+      {
+        if (weights[k]<=diff)
+        {
+          for (i=0; i<sqrFiltLength; i++)
+          {
+            m_filterCoeffQuantMod[i]=filterCoeffQuant[i];
+          }
+          m_filterCoeffQuantMod[k]--;
+          for (i=0; i<sqrFiltLength; i++)
+          {
+            filterCoeff[i]=(double)m_filterCoeffQuantMod[i]/(double)factor;
+          }
+          error=calculateErrorCoeffProvided(E, y, filterCoeff, sqrFiltLength);
+          if (error<errMin || minInd==-1)
+          {
+            errMin=error;
+            minInd=k;
+          }
+        } // if (weights(k)<=diff)
+      } // for (k=0; k<sqrFiltLength; k++)
+      filterCoeffQuant[minInd]--;
+    }
+    else
+    {
+      diff=targetCoeffSumInt-quantCoeffSum;
+      errMin=0; minInd=-1;
+      for (k=0; k<sqrFiltLength; k++)
+      {
+        if (weights[k]<=diff)
+        {
+          for (i=0; i<sqrFiltLength; i++)
+          {
+            m_filterCoeffQuantMod[i]=filterCoeffQuant[i];
+          }
+          m_filterCoeffQuantMod[k]++;
+          for (i=0; i<sqrFiltLength; i++)
+          {
+            filterCoeff[i]=(double)m_filterCoeffQuantMod[i]/(double)factor;
+          }
+          error=calculateErrorCoeffProvided(E, y, filterCoeff, sqrFiltLength);
+          if (error<errMin || minInd==-1)
+          {
+            errMin=error;
+            minInd=k;
+          }
+        } // if (weights(k)<=diff)
+      } // for (k=0; k<sqrFiltLength; k++)
+      filterCoeffQuant[minInd]++;
+    }
+    
+    quantCoeffSum=0;
+    for (i=0; i<sqrFiltLength; i++)
+    {
+      quantCoeffSum+=weights[i]*filterCoeffQuant[i];
+    }
+  }
+  if( count == 10 )
+  {
+    for (i=0; i<sqrFiltLength; i++)
+    {
+      filterCoeffQuant[i] = 0;
+    }
+  }
+  
+  checkFilterCoeffValue(filterCoeffQuant, sqrFiltLength, false);
+
+  for (i=0; i<sqrFiltLength; i++)
+  {
+    filterCoeff[i]=(double)filterCoeffQuant[i]/(double)factor;
+  }
+  
+  error=calculateErrorCoeffProvided(E, y, filterCoeff, sqrFiltLength);
+  return(error);
+}
+Double TEncAdaptiveLoopFilter::findFilterCoeff(double ***EGlobalSeq, double **yGlobalSeq, double *pixAccGlobalSeq, int **filterCoeffSeq, int **filterCoeffQuantSeq, int intervalBest[NO_VAR_BINS][2], int varIndTab[NO_VAR_BINS], int sqrFiltLength, int filters_per_fr, int *weights, double errorTabForce0Coeff[NO_VAR_BINS][2])
+{
+  static double pixAcc_temp;
+  double error;
+  int k, filtNo;
+  
+  error = 0;
+  for(filtNo = 0; filtNo < filters_per_fr; filtNo++)
+  {
+    add_A(m_E_temp, EGlobalSeq, intervalBest[filtNo][0], intervalBest[filtNo][1], sqrFiltLength);
+    add_b(m_y_temp, yGlobalSeq, intervalBest[filtNo][0], intervalBest[filtNo][1], sqrFiltLength);
+    
+    pixAcc_temp = 0;    
+    for(k = intervalBest[filtNo][0]; k <= intervalBest[filtNo][1]; k++)
+      pixAcc_temp += pixAccGlobalSeq[k];
+    
+    // Find coeffcients
+    errorTabForce0Coeff[filtNo][1] = pixAcc_temp + QuantizeIntegerFilterPP(m_filterCoeff, m_filterCoeffQuant, m_E_temp, m_y_temp, sqrFiltLength, weights);
+    errorTabForce0Coeff[filtNo][0] = pixAcc_temp;
+    error += errorTabForce0Coeff[filtNo][1];
+    
+    for(k = 0; k < sqrFiltLength; k++)
+    {
+      filterCoeffSeq[filtNo][k] = m_filterCoeffQuant[k];
+      filterCoeffQuantSeq[filtNo][k] = m_filterCoeffQuant[k];
+    }
+  }
+  
+  for(filtNo = 0; filtNo < filters_per_fr; filtNo++)
+  {
+    for(k = intervalBest[filtNo][0]; k <= intervalBest[filtNo][1]; k++)
+      varIndTab[k] = filtNo;
+  }
+  
+  return(error);
+}
+
+
+/** Estimate filtering distortion by correlation values and filter coefficients
+ * \param ppdE auto-correlation matrix
+ * \param pdy cross-correlation array
+ * \param piCoeff  filter coefficients
+ * \param iFiltLength numbr of filter taps
+ * \returns estimated distortion
+ */
+Int64 TEncAdaptiveLoopFilter::xFastFiltDistEstimation(Double** ppdE, Double* pdy, Int* piCoeff, Int iFiltLength)
+{
+  //static memory
+  Double pdcoeff[ALF_MAX_NUM_COEF];
+  //variable
+  Int    i,j;
+  Int64  iDist;
+  Double dDist, dsum;
+#if LCUALF_QP_DEPENDENT_BITS
+  Int alfPrecisionBit = getAlfPrecisionBit( m_alfQP );
+#endif
+
+  for(i=0; i< iFiltLength; i++)
+  {
+#if LCUALF_QP_DEPENDENT_BITS
+    pdcoeff[i]= (Double)piCoeff[i] / (Double)(1<<alfPrecisionBit);
+#else
+    pdcoeff[i]= (Double)piCoeff[i] / (Double)(1<< ((Int)ALF_NUM_BIT_SHIFT) );
+#endif
+  }
+
+  dDist =0;
+  for(i=0; i< iFiltLength; i++)
+  {
+    dsum= ((Double)ppdE[i][i]) * pdcoeff[i];
+    for(j=i+1; j< iFiltLength; j++)
+    {
+      dsum += (Double)(2*ppdE[i][j])* pdcoeff[j];
+    }
+
+    dDist += ((dsum - 2.0 * pdy[i])* pdcoeff[i] );
+  }
+
+
+  UInt uiShift = g_uiBitIncrement<<1;
+  if(dDist < 0)
+  {
+    iDist = -(((Int64)(-dDist + 0.5)) >> uiShift);
+  }
+  else //dDist >=0
+  {
+    iDist= ((Int64)(dDist+0.5)) >> uiShift;
+  }
+
+  return iDist;
+
+}
+
+
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h	(revision 341)
@@ -0,0 +1,334 @@
+/* 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-2012, 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     TEncAdaptiveLoopFilter.h
+ \brief    estimation part of adaptive loop filter class (header)
+ */
+
+#ifndef __TENCADAPTIVELOOPFILTER__
+#define __TENCADAPTIVELOOPFILTER__
+
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComPic.h"
+
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TLibCommon/TComBitCounter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#define LCUALF_FILTER_BUDGET_CONTROL_ENC        1 //!< filter budget control 
+#define LCUALF_AVOID_USING_BOTTOM_LINES_ENCODER 1 //!< avoid using LCU bottom lines when lcu-based encoder RDO is used
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// correlation info
+struct AlfCorrData
+{
+  Double*** ECorr; //!< auto-correlation matrix
+  Double**  yCorr; //!< cross-correlation
+  Double*   pixAcc;
+  Int componentID;
+
+  //constructor & operator
+  AlfCorrData();
+  AlfCorrData(Int cIdx);
+  ~AlfCorrData();
+  Void reset();
+  Void mergeFrom(const AlfCorrData& src, Int* mergeTable, Bool doPixAccMerge);
+  AlfCorrData& operator += (const AlfCorrData& src);
+};
+
+/// picture quad-tree info
+struct AlfPicQTPart
+{
+  Int         componentID;
+  Int         partCUXS;
+  Int         partCUYS;
+  Int         partCUXE;
+  Int         partCUYE;
+  Int         partIdx;
+  Int         partLevel;
+  Int         partCol;
+  Int         partRow;
+  Int         childPartIdx[4];
+  Int         parentPartIdx;
+  Bool        isBottomLevel;
+  Bool        isSplit;
+  Bool        isProcessed;
+  Double      splitMinCost;
+  Int64       splitMinDist;
+  Int64       splitMinRate;
+  Double      selfMinCost;
+  Int64       selfMinDist;
+  Int64       selfMinRate;
+  Int         numFilterBudget;
+
+  AlfUnitParam* alfUnitParam; 
+  AlfCorrData*  alfCorr;
+
+  //constructor & operator
+  AlfPicQTPart();
+  ~AlfPicQTPart();
+  AlfPicQTPart& operator= (const AlfPicQTPart& src);
+};
+
+
+
+/// estimation part of adaptive loop filter class
+class TEncAdaptiveLoopFilter : public TComAdaptiveLoopFilter
+{
+private:
+  ///
+  /// variables for correlation calculation
+  ///
+  double **m_y_merged;
+  double ***m_E_merged;
+  double *m_pixAcc_merged;
+  double *m_y_temp;
+  double **m_E_temp;
+  static const Int  m_alfNumPartsInRowTab[5];
+  static const Int  m_alfNumPartsLevelTab[5];
+  static const Int  m_alfNumCulPartsLevelTab[5];
+
+  Int    m_lastSliceIdx;
+  Bool   m_picBasedALFEncode;
+  Bool   m_alfCoefInSlice;
+  Int*   m_numSlicesDataInOneLCU;
+  Int*   m_coeffNoFilter[NO_VAR_BINS]; //!< used for RDO
+  AlfParamSet* m_bestAlfParamSet;
+  AlfCorrData** m_alfCorr[NUM_ALF_COMPONENT];
+  AlfCorrData*  m_alfCorrMerged[NUM_ALF_COMPONENT]; //!< used for RDO
+  AlfUnitParam* m_alfPicFiltUnits[NUM_ALF_COMPONENT];
+  Int    m_alfPQTMaxDepth;
+  AlfPicQTPart* m_alfPQTPart[NUM_ALF_COMPONENT]; 
+#if LCUALF_FILTER_BUDGET_CONTROL_ENC
+  Double m_alfFiltBudgetPerLcu;
+  Int    m_alfUsedFilterNum;
+#endif
+
+  ///
+  /// ALF parameters
+  ///
+  ALFParam *m_tempALFp;
+
+  ///
+  /// temporary picture buffers or pointers
+  ///
+  TComPicYuv* m_pcPicYuvBest;
+  TComPicYuv* m_pcPicYuvTmp;
+
+  ///
+  /// temporary filter buffers or pointers
+  ///
+  Int    *m_filterCoeffQuantMod;
+  double *m_filterCoeff;
+  Int    *m_filterCoeffQuant;
+  Int    **m_filterCoeffSymQuant;
+  Int    **m_diffFilterCoeffQuant;
+  Int    **m_FilterCoeffQuantTemp;
+  ///
+  /// coding control parameters
+  ///
+  Double m_dLambdaLuma;
+  Double m_dLambdaChroma;
+  Int  m_iALFEncodePassReduction; //!< 0: 16-pass encoding, 1: 1-pass encoding, 2: 2-pass encoding
+
+  Int  m_iALFMaxNumberFilters;    //!< ALF Max Number Filters per unit
+
+  Int  m_iALFNumOfRedesign;       //!< number of redesigning filter for each CU control depth
+
+  ///
+  /// variables for on/off control
+  ///
+  Pel **m_maskImg;
+  Bool m_bAlfCUCtrlEnabled;                         //!< if input ALF CU control param is NULL, this variable is set to be false (Disable CU control)
+  std::vector<AlfCUCtrlInfo> m_vBestAlfCUCtrlParam; //!< ALF CU control parameters container to store the ALF CU control parameters after RDO
+
+  ///
+  /// miscs. 
+  ///
+  TEncEntropy* m_pcEntropyCoder;
+private:
+
+  Void disableComponentAlfParam(Int compIdx, AlfParamSet* alfParamSet, AlfUnitParam* alfUnitPic);
+  Void copyAlfParamSet(AlfParamSet* dst, AlfParamSet* src);
+  Void initALFEncoderParam(AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam);
+  Void assignALFEncoderParam(AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam);
+  Void getStatistics(TComPicYuv* pPicOrg, TComPicYuv* pPicDec);
+  Void getOneCompStatistics(AlfCorrData** alfCorrComp, Int compIdx, Pel* imgOrg, Pel* imgDec, Int stride, Int formatShift, Bool isRedesignPhase);
+  Void getStatisticsOneLCU(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo* alfLCU, AlfCorrData* alfCorr, Pel* pPicOrg, Pel* pPicSrc, Int stride, Int formatShift, Bool isRedesignPhase);
+#if HHI_INTERVIEW_SKIP
+  Void decideParameters(TComPicYuv* pPicOrg, TComPicYuv* pPicDec, TComPicYuv* pPicRest, TComPicYuv* pUsedPelMap, AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam) ;
+#else
+  Void decideParameters(TComPicYuv* pPicOrg, TComPicYuv* pPicDec, TComPicYuv* pPicRest, AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam);
+#endif
+  Void deriveFilterInfo(Int compIdx, AlfCorrData* alfCorr, ALFParam* alfFiltParam, Int maxNumFilters);
+#if HHI_INTERVIEW_SKIP
+  Void decideBlockControl(Pel* pOrg, Pel* pDec, Pel* pRest, Pel* pUsed, Int stride, AlfPicQTPart* alfPicQTPart, AlfParamSet* & alfParamSet, Int64 &minRate, Int64 &minDist, Double &minCost);
+#else
+  Void decideBlockControl(Pel* pOrg, Pel* pDec, Pel* pRest, Int stride, AlfPicQTPart* alfPicQTPart, AlfParamSet* & alfParamSet, Int64 &minRate, Int64 &minDist, Double &minCost);
+#endif
+  Void copyPicQT(AlfPicQTPart* alfPicQTPartDest, AlfPicQTPart* alfPicQTPartSrc);
+  Void copyPixelsInOneRegion(Pel* imgDest, Pel* imgSrc, Int stride, Int yPos, Int height, Int xPos, Int width);
+  Void reDesignQT(AlfPicQTPart *alfPicQTPart, Int partIdx, Int partLevel);
+#if HHI_INTERVIEW_SKIP
+  Void setCUAlfCtrlFlags(UInt uiAlfCtrlDepth, Pel* imgOrg, Pel* imgDec, Pel* imgRest, Pel* imgUsed, Int stride, UInt64& ruiDist, std::vector<AlfCUCtrlInfo>& vAlfCUCtrlParam);
+  Void setCUAlfCtrlFlag(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiAlfCtrlDepth, Pel* imgOrg, Pel* imgDec, Pel* imgRest, Pel* imgUsed, Int stride, UInt64& ruiDist, std::vector<UInt>& vCUCtrlFlag) ;
+#else
+  Void setCUAlfCtrlFlags(UInt uiAlfCtrlDepth, Pel* imgOrg, Pel* imgDec, Pel* imgRest, Int stride, UInt64& ruiDist, std::vector<AlfCUCtrlInfo>& vAlfCUCtrlParam);
+  Void setCUAlfCtrlFlag(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiAlfCtrlDepth, Pel* imgOrg, Pel* imgDec, Pel* imgRest, Int stride, UInt64& ruiDist, std::vector<UInt>& vCUCtrlFlag);
+#endif
+  Void xCopyDecToRestCUs( Pel* imgDec, Pel* imgRest, Int stride );
+  Void xCopyDecToRestCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Pel* imgDec, Pel* imgRest, Int stride );
+  Void calcCorrOneCompRegionChma(Pel* imgOrg, Pel* imgPad, Int stride, Int yPos, Int xPos, Int height, Int width, Double **eCorr, Double *yCorr, Bool isSymmCopyBlockMatrix); //!< Calculate correlations for chroma                                        
+  Void calcCorrOneCompRegionLuma(Pel* imgOrg, Pel* imgPad, Int stride, Int yPos, Int xPos, Int height, Int width, Double ***eCorr, Double **yCorr, Double *pixAcc, Bool isforceCollection, Bool isSymmCopyBlockMatrix);
+
+  //LCU-based mode decision
+#if HHI_INTERVIEW_SKIP
+  Void  executeLCUBasedModeDecision(AlfParamSet* alfParamSet, Int compIdx, Pel* pOrg, Pel* pDec, Pel* pRest, Pel* pUsed, Int stride, Int formatShift, AlfCorrData** alfCorrLCUs);
+#else
+  Void  executeLCUBasedModeDecision(AlfParamSet* alfParamSet, Int compIdx, Pel* pOrg, Pel* pDec, Pel* pRest, Int stride, Int formatShift, AlfCorrData** alfCorrLCUs);
+#endif
+  Void  decideLCUALFUnitParam(Int compIdx, AlfUnitParam* alfUnitPic, Int lcuIdx, Int lcuPos, Int numLCUWidth, AlfUnitParam* alfUnitParams, AlfCorrData* alfCorr, std::vector<ALFParam*>& storedFilters, Int maxNumFilter, Double lambda, Bool isLeftUnitAvailable, Bool isUpUnitAvailable);
+  Void  getFiltOffAlfUnitParam(AlfUnitParam* alfFiltOffParam, Int lcuPos, AlfUnitParam* alfUnitPic, Bool isLeftUnitAvailable, Bool isUpUnitAvailable);
+  Int64 estimateFilterDistortion(Int compIdx, AlfCorrData* alfCorr, Int** coeff = NULL, Int filterSetSize = 1, Int* mergeTable = NULL, Bool doPixAccMerge = false);
+  Int   calculateAlfUnitRateRDO(AlfUnitParam* alfUnitParam, Int numStoredFilters = 0);
+#if HHI_INTERVIEW_SKIP
+  Int64 calcAlfLCUDist(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo& alfLCUInfo, Pel* picSrc, Pel* picCmp, Pel* picUsed, Int stride, Int formatShift) ;
+#else
+  Int64 calcAlfLCUDist(Bool skipLCUBottomLines, Int compIdx, AlfLCUInfo& alfLCUInfo, Pel* picSrc, Pel* picCmp, Int stride, Int formatShift);
+#endif
+  Void  reconstructOneAlfLCU(Int compIdx, AlfLCUInfo& alfLCUInfo, AlfUnitParam* alfUnitParam, Pel* picDec, Pel* picRest, Int stride, Int formatShift);
+  Void  copyOneAlfLCU(AlfLCUInfo& alfLCUInfo, Pel* picDst, Pel* picSrc, Int stride, Int formatShift);
+
+  //picture-based mode decision
+#if HHI_INTERVIEW_SKIP
+  Void executePicBasedModeDecision(AlfParamSet* alfParamSet, AlfPicQTPart* alfPicQTPart, Int compIdx, Pel* pOrg, Pel* pDec, Pel* pRest, Pel* pUsed, Int stride, Int formatShift, AlfCorrData** alfCorrLCUs);
+#else
+  Void executePicBasedModeDecision(AlfParamSet* alfParamSet, AlfPicQTPart* alfPicQTPart, Int compIdx, Pel* pOrg, Pel* pDec, Pel* pRest, Int stride, Int formatShift, AlfCorrData** alfCorrLCUs);
+#endif
+  Void creatPQTPart               (Int partLevel, Int partRow, Int partCol, Int parentPartIdx, Int partCUXS, Int partCUXE, Int partCUYS, Int partCUYE);
+  Void resetPQTPart               ();
+  Int  convertLevelRowCol2Idx     (Int level, Int row, Int col);
+  Void convertIdx2LevelRowCol     (Int idx, Int *level, Int *row, Int *col);
+  Void executeModeDecisionOnePart (AlfPicQTPart *alfPicQTPart, AlfCorrData** alfPicLCUCorr, Int partIdx, Int partLevel);
+  Void decideQTPartition          (AlfPicQTPart* alfPicQTPart, AlfCorrData** alfPicLCUCorr, Int partIdx, Int partLevel, Double &cost, Int64 &dist, Int64 &rate);
+  Void patchAlfUnitParams(AlfPicQTPart* alfPicQTPart, Int partIdx, AlfUnitParam* alfUnitPic);
+  Void checkMerge(Int compIdx, AlfUnitParam* alfUnitPic);
+  Void transferToAlfParamSet(Int compIdx, AlfUnitParam* alfUnitPic, AlfParamSet* & alfParamSet);
+  Int  calculateAlfParamSetRateRDO(Int compIdx, AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCUCtrlParam);
+  // ALF on/off control related functions
+  Void xCreateTmpAlfCtrlFlags   ();
+  Void xDestroyTmpAlfCtrlFlags  ();
+  Void xCopyTmpAlfCtrlFlagsTo   ();
+  Void xCopyTmpAlfCtrlFlagsFrom ();
+  Void getCtrlFlagsFromCU(AlfLCUInfo* pcAlfLCU, std::vector<UInt> *pvFlags, Int iAlfDepth, UInt uiMaxNumSUInLCU);
+  Void xEncodeCUAlfCtrlFlags  (std::vector<AlfCUCtrlInfo> &vAlfCUCtrlParam);
+  Void xEncodeCUAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+  // functions related to filtering
+  Void xFilterCoefQuickSort   ( Double *coef_data, Int *coef_num, Int upper, Int lower );
+  Void xQuantFilterCoef       ( Double* h, Int* qh, Int tap, int bit_depth );
+  // distortion / misc functions
+#if HHI_INTERVIEW_SKIP
+  UInt64 xCalcSSD             ( Pel* pOrg, Pel* pCmp, Pel* pUsed, Int iWidth, Int iHeight, Int iStride );
+#else
+  UInt64 xCalcSSD             ( Pel* pOrg, Pel* pCmp, Int iWidth, Int iHeight, Int iStride );
+#endif
+  Int64 xFastFiltDistEstimation(Double** ppdE, Double* pdy, Int* piCoeff, Int iFiltLength); //!< Estimate filtering distortion by correlation values and filter coefficients
+
+  /// code filter coefficients
+  UInt xcodeFiltCoeff(Int **filterCoeffSymQuant, Int filter_shape, Int varIndTab[], Int filters_per_fr_best, ALFParam* ALFp);
+  Void xfindBestFilterVarPred(double **ySym, double ***ESym, double *pixAcc, Int **filterCoeffSym, Int **filterCoeffSymQuant,Int filter_shape, Int *filters_per_fr_best, Int varIndTab[], Pel **imgY_rec, Pel **varImg, Pel **maskImg, Pel **imgY_pad, double lambda_val, Int numMaxFilters = NO_FILTERS);
+  double xfindBestCoeffCodMethod(int **filterCoeffSymQuant, int filter_shape, int sqrFiltLength, int filters_per_fr, double errorForce0CoeffTab[NO_VAR_BINS][2], double lambda);
+  Int xsendAllFiltersPPPred(int **FilterCoeffQuant, int filter_shape, int sqrFiltLength, int filters_per_group, int createBistream, ALFParam* ALFp);
+  Int xcodeAuxInfo(int filters_per_fr, int varIndTab[NO_VAR_BINS], int filter_shape, ALFParam* ALFp);
+  Int xcodeFilterCoeff(int **pDiffQFilterCoeffIntPP, int filter_shape, int sqrFiltLength, int filters_per_group, int createBitstream);
+  Int lengthGolomb(int coeffVal, int k);
+  Int lengthPredFlags(int force0, int predMethod, int codedVarBins[NO_VAR_BINS], int filters_per_group, int createBitstream);
+  Int lengthFilterCoeffs(int sqrFiltLength, int filters_per_group, int pDepthInt[], int **FilterCoeff, int kMinTab[], int createBitstream);
+  Void predictALFCoeffLumaEnc(ALFParam* pcAlfParam, Int **pfilterCoeffSym, Int filter_shape); //!< prediction of luma ALF coefficients
+  //cholesky related
+  Int   xGauss( Double **a, Int N );
+  Double findFilterCoeff(double ***EGlobalSeq, double **yGlobalSeq, double *pixAccGlobalSeq, int **filterCoeffSeq,int **filterCoeffQuantSeq, int intervalBest[NO_VAR_BINS][2], int varIndTab[NO_VAR_BINS], int sqrFiltLength, int filters_per_fr, int *weights, double errorTabForce0Coeff[NO_VAR_BINS][2]);
+  Double QuantizeIntegerFilterPP(Double *filterCoeff, Int *filterCoeffQuant, Double **E, Double *y, Int sqrFiltLength, Int *weights);
+  Void roundFiltCoeff(int *FilterCoeffQuan, double *FilterCoeff, int sqrFiltLength, int factor);
+  double mergeFiltersGreedy(double **yGlobalSeq, double ***EGlobalSeq, double *pixAccGlobalSeq, int intervalBest[NO_VAR_BINS][2], int sqrFiltLength, int noIntervals);
+  double calculateErrorAbs(double **A, double *b, double y, int size);
+  double calculateErrorCoeffProvided(double **A, double *b, double *c, int size);
+  Void add_b(double *bmerged, double **b, int start, int stop, int size);
+  Void add_A(double **Amerged, double ***A, int start, int stop, int size);
+  Int  gnsSolveByChol(double **LHS, double *rhs, double *x, int noEq);
+  Void gnsBacksubstitution(double R[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], double z[ALF_MAX_NUM_COEF], int R_size, double A[ALF_MAX_NUM_COEF]);
+  Void gnsTransposeBacksubstitution(double U[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], double rhs[], double x[],int order);
+  Int  gnsCholeskyDec(double **inpMatr, double outMatr[ALF_MAX_NUM_COEF][ALF_MAX_NUM_COEF], int noEq);
+
+public:
+  TEncAdaptiveLoopFilter          ();
+  virtual ~TEncAdaptiveLoopFilter () {}
+
+  Void startALFEnc(TComPic* pcPic, TEncEntropy* pcEntropyCoder); //!< allocate temporal memory
+  Void endALFEnc(); //!< destroy temporal memory
+#if ALF_CHROMA_LAMBDA
+#if HHI_INTERVIEW_SKIP
+  Void ALFProcess( AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam, Double lambdaLuma, Double lambdaChroma, Bool bInterviewSkip);
+#else
+  Void ALFProcess( AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam, Double lambdaLuma, Double lambdaChroma);
+#endif
+#else
+#if HHI_INTERVIEW_SKIP
+  Void ALFProcess( AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam, Double lambda, Bool bInterviewSkip);
+#else
+  Void ALFProcess( AlfParamSet* alfParamSet, std::vector<AlfCUCtrlInfo>* alfCtrlParam, Double lambda);
+#endif
+#endif
+  Void initALFEnc(Bool isAlfParamInSlice, Bool isPicBasedEncode, Int numSlices, AlfParamSet* & alfParams, std::vector<AlfCUCtrlInfo>* & alfCUCtrlParam);
+  Void uninitALFEnc(AlfParamSet* & alfParams, std::vector<AlfCUCtrlInfo>* & alfCUCtrlParam);
+  Void resetPicAlfUnit();
+  Void setAlfCoefInSlice(Bool b) {m_alfCoefInSlice = b;}
+  Void setALFEncodePassReduction (Int iVal) {m_iALFEncodePassReduction = iVal;} //!< set N-pass encoding. 0: 16(14)-pass encoding, 1: 1-pass encoding, 2: 2-pass encoding
+
+  Void setALFMaxNumberFilters    (Int iVal) {m_iALFMaxNumberFilters = iVal;} //!< set ALF Max Number of Filters
+
+  Void createAlfGlobalBuffers(); //!< create ALF global buffers
+  Void initPicQuadTreePartition(Bool isPicBasedEncode);
+  Void destroyAlfGlobalBuffers(); //!< destroy ALF global buffers
+  Void PCMLFDisableProcess (TComPic* pcPic);
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 341)
@@ -0,0 +1,154 @@
+/* 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-2012, 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.h
+    \brief    encoder analyzer class (header)
+*/
+
+#ifndef __TENCANALYZE__
+#define __TENCANALYZE__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdio.h>
+#include <memory.h>
+#include <assert.h>
+#include "TLibCommon/CommonDef.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder analyzer class
+class TEncAnalyze
+{
+private:
+  Double    m_dPSNRSumY;
+  Double    m_dPSNRSumU;
+  Double    m_dPSNRSumV;
+  Double    m_dAddBits;
+  UInt      m_uiNumPic;
+  Double    m_dFrmRate; //--CFG_KDY
+  
+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;
+    m_dAddBits  += bits;
+    
+    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;   }
+  
+  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 )
+  {
+    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 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);
+  }
+  
+  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);
+  }
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCANALYZE_H__C79BCAA2_6AC8_4175_A0FE_CF02F5829233__INCLUDED_)
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 341)
@@ -0,0 +1,83 @@
+/* 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-2012, 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     TEncBinCoder.h
+    \brief    binary entropy encoder interface
+*/
+
+#ifndef __TENC_BIN_CODER__
+#define __TENC_BIN_CODER__
+
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComBitStream.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncBinCABAC;
+
+class TEncBinIf
+{
+public:
+  virtual Void  init              ( TComBitIf* pcTComBitIf )                  = 0;
+  virtual Void  uninit            ()                                          = 0;
+
+  virtual Void  start             ()                                          = 0;
+  virtual Void  finish            ()                                          = 0;
+  virtual Void  copyState         ( TEncBinIf* pcTEncBinIf )                  = 0;
+  virtual Void  flush            ()                                           = 0;
+
+  virtual Void  encodeFlush     (Bool bEnd) = 0;
+
+  virtual Void  resetBac          ()                                          = 0;
+  virtual Void  encodeNumSubseqIPCM( Int numSubseqIPCM )                   = 0;
+  virtual Void  encodePCMAlignBits()                                          = 0;
+  virtual Void  xWritePCMCode     ( UInt uiCode, UInt uiLength )              = 0;
+
+  virtual Void  resetBits         ()                                          = 0;
+  virtual UInt  getNumWrittenBits ()                                          = 0;
+
+  virtual Void  encodeBin         ( UInt  uiBin,  ContextModel& rcCtxModel )  = 0;
+  virtual Void  encodeBinEP       ( UInt  uiBin                            )  = 0;
+  virtual Void  encodeBinsEP      ( UInt  uiBins, Int numBins              )  = 0;
+  virtual Void  encodeBinTrm      ( UInt  uiBin                            )  = 0;
+
+  virtual TEncBinCABAC*   getTEncBinCABAC   ()  { return 0; }
+  
+  virtual ~TEncBinIf() {}
+};
+
+//! \}
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 341)
@@ -0,0 +1,409 @@
+/* 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-2012, 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     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABAC.h"
+#include "TLibCommon/TComRom.h"
+
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+TEncBinCABAC::TEncBinCABAC()
+: m_pcTComBitIf( 0 )
+, m_binCountIncrement( 0 )
+#if FAST_BIT_EST
+, m_fracBits( 0 )
+#endif
+{
+}
+
+TEncBinCABAC::~TEncBinCABAC()
+{
+}
+
+Void TEncBinCABAC::init( TComBitIf* pcTComBitIf )
+{
+  m_pcTComBitIf = pcTComBitIf;
+}
+
+Void TEncBinCABAC::uninit()
+{
+  m_pcTComBitIf = 0;
+}
+
+Void TEncBinCABAC::start()
+{
+  m_uiLow            = 0;
+  m_uiRange          = 510;
+  m_bitsLeft         = 23;
+  m_numBufferedBytes = 0;
+  m_bufferedByte     = 0xff;
+}
+
+Void TEncBinCABAC::finish()
+{
+  if ( m_uiLow >> ( 32 - m_bitsLeft ) )
+  {
+    //assert( m_numBufferedBytes > 0 );
+    //assert( m_bufferedByte != 0xff );
+    m_pcTComBitIf->write( m_bufferedByte + 1, 8 );
+    while ( m_numBufferedBytes > 1 )
+    {
+      m_pcTComBitIf->write( 0x00, 8 );
+      m_numBufferedBytes--;
+    }
+    m_uiLow -= 1 << ( 32 - m_bitsLeft );
+  }
+  else
+  {
+    if ( m_numBufferedBytes > 0 )
+    {
+      m_pcTComBitIf->write( m_bufferedByte, 8 );
+    }
+    while ( m_numBufferedBytes > 1 )
+    {
+      m_pcTComBitIf->write( 0xff, 8 );
+      m_numBufferedBytes--;
+    }    
+  }
+  m_pcTComBitIf->write( m_uiLow >> 8, 24 - m_bitsLeft );
+}
+
+Void TEncBinCABAC::flush()
+{
+  encodeBinTrm(1);
+  finish();
+  m_pcTComBitIf->write(1, 1);
+#if OL_FLUSH_ALIGN
+  m_pcTComBitIf->writeAlignZero();
+#endif
+
+  start();
+}
+
+/** Reset BAC register and counter values.
+ * \returns Void
+ */
+Void TEncBinCABAC::resetBac()
+{
+  start();
+}
+
+/** Encode # of subsequent IPCM blocks.
+ * \param numSubseqIPCM 
+ * \returns Void
+ */
+Void TEncBinCABAC::encodeNumSubseqIPCM( Int numSubseqIPCM )
+{
+  finish();
+  m_pcTComBitIf->write( 1, 1 ); // stop bit
+
+  m_pcTComBitIf->write( numSubseqIPCM ? 1 : 0, 1);
+
+  if ( numSubseqIPCM > 0)
+  {
+    Bool bCodeLast = ( 3 > numSubseqIPCM );
+
+    while( --numSubseqIPCM )
+    {
+      m_pcTComBitIf->write( 1, 1 );
+    }
+    if( bCodeLast )
+    {
+      m_pcTComBitIf->write( 0, 1 );
+    }
+  }
+}
+
+/** Encode PCM alignment zero bits.
+ * \returns Void
+ */
+Void TEncBinCABAC::encodePCMAlignBits()
+{
+  m_pcTComBitIf->writeAlignZero(); // pcm align zero
+}
+
+/** Write a PCM code.
+ * \param uiCode code value
+ * \param uiLength code bit-depth
+ * \returns Void
+ */
+Void TEncBinCABAC::xWritePCMCode(UInt uiCode, UInt uiLength)
+{
+  m_pcTComBitIf->write(uiCode, uiLength);
+}
+
+Void TEncBinCABAC::copyState( TEncBinIf* pcTEncBinIf )
+{
+  TEncBinCABAC* pcTEncBinCABAC = pcTEncBinIf->getTEncBinCABAC();
+  m_uiLow           = pcTEncBinCABAC->m_uiLow;
+  m_uiRange         = pcTEncBinCABAC->m_uiRange;
+  m_bitsLeft        = pcTEncBinCABAC->m_bitsLeft;
+  m_bufferedByte    = pcTEncBinCABAC->m_bufferedByte;
+  m_numBufferedBytes = pcTEncBinCABAC->m_numBufferedBytes;
+#if FAST_BIT_EST
+  m_fracBits = pcTEncBinCABAC->m_fracBits;
+#endif
+}
+
+Void TEncBinCABAC::resetBits()
+{
+  m_uiLow            = 0;
+  m_bitsLeft         = 23;
+  m_numBufferedBytes = 0;
+  m_bufferedByte     = 0xff;
+  if ( m_binCountIncrement )
+  {
+    m_uiBinsCoded = 0;
+  }
+#if FAST_BIT_EST
+  m_fracBits &= 32767;
+#endif
+}
+
+UInt TEncBinCABAC::getNumWrittenBits()
+{
+  return m_pcTComBitIf->getNumberOfWrittenBits() + 8 * m_numBufferedBytes + 23 - m_bitsLeft;
+}
+
+/**
+ * \brief Encode bin
+ *
+ * \param binValue   bin value
+ * \param rcCtxModel context model
+ */
+Void TEncBinCABAC::encodeBin( UInt binValue, ContextModel &rcCtxModel )
+{
+  {
+    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" )
+  }
+  m_uiBinsCoded += m_binCountIncrement;
+#if CABAC_INIT_FLAG
+  rcCtxModel.setBinsCoded( 1 );
+#endif
+  
+  UInt  uiLPS   = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) & 3 ];
+  m_uiRange    -= uiLPS;
+  
+  if( binValue != rcCtxModel.getMps() )
+  {
+    Int numBits = TComCABACTables::sm_aucRenormTable[ uiLPS >> 3 ];
+    m_uiLow     = ( m_uiLow + m_uiRange ) << numBits;
+    m_uiRange   = uiLPS << numBits;
+    rcCtxModel.updateLPS();
+    
+    m_bitsLeft -= numBits;
+  }
+  else
+  {
+    rcCtxModel.updateMPS();
+    if ( m_uiRange >= 256 )
+    {
+      return;
+    }
+    
+    m_uiLow <<= 1;
+    m_uiRange <<= 1;
+    m_bitsLeft--;
+  }
+  
+  testAndWriteOut();
+}
+
+/**
+ * \brief Encode equiprobable bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABAC::encodeBinEP( UInt binValue )
+{
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tEPsymbol=" )
+    DTRACE_CABAC_V( binValue )
+    DTRACE_CABAC_T( "\n" )
+  }
+  m_uiBinsCoded += m_binCountIncrement;
+  m_uiLow <<= 1;
+  if( binValue )
+  {
+    m_uiLow += m_uiRange;
+  }
+  m_bitsLeft--;
+  
+  testAndWriteOut();
+}
+
+/**
+ * \brief Encode equiprobable bins
+ *
+ * \param binValues bin values
+ * \param numBins number of bins
+ */
+Void TEncBinCABAC::encodeBinsEP( UInt binValues, Int numBins )
+{
+  m_uiBinsCoded += numBins & -m_binCountIncrement;
+  
+  for ( Int i = 0; i < numBins; i++ )
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tEPsymbol=" )
+    DTRACE_CABAC_V( ( binValues >> ( numBins - 1 - i ) ) & 1 )
+    DTRACE_CABAC_T( "\n" )
+  }
+  
+  while ( numBins > 8 )
+  {
+    numBins -= 8;
+    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();
+}
+
+/**
+ * \brief Encode terminating bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABAC::encodeBinTrm( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_uiRange -= 2;
+  if( binValue )
+  {
+    m_uiLow  += m_uiRange;
+    m_uiLow <<= 7;
+    m_uiRange = 2 << 7;
+    m_bitsLeft -= 7;
+  }
+  else if ( m_uiRange >= 256 )
+  {
+    return;
+  }
+  else
+  {
+    m_uiLow   <<= 1;
+    m_uiRange <<= 1;
+    m_bitsLeft--;    
+  }
+  
+  testAndWriteOut();
+}
+
+Void TEncBinCABAC::testAndWriteOut()
+{
+  if ( m_bitsLeft < 12 )
+  {
+    writeOut();
+  }
+}
+
+/**
+ * \brief Move bits from register into bitstream
+ */
+Void TEncBinCABAC::writeOut()
+{
+  UInt leadByte = m_uiLow >> (24 - m_bitsLeft);
+  m_bitsLeft += 8;
+  m_uiLow &= 0xffffffffu >> m_bitsLeft;
+  
+  if ( leadByte == 0xff )
+  {
+    m_numBufferedBytes++;
+  }
+  else
+  {
+    if ( m_numBufferedBytes > 0 )
+    {
+      UInt carry = leadByte >> 8;
+      UInt byte = m_bufferedByte + carry;
+      m_bufferedByte = leadByte & 0xff;
+      m_pcTComBitIf->write( byte, 8 );
+      
+      byte = ( 0xff + carry ) & 0xff;
+      while ( m_numBufferedBytes > 1 )
+      {
+        m_pcTComBitIf->write( byte, 8 );
+        m_numBufferedBytes--;
+      }
+    }
+    else
+    {
+      m_numBufferedBytes = 1;
+      m_bufferedByte = leadByte;
+    }      
+  }    
+}
+
+/** flush bits when CABAC termination
+  * \param [in] bEnd true means this flushing happens at the end of RBSP. No need to encode stop bit
+  */
+Void TEncBinCABAC::encodeFlush(Bool bEnd)
+{
+  m_uiRange = 2;
+
+  m_uiLow  += 2;
+  m_uiLow <<= 7;
+  m_uiRange = 2 << 7;
+  m_bitsLeft -= 7;
+  testAndWriteOut();
+  finish();
+
+  if(!bEnd)
+  {
+    m_pcTComBitIf->write( 1, 1 ); // stop bit
+  }
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 341)
@@ -0,0 +1,107 @@
+/* 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-2012, 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     TEncBinCoderCABAC.h
+    \brief    binary entropy encoder of CABAC
+*/
+
+#ifndef __TENC_BIN_CODER_CABAC__
+#define __TENC_BIN_CODER_CABAC__
+
+#include "TLibCommon/TComCABACTables.h"
+#include "TEncBinCoder.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncBinCABAC : public TEncBinIf
+{
+public:
+  TEncBinCABAC ();
+  virtual ~TEncBinCABAC();
+  
+  Void  init              ( TComBitIf* pcTComBitIf );
+  Void  uninit            ();
+  
+  Void  start             ();
+  Void  finish            ();
+  Void  copyState         ( TEncBinIf* pcTEncBinIf );
+  Void  flush            ();
+
+  Void  resetBac          ();
+  Void  encodeNumSubseqIPCM( Int numSubseqIPCM );
+  Void  encodePCMAlignBits();
+  Void  xWritePCMCode     ( UInt uiCode, UInt uiLength );
+  
+  Void encodeFlush(Bool bEnd);  //!< flush bits when CABAC termination
+
+  Void  resetBits         ();
+  UInt  getNumWrittenBits ();
+  
+  Void  encodeBin         ( UInt  binValue,  ContextModel& rcCtxModel );
+  Void  encodeBinEP       ( UInt  binValue                            );
+  Void  encodeBinsEP      ( UInt  binValues, Int numBins              );
+  Void  encodeBinTrm      ( UInt  binValue                            );
+  
+  TEncBinCABAC* getTEncBinCABAC()  { 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:
+#else
+private:
+#endif
+  Void testAndWriteOut();
+  Void writeOut();
+  
+  TComBitIf*          m_pcTComBitIf;
+  UInt                m_uiLow;
+  UInt                m_uiRange;
+  UInt                m_bufferedByte;
+  Int                 m_numBufferedBytes;
+  Int                 m_bitsLeft;
+  UInt                m_uiBinsCoded;
+  Int                 m_binCountIncrement;
+#if FAST_BIT_EST
+  UInt64 m_fracBits;
+#endif
+};
+
+//! \}
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 341)
@@ -0,0 +1,116 @@
+/* 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-2012, 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     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABACCounter.h"
+#include "TLibCommon/TComRom.h"
+
+#if FAST_BIT_EST
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+TEncBinCABACCounter::TEncBinCABACCounter()
+{
+}
+
+TEncBinCABACCounter::~TEncBinCABACCounter()
+{
+}
+
+Void TEncBinCABACCounter::finish()
+{
+  m_pcTComBitIf->write(0, UInt(m_fracBits >> 15) );
+  m_fracBits &= 32767;
+}
+
+UInt TEncBinCABACCounter::getNumWrittenBits()
+{
+  return m_pcTComBitIf->getNumberOfWrittenBits() + UInt( m_fracBits >> 15 );
+}
+
+/**
+ * \brief Encode bin
+ *
+ * \param binValue   bin value
+ * \param rcCtxModel context model
+ */
+Void TEncBinCABACCounter::encodeBin( UInt binValue, ContextModel &rcCtxModel )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  
+  m_fracBits += rcCtxModel.getEntropyBits( binValue );
+  rcCtxModel.update( binValue );
+}
+
+/**
+ * \brief Encode equiprobable bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABACCounter::encodeBinEP( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_fracBits += 32768;
+}
+
+/**
+ * \brief Encode equiprobable bins
+ *
+ * \param binValues bin values
+ * \param numBins number of bins
+ */
+Void TEncBinCABACCounter::encodeBinsEP( UInt binValues, Int numBins )
+{
+  m_uiBinsCoded += numBins & -m_binCountIncrement;
+  m_fracBits += 32768 * numBins;
+}
+
+/**
+ * \brief Encode terminating bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABACCounter::encodeBinTrm( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_fracBits += ContextModel::getEntropyBitsTrm( binValue );
+}
+
+//! \}
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 341)
@@ -0,0 +1,72 @@
+/* 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-2012, 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     TEncBinCoderCABAC.h
+    \brief    binary entropy encoder of CABAC
+*/
+
+#ifndef __TENC_BIN_CODER_CABAC_COUNTER__
+#define __TENC_BIN_CODER_CABAC_COUNTER__
+
+
+#include "TEncBinCoderCABAC.h"
+
+#if FAST_BIT_EST
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+class TEncBinCABACCounter : public TEncBinCABAC
+{
+public:
+  TEncBinCABACCounter ();
+  virtual ~TEncBinCABACCounter();
+  
+  Void  finish            ();
+  UInt  getNumWrittenBits ();
+
+  Void  encodeBin         ( UInt  binValue,  ContextModel& rcCtxModel );
+  Void  encodeBinEP       ( UInt  binValue                            );
+  Void  encodeBinsEP      ( UInt  binValues, Int numBins              );
+  Void  encodeBinTrm      ( UInt  binValue                            );
+  
+private:
+};
+
+//! \}
+
+#endif
+
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 341)
@@ -0,0 +1,1901 @@
+/* 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-2012, 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     TEncCavlc.cpp
+    \brief    CAVLC encoder class
+*/
+
+#include "../TLibCommon/CommonDef.h"
+#include "TEncCavlc.h"
+#include "SEIwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+#define WRITE_CODE( value, length, name)    xWriteCodeTr ( value, length, name )
+#define WRITE_UVLC( value,         name)    xWriteUvlcTr ( value,         name )
+#define WRITE_SVLC( value,         name)    xWriteSvlcTr ( value,         name )
+#define WRITE_FLAG( value,         name)    xWriteFlagTr ( value,         name )
+
+Void  xWriteUvlcTr          ( UInt value,               const Char *pSymbolName);
+Void  xWriteSvlcTr          ( Int  value,               const Char *pSymbolName);
+Void  xWriteFlagTr          ( UInt value,               const Char *pSymbolName);
+
+Void  xTraceSPSHeader (TComSPS *pSPS)
+{
+  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
+}
+
+Void  xTracePPSHeader (TComPPS *pPPS)
+{
+  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
+}
+
+Void  xTraceAPSHeader (TComAPS *pAPS)
+{
+  fprintf( g_hTrace, "=========== Adaptation Parameter Set ===========\n");
+}
+
+Void  xTraceSliceHeader (TComSlice *pSlice)
+{
+  fprintf( g_hTrace, "=========== Slice ===========\n");
+}
+
+
+Void  TEncCavlc::xWriteCodeTr (UInt value, UInt  length, const Char *pSymbolName)
+{
+  xWriteCode (value,length);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s u(%d) : %d\n", pSymbolName, length, value ); 
+}
+
+Void  TEncCavlc::xWriteUvlcTr (UInt value, const Char *pSymbolName)
+{
+  xWriteUvlc (value);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s u(v) : %d\n", pSymbolName, value ); 
+}
+
+Void  TEncCavlc::xWriteSvlcTr (Int value, const Char *pSymbolName)
+{
+  xWriteSvlc(value);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s s(v) : %d\n", pSymbolName, value ); 
+}
+
+Void  TEncCavlc::xWriteFlagTr(UInt value, const Char *pSymbolName)
+{
+  xWriteFlag(value);
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-40s u(1) : %d\n", pSymbolName, value ); 
+}
+
+#else
+
+#define WRITE_CODE( value, length, name)     xWriteCode ( value, length )
+#define WRITE_UVLC( value,         name)     xWriteUvlc ( value )
+#define WRITE_SVLC( value,         name)     xWriteSvlc ( value )
+#define WRITE_FLAG( value,         name)     xWriteFlag ( value )
+
+#endif
+
+
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncCavlc::TEncCavlc()
+{
+  m_pcBitIf           = NULL;
+  m_uiCoeffCost       = 0;
+  m_bAlfCtrl = false;
+  m_uiMaxAlfCtrlDepth = 0;
+  
+  m_iSliceGranularity = 0;
+}
+
+TEncCavlc::~TEncCavlc()
+{
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncCavlc::resetEntropy()
+{
+}
+
+/**
+ * marshall the SEI message sei.
+ */
+void TEncCavlc::codeSEI(const SEI& sei)
+{
+  writeSEImessage(*m_pcBitIf, sei);
+}
+
+Void  TEncCavlc::codeAPSInitInfo(TComAPS* pcAPS)
+{
+
+#if ENC_DEC_TRACE  
+  xTraceAPSHeader(pcAPS);
+#endif
+  //APS ID
+  WRITE_UVLC( pcAPS->getAPSID(), "aps_id" );
+
+  WRITE_FLAG( pcAPS->getScalingListEnabled()?1:0, "aps_scaling_list_data_present_flag");
+  //DF flag
+  WRITE_FLAG(pcAPS->getLoopFilterOffsetInAPS()?1:0, "aps_deblocking_filter_flag");
+}
+Void TEncCavlc::codeAPSAlflag(UInt uiCode)
+{
+  WRITE_FLAG(uiCode, "aps_adaptive_loop_filter_flag");
+}
+
+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 )
+{
+#if PRINT_RPS_INFO
+  int lastBits = getNumberOfWrittenBits();
+#endif
+  WRITE_FLAG( rps->getInterRPSPrediction(), "inter_ref_pic_set_prediction_flag" ); // inter_RPS_prediction_flag
+  if (rps->getInterRPSPrediction()) 
+  {
+    Int deltaRPS = rps->getDeltaRPS();
+    WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+    WRITE_CODE( (deltaRPS >=0 ? 0: 1), 1, "delta_rps_sign" ); //delta_rps_sign
+    WRITE_UVLC( abs(deltaRPS) - 1, "abs_delta_rps_minus1"); // absolute delta RPS minus 1
+
+    for(Int j=0; j < rps->getNumRefIdc(); j++)
+    {
+      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, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
+      }
+    }
+  }
+  else
+  {
+    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++)
+    {
+      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"); 
+    }
+    prev = 0;
+    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
+    {
+      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" ); 
+    }
+  }
+
+#if PRINT_RPS_INFO
+  printf("irps=%d (%2d bits) ", rps->getInterRPSPrediction(), getNumberOfWrittenBits() - lastBits);
+  rps->printDeltaPOC();
+#endif
+}
+
+
+Void TEncCavlc::codePPS( TComPPS* pcPPS )
+{
+#if ENC_DEC_TRACE  
+  xTracePPSHeader (pcPPS);
+#endif
+  
+  WRITE_UVLC( pcPPS->getPPSId(),                             "pic_parameter_set_id" );
+  WRITE_UVLC( pcPPS->getSPSId(),                             "seq_parameter_set_id" );
+
+  WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
+  if( pcPPS->getSignHideFlag() )
+  {
+    WRITE_CODE(pcPPS->getTSIG(), 4, "sign_hiding_threshold");
+  }
+#if CABAC_INIT_FLAG
+  WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
+#endif
+  // entropy_coding_mode_flag
+  // We code the entropy_coding_mode_flag, it's needed for tests.
+  WRITE_FLAG( pcPPS->getEntropyCodingMode() ? 1 : 0,         "entropy_coding_mode_flag" );
+  if (pcPPS->getEntropyCodingMode())
+  {
+  }
+  //   num_ref_idx_l0_default_active_minus1
+  //   num_ref_idx_l1_default_active_minus1
+  WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "pic_init_qp_minus26");
+  WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
+  WRITE_FLAG( pcPPS->getEnableTMVPFlag() ? 1 : 0,            "enable_temporal_mvp_flag" );
+  WRITE_CODE( pcPPS->getSliceGranularity(), 2,               "slice_granularity");
+  WRITE_UVLC( pcPPS->getMaxCuDQPDepth() + pcPPS->getUseDQP(),                   "max_cu_qp_delta_depth" );
+
+  WRITE_SVLC( pcPPS->getChromaQpOffset(),                   "chroma_qp_offset"     );
+  WRITE_SVLC( pcPPS->getChromaQpOffset2nd(),                "chroma_qp_offset_2nd" );
+
+  WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
+  WRITE_CODE( pcPPS->getWPBiPredIdc(), 2, "weighted_bipred_idc" );  // Use of Weighting Bi-Prediction (B_SLICE)
+  WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,  "output_flag_present_flag" );
+  if(pcPPS->getSPS()->getTilesOrEntropyCodingSyncIdc()==1)
+  {
+    WRITE_FLAG( pcPPS->getColumnRowInfoPresent(),           "tile_info_present_flag" );
+    WRITE_FLAG( pcPPS->getTileBehaviorControlPresentFlag(),  "tile_control_present_flag");
+    if( pcPPS->getColumnRowInfoPresent() == 1 )
+    {
+      WRITE_UVLC( pcPPS->getNumColumnsMinus1(),                                    "num_tile_columns_minus1" );
+      WRITE_UVLC( pcPPS->getNumRowsMinus1(),                                       "num_tile_rows_minus1" );
+      WRITE_FLAG( pcPPS->getUniformSpacingIdr(),                                   "uniform_spacing_flag" );
+      if( pcPPS->getUniformSpacingIdr() == 0 )
+      {
+        for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
+        {
+          WRITE_UVLC( pcPPS->getColumnWidth(i),                                    "column_width" );
+        }
+        for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
+        {
+          WRITE_UVLC( pcPPS->getRowHeight(i),                                      "row_height" );
+        }
+      }
+    }
+
+    if(pcPPS->getTileBehaviorControlPresentFlag() == 1)
+    {
+      Int iNumColTilesMinus1 = (pcPPS->getColumnRowInfoPresent() == 1)?(pcPPS->getNumColumnsMinus1()):(pcPPS->getSPS()->getNumColumnsMinus1());
+      Int iNumRowTilesMinus1 = (pcPPS->getColumnRowInfoPresent() == 1)?(pcPPS->getNumColumnsMinus1()):(pcPPS->getSPS()->getNumRowsMinus1());
+
+      if(iNumColTilesMinus1 !=0 || iNumRowTilesMinus1 !=0)
+      {
+          WRITE_FLAG( pcPPS->getLFCrossTileBoundaryFlag()?1 : 0,            "loop_filter_across_tile_flag");
+      }
+    }
+  }
+  else if(pcPPS->getSPS()->getTilesOrEntropyCodingSyncIdc()==2)
+  {
+    WRITE_UVLC( pcPPS->getNumSubstreams()-1,               "num_substreams_minus1" );
+  }
+
+  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresent()?1 : 0, "deblocking_filter_control_present_flag");
+  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
+  WRITE_FLAG( 0, "pps_extension_flag" );
+}
+
+#if QC_MVHEVC_B0046
+Void TEncCavlc::codeVPS( TComVPS* pcVPS )
+{
+  WRITE_CODE( pcVPS->getVPSId(),               4,        "video_parameter_set_id"     );
+  WRITE_FLAG( pcVPS->getTemporalNestingFlag() -1,        "temporal_id_nesting_flag"   );
+  WRITE_CODE( 0,                 2,        "vps_reserved_zero_2bits"    );
+  WRITE_CODE( pcVPS->getMaxLayers() - 1,       6,        "vps_max_layers_minus1"      );
+  WRITE_CODE( pcVPS->getMaxTLayers() - 1,      3,        "vps_max_sub_layers_minus1"  );
+  //to be determined
+  //profile_tier_level( 1, vps_max_sub_layers_minus1 );
+  //to be modified
+  WRITE_CODE( 0,                              12,         "vps_extension_offset"      );
+  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
+  {
+    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i),           "max_dec_pic_buffering[i]" );
+    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "num_reorder_pics[i]"      );
+    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "max_latency_increase[i]"  );
+  }
+  //!!!waste one bit: 3-view, 3; 2-view or more views: 1
+  WRITE_UVLC(pcVPS->getNumHRDParameters(),                 "vps_num_hrd_parameters"   );
+  assert(pcVPS->getNumHRDParameters()==0);
+  for ( UInt i = 0; i < pcVPS->getNumHRDParameters(); i ++)
+  {
+   //   if( i > 0 )  
+    //{
+    //  WRITE_UVLC (0, "op_num_layer_id_values_minus1[ opIdx ]");
+    //  for( i = 0; i <= op_num_layer_id_values_minus1[ opIdx ]; i++ )  
+    //    WRITE_CODE(0, 6, "op_layer_id[ opIdx ][ i ]");
+    //}  
+    //hrd_parameters( i  = =  0, vps_max_sub_layers_minus1 );  
+  }
+  WRITE_CODE( 1,      1,        "bit_equal_to_one" ); 
+  //btye aligned
+  m_pcBitIf->writeAlignOne();
+
+  if(pcVPS->getMaxLayers() == 3)
+    pcVPS->setNumAddiLayerOperationPoints (pcVPS->getMaxLayers());    //may be configured 
+  else
+    pcVPS->setNumAddiLayerOperationPoints (1);    
+  pcVPS->setNumAddiProLevelSets         (1);
+  WRITE_CODE( pcVPS->getNumAddiLayerOperationPoints(),         8,               "num_additional_layer_operation_points" );    
+  WRITE_CODE( pcVPS->getNumAddiProLevelSets(),                 8,               "num_additional_profile_level_sets"     );    
+  for(UInt i=0; i <= pcVPS->getMaxLayers()-1; i++)
+  {
+    WRITE_CODE( 0,         4,               "num_types_zero_4bits[i]" );   
+    WRITE_CODE( 0,         4,               "type_zero_4bits[i]"      );   
+    WRITE_CODE( pcVPS->getViewId(i),         8,               "view_id[i]" );    
+    if(i)
+    {
+      WRITE_CODE( pcVPS->getNumDirectRefLayer(i), 6,  "num_direct_ref_layers[ i ]" );    
+      for (UInt j = 0; j< pcVPS->getNumDirectRefLayer(i); j++)
+      {
+        WRITE_CODE( pcVPS->getDirectRefLayerId (i, j), 6,  "ref_layer_id[i][j]" ); 
+      }
+    }
+  }
+  for( UInt i=1; i<=pcVPS->getNumAddiProLevelSets(); i++)
+  {
+    //profile_tier_level
+  }
+  for( UInt i=1; i<= pcVPS->getNumAddiLayerOperationPoints(); i++)
+  {   
+    if(pcVPS->getMaxLayers() == 3)
+    {
+      pcVPS->setNumOpLayerIdMinus1((i < pcVPS->getNumAddiLayerOperationPoints() ? 1: 2), (i-1)); 
+    }
+    else if( i==1 )
+    {
+      assert(pcVPS->getNumAddiLayerOperationPoints()==1);
+      pcVPS->setNumOpLayerIdMinus1(pcVPS->getMaxLayers()-1, (i-1)); 
+    }
+    WRITE_UVLC( pcVPS->getNumOpLayerIdMinus1(i-1),           "op_num_layer_id_values_minus1[ opIdx ]" );
+    for(UInt j = 0; j <= pcVPS->getNumOpLayerIdMinus1(i-1); j++ )
+    {
+      if(pcVPS->getMaxLayers() == 3 && i== 2 && j==1)
+        pcVPS->setNumOpLayerId (2, i-1, j);
+      else
+        pcVPS->setNumOpLayerId (j, i-1, j);
+      WRITE_UVLC( pcVPS->getNumOpLayerId(i-1, j),           "op_layer_id[ opIdx ][ i ]" );
+    }
+    if (pcVPS->getNumAddiProLevelSets())
+    {
+      //profile_level_idx[ i ]
+    }
+  }
+  return;
+}
+#else
+#if VIDYO_VPS_INTEGRATION
+Void TEncCavlc::codeVPS( TComVPS* pcVPS )
+{
+  WRITE_CODE( pcVPS->getMaxTLayers() - 1,     3,        "max_temporal_layers_minus1" );
+  WRITE_CODE( pcVPS->getMaxLayers() - 1,      5,        "max_layers_minus1" );
+  WRITE_FLAG( pcVPS->getTemporalNestingFlag() - 1,      "temporal_id_nesting_flag" );
+  WRITE_UVLC( pcVPS->getVPSId(),                        "video_parameter_set_id" );
+  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
+  {
+    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i),           "max_dec_pic_buffering[i]" );
+    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "num_reorder_pics[i]" );
+    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "max_latency_increase[i]" );
+  }
+  
+  WRITE_CODE( 1,      1,        "bit_equal_to_one" );
+  
+  if( pcVPS->getMaxLayers() - 1 > 0 )
+  {
+    WRITE_UVLC( pcVPS->getExtensionType(),                        "extension_type" );
+    
+    for(UInt i=1; i <= pcVPS->getMaxLayers()-1; i++)
+    {
+      WRITE_FLAG( pcVPS->getDependentFlag(i),                     "dependent_flag[i]" );
+      if( pcVPS->getDependentFlag(i) )
+      {
+        WRITE_UVLC( i - pcVPS->getDependentLayer(i) - 1,          "delta_reference_layer_id_minus1[i]" );
+        if( pcVPS->getExtensionType() == VPS_EXTENSION_TYPE_MULTI_VIEW )
+        {
+          WRITE_UVLC( pcVPS->getViewId(i),                        "view_id[i]" );
+          WRITE_FLAG( pcVPS->getDepthFlag(i),                     "depth_flag[i]" );
+          WRITE_SVLC( pcVPS->getViewOrderIdx(i),                  "view_order_idx[i]" );
+        }
+        
+      }
+    }
+#if INTER_VIEW_VECTOR_SCALING_C0115
+      WRITE_FLAG( pcVPS->getIVScalingFlag(),                      "inter_view_vector_scaling_flag" );
+#endif
+  }
+  
+  WRITE_FLAG( 0,                     "vps_extension_flag" );
+  
+  //future extensions here..
+  
+  return;
+}
+#endif
+#endif
+#if HHI_MPI || H3D_QTL 
+Void TEncCavlc::codeSPS( TComSPS* pcSPS, Bool bIsDepth )
+#else
+Void TEncCavlc::codeSPS( TComSPS* pcSPS )
+#endif
+{
+#if ENC_DEC_TRACE  
+  xTraceSPSHeader (pcSPS);
+#endif
+  WRITE_CODE( pcSPS->getProfileIdc (),     8,       "profile_idc" );
+  WRITE_CODE( 0,                           8,       "reserved_zero_8bits" );
+  WRITE_CODE( pcSPS->getLevelIdc (),       8,       "level_idc" );
+  WRITE_UVLC( pcSPS->getSPSId (),                   "seq_parameter_set_id" );
+#if VIDYO_VPS_INTEGRATION
+  WRITE_UVLC( pcSPS->getVPSId (),                   "video_parameter_set_id" );
+#endif
+  WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
+  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "max_temporal_layers_minus1" );
+  WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
+  WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
+  WRITE_FLAG( pcSPS->getPicCroppingFlag(),          "pic_cropping_flag" );
+  if (pcSPS->getPicCroppingFlag())
+  {
+    WRITE_UVLC( pcSPS->getPicCropLeftOffset(),      "pic_crop_left_offset" );
+    WRITE_UVLC( pcSPS->getPicCropRightOffset(),     "pic_crop_right_offset" );
+    WRITE_UVLC( pcSPS->getPicCropTopOffset(),       "pic_crop_top_offset" );
+    WRITE_UVLC( pcSPS->getPicCropBottomOffset(),    "pic_crop_bottom_offset" );
+  }
+
+#if FULL_NBIT
+  WRITE_UVLC( pcSPS->getBitDepth() - 8,             "bit_depth_luma_minus8" );
+#else
+  WRITE_UVLC( pcSPS->getBitIncrement(),             "bit_depth_luma_minus8" );
+#endif
+#if FULL_NBIT
+  WRITE_UVLC( pcSPS->getBitDepth() - 8,             "bit_depth_chroma_minus8" );
+#else
+  WRITE_UVLC( pcSPS->getBitIncrement(),             "bit_depth_chroma_minus8" );
+#endif
+
+  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                   "pcm_enabled_flag");
+
+  if( pcSPS->getUsePCM() )
+  {
+  WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,   "pcm_bit_depth_luma_minus1" );
+  WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4, "pcm_bit_depth_chroma_minus1" );
+  }
+
+#if LOSSLESS_CODING
+  WRITE_FLAG( (pcSPS->getUseLossless ()) ? 1 : 0,                                    "qpprime_y_zero_transquant_bypass_flag" );
+#endif
+
+  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i),           "max_dec_pic_buffering[i]" );
+    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "num_reorder_pics[i]" );
+    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "max_latency_increase[i]" );
+  }
+  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
+  
+  UInt MinCUSize = pcSPS->getMaxCUWidth() >> ( pcSPS->getMaxCUDepth()-g_uiAddCUDepth );
+  UInt log2MinCUSize = 0;
+  while(MinCUSize > 1)
+  {
+    MinCUSize >>= 1;
+    log2MinCUSize++;
+  }
+
+  WRITE_FLAG( pcSPS->getRestrictedRefPicListsFlag(),                                 "restricted_ref_pic_lists_flag" );
+  if( pcSPS->getRestrictedRefPicListsFlag() )
+  {
+    WRITE_FLAG( pcSPS->getListsModificationPresentFlag(),                            "lists_modification_present_flag" );
+  }
+  WRITE_UVLC( log2MinCUSize - 3,                                                     "log2_min_coding_block_size_minus3" );
+  WRITE_UVLC( pcSPS->getMaxCUDepth()-g_uiAddCUDepth,                                 "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" );
+
+  if(log2MinCUSize == 3)
+  {
+    xWriteFlag  ( (pcSPS->getDisInter4x4()) ? 1 : 0 );
+  }
+
+  if( pcSPS->getUsePCM() )
+  {
+    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_coding_block_size_minus3" );
+    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_coding_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->getUseLMChroma () ? 1 : 0,                                      "chroma_pred_from_luma_enabled_flag" ); 
+  WRITE_FLAG( pcSPS->getUseDF() ? 1 : 0,                                             "deblocking_filter_in_aps_enabled_flag");
+  WRITE_FLAG( pcSPS->getLFCrossSliceBoundaryFlag()?1 : 0,                            "seq_loop_filter_across_slices_enabled_flag");
+  WRITE_FLAG( pcSPS->getUseAMP(),                                                    "asymmetric_motion_partitions_enabled_flag" );
+  WRITE_FLAG( pcSPS->getUseNSQT(),                                                   "non_square_quadtree_enabled_flag" );
+  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
+  WRITE_FLAG( pcSPS->getUseALF () ? 1 : 0,                                           "adaptive_loop_filter_enabled_flag");
+  if(pcSPS->getUseALF())
+  {
+    WRITE_FLAG( (pcSPS->getUseALFCoefInSlice()) ? 1 : 0,                             "alf_coef_in_slice_flag");
+  }
+
+  if( pcSPS->getUsePCM() )
+  {
+  WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                                "pcm_loop_filter_disable_flag");
+  }
+
+  assert( pcSPS->getMaxTLayers() > 0 );         
+
+  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "temporal_id_nesting_flag" );
+
+  TComRPSList* rpsList = pcSPS->getRPSList();
+  TComReferencePictureSet*      rps;
+
+  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);
+  }    
+  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
+  // AMVP mode for each depth
+  for (Int i = 0; i < pcSPS->getMaxCUDepth(); i++)
+  {
+    xWriteFlag( pcSPS->getAMVPMode(i) ? 1 : 0);
+  }
+
+  Int tilesOrEntropyCodingSyncIdc = 0;
+  if ( pcSPS->getNumColumnsMinus1() > 0 || pcSPS->getNumRowsMinus1() > 0)
+  {
+    tilesOrEntropyCodingSyncIdc = 1;
+  }
+  else if ( pcSPS->getNumSubstreams() > 1 )
+  {
+    tilesOrEntropyCodingSyncIdc = 2;
+  }
+  pcSPS->setTilesOrEntropyCodingSyncIdc( tilesOrEntropyCodingSyncIdc );
+  WRITE_CODE(tilesOrEntropyCodingSyncIdc, 2, "tiles_or_entropy_coding_sync_idc");
+
+  if(tilesOrEntropyCodingSyncIdc == 1)
+  {
+    WRITE_UVLC( pcSPS->getNumColumnsMinus1(),                           "num_tile_columns_minus1" );
+    WRITE_UVLC( pcSPS->getNumRowsMinus1(),                              "num_tile_rows_minus1" );
+    WRITE_FLAG( pcSPS->getUniformSpacingIdr(),                          "uniform_spacing_flag" );
+
+    if( pcSPS->getUniformSpacingIdr()==0 )
+    {
+      for(UInt i=0; i<pcSPS->getNumColumnsMinus1(); i++)
+      {
+        WRITE_UVLC( pcSPS->getColumnWidth(i),                           "column_width" );
+      }
+      for(UInt i=0; i<pcSPS->getNumRowsMinus1(); i++)
+      {
+        WRITE_UVLC( pcSPS->getRowHeight(i),                             "row_height" );
+      }
+    }
+
+    if( pcSPS->getNumColumnsMinus1() !=0 || pcSPS->getNumRowsMinus1() != 0)
+    {
+        WRITE_FLAG( pcSPS->getLFCrossTileBoundaryFlag()?1 : 0,            "loop_filter_across_tile_flag");
+    }
+  }
+  WRITE_FLAG( 1, "sps_extension_flag" );
+#if !QC_MVHEVC_B0046
+  WRITE_FLAG( (pcSPS->getNumberOfUsableInterViewRefs() > 0) ? 1 : 0, "interview_refs_present_flag" );
+  if( pcSPS->getNumberOfUsableInterViewRefs() > 0 )
+  {
+    WRITE_UVLC( pcSPS->getNumberOfUsableInterViewRefs() - 1,   "num_usable_interview_refs_minus1" );
+
+    Int prev = 0;
+    for( Int j = 0 ; j < pcSPS->getNumberOfUsableInterViewRefs(); j++ )
+    {
+      WRITE_UVLC( prev - pcSPS->getUsableInterViewRef( j ) - 1, "delta_usable_interview_ref_minus1" );
+      prev = pcSPS->getUsableInterViewRef( j );
+    }
+  }
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  WRITE_FLAG( pcSPS->getUseDMM(), "enable_dmm_flag" );
+#endif
+
+#if HHI_MPI
+  if( bIsDepth )
+  {
+    WRITE_FLAG( pcSPS->getUseMVI() ? 1 : 0, "use_mvi_flag" );
+  }
+#endif
+
+#if H3D_QTL
+  if( bIsDepth )
+  {
+    WRITE_FLAG( pcSPS->getUseQTLPC() ? 1 : 0, "use_qtlpc_flag");
+  }
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  if( bIsDepth )
+  {
+    WRITE_FLAG( pcSPS->getUseDLT() ? 1 : 0, "use_dlt_flag" );
+    if( pcSPS->getUseDLT() )
+    {
+      // code mapping
+      xWriteUvlc  ( pcSPS->getNumDepthValues() );
+      for(UInt i=0; i<pcSPS->getNumDepthValues(); i++)
+      {
+        xWriteUvlc( pcSPS->idx2DepthValue(i) );
+      }
+    }
+  }
+#endif
+
+  if( pcSPS->getViewId() || pcSPS->isDepth() )
+  {
+    WRITE_FLAG( 0, "base_view_flag" ); 
+    if( pcSPS->isDepth() )
+    {
+      WRITE_FLAG( 1, "depth_flag" ); 
+      WRITE_UVLC( pcSPS->getViewId(), "view_id" );
+      WRITE_SVLC( pcSPS->getViewOrderIdx(), "view_order_idx" );
+#if FCO_FIX_SPS_CHANGE
+      if ( pcSPS->getViewId() )
+      {
+        WRITE_UVLC( pcSPS->getCamParPrecision(), "camera_parameter_precision" );
+        WRITE_FLAG( pcSPS->hasCamParInSliceHeader() ? 1 : 0, "camera_parameter_in_slice_header" );
+        if( !pcSPS->hasCamParInSliceHeader() )
+        {
+          for( UInt uiId = 0; uiId < pcSPS->getViewId(); uiId++ )
+          {
+            WRITE_SVLC( pcSPS->getCodedScale    ()[ uiId ], "coded_scale" );
+            WRITE_SVLC( pcSPS->getCodedOffset   ()[ uiId ], "coded_offset" );
+            WRITE_SVLC( pcSPS->getInvCodedScale ()[ uiId ] + pcSPS->getCodedScale ()[ uiId ], "inverse_coded_scale_plus_coded_scale" );
+            WRITE_SVLC( pcSPS->getInvCodedOffset()[ uiId ] + pcSPS->getCodedOffset()[ uiId ], "inverse_coded_offset_plus_coded_offset" );
+          }
+        }      
+      }
+#endif
+    }
+    else
+    {
+      WRITE_FLAG( 0, "depth_flag" ); 
+      WRITE_UVLC( pcSPS->getViewId() - 1, "view_id_minus1" );
+      WRITE_SVLC( pcSPS->getViewOrderIdx(), "view_order_idx" );
+      WRITE_UVLC( pcSPS->getCamParPrecision(), "camera_parameter_precision" );
+      WRITE_FLAG( pcSPS->hasCamParInSliceHeader() ? 1 : 0, "camera_parameter_in_slice_header" );
+      if( !pcSPS->hasCamParInSliceHeader() )
+      {
+        for( UInt uiId = 0; uiId < pcSPS->getViewId(); uiId++ )
+        {
+          WRITE_SVLC( pcSPS->getCodedScale    ()[ uiId ], "coded_scale" );
+          WRITE_SVLC( pcSPS->getCodedOffset   ()[ uiId ], "coded_offset" );
+          WRITE_SVLC( pcSPS->getInvCodedScale ()[ uiId ] + pcSPS->getCodedScale ()[ uiId ], "inverse_coded_scale_plus_coded_scale" );
+          WRITE_SVLC( pcSPS->getInvCodedOffset()[ uiId ] + pcSPS->getCodedOffset()[ uiId ], "inverse_coded_offset_plus_coded_offset" );
+        }
+      }
+#if DEPTH_MAP_GENERATION
+      WRITE_UVLC( pcSPS->getPredDepthMapGeneration(), "Pdm_generation" );
+      if( pcSPS->getPredDepthMapGeneration() )
+      {
+        WRITE_UVLC( pcSPS->getPdmPrecision(), "Pdm_precision" );
+        for( UInt uiId = 0; uiId < pcSPS->getViewId(); uiId++ )
+        {
+          WRITE_SVLC( pcSPS->getPdmScaleNomDelta()[ uiId ], "Pdm_scale_nom_delta" );
+          WRITE_SVLC( pcSPS->getPdmOffset       ()[ uiId ], "Pdm_offset" );
+        }
+#if H3D_IVMP
+        WRITE_UVLC( pcSPS->getMultiviewMvPredMode(), "multi_view_mv_pred_mode" );
+#endif
+#if H3D_IVRP
+        WRITE_FLAG  ( pcSPS->getMultiviewResPredMode(), "multi_view_residual_pred_mode" );
+#endif
+      }
+#endif
+    }
+  }
+  else
+  {
+    WRITE_FLAG( 1, "base_view_flag" );   
+  }
+  WRITE_FLAG( 0, "sps_extension2_flag" );
+#endif
+}
+
+Void TEncCavlc::writeTileMarker( UInt uiTileIdx, UInt uiBitsUsed )
+{
+  xWriteCode( uiTileIdx, uiBitsUsed );
+}
+
+Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
+{
+#if ENC_DEC_TRACE  
+  xTraceSliceHeader (pcSlice);
+#endif
+
+  // if( nal_ref_idc != 0 )
+  //   dec_ref_pic_marking( )
+  // if( entropy_coding_mode_flag  &&  slice_type  !=  I)
+  //   cabac_init_idc
+  // first_slice_in_pic_flag
+  // if( first_slice_in_pic_flag == 0 )
+  //    slice_address
+  //calculate number of bits required for slice address
+  Int maxAddrOuter = pcSlice->getPic()->getNumCUsInFrame();
+  Int reqBitsOuter = 0;
+  while(maxAddrOuter>(1<<reqBitsOuter)) 
+  {
+    reqBitsOuter++;
+  }
+  Int maxAddrInner = pcSlice->getPic()->getNumPartInCU()>>(2);
+  maxAddrInner = (1<<(pcSlice->getPPS()->getSliceGranularity()<<1));
+  Int reqBitsInner = 0;
+  
+  while(maxAddrInner>(1<<reqBitsInner))
+  {
+    reqBitsInner++;
+  }
+  Int lCUAddress;
+  Int innerAddress;
+  if (pcSlice->isNextSlice())
+  {
+    // Calculate slice address
+    lCUAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
+    innerAddress = (pcSlice->getSliceCurStartCUAddr()%(pcSlice->getPic()->getNumPartInCU()))>>((pcSlice->getSPS()->getMaxCUDepth()-pcSlice->getPPS()->getSliceGranularity())<<1);
+  }
+  else
+  {
+    // Calculate slice address
+    lCUAddress = (pcSlice->getEntropySliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
+    innerAddress = (pcSlice->getEntropySliceCurStartCUAddr()%(pcSlice->getPic()->getNumPartInCU()))>>((pcSlice->getSPS()->getMaxCUDepth()-pcSlice->getPPS()->getSliceGranularity())<<1);
+    
+  }
+  //write slice address
+  Int address = (pcSlice->getPic()->getPicSym()->getCUOrderMap(lCUAddress) << reqBitsInner) + innerAddress;
+  WRITE_FLAG( address==0, "first_slice_in_pic_flag" );
+
+#if LGE_ILLUCOMP_B0045
+  // IC flag is on only first_slice_in_pic
+  if (address==0)
+  {
+    if( pcSlice->getSPS()->getViewId() 
+#if !LGE_ILLUCOMP_DEPTH_C0046
+        && !pcSlice->getIsDepth()
+#endif
+        )
+    {
+      WRITE_FLAG( pcSlice->getApplyIC() ? 1 : 0, "applying IC flag" );
+    }
+  }
+#endif
+
+  if(address>0) 
+  {
+    WRITE_CODE( address, reqBitsOuter+reqBitsInner, "slice_address" );
+  }
+
+  WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
+  Bool bEntropySlice = (!pcSlice->isNextSlice());
+  WRITE_FLAG( bEntropySlice ? 1 : 0, "lightweight_slice_flag" );
+  
+  if (!bEntropySlice)
+  {
+#if QC_MVHEVC_B0046
+    WRITE_UVLC( 0, "pic_parameter_set_id" );
+#else
+    WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "pic_parameter_set_id" );
+#endif
+    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
+    {
+      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
+    }
+#if QC_REM_IDV_B0046
+    if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_IDR && pcSlice->getViewId() == 0) 
+#else
+    if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_IDR) 
+#endif
+    {
+      WRITE_UVLC( 0, "idr_pic_id" );
+      WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
+    }
+    else
+    {
+      WRITE_CODE( (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC()), pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
+#if QC_REM_IDV_B0046
+      if( pcSlice->getPOC() == 0 && !(pcSlice->getSPS()->getViewId() && (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)))
+#else
+      if( pcSlice->getPOC() == 0 && pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_IDV )
+#endif
+      {
+        TComReferencePictureSet* rps = pcSlice->getRPS();
+        if(pcSlice->getRPSidx() < 0)
+        {
+          WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
+          codeShortTermRefPicSet(pcSlice->getSPS(), rps);
+        }
+        else
+        {
+          WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
+          WRITE_UVLC( pcSlice->getRPSidx(), "short_term_ref_pic_set_idx" );
+        }
+        if(pcSlice->getSPS()->getLongTermRefsPresent())
+        {
+          WRITE_UVLC( rps->getNumberOfLongtermPictures(), "num_long_term_pics");
+          Int maxPocLsb = 1<<pcSlice->getSPS()->getBitsForPOC();
+          Int prev = 0;
+          Int prevDeltaPocLt=0;
+          Int currDeltaPocLt=0;
+          for(Int i=rps->getNumberOfPictures()-1 ; i > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; i--)
+          {
+            WRITE_UVLC((maxPocLsb-rps->getDeltaPOC(i)+prev)%maxPocLsb, "delta_poc_lsb_lt");
+          
+            currDeltaPocLt=((maxPocLsb-rps->getDeltaPOC(i)+prev)%maxPocLsb)+prevDeltaPocLt;
+
+            Int deltaMsbCycle=0;
+            if( (i==(rps->getNumberOfPictures()-1)) )
+            {
+              deltaMsbCycle=((-rps->getDeltaPOC(i))/maxPocLsb)-1;
+            }
+            else if( prevDeltaPocLt!=currDeltaPocLt )
+            {
+              deltaMsbCycle=((-rps->getDeltaPOC(i))/maxPocLsb)-1;
+              if( ((prevDeltaPocLt==maxPocLsb-1) && (currDeltaPocLt==maxPocLsb+1)) ||  ((prevDeltaPocLt==maxPocLsb-2) && (currDeltaPocLt==maxPocLsb)))
+              {
+                deltaMsbCycle=deltaMsbCycle-1;
+              }
+            }
+            else
+            {
+              deltaMsbCycle=((rps->getDeltaPOC(i+1)-rps->getDeltaPOC(i))/maxPocLsb)-1;
+            }
+
+            if(deltaMsbCycle>=0)
+            {
+              WRITE_FLAG( 1, "delta_poc_msb_present_flag");
+              WRITE_UVLC(deltaMsbCycle, "delta_poc_msb_cycle_lt_minus1");
+            }
+            else
+            {
+              WRITE_FLAG( 0, "delta_poc_msb_present_flag");
+            }
+            prevDeltaPocLt=currDeltaPocLt;
+            prev = rps->getDeltaPOC(i);
+            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
+          }
+        }
+      }
+      if( pcSlice->getPOC() != 0 )
+      {
+        TComReferencePictureSet* rps = pcSlice->getRPS();
+        if(pcSlice->getRPSidx() < 0)
+        {
+          WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
+          codeShortTermRefPicSet(pcSlice->getSPS(), rps);
+        }
+        else
+        {
+          WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
+          WRITE_UVLC( pcSlice->getRPSidx(), "short_term_ref_pic_set_idx" );
+        }
+        if(pcSlice->getSPS()->getLongTermRefsPresent())
+        {
+          WRITE_UVLC( rps->getNumberOfLongtermPictures(), "num_long_term_pics");
+          Int maxPocLsb = 1<<pcSlice->getSPS()->getBitsForPOC();
+          Int prev = 0;
+          Int prevDeltaPocLt=0;
+          Int currDeltaPocLt=0;
+          for(Int i=rps->getNumberOfPictures()-1 ; i > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; i--)
+          {
+            WRITE_UVLC((maxPocLsb-rps->getDeltaPOC(i)+prev)%maxPocLsb, "delta_poc_lsb_lt");
+          
+            currDeltaPocLt=((maxPocLsb-rps->getDeltaPOC(i)+prev)%maxPocLsb)+prevDeltaPocLt;
+
+            Int deltaMsbCycle=0;
+            if( (i==(rps->getNumberOfPictures()-1)) )
+            {
+              deltaMsbCycle=((-rps->getDeltaPOC(i))/maxPocLsb)-1;
+            }
+            else if( prevDeltaPocLt!=currDeltaPocLt )
+            {
+              deltaMsbCycle=((-rps->getDeltaPOC(i))/maxPocLsb)-1;
+              if( ((prevDeltaPocLt==maxPocLsb-1) && (currDeltaPocLt==maxPocLsb+1)) ||  ((prevDeltaPocLt==maxPocLsb-2) && (currDeltaPocLt==maxPocLsb)))
+              {
+                deltaMsbCycle=deltaMsbCycle-1;
+              }
+            }
+            else
+            {
+              deltaMsbCycle=((rps->getDeltaPOC(i+1)-rps->getDeltaPOC(i))/maxPocLsb)-1;
+            }
+
+            if(deltaMsbCycle>=0)
+            {
+              WRITE_FLAG( 1, "delta_poc_msb_present_flag");
+              WRITE_UVLC(deltaMsbCycle, "delta_poc_msb_cycle_lt_minus1");
+            }
+            else
+            {
+              WRITE_FLAG( 0, "delta_poc_msb_present_flag");
+            }
+            prevDeltaPocLt=currDeltaPocLt;
+            prev = rps->getDeltaPOC(i);
+            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
+          }
+        }
+      }
+    }
+
+    if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF()|| pcSlice->getSPS()->getScalingListFlag() || pcSlice->getSPS()->getUseDF())
+    {
+      if (pcSlice->getSPS()->getUseALF())
+      {
+         WRITE_FLAG( pcSlice->getAlfEnabledFlag(), "ALF on/off flag in slice header" );
+      }
+      if (pcSlice->getSPS()->getUseSAO())
+      {
+        WRITE_FLAG( pcSlice->getSaoInterleavingFlag(), "SAO interleaving flag" );
+         assert (pcSlice->getSaoEnabledFlag() == pcSlice->getAPS()->getSaoEnabled());
+         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "SAO on/off flag in slice header" );
+         if (pcSlice->getSaoInterleavingFlag()&&pcSlice->getSaoEnabledFlag() )
+         {
+           WRITE_FLAG( pcSlice->getAPS()->getSaoParam()->bSaoFlag[1], "SAO on/off flag for Cb in slice header" );
+           WRITE_FLAG( pcSlice->getAPS()->getSaoParam()->bSaoFlag[2], "SAO on/off flag for Cr in slice header" );
+         }
+      }
+      WRITE_UVLC( pcSlice->getAPS()->getAPSID(), "aps_id");
+    }
+
+    // we always set num_ref_idx_active_override_flag equal to one. this might be done in a more intelligent way 
+    if (!pcSlice->isIntra())
+    {
+      WRITE_FLAG( 1 ,                                             "num_ref_idx_active_override_flag");
+      WRITE_CODE( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1, 3, "num_ref_idx_l0_active_minus1" );
+    }
+    else
+    {
+      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
+    }
+    if (pcSlice->isInterB())
+    {
+      WRITE_CODE( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1, 3, "num_ref_idx_l1_active_minus1" );
+    }
+    else
+    {
+      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+    }
+    if( pcSlice->getSPS()->getListsModificationPresentFlag() )
+    {
+    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+    if( !pcSlice->isIntra() )
+    {
+      WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
+      if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
+      {
+        Int NumPocTotalCurr = pcSlice->getNumPocTotalCurrMvc();
+        if (NumPocTotalCurr > 1)
+        {
+          Int length = 1;
+          NumPocTotalCurr --;
+          while ( NumPocTotalCurr >>= 1) 
+          {
+            length ++;
+          }
+          for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
+          {
+            WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
+          }
+        }
+      }
+    }
+    if(pcSlice->isInterB())
+    {    
+      WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
+      if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
+      {
+        Int NumPocTotalCurr = pcSlice->getNumPocTotalCurrMvc();
+        if ( NumPocTotalCurr > 1 )
+        {
+          Int length = 1;
+          NumPocTotalCurr --;
+          while ( NumPocTotalCurr >>= 1)
+          {
+            length ++;
+          }
+          for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
+          {
+            WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
+          }
+        }
+      }
+    }
+    }
+  }
+  // ref_pic_list_combination( )
+  // maybe move to own function?
+  if (pcSlice->isInterB())
+  {
+    WRITE_FLAG(pcSlice->getRefPicListCombinationFlag() ? 1 : 0,       "ref_pic_list_combination_flag" );
+    if(pcSlice->getRefPicListCombinationFlag())
+    {
+      WRITE_UVLC( pcSlice->getNumRefIdx(REF_PIC_LIST_C) - 1,          "num_ref_idx lc_active_minus1");
+      
+      if( pcSlice->getSPS()->getListsModificationPresentFlag() )
+      {
+        WRITE_FLAG( pcSlice->getRefPicListModificationFlagLC() ? 1 : 0, "ref_pic_list_modification_flag_lc" );
+        if(pcSlice->getRefPicListModificationFlagLC())
+        {
+          for (UInt i=0;i<pcSlice->getNumRefIdx(REF_PIC_LIST_C);i++)
+          {
+            WRITE_FLAG( pcSlice->getListIdFromIdxOfLC(i),               "pic_from_list_0_flag" );
+          if (((pcSlice->getListIdFromIdxOfLC(i)==REF_PIC_LIST_0) && pcSlice->getNumRefIdx( REF_PIC_LIST_0 )>1 ) || ((pcSlice->getListIdFromIdxOfLC(i)==REF_PIC_LIST_1) && pcSlice->getNumRefIdx( REF_PIC_LIST_1 )>1 ) )
+          {
+            WRITE_UVLC( pcSlice->getRefIdxFromIdxOfLC(i),               "ref_idx_list_curr" );
+          }
+          }
+        }
+      }
+    }
+  }
+    
+  if (pcSlice->isInterB())
+  {
+    WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
+  }
+
+  if(pcSlice->getPPS()->getEntropyCodingMode() && !pcSlice->isIntra())
+  {
+#if CABAC_INIT_FLAG
+    if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
+    {
+      SliceType sliceType   = pcSlice->getSliceType();
+      Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
+      Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=0) ? true : false;
+      pcSlice->setCabacInitFlag( encCabacInitFlag );
+      WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
+    }
+#else
+    WRITE_UVLC(pcSlice->getCABACinitIDC(),  "cabac_init_idc");
+#endif
+  }
+
+  // if( !lightweight_slice_flag ) {
+  if (!bEntropySlice)
+  {
+    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
+    WRITE_SVLC( iCode, "slice_qp_delta" ); 
+    if (pcSlice->getPPS()->getDeblockingFilterControlPresent())
+    {
+      if ( pcSlice->getSPS()->getUseDF() )
+      {
+        WRITE_FLAG(pcSlice->getInheritDblParamFromAPS(), "inherit_dbl_param_from_APS_flag");
+      }
+      if (!pcSlice->getInheritDblParamFromAPS())
+      {
+        WRITE_FLAG(pcSlice->getLoopFilterDisable(), "loop_filter_disable");  // should be an IDC
+        if(!pcSlice->getLoopFilterDisable())
+        {
+          WRITE_SVLC (pcSlice->getLoopFilterBetaOffset(), "beta_offset_div2");
+          WRITE_SVLC (pcSlice->getLoopFilterTcOffset(), "tc_offset_div2");
+        }
+      }
+    }
+    if ( pcSlice->getSliceType() == B_SLICE )
+    {
+      WRITE_FLAG( pcSlice->getColDir(), "collocated_from_l0_flag" );
+    }
+
+#if COLLOCATED_REF_IDX
+    if ( pcSlice->getSliceType() != I_SLICE &&
+      ((pcSlice->getColDir()==0 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
+      (pcSlice->getColDir()==1  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
+    {
+      WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
+    }
+#endif
+
+#if FIX_LGE_WP_FOR_3D_C0223
+    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPredIdc() && pcSlice->getSliceType()==B_SLICE) )
+#else
+    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPredIdc()==1 && pcSlice->getSliceType()==B_SLICE) )
+#endif    
+    {
+      xCodePredWeightTable( pcSlice );
+    }
+  }
+
+  // !!!! sytnax elements not in the WD !!!!
+  if (!bEntropySlice)
+  {
+    if( pcSlice->getSPS()->hasCamParInSliceHeader() )
+    {
+      for( UInt uiId = 0; uiId < pcSlice->getSPS()->getViewId(); uiId++ )
+      {
+        WRITE_SVLC( pcSlice->getCodedScale    ()[ uiId ], "coded_scale" );
+        WRITE_SVLC( pcSlice->getCodedOffset   ()[ uiId ], "coded_offset" );
+        WRITE_SVLC( pcSlice->getInvCodedScale ()[ uiId ] + pcSlice->getCodedScale ()[ uiId ], "inverse_coded_scale_plus_coded_scale" );
+        WRITE_SVLC( pcSlice->getInvCodedOffset()[ uiId ] + pcSlice->getCodedOffset()[ uiId ], "inverse_coded_offset_plus_coded_offset" );
+      }
+    }
+  }
+  
+#if ( HHI_MPI || H3D_IVMP )
+  #if ( HHI_MPI && H3D_IVMP )
+  const int iExtraMergeCandidates = ( pcSlice->getSPS()->getUseMVI() || pcSlice->getSPS()->getMultiviewMvPredMode() ) ? 1 : 0;
+  #elif HHI_MPI
+  const int iExtraMergeCandidates = pcSlice->getSPS()->getUseMVI() ? 1 : 0;
+  #elif MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  const int iExtraMergeCandidates = ( pcSlice->getIsDepth() || pcSlice->getSPS()->getMultiviewMvPredMode() ) ? 1 : 0;
+  #else
+  const int iExtraMergeCandidates = pcSlice->getSPS()->getMultiviewMvPredMode() ? 1 : 0;
+  #endif
+  assert(pcSlice->getMaxNumMergeCand()<=(MRG_MAX_NUM_CANDS_SIGNALED+iExtraMergeCandidates));
+  assert(MRG_MAX_NUM_CANDS_SIGNALED<=MRG_MAX_NUM_CANDS);
+  WRITE_UVLC(MRG_MAX_NUM_CANDS + iExtraMergeCandidates - pcSlice->getMaxNumMergeCand(), "maxNumMergeCand");
+#else
+  assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS_SIGNALED);
+  assert(MRG_MAX_NUM_CANDS_SIGNALED<=MRG_MAX_NUM_CANDS);
+  WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "maxNumMergeCand");
+#endif
+}
+
+
+Void TEncCavlc::codeTileMarkerFlag(TComSlice* pcSlice) 
+{
+  Bool bEntropySlice = (!pcSlice->isNextSlice());
+  if (!bEntropySlice)
+  {
+    xWriteFlag  (pcSlice->getTileMarkerFlag() ? 1 : 0 );
+  }
+}
+
+/**
+ - write wavefront substreams sizes for the slice header.
+ .
+ \param pcSlice Where we find the substream size information.
+ */
+Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  Int tilesOrEntropyCodingSyncIdc = pSlice->getSPS()->getTilesOrEntropyCodingSyncIdc();
+
+  if ( tilesOrEntropyCodingSyncIdc == 0 )
+  {
+    return;
+  }
+
+  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
+  UInt *entryPointOffset = NULL;
+  if (tilesOrEntropyCodingSyncIdc == 1) // tiles
+  {
+    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 (tilesOrEntropyCodingSyncIdc == 2) // wavefront
+  {
+    Int  numZeroSubstreamsAtEndOfSlice  = 0;
+    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
+    // Find number of zero substreams at the end of slice
+    for (Int idx=pSlice->getPPS()->getNumSubstreams()-2; idx>=0; idx--)
+    {
+      if ( pSubstreamSizes[ idx ] ==  0 )
+      {
+        numZeroSubstreamsAtEndOfSlice++; 
+      }
+      else
+      {
+        break;
+      }
+    }
+    numEntryPointOffsets       = pSlice->getPPS()->getNumSubstreams() - 1 - numZeroSubstreamsAtEndOfSlice;
+    entryPointOffset           = new UInt[numEntryPointOffsets];
+    for (Int idx=0; idx<numEntryPointOffsets; idx++)
+    {
+      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx ] >> 3 ) ;
+      if ( entryPointOffset[ idx ] > maxOffset )
+      {
+        maxOffset = entryPointOffset[ idx ];
+      }
+    }
+  }
+
+  maxOffset += ((m_pcBitIf->getNumberOfWrittenBits() + 16) >> 3) + 8 + 2; // allowing for NALU header, slice header, bytes added for "offset_len_minus1" and "num_entry_point_offsets"
+
+  // Determine number of bits "offsetLenMinus1+1" required for entry point information
+  offsetLenMinus1 = 0;
+  while (1)
+  {
+    if (maxOffset >= (1 << offsetLenMinus1) )
+    {
+      offsetLenMinus1++;
+      if ( offsetLenMinus1 > 32 )
+      {
+        FATAL_ERROR_0("exceeded 32-bits", -1);
+      }
+    }
+    else
+    {
+      break;
+    }
+  }
+
+  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
+  if (numEntryPointOffsets>0)
+  {
+    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
+  }
+
+  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+  {
+    if ( idx == 0 )
+    {
+      // Adding sizes of NALU header and slice header information to entryPointOffset[ 0 ]
+      Int bitDistFromNALUHdrStart    = m_pcBitIf->getNumberOfWrittenBits() + 16;
+      entryPointOffset[ idx ] += ( bitDistFromNALUHdrStart + numEntryPointOffsets*(offsetLenMinus1+1) ) >> 3;
+    }
+    WRITE_CODE(entryPointOffset[ idx ], offsetLenMinus1+1, "entry_point_offset");
+  }
+
+  delete [] entryPointOffset;
+}
+
+Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
+{
+}
+
+Void TEncCavlc::codeSliceFinish ()
+{
+}
+
+#if H3D_IVMP
+Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Int iNum )
+#else
+Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+#endif
+{
+  assert(0);
+}
+
+Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+#if H3D_IVRP
+Void
+TEncCavlc::codeResPredFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#endif
+
+Void TEncCavlc::codeAlfCtrlFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{  
+  if (!m_bAlfCtrl)
+  {
+    return;
+  }
+  
+  if( pcCU->getDepth(uiAbsPartIdx) > m_uiMaxAlfCtrlDepth && !pcCU->isFirstAbsZorderIdxInDepth(uiAbsPartIdx, m_uiMaxAlfCtrlDepth))
+  {
+    return;
+  }
+  
+  // get context function is here
+  UInt uiSymbol = pcCU->getAlfCtrlFlag( uiAbsPartIdx ) ? 1 : 0;
+  
+  xWriteFlag( uiSymbol );
+}
+
+Void TEncCavlc::codeApsExtensionFlag ()
+{
+  WRITE_FLAG(0, "aps_extension_flag");
+}
+
+Void TEncCavlc::codeAlfCtrlDepth()
+{  
+  if (!m_bAlfCtrl)
+  {
+    return;
+  }
+  
+  UInt uiDepth = m_uiMaxAlfCtrlDepth;
+  
+  xWriteUvlc(uiDepth);
+}
+
+Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+#if LGE_ILLUCOMP_B0045
+Void TEncCavlc::codeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#endif
+
+Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+/** Code I_PCM information. 
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param numIPCM the number of succesive IPCM blocks with the same size 
+ * \param firstIPCMFlag 
+ * \returns Void
+ */
+Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag)
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
+
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  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 )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeAlfFlag( UInt uiCode )
+{  
+  xWriteFlag( uiCode );
+}
+
+Void TEncCavlc::codeAlfCtrlFlag( UInt uiSymbol )
+{
+  xWriteFlag( uiSymbol );
+}
+
+Void TEncCavlc::codeAlfUvlc( UInt uiCode )
+{
+  xWriteUvlc( uiCode );
+}
+
+Void TEncCavlc::codeAlfSvlc( Int iCode )
+{
+  xWriteSvlc( iCode );
+}
+/** Code the fixed length code (smaller than one max value) in OSALF
+ * \param idx:  coded value 
+ * \param maxValue: max value
+ */
+Void TEncCavlc::codeAlfFixedLengthIdx( UInt idx, UInt maxValue)
+{
+  UInt length = 0;
+  assert(idx<=maxValue);
+
+  UInt temp = maxValue;
+  for(UInt i=0; i<32; i++)
+  {
+    if(temp&0x1)
+    {
+      length = i+1;
+    }
+    temp = (temp >> 1);
+  }
+
+  if(length)
+  {
+    xWriteCode( idx, length );
+  }
+}
+
+Void TEncCavlc::codeSaoFlag( UInt uiCode )
+{
+  xWriteFlag( uiCode );
+}
+
+Void TEncCavlc::codeSaoUvlc( UInt uiCode )
+{
+    xWriteUvlc( uiCode );
+}
+
+Void TEncCavlc::codeSaoSvlc( Int iCode )
+{
+    xWriteSvlc( iCode );
+}
+/** Code SAO run. 
+ * \param uiCode
+ * \param maxValue
+ */
+Void TEncCavlc::codeSaoRun( UInt uiCode, UInt maxValue)
+{
+  UInt uiLength = 0;
+  if (!maxValue)
+  {
+    return;
+  }
+  assert(uiCode<=maxValue);              
+
+  for(UInt i=0; i<32; i++)                                     
+  {                                                            
+    if(maxValue&0x1)                                               
+    {                                                          
+      uiLength = i+1;                                          
+    }                                                          
+    maxValue = (maxValue >> 1);                                        
+  }
+  WRITE_CODE( uiCode, uiLength, "sao_run_diff");
+}
+
+Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
+{
+  // printf("error : no VLC mode support in this version\n");
+  return;
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TEncCavlc::xWriteCode     ( UInt uiCode, UInt uiLength )
+{
+  assert ( uiLength > 0 );
+  m_pcBitIf->write( uiCode, uiLength );
+}
+
+Void TEncCavlc::xWriteUvlc     ( UInt uiCode )
+{
+  UInt uiLength = 1;
+  UInt uiTemp = ++uiCode;
+  
+  assert ( uiTemp );
+  
+  while( 1 != uiTemp )
+  {
+    uiTemp >>= 1;
+    uiLength += 2;
+  }
+  
+  //m_pcBitIf->write( uiCode, uiLength );
+  // Take care of cases where uiLength > 32
+  m_pcBitIf->write( 0, uiLength >> 1);
+  m_pcBitIf->write( uiCode, (uiLength+1) >> 1);
+}
+
+Void TEncCavlc::xWriteSvlc     ( Int iCode )
+{
+  UInt uiCode;
+  
+  uiCode = xConvertToUInt( iCode );
+  xWriteUvlc( uiCode );
+}
+
+Void TEncCavlc::xWriteFlag( UInt uiCode )
+{
+  m_pcBitIf->write( uiCode, 1 );
+}
+
+/** Write PCM alignment bits. 
+ * \returns Void
+ */
+Void  TEncCavlc::xWritePCMAlignZero    ()
+{
+  m_pcBitIf->writeAlignZero();
+}
+
+Void TEncCavlc::xWriteUnaryMaxSymbol( UInt uiSymbol, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    return;
+  }
+  xWriteFlag( uiSymbol ? 1 : 0 );
+  if ( uiSymbol == 0 )
+  {
+    return;
+  }
+  
+  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
+  
+  while( --uiSymbol )
+  {
+    xWriteFlag( 1 );
+  }
+  if( bCodeLast )
+  {
+    xWriteFlag( 0 );
+  }
+  return;
+}
+
+Void TEncCavlc::xWriteExGolombLevel( UInt uiSymbol )
+{
+  if( uiSymbol )
+  {
+    xWriteFlag( 1 );
+    UInt uiCount = 0;
+    Bool bNoExGo = (uiSymbol < 13);
+    
+    while( --uiSymbol && ++uiCount < 13 )
+    {
+      xWriteFlag( 1 );
+    }
+    if( bNoExGo )
+    {
+      xWriteFlag( 0 );
+    }
+    else
+    {
+      xWriteEpExGolomb( uiSymbol, 0 );
+    }
+  }
+  else
+  {
+    xWriteFlag( 0 );
+  }
+  return;
+}
+
+Void TEncCavlc::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
+{
+  while( uiSymbol >= (UInt)(1<<uiCount) )
+  {
+    xWriteFlag( 1 );
+    uiSymbol -= 1<<uiCount;
+    uiCount  ++;
+  }
+  xWriteFlag( 0 );
+  while( uiCount-- )
+  {
+    xWriteFlag( (uiSymbol>>uiCount) & 1 );
+  }
+  return;
+}
+
+/** code explicit wp tables
+ * \param TComSlice* pcSlice
+ * \returns Void
+ */
+Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
+{
+  wpScalingParam  *wp;
+  Bool            bChroma     = true; // color always present in HEVC ?
+  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
+  Bool            bDenomCoded  = false;
+
+  UInt            uiMode = 0;
+  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPredIdc()==1 && pcSlice->getRefPicListCombinationFlag()==0 ) )
+    uiMode = 1; // explicit
+  else if ( pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPredIdc()==2 )
+    uiMode = 2; // implicit (does not use this mode in this syntax)
+  if (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPredIdc()==1 && pcSlice->getRefPicListCombinationFlag())
+    uiMode = 3; // combined explicit
+  if(uiMode == 1)
+  {
+    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
+    {
+      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+        if ( !bDenomCoded ) 
+        {
+          Int iDeltaDenom;
+          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): 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
+          }
+          bDenomCoded = true;
+        }
+
+        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
+
+        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 ) 
+        {
+          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
+
+          if ( wp[1].bPresentFlag )
+          {
+            for ( Int j=1 ; j<3 ; j++ ) 
+            {
+              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
+              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
+
+              Int iDeltaChroma = (wp[j].iOffset + ( ( (g_uiIBDI_MAX>>1)*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) - (g_uiIBDI_MAX>>1));
+              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
+            }
+          }
+        }
+      }
+    }
+  }
+  else if (uiMode == 3)
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(REF_PIC_LIST_C) ; iRefIdx++ ) 
+    {
+      RefPicList  eRefPicList = (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIdx);
+      Int iCombRefIdx = pcSlice->getRefIdxFromIdxOfLC(iRefIdx);
+
+      pcSlice->getWpScaling(eRefPicList, iCombRefIdx, wp);
+      if ( !bDenomCoded ) 
+      {
+        Int iDeltaDenom;
+        WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );       // ue(v): 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
+        }
+        bDenomCoded = true;
+      }
+
+      WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lc_flag" );                 // u(1): luma_weight_lc_flag
+
+      if ( wp[0].bPresentFlag ) 
+      {
+        Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
+        WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lc" );                    // se(v): delta_luma_weight_lc
+        WRITE_SVLC( wp[0].iOffset, "luma_offset_lc" );                         // se(v): luma_offset_lc
+      }
+      if ( bChroma ) 
+      {
+        WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lc_flag" );             // u(1): luma_weight_lc_flag
+
+        if ( wp[1].bPresentFlag )
+        {
+          for ( Int j=1 ; j<3 ; j++ ) 
+          {
+            Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
+            WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lc" );              // se(v): delta_chroma_weight_lc
+
+            Int iDeltaChroma = (wp[j].iOffset + ( ( (g_uiIBDI_MAX>>1)*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) - (g_uiIBDI_MAX>>1));
+            WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lc" );              // se(v): delta_chroma_offset_lc
+          }
+        }
+      }
+    }
+  }
+}
+
+/** code quantization matrix
+ *  \param scalingList quantization matrix information
+ */
+Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
+{
+  UInt listId,sizeId;
+  Bool scalingListPredModeFlag;
+
+#if SCALING_LIST_OUTPUT_RESULT
+  Int startBit;
+  Int startTotalBit;
+  startBit = m_pcBitIf->getNumberOfWrittenBits();
+  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
+#endif
+
+  WRITE_FLAG( scalingList->getScalingListPresentFlag (), "scaling_list_present_flag" );
+
+  if(scalingList->getScalingListPresentFlag () == false)
+  {
+#if SCALING_LIST_OUTPUT_RESULT
+    printf("Header Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startBit);
+#endif
+    //for each size
+    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+    {
+      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+      {
+#if SCALING_LIST_OUTPUT_RESULT
+        startBit = m_pcBitIf->getNumberOfWrittenBits();
+#endif
+        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) - 1, "scaling_list_pred_matrix_id_delta");
+        }
+        else// DPCM Mode
+        {
+          xCodeScalingList(scalingList, sizeId, listId);
+        }
+#if SCALING_LIST_OUTPUT_RESULT
+        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
+#endif
+      }
+    }
+  }
+#if SCALING_LIST_OUTPUT_RESULT
+  else
+  {
+    printf("Header Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
+  }
+  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
+#endif
+  return;
+}
+/** code DPCM
+ * \param scalingList quantization matrix information
+ * \param sizeIdc size index
+ * \param listIdc list index
+ */
+Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
+{
+  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+  UInt* scan    = g_auiFrameScanXY [ (sizeId == 0)? 1 : 2];
+  Int nextCoef = SCALING_LIST_START_VALUE;
+  Int data;
+  Int *src = scalingList->getScalingListAddress(sizeId, listId);
+  if(sizeId > SCALING_LIST_8x8 && scalingList->getUseDefaultScalingMatrixFlag(sizeId,listId))
+  {
+    WRITE_SVLC( -8, "scaling_list_dc_coef_minus8");
+  }
+  else if(sizeId < SCALING_LIST_16x16 && scalingList->getUseDefaultScalingMatrixFlag(sizeId,listId))
+  {
+    WRITE_SVLC( -8, "scaling_list_delta_coef");
+  }
+  else
+  {
+    if( sizeId > SCALING_LIST_8x8 )
+    {
+      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
+    }
+    for(Int i=0;i<coefNum;i++)
+    {
+      data = src[scan[i]] - nextCoef;
+      nextCoef = src[scan[i]];
+      if(data > 127)
+      {
+        data = data - 256;
+      }
+      if(data < -128)
+      {
+        data = data + 256;
+      }
+
+      WRITE_SVLC( data,  "scaling_list_delta_coef");
+    }
+  }
+}
+Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
+{
+  for(Int predListIdx = (Int)listId -1 ; predListIdx >= 0; predListIdx--)
+  {
+    if( !memcmp(getScalingListAddress(sizeId,listId),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;
+}
+
+#if RWTH_SDC_DLT_B0036
+Void TEncCavlc::codeSDCFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeSDCResidualData  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeSDCPredMode ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#endif
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCavlc.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCavlc.h	(revision 341)
@@ -0,0 +1,221 @@
+/* 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-2012, 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     TEncCavlc.h
+    \brief    CAVLC encoder class (header)
+*/
+
+#ifndef __TENCCAVLC__
+#define __TENCCAVLC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TEncEntropy.h"
+#include "TLibCommon/TComRom.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CAVLC encoder class
+class TEncCavlc : public TEncEntropyIf
+{
+public:
+  TEncCavlc();
+  virtual ~TEncCavlc();
+  
+protected:
+  TComBitIf*    m_pcBitIf;
+  TComSlice*    m_pcSlice;
+  UInt          m_uiCoeffCost;
+  Bool          m_bAlfCtrl;
+  UInt          m_uiMaxAlfCtrlDepth;
+  Int           m_iSliceGranularity;  //!< slice granularity
+  
+  Void  xWriteCode            ( UInt uiCode, UInt uiLength );
+  Void  xWriteUvlc            ( UInt uiCode );
+  Void  xWriteSvlc            ( Int  iCode   );
+  Void  xWriteFlag            ( UInt uiCode );
+#if ENC_DEC_TRACE
+  Void  xWriteCodeTr          ( UInt value, UInt  length, const Char *pSymbolName);
+  Void  xWriteUvlcTr          ( UInt value,               const Char *pSymbolName);
+  Void  xWriteSvlcTr          ( Int  value,               const Char *pSymbolName);
+  Void  xWriteFlagTr          ( UInt value,               const Char *pSymbolName);
+#endif
+  
+  Void  xWritePCMAlignZero    ();
+  Void  xWriteEpExGolomb      ( UInt uiSymbol, UInt uiCount );
+  Void  xWriteExGolombLevel    ( UInt uiSymbol );
+  Void  xWriteUnaryMaxSymbol  ( UInt uiSymbol, UInt uiMaxSymbol );
+
+  Void codeShortTermRefPicSet              ( TComSPS* pcSPS, TComReferencePictureSet* pcRPS );
+  
+  UInt  xConvertToUInt        ( Int iValue ) {  return ( iValue <= 0) ? -iValue<<1 : (iValue<<1)-1; }
+  
+public:
+  
+  Void  resetEntropy          ();
+#if CABAC_INIT_FLAG
+  Void  determineCabacInitIdx  () {};
+#endif
+
+  Void  setBitstream          ( TComBitIf* p )  { m_pcBitIf = p;  }
+  Void  setSlice              ( TComSlice* p )  { m_pcSlice = p;  }
+  Bool getAlfCtrl() {return m_bAlfCtrl;}
+  UInt getMaxAlfCtrlDepth() {return m_uiMaxAlfCtrlDepth;}
+  Void setAlfCtrl(Bool bAlfCtrl) {m_bAlfCtrl = bAlfCtrl;}
+  Void setMaxAlfCtrlDepth(UInt uiMaxAlfCtrlDepth) {m_uiMaxAlfCtrlDepth = uiMaxAlfCtrlDepth;}
+  Void  resetBits             ()                { m_pcBitIf->resetBits(); }
+  Void  resetCoeffCost        ()                { m_uiCoeffCost = 0;  }
+  UInt  getNumberOfWrittenBits()                { return  m_pcBitIf->getNumberOfWrittenBits();  }
+  UInt  getCoeffCost          ()                { return  m_uiCoeffCost;  }
+  
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void  codeVPS                 ( TComVPS* pcVPS );
+#endif
+
+#if HHI_MPI || H3D_QTL 
+  Void  codeSPS                 ( TComSPS* pcSPS, Bool bIsDepth );
+#else
+  Void  codeSPS                 ( TComSPS* pcSPS );
+#endif
+  Void  codePPS                 ( TComPPS* pcPPS );
+  void codeSEI(const SEI&);
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+
+  Void codeTileMarkerFlag(TComSlice* pcSlice);
+
+  Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast );
+  Void  codeSliceFinish         ();
+  Void  codeFlush               () {}
+  Void  encodeStart             () {}
+  
+#if H3D_IVMP
+  Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Int iNum );
+#else
+  Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+#endif
+  Void codeAlfFlag       ( UInt uiCode );
+  Void codeAlfUvlc       ( UInt uiCode );
+  Void codeAlfSvlc       ( Int   iCode );
+  Void codeAlfCtrlDepth();
+  Void codeAPSAlflag(UInt uiCode);
+  Void codeAlfFixedLengthIdx( UInt idx, UInt numFilterSetsInBuffer);
+  Void codeSaoFlag       ( UInt uiCode );
+  Void codeSaoUvlc       ( UInt uiCode );
+  Void codeSaoSvlc       ( Int   iCode );
+  Void codeSaoRun        ( UInt uiCode, UInt maxValue  );
+  Void codeSaoMergeLeft  ( UInt uiCode, UInt compIdx ){;}
+  Void codeSaoMergeUp    ( UInt uiCode ){;}
+  Void codeSaoTypeIdx    ( UInt uiCode ){ xWriteUvlc(uiCode   );}
+  Void codeSaoUflc       ( UInt uiCode ){ assert(uiCode < 32); xWriteCode(uiCode, 5);}
+
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if LGE_ILLUCOMP_B0045
+  Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if H3D_IVRP
+  Void codeResPredFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
+  Void codeApsExtensionFlag ();
+
+  /// set slice granularity
+  Void setSliceGranularity(Int iSliceGranularity)  {m_iSliceGranularity = iSliceGranularity;}
+
+  ///get slice granularity
+  Int  getSliceGranularity()                       {return m_iSliceGranularity;             }
+
+  Void codeAlfCtrlFlag   ( UInt uiSymbol );
+  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, Int numIPCM, Bool firstIPCMFlag);
+
+  Void codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
+  Void codeQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeInterDir      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeRefFrmIdx     ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void codeMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+  Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+  
+  Void xCodePredWeightTable          ( TComSlice* pcSlice );
+  Void updateContextTables           ( SliceType eSliceType, Int iQp, Bool bExecuteFinish=true ) { return;   }
+  Void updateContextTables           ( SliceType eSliceType, Int iQp  )                          { return;   }
+  Void writeTileMarker               ( UInt uiTileIdx, UInt uiBitsUsed );
+
+  Void  codeAPSInitInfo(TComAPS* pcAPS);  //!< code APS flags before encoding SAO and ALF parameters
+  Void  codeFinish(Bool bEnd) { /*do nothing*/}
+  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 RWTH_SDC_DLT_B0036
+  Void codeSDCFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSDCResidualData  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment );
+  Void codeSDCPredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCCAVLC_H__EE8A0B30_945B_4169_B290_24D3AD52296F__INCLUDED_)
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCfg.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCfg.h	(revision 341)
@@ -0,0 +1,815 @@
+/* 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-2012, 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     TEncCfg.h
+    \brief    encoder configuration class (header)
+*/
+
+#ifndef __TENCCFG__
+#define __TENCCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include <assert.h>
+
+struct GOPEntryMvc
+{
+  Int m_POC;
+  Int m_QPOffset;
+  Double m_QPFactor;
+  Int m_temporalId;
+  Bool m_refPic;
+  Int m_numRefPicsActive;
+  Char m_sliceType;
+  Int m_numRefPics;
+  Int m_referencePics[MAX_NUM_REF_PICS];
+  Int m_usedByCurrPic[MAX_NUM_REF_PICS];
+  Bool m_interRPSPrediction;
+  Int m_deltaRIdxMinus1;
+  Int m_deltaRPS;
+  Int m_numRefIdc;
+  Int m_refIdc[MAX_NUM_REF_PICS+1];
+  Int m_numInterViewRefPics;
+  Int m_interViewRefs[MAX_NUM_REF_PICS];
+  Int m_interViewRefPosL0[MAX_NUM_REF_PICS];
+  Int m_interViewRefPosL1[MAX_NUM_REF_PICS];
+ GOPEntryMvc()
+  : m_POC(-1)
+  , m_QPOffset()
+  , m_QPFactor()
+  , m_temporalId()
+  , m_refPic()
+  , m_numRefPicsActive()
+  , m_sliceType()
+  , m_numRefPics()
+  , m_interRPSPrediction()
+  , m_deltaRIdxMinus1()
+  , m_deltaRPS()
+  , m_numRefIdc()
+  , m_numInterViewRefPics()
+  {
+    ::memset( m_referencePics, 0, sizeof(m_referencePics) );
+    ::memset( m_usedByCurrPic, 0, sizeof(m_usedByCurrPic) );
+    ::memset( m_refIdc,        0, sizeof(m_refIdc) );
+    ::memset( m_interViewRefs,   0, sizeof(m_interViewRefs) );
+    ::memset( m_interViewRefPosL0, 0, sizeof(m_interViewRefPosL0) );
+    ::memset( m_interViewRefPosL1, 0, sizeof(m_interViewRefPosL1) );
+  }
+};
+
+std::istringstream &operator>>(std::istringstream &in, GOPEntryMvc &entry);
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TEncCfg
+{
+protected:
+  //==== File I/O ========
+  Int       m_iFrameRate;
+  Int       m_FrameSkip;
+  Int       m_iSourceWidth;
+  Int       m_iSourceHeight;
+  Int       m_croppingMode;
+  Int       m_cropLeft;
+  Int       m_cropRight;
+  Int       m_cropTop;
+  Int       m_cropBottom;
+  Int       m_iFrameToBeEncoded;
+  Double    m_adLambdaModifier[ MAX_TLAYER ];
+
+  //====== Coding Structure ========
+  UInt      m_uiIntraPeriod;
+  UInt      m_uiDecodingRefreshType;            ///< the type of decoding refresh employed for the random access.
+  Int       m_iGOPSize;
+  GOPEntryMvc m_GOPList[MAX_GOP+1];
+  Int       m_extraRPSs;
+  Int       m_maxDecPicBuffering[MAX_TLAYER];
+  Int       m_numReorderPics[MAX_TLAYER];
+  
+  Int       m_iQP;                              //  if (AdaptiveQP == OFF)
+  
+  Int       m_aiTLayerQPOffset[MAX_TLAYER];
+  Int       m_aiPad[2];
+  
+
+  Int       m_iMaxRefPicNum;                     ///< this is used to mimic the sliding mechanism used by the decoder
+                                                 // TODO: We need to have a common sliding mechanism used by both the encoder and decoder
+
+  Int       m_maxTempLayer;                      ///< Max temporal layer
+  Bool      m_bDisInter4x4;
+  Bool m_useAMP;
+  //======= Transform =============
+  UInt      m_uiQuadtreeTULog2MaxSize;
+  UInt      m_uiQuadtreeTULog2MinSize;
+  UInt      m_uiQuadtreeTUMaxDepthInter;
+  UInt      m_uiQuadtreeTUMaxDepthIntra;
+  
+  Bool      m_useNSQT;
+  
+  //====== Loop/Deblock Filter ========
+  Bool      m_bLoopFilterDisable;
+  Bool      m_loopFilterOffsetInAPS;
+  Int       m_loopFilterBetaOffsetDiv2;
+  Int       m_loopFilterTcOffsetDiv2;
+  Bool      m_DeblockingFilterControlPresent;
+  Bool      m_bUseSAO;
+#if LGE_ILLUCOMP_B0045
+  Bool      m_bUseIC;
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Bool      m_bUseIVS;
+#endif
+  Int       m_maxNumOffsetsPerPic;
+  Bool      m_saoInterleavingFlag;
+
+  //====== Lossless ========
+#if LOSSLESS_CODING
+  Bool      m_useLossless;
+#endif
+  //====== Motion search ========
+  Int       m_iFastSearch;                      //  0:Full search  1:Diamond  2:PMVFAST
+  Int       m_iSearchRange;                     //  0:Full frame
+  Int       m_bipredSearchRange;
+#if DV_V_RESTRICTION_B0037
+  Bool      m_bUseDisparitySearchRangeRestriction;
+  Int       m_iVerticalDisparitySearchRange;
+#endif
+  //====== Quality control ========
+  Int       m_iMaxDeltaQP;                      //  Max. absolute delta QP (1:default)
+  Int       m_iMaxCuDQPDepth;                   //  Max. depth for a minimum CuDQP (0:default)
+
+  Int       m_iChromaQpOffset  ;                //  ChromaQpOffset    (0:default)
+  Int       m_iChromaQpOffset2nd;               //  ChromaQpOffset2nd (0:default)
+
+#if ADAPTIVE_QP_SELECTION
+  Bool      m_bUseAdaptQpSelect;
+#endif
+
+  Bool      m_bUseAdaptiveQP;
+  Int       m_iQPAdaptationRange;
+  
+#if HHI_VSO
+  //====== View Synthesis Optimization ======
+  Bool      m_bUseVSO;
+  Bool      m_bForceLambdaScale;
+#if HHI_VSO_DIST_INT
+  Bool      m_bAllowNegDist;
+#endif
+  Double    m_dLambdaScaleVSO;
+  UInt      m_uiVSOMode;
+#if LGE_WVSO_A0119
+  Bool      m_bUseWVSO;
+  Int       m_iVSOWeight;
+  Int       m_iVSDWeight;
+  Int       m_iDWeight;
+#endif
+#endif
+#if SAIT_VSO_EST_A0033
+  Bool      m_bUseEstimatedVSD; 
+  Double    m_dDispCoeff;
+#endif
+
+
+  //====== Tool list ========
+  Bool      m_bUseSBACRD;
+  Bool      m_bUseALF;
+  Int       m_iALFEncodePassReduction;
+
+  Int       m_iALFMaxNumberFilters;
+  Bool      m_bALFParamInSlice;
+  Bool      m_bALFPicBasedEncode;
+
+  Bool      m_bUseASR;
+  Bool      m_bUseHADME;
+  Bool      m_bUseLComb;
+  Bool      m_bLCMod;
+  Bool      m_bUseRDOQ;
+  Bool      m_bUseFastEnc;
+  Bool      m_bUseEarlyCU;
+
+  Bool      m_useFastDecisionForMerge;
+  Bool      m_bUseCbfFastMode;
+  Bool      m_bUseLMChroma; 
+#if HHI_MPI
+  Bool      m_bUseMVI;
+#endif
+#if RWTH_SDC_DLT_B0036
+  Bool      m_bUseDLT;
+  Bool      m_bUseSDC;
+#endif
+
+  Int*      m_aidQP;
+  UInt      m_uiDeltaQpRD;
+  
+  Bool      m_bUseConstrainedIntraPred;
+  Bool      m_usePCM;
+  UInt      m_pcmLog2MaxSize;
+  UInt      m_uiPCMLog2MinSize;
+  //====== Slice ========
+  Int       m_iSliceMode;
+  Int       m_iSliceArgument; 
+  //====== Entropy Slice ========
+  Int       m_iEntropySliceMode;
+  Int       m_iEntropySliceArgument;
+  Int       m_iSliceGranularity;
+  Bool      m_bLFCrossSliceBoundaryFlag;
+
+  Bool      m_bPCMInputBitDepthFlag;
+  UInt      m_uiPCMBitDepthLuma;
+  UInt      m_uiPCMBitDepthChroma;
+  Bool      m_bPCMFilterDisableFlag;
+  Int       m_iTileBehaviorControlPresentFlag;
+  Bool      m_bLFCrossTileBoundaryFlag;
+  Int       m_iColumnRowInfoPresent;
+  Int       m_iUniformSpacingIdr;
+  Int       m_iNumColumnsMinus1;
+  UInt*     m_puiColumnWidth;
+  Int       m_iNumRowsMinus1;
+  UInt*     m_puiRowHeight;
+  Int       m_iTileLocationInSliceHeaderFlag; //< enable(1)/disable(0) transmitssion of tile location in slice header
+
+  Int       m_iTileMarkerFlag;              //< enable(1)/disable(0) transmitssion of light weight tile marker
+  Int       m_iMaxTileMarkerEntryPoints;    //< maximum number of tile markers allowed in a slice (controls degree of parallelism)
+  Double    m_dMaxTileMarkerOffset;         //< Calculated offset. Light weight tile markers will be transmitted for TileIdx= Offset, 2*Offset, 3*Offset ... 
+
+  Int       m_iWaveFrontSynchro;
+  Int       m_iWaveFrontFlush;
+  Int       m_iWaveFrontSubstreams;
+
+  Bool      m_pictureDigestEnabled; ///< enable(1)/disable(0) md5 computation and SEI signalling
+
+  //====== Weighted Prediction ========
+  Bool      m_bUseWeightPred;       //< Use of Weighting Prediction (P_SLICE)
+  UInt      m_uiBiPredIdc;          //< Use of Bi-Directional Weighting Prediction (B_SLICE)
+  Int       m_useScalingListId;            ///< Using quantization matrix i.e. 0=off, 1=default, 2=file.
+  char*     m_scalingListFile;          ///< quantization matrix file name
+
+  Bool      m_bEnableTMVP;
+  Int       m_signHideFlag;
+  Int       m_signHidingThreshold;
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  UInt     m_layerId;
+#endif
+  
+  Int      m_viewId;
+  Bool     m_isDepth;
+
+#if HHI_INTERVIEW_SKIP
+  Bool        m_bInterViewSkip;
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  Double      m_dInterViewSkipLambdaScale;
+#endif
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool     m_bUseDMM;
+#endif
+
+#if HHI_DMM_PRED_TEX && FLEX_CODING_ORDER_M23723
+  Bool m_bUseDMM34;
+#endif
+
+#if H3D_QTL
+  Bool     m_bUseQTLPC;
+#endif
+
+  Int      m_iViewOrderIdx;
+
+  UInt     m_uiCamParPrecision;
+  Bool     m_bCamParInSliceHeader;
+  Int**    m_aaiCodedScale;
+  Int**    m_aaiCodedOffset;
+
+#if DEPTH_MAP_GENERATION
+  UInt     m_uiPredDepthMapGeneration;
+  UInt     m_uiPdmPrecision;
+  Int**    m_aaiPdmScaleNomDelta;
+  Int**    m_aaiPdmOffset;
+#endif
+
+#if H3D_IVMP
+  UInt        m_uiMultiviewMvPredMode;
+  UInt        m_uiMultiviewMvRegMode;
+  Double      m_dMultiviewMvRegLambdaScale;
+#endif
+#if H3D_IVRP
+  UInt        m_uiMultiviewResPredMode;
+#endif
+
+public:
+  TEncCfg()          {}
+  virtual ~TEncCfg()
+  {
+    if( m_iUniformSpacingIdr == 0 )
+    {
+      if( m_iNumColumnsMinus1 )
+      { 
+        delete[] m_puiColumnWidth; 
+        m_puiColumnWidth = NULL;
+      }
+      if( m_iNumRowsMinus1 )
+      {
+        delete[] m_puiRowHeight;
+        m_puiRowHeight = NULL;
+      }
+    }
+    m_iTileLocationInSliceHeaderFlag = 0;
+    m_iTileMarkerFlag              = 0;
+  }
+  
+  Void      setFrameRate                    ( Int   i )      { m_iFrameRate = i; }
+  Void      setFrameSkip                    ( unsigned int i ) { m_FrameSkip = i; }
+  Void      setSourceWidth                  ( Int   i )      { m_iSourceWidth = i; }
+  Void      setSourceHeight                 ( Int   i )      { m_iSourceHeight = i; }
+  Void      setCroppingMode                 ( Int   i )      { m_croppingMode = i; }
+  Void      setCropLeft                     ( Int   i )      { m_cropLeft = i; }
+  Void      setCropRight                    ( Int   i )      { m_cropRight = i; }
+  Void      setCropTop                      ( Int   i )      { m_cropTop = i; }
+  Void      setCropBottom                   ( Int   i )      { m_cropBottom = i; }
+  Void      setFrameToBeEncoded             ( Int   i )      { m_iFrameToBeEncoded = i; }
+  
+  //====== Coding Structure ========
+  Void      setIntraPeriod                  ( Int   i )      { m_uiIntraPeriod = (UInt)i; }
+  Void      setDecodingRefreshType          ( Int   i )      { m_uiDecodingRefreshType = (UInt)i; }
+  Void      setGOPSize                      ( Int   i )      { m_iGOPSize = i; }
+  Void      setGopList                      ( GOPEntryMvc* GOPList ) { for( Int i = 0; i < MAX_GOP+1; i++ ) m_GOPList[i] = GOPList[i]; }
+  Void      setExtraRPSs                    ( Int   i )      { m_extraRPSs = i; }
+  GOPEntryMvc getGOPEntry                   ( Int   i )      { return m_GOPList[i]; }
+  Void      setMaxDecPicBuffering           ( UInt u, UInt tlayer ) { m_maxDecPicBuffering[tlayer] = u;    }
+  Void      setNumReorderPics               ( Int  i, UInt tlayer ) { m_numReorderPics[tlayer] = i;    }
+  
+#if HHI_INTERVIEW_SKIP
+  Void      setInterViewSkip            ( UInt  u )       { m_bInterViewSkip         = u; }
+  Bool      getInterViewSkip            ( )       { return m_bInterViewSkip  ;}
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  Void      setInterViewSkipLambdaScale ( UInt  u )       { m_dInterViewSkipLambdaScale = u; }
+  Double      getInterViewSkipLambdaScale ()                { return m_dInterViewSkipLambdaScale; }
+#endif
+#endif
+  Void      setQP                           ( Int   i )      { m_iQP = i; }
+  
+  Void      setTemporalLayerQPOffset        ( Int*  piTemporalLayerQPOffset )      { for ( Int i = 0; i < MAX_TLAYER; i++ ) m_aiTLayerQPOffset[i] = piTemporalLayerQPOffset[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;  }
+
+  Bool      getMaxTempLayer                 ()                              { return m_maxTempLayer;              } 
+  Void      setMaxTempLayer                 ( Int maxTempLayer )            { m_maxTempLayer = maxTempLayer;      }
+
+  Bool      getDisInter4x4                  ()              { return m_bDisInter4x4;        }
+  Void      setDisInter4x4                  ( Bool b )      { m_bDisInter4x4  = b;          }
+  Bool      isDepthCoder                    ()               { return m_isDepth; }
+  
+#if DEPTH_MAP_GENERATION
+  Void      setPredDepthMapGeneration       ( UInt  u )      { m_uiPredDepthMapGeneration   = u; }
+  Void      setPdmPrecision                 ( UInt  u )      { m_uiPdmPrecision             = u; }
+  Void      setPdmScaleNomDelta             ( Int** p )      { m_aaiPdmScaleNomDelta        = p; }
+  Void      setPdmOffset                    ( Int** p )      { m_aaiPdmOffset               = p; }
+#endif
+
+#if H3D_IVMP
+  Void      setMultiviewMvPredMode          ( UInt  u )      { m_uiMultiviewMvPredMode      = u; }
+  Void      setMultiviewMvRegMode           ( UInt  u )      { m_uiMultiviewMvRegMode       = u; }
+  Void      setMultiviewMvRegLambdaScale    ( Double d)      { m_dMultiviewMvRegLambdaScale = d; }
+#endif
+#if H3D_IVRP
+  Void      setMultiviewResPredMode         ( UInt  u )      { m_uiMultiviewResPredMode     = u; }
+#endif
+  
+  //======== Transform =============
+  Void      setQuadtreeTULog2MaxSize        ( UInt  u )      { m_uiQuadtreeTULog2MaxSize = u; }
+  Void      setQuadtreeTULog2MinSize        ( UInt  u )      { m_uiQuadtreeTULog2MinSize = u; }
+  Void      setQuadtreeTUMaxDepthInter      ( UInt  u )      { m_uiQuadtreeTUMaxDepthInter = u; }
+  Void      setQuadtreeTUMaxDepthIntra      ( UInt  u )      { m_uiQuadtreeTUMaxDepthIntra = u; }
+  
+  Void setUseNSQT( Bool b ) { m_useNSQT = b; }
+  Void setUseAMP( Bool b ) { m_useAMP = b; }
+  
+  //====== Loop/Deblock Filter ========
+  Void      setLoopFilterDisable            ( Bool  b )      { m_bLoopFilterDisable       = b; }
+  Void      setLoopFilterOffsetInAPS        ( Bool  b )      { m_loopFilterOffsetInAPS      = b; }
+  Void      setLoopFilterBetaOffset         ( Int   i )      { m_loopFilterBetaOffsetDiv2  = i; }
+  Void      setLoopFilterTcOffset           ( Int   i )      { m_loopFilterTcOffsetDiv2    = i; }
+  Void      setDeblockingFilterControlPresent ( Bool b ) { m_DeblockingFilterControlPresent = b; }
+
+  //====== Motion search ========
+  Void      setFastSearch                   ( Int   i )      { m_iFastSearch = i; }
+  Void      setSearchRange                  ( Int   i )      { m_iSearchRange = i; }
+  Void      setBipredSearchRange            ( Int   i )      { m_bipredSearchRange = i; }
+#if DV_V_RESTRICTION_B0037
+  Void      setUseDisparitySearchRangeRestriction ( Bool   b )      { m_bUseDisparitySearchRangeRestriction = b; }
+  Void      setVerticalDisparitySearchRange ( Int   i )      { m_iVerticalDisparitySearchRange = i; }
+#endif
+#if H3D_IVMP
+  UInt      getMultiviewMvRegMode           ()      { return  m_uiMultiviewMvRegMode; }
+  Double    getMultiviewMvRegLambdaScale    ()      { return  m_dMultiviewMvRegLambdaScale; }
+#endif
+
+#if HHI_VSO
+ //==== VSO  ==========
+  Void      setVSOMode                      ( UInt  ui )    { m_uiVSOMode   = ui; }
+  Void      setForceLambdaScaleVSO          ( Bool  b )     { m_bForceLambdaScale = b; };
+  Void      setLambdaScaleVSO               ( Double d )    { m_dLambdaScaleVSO   = d; };
+#if HHI_VSO_DIST_INT
+  Void      setAllowNegDist                 ( Bool b  )     { m_bAllowNegDist     = b; };
+#endif
+#if LGE_WVSO_A0119
+  Void      setUseWVSO                      ( Bool  b )     { m_bUseWVSO   = b; }
+  Void      setVSOWeight                    ( Int   i )     { m_iVSOWeight = i; }
+  Void      setVSDWeight                    ( Int   i )     { m_iVSDWeight = i; }
+  Void      setDWeight                      ( Int   i )     { m_iDWeight   = i; }
+#endif
+#endif
+
+  //====== Quality control ========
+  Void      setMaxDeltaQP                   ( Int   i )      { m_iMaxDeltaQP = i; }
+  Void      setMaxCuDQPDepth                ( Int   i )      { m_iMaxCuDQPDepth = i; }
+
+  Void      setChromaQpOffset               ( Int   i ) { m_iChromaQpOffset    = i; }
+  Void      setChromaQpOffset2nd            ( Int   i ) { m_iChromaQpOffset2nd = i; }
+
+#if ADAPTIVE_QP_SELECTION
+  Void      setUseAdaptQpSelect             ( Bool   i ) { m_bUseAdaptQpSelect    = i; }
+  Bool      getUseAdaptQpSelect             ()           { return   m_bUseAdaptQpSelect; }
+#endif
+
+  Void      setUseAdaptiveQP                ( Bool  b )      { m_bUseAdaptiveQP = b; }
+  Void      setQPAdaptationRange            ( Int   i )      { m_iQPAdaptationRange = i; }
+  
+  //====== Lossless ========
+#if LOSSLESS_CODING
+  Void      setUseLossless                  (Bool    b  )        { m_useLossless = b;  }
+#endif
+  //====== Sequence ========
+  Int       getFrameRate                    ()      { return  m_iFrameRate; }
+  unsigned int getFrameSkip                 ()      { return  m_FrameSkip; }
+  Int       getSourceWidth                  ()      { return  m_iSourceWidth; }
+  Int       getSourceHeight                 ()      { return  m_iSourceHeight; }
+  Int       getCroppingMode                 ()      { return  m_croppingMode; }
+  Int       getCropLeft                     ()      { return  m_cropLeft; }
+  Int       getCropRight                    ()      { return  m_cropRight; }
+  Int       getCropTop                      ()      { return  m_cropTop; }
+  Int       getCropBottom                   ()      { return  m_cropBottom; }
+  Int       getFrameToBeEncoded             ()      { return  m_iFrameToBeEncoded; }
+  void setLambdaModifier                    ( UInt uiIndex, Double dValue ) { m_adLambdaModifier[ uiIndex ] = dValue; }
+  Double getLambdaModifier                  ( UInt uiIndex ) const { return m_adLambdaModifier[ uiIndex ]; }
+
+  //==== Coding Structure ========
+  UInt      getIntraPeriod                  ()      { return  m_uiIntraPeriod; }
+  UInt      getDecodingRefreshType          ()      { return  m_uiDecodingRefreshType; }
+  Int       getGOPSize                      ()      { return  m_iGOPSize; }
+  Int       getMaxDecPicBuffering           (UInt tlayer) { return m_maxDecPicBuffering[tlayer]; }
+  Int       getNumReorderPics               (UInt tlayer) { return m_numReorderPics[tlayer]; }
+  Int       getQP                           ()      { return  m_iQP; }
+  
+  Int       getTemporalLayerQPOffset        ( Int i )      { assert (i < MAX_TLAYER ); return  m_aiTLayerQPOffset[i]; }
+  Int       getPad                          ( Int i )      { assert (i < 2 );                      return  m_aiPad[i]; }
+  
+  //======== Transform =============
+  UInt      getQuadtreeTULog2MaxSize        ()      const { return m_uiQuadtreeTULog2MaxSize; }
+  UInt      getQuadtreeTULog2MinSize        ()      const { return m_uiQuadtreeTULog2MinSize; }
+  UInt      getQuadtreeTUMaxDepthInter      ()      const { return m_uiQuadtreeTUMaxDepthInter; }
+  UInt      getQuadtreeTUMaxDepthIntra      ()      const { return m_uiQuadtreeTUMaxDepthIntra; }
+  
+  //==== Loop/Deblock Filter ========
+  Bool      getLoopFilterDisable            ()      { return  m_bLoopFilterDisable;       }
+  Bool      getLoopFilterOffsetInAPS        ()      { return m_loopFilterOffsetInAPS; }
+  Int       getLoopFilterBetaOffset         ()      { return m_loopFilterBetaOffsetDiv2; }
+  Int       getLoopFilterTcOffset           ()      { return m_loopFilterTcOffsetDiv2; }
+  Bool      getDeblockingFilterControlPresent()  { return  m_DeblockingFilterControlPresent; }
+
+  //==== Motion search ========
+  Int       getFastSearch                   ()      { return  m_iFastSearch; }
+  Int       getSearchRange                  ()      { return  m_iSearchRange; }
+#if DV_V_RESTRICTION_B0037
+  Bool      getUseDisparitySearchRangeRestriction ()      { return  m_bUseDisparitySearchRangeRestriction; }
+  Int       getVerticalDisparitySearchRange ()      { return  m_iVerticalDisparitySearchRange; }
+#endif
+#if HHI_VSO
+  //==== VSO  ==========
+  UInt      getVSOMode                      ()      { return m_uiVSOMode; }
+  Bool      getForceLambdaScaleVSO          ()      { return m_bForceLambdaScale; }
+  Double    getLambdaScaleVSO               ()      { return m_dLambdaScaleVSO;   }
+#if HHI_VSO_DIST_INT
+  Bool      getAllowNegDist                 ()      { return m_bAllowNegDist;     }
+#endif
+#if LGE_WVSO_A0119
+  Bool      getUseWVSO                      ()      { return m_bUseWVSO;     }
+  Int       getVSOWeight                    ()      { return m_iVSOWeight;    }
+  Int       getVSDWeight                    ()      { return m_iVSDWeight;    }
+  Int       getDWeight                      ()      { return m_iDWeight;    }
+#endif
+#endif
+
+  //==== Quality control ========
+  Int       getMaxDeltaQP                   ()      { return  m_iMaxDeltaQP; }
+  Int       getMaxCuDQPDepth                ()      { return  m_iMaxCuDQPDepth; }
+  Bool      getUseAdaptiveQP                ()      { return  m_bUseAdaptiveQP; }
+  Int       getQPAdaptationRange            ()      { return  m_iQPAdaptationRange; }
+  //====== Lossless ========
+#if LOSSLESS_CODING
+  Bool      getUseLossless                  ()      { return  m_useLossless;  }
+#endif
+  
+  //==== Tool list ========
+  Void      setUseSBACRD                    ( Bool  b )     { m_bUseSBACRD  = b; }
+  Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
+  Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
+  Void      setUseALF                       ( Bool  b )     { m_bUseALF   = b; }
+  Void      setUseLComb                     ( Bool  b )     { m_bUseLComb   = b; }
+  Void      setLCMod                        ( Bool  b )     { m_bLCMod   = b;    }
+  Void      setUseRDOQ                      ( Bool  b )     { m_bUseRDOQ    = b; }
+#if HHI_VSO
+  Void      setUseVSO                       ( Bool  b )     { m_bUseVSO     = b; }
+#endif
+
+#if SAIT_VSO_EST_A0033
+  Void      setUseEstimatedVSD              ( Bool  b )     { m_bUseEstimatedVSD = b; }
+  Void      setDispCoeff                    ( Double  d )   { m_dDispCoeff  = d; }
+#endif
+
+  Void      setUseFastEnc                   ( Bool  b )     { m_bUseFastEnc = b; }
+  Void      setUseEarlyCU                   ( Bool  b )     { m_bUseEarlyCU = b; }
+  Void      setUseFastDecisionForMerge      ( Bool  b )     { m_useFastDecisionForMerge = b; }
+  Void      setUseCbfFastMode            ( Bool  b )     { m_bUseCbfFastMode = b; }
+  Void      setUseConstrainedIntraPred      ( Bool  b )     { m_bUseConstrainedIntraPred = b; }
+  Void      setPCMInputBitDepthFlag         ( Bool  b )     { m_bPCMInputBitDepthFlag = b; }
+  Void      setPCMFilterDisableFlag         ( Bool  b )     {  m_bPCMFilterDisableFlag = b; }
+  Void      setUsePCM                       ( Bool  b )     {  m_usePCM = b;               }
+  Void      setPCMLog2MaxSize               ( UInt u )      { m_pcmLog2MaxSize = u;      }
+  Void      setPCMLog2MinSize               ( UInt u )     { m_uiPCMLog2MinSize = u;      }
+  Void      setdQPs                         ( Int*  p )     { m_aidQP       = p; }
+  Void      setDeltaQpRD                    ( UInt  u )     {m_uiDeltaQpRD  = u; }
+  Bool      getUseSBACRD                    ()      { return m_bUseSBACRD;  }
+  Bool      getUseASR                       ()      { return m_bUseASR;     }
+  Bool      getUseHADME                     ()      { return m_bUseHADME;   }
+  Bool      getUseALF                       ()      { return m_bUseALF;     }
+  Void      setALFEncodePassReduction       (Int i)  { m_iALFEncodePassReduction = i; }
+  Int       getALFEncodePassReduction       ()       { return m_iALFEncodePassReduction; }
+
+  Void      setALFMaxNumberFilters          (Int i)  { m_iALFMaxNumberFilters = i; } 
+  Int       getALFMaxNumberFilters          ()       { return m_iALFMaxNumberFilters; } 
+  Void      setALFParamInSlice              (Bool b) {m_bALFParamInSlice = b;}
+  Bool      getALFParamInSlice              ()       {return m_bALFParamInSlice;}
+  Void      setALFPicBasedEncode            (Bool b) {m_bALFPicBasedEncode = b;}
+  Bool      getALFPicBasedEncode            ()       {return m_bALFPicBasedEncode;}
+
+  Bool      getUseLComb                     ()      { return m_bUseLComb;   }
+  Bool      getLCMod                        ()      { return m_bLCMod; }
+  Bool      getUseRDOQ                      ()      { return m_bUseRDOQ;    }
+
+#if HHI_VSO
+  Bool      getUseVSO                       ()      { return m_bUseVSO;     }
+#endif
+#if SAIT_VSO_EST_A0033
+  Bool      getUseEstimatedVSD              ()      { return m_bUseEstimatedVSD; }
+  Double    getDispCoeff                    ()      { return m_dDispCoeff;    }
+#endif
+
+  Bool      getUseFastEnc                   ()      { return m_bUseFastEnc; }
+  Bool      getUseEarlyCU                   ()      { return m_bUseEarlyCU; }
+  Bool      getUseFastDecisionForMerge      ()      { return m_useFastDecisionForMerge; }
+  Bool      getUseCbfFastMode           ()      { return m_bUseCbfFastMode; }
+  Bool      getUseConstrainedIntraPred      ()      { return m_bUseConstrainedIntraPred; }
+#if NS_HAD
+  Bool      getUseNSQT                      ()      { return m_useNSQT; }
+#endif
+  Bool      getPCMInputBitDepthFlag         ()      { return m_bPCMInputBitDepthFlag;   } 
+  Bool      getPCMFilterDisableFlag         ()      { return m_bPCMFilterDisableFlag;   } 
+  Bool      getUsePCM                       ()      { return m_usePCM;                 }
+  UInt      getPCMLog2MaxSize               ()      { return m_pcmLog2MaxSize;  }
+  UInt      getPCMLog2MinSize               ()      { return  m_uiPCMLog2MinSize;  }
+
+  Bool getUseLMChroma                       ()      { return m_bUseLMChroma;        }
+  Void setUseLMChroma                       ( Bool b ) { m_bUseLMChroma  = b;       }
+
+  Int*      getdQPs                         ()      { return m_aidQP;       }
+  UInt      getDeltaQpRD                    ()      { return m_uiDeltaQpRD; }
+
+  //====== Slice ========
+  Void  setSliceMode                   ( Int  i )       { m_iSliceMode = i;              }
+  Void  setSliceArgument               ( Int  i )       { m_iSliceArgument = i;          }
+  Int   getSliceMode                   ()              { return m_iSliceMode;           }
+  Int   getSliceArgument               ()              { return m_iSliceArgument;       }
+  //====== Entropy Slice ========
+  Void  setEntropySliceMode            ( Int  i )      { m_iEntropySliceMode = i;       }
+  Void  setEntropySliceArgument        ( Int  i )      { m_iEntropySliceArgument = i;   }
+  Int   getEntropySliceMode            ()              { return m_iEntropySliceMode;    }
+  Int   getEntropySliceArgument        ()              { return m_iEntropySliceArgument;}
+  Void  setSliceGranularity            ( Int  i )      { m_iSliceGranularity = i;       }
+  Int   getSliceGranularity            ()              { return m_iSliceGranularity;    }
+  Void  setLFCrossSliceBoundaryFlag    ( Bool   bValue  )    { m_bLFCrossSliceBoundaryFlag = bValue; }
+  Bool  getLFCrossSliceBoundaryFlag    ()                    { return m_bLFCrossSliceBoundaryFlag;   }
+
+#if HHI_MPI
+  Void  setUseMVI                      ( Bool bVal )   {m_bUseMVI = bVal;}
+#endif
+#if RWTH_SDC_DLT_B0036
+  Void  setUseDLT                       ( Bool  b )     { m_bUseDLT   = b; }
+  Void  setUseSDC                       ( Bool  b )     { m_bUseSDC   = b; }
+#endif
+  Void  setUseSAO                      ( Bool bVal )   {m_bUseSAO = bVal;}
+  Bool  getUseSAO                      ()              {return m_bUseSAO;}
+#if LGE_ILLUCOMP_B0045
+  Void  setUseIC                       ( Bool bVal )   {m_bUseIC = bVal;}
+  Bool  getUseIC                       ()              {return m_bUseIC;}
+#endif
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Void  setUseIVS                       ( Bool bVal )   {m_bUseIVS = bVal;}
+  Bool  getUseIVS                       ()              {return m_bUseIVS;}
+#endif
+  Void  setMaxNumOffsetsPerPic                   (Int iVal)            { m_maxNumOffsetsPerPic = iVal; }
+  Int   getMaxNumOffsetsPerPic                   ()                    { return m_maxNumOffsetsPerPic; }
+  Void  setSaoInterleavingFlag                   (bool bVal)           { m_saoInterleavingFlag = bVal; }
+  Bool  getSaoInterleavingFlag                   ()                    { return m_saoInterleavingFlag; }
+  Void  setTileBehaviorControlPresentFlag        ( Int i )             { m_iTileBehaviorControlPresentFlag = i;    }
+  Int   getTileBehaviorControlPresentFlag        ()                    { return m_iTileBehaviorControlPresentFlag; }
+  Void  setLFCrossTileBoundaryFlag               ( Bool   bValue  )    { m_bLFCrossTileBoundaryFlag = bValue; }
+  Bool  getLFCrossTileBoundaryFlag               ()                    { return m_bLFCrossTileBoundaryFlag;   }
+  Void  setColumnRowInfoPresent        ( Int i )           { m_iColumnRowInfoPresent = i; }
+  Int   getColumnRowInfoPresent        ()                  { return m_iColumnRowInfoPresent; }
+  Void  setUniformSpacingIdr           ( Int i )           { m_iUniformSpacingIdr = i; }
+  Int   getUniformSpacingIdr           ()                  { return m_iUniformSpacingIdr; }
+  Void  setNumColumnsMinus1            ( Int i )           { m_iNumColumnsMinus1 = i; }
+  Int   getNumColumnsMinus1            ()                  { return m_iNumColumnsMinus1; }
+  Void  setColumnWidth ( char* str )
+  {
+    char *columnWidth;
+    int  i=0;
+    Int  m_iWidthInCU = ( m_iSourceWidth%g_uiMaxCUWidth ) ? m_iSourceWidth/g_uiMaxCUWidth + 1 : m_iSourceWidth/g_uiMaxCUWidth;
+
+    if( m_iUniformSpacingIdr == 0 && m_iNumColumnsMinus1 > 0 )
+    {
+      m_puiColumnWidth = new UInt[m_iNumColumnsMinus1];
+
+      columnWidth = strtok(str, " ,-");
+      while(columnWidth!=NULL)
+      {
+        if( i>=m_iNumColumnsMinus1 )
+        {
+          printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
+          exit( EXIT_FAILURE );
+        }
+        *( m_puiColumnWidth + i ) = atoi( columnWidth );
+        printf("col: m_iWidthInCU= %4d i=%4d width= %4d\n",m_iWidthInCU,i,m_puiColumnWidth[i]); //AFU
+        columnWidth = strtok(NULL, " ,-");
+        i++;
+      }
+      if( i<m_iNumColumnsMinus1 )
+      {
+        printf( "The width of some columns is not defined.\n" );
+        exit( EXIT_FAILURE );
+      }
+    }
+  }
+  UInt  getColumnWidth                 ( UInt columnidx )  { return *( m_puiColumnWidth + columnidx ); }
+  Void  setNumRowsMinus1               ( Int i )           { m_iNumRowsMinus1 = i; }
+  Int   getNumRowsMinus1               ()                  { return m_iNumRowsMinus1; }
+  Void  setRowHeight (char* str)
+  {
+    char *rowHeight;
+    int  i=0;
+    Int  m_iHeightInCU = ( m_iSourceHeight%g_uiMaxCUHeight ) ? m_iSourceHeight/g_uiMaxCUHeight + 1 : m_iSourceHeight/g_uiMaxCUHeight;
+
+    if( m_iUniformSpacingIdr == 0 && m_iNumRowsMinus1 > 0 )
+    {
+      m_puiRowHeight = new UInt[m_iNumRowsMinus1];
+
+      rowHeight = strtok(str, " ,-");
+      while(rowHeight!=NULL)
+      {
+        if( i>=m_iNumRowsMinus1 )
+        {
+          printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
+          exit( EXIT_FAILURE );
+        }
+        *( m_puiRowHeight + i ) = atoi( rowHeight );
+        printf("row: m_iHeightInCU=%4d i=%4d height=%4d\n",m_iHeightInCU,i,m_puiRowHeight[i]); //AFU
+        rowHeight = strtok(NULL, " ,-");
+        i++;
+      }
+      if( i<m_iNumRowsMinus1 )
+      {
+        printf( "The height of some rows is not defined.\n" );
+        exit( EXIT_FAILURE );
+     }
+    }
+  }
+  UInt  getRowHeight                   ( UInt rowIdx )     { return *( m_puiRowHeight + rowIdx ); }
+  Void  xCheckGSParameters();
+  Int  getTileLocationInSliceHeaderFlag ()                 { return m_iTileLocationInSliceHeaderFlag; }
+  Void setTileLocationInSliceHeaderFlag ( Int iFlag )      { m_iTileLocationInSliceHeaderFlag = iFlag;}
+  Int  getTileMarkerFlag              ()                 { return m_iTileMarkerFlag;              }
+  Void setTileMarkerFlag              ( Int iFlag )      { m_iTileMarkerFlag = iFlag;             }
+  Int  getMaxTileMarkerEntryPoints    ()                 { return m_iMaxTileMarkerEntryPoints;    }
+  Void setMaxTileMarkerEntryPoints    ( Int iCount )     { m_iMaxTileMarkerEntryPoints = iCount;  }
+  Double getMaxTileMarkerOffset       ()                 { return m_dMaxTileMarkerOffset;         }
+  Void setMaxTileMarkerOffset         ( Double dCount )  { m_dMaxTileMarkerOffset = dCount;       }
+  Void  setWaveFrontSynchro(Int iWaveFrontSynchro)       { m_iWaveFrontSynchro = iWaveFrontSynchro; }
+  Int   getWaveFrontsynchro()                            { return m_iWaveFrontSynchro; }
+  Void  setWaveFrontFlush(Int iWaveFrontFlush)           { m_iWaveFrontFlush = iWaveFrontFlush; }
+  Int   getWaveFrontFlush()                              { return m_iWaveFrontFlush; }
+  Void  setWaveFrontSubstreams(Int iWaveFrontSubstreams) { m_iWaveFrontSubstreams = iWaveFrontSubstreams; }
+  Int   getWaveFrontSubstreams()                         { return m_iWaveFrontSubstreams; }
+  void setPictureDigestEnabled(bool b) { m_pictureDigestEnabled = b; }
+  bool getPictureDigestEnabled() { return m_pictureDigestEnabled; }
+
+  Void      setUseWP               ( Bool  b )   { m_bUseWeightPred    = b;    }
+  Void      setWPBiPredIdc         ( UInt u )    { m_uiBiPredIdc       = u;    }
+  Bool      getUseWP               ()            { return m_bUseWeightPred;    }
+  UInt      getWPBiPredIdc         ()            { return m_uiBiPredIdc;       }
+  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      setEnableTMVP          ( Bool b )    { m_bEnableTMVP = b;    }
+  Bool      getEnableTMVP          ()            { return m_bEnableTMVP; }
+  Void      setSignHideFlag( Int signHideFlag )  { m_signHideFlag = signHideFlag; }
+  Void      setTSIG( Int tsig )                  { m_signHidingThreshold = tsig; }
+  Int       getSignHideFlag()                    { return m_signHideFlag; }
+  Int       getTSIG()                            { return m_signHidingThreshold; }
+#if VIDYO_VPS_INTEGRATION |QC_MVHEVC_B0046
+  Void      setLayerId             ( UInt layerId )   { m_layerId = layerId; }
+  UInt      getLayerId             ()               { return m_layerId; }
+#endif
+
+  Void      setViewId             ( Int viewId )   { m_viewId = viewId; }
+  Int       getViewId             ()               { return m_viewId; }
+  Void      setIsDepth            ( Bool isDepth ) { m_isDepth = isDepth; }
+  Bool      getIsDepth            ()               { return m_isDepth; }
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void      setUseDMM( Bool b) { m_bUseDMM = b;    }
+  Bool      getUseDMM()        { return m_bUseDMM; }
+#endif
+
+#if HHI_DMM_PRED_TEX && FLEX_CODING_ORDER_M23723
+  Void setUseDMM34( Bool b) { m_bUseDMM34 = b;    }
+  Bool getUseDMM34()        { return m_bUseDMM34; }
+#endif
+
+#if H3D_QTL
+  Void      setUseQTLPC( Bool b ) { m_bUseQTLPC = b;    }
+  Bool      getUseQTLPC()         { return m_bUseQTLPC; }
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  Bool      getUseDLT()      { return m_bUseDLT;     }
+  Bool      getUseSDC()      { return m_bUseSDC;     }
+#endif
+
+  Void      setViewOrderIdx       ( Int   i )      { m_iViewOrderIdx          = i; }
+  Void      setCamParPrecision              ( UInt  u )      { m_uiCamParPrecision      = u; }
+  Void      setCamParInSliceHeader          ( Bool  b )      { m_bCamParInSliceHeader   = b; }
+  Void      setCodedScale                   ( Int** p )      { m_aaiCodedScale          = p; }
+  Void      setCodedOffset                  ( Int** p )      { m_aaiCodedOffset         = p; }
+
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  Int       getViewOrderIdx                 ()      { return  m_iViewOrderIdx; }    // will be changed to view_id
+#endif
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCCFG_H__6B99B797_F4DA_4E46_8E78_7656339A6C41__INCLUDED_)
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCu.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCu.cpp	(revision 341)
@@ -0,0 +1,2899 @@
+/* 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-2012, 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     TEncCu.cpp
+    \brief    Coding Unit (CU) encoder class
+*/
+
+#include <stdio.h>
+#include "TEncTop.h"
+#include "TEncCu.h"
+#include "TEncAnalyze.h"
+
+#include <cmath>
+#include <algorithm>
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+/**
+ \param    uiTotalDepth  total number of allowable depth
+ \param    uiMaxWidth    largest CU width
+ \param    uiMaxHeight   largest CU height
+ */
+Void TEncCu::create(UChar uhTotalDepth, UInt uiMaxWidth, UInt uiMaxHeight)
+{
+  Int i;
+  
+  m_uhTotalDepth   = uhTotalDepth + 1;
+  m_ppcBestCU      = new TComDataCU*[m_uhTotalDepth-1];
+  m_ppcTempCU      = new TComDataCU*[m_uhTotalDepth-1];
+  
+  m_ppcPredYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcResiYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcRecoYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcPredYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcResiYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcRecoYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcOrigYuv     = new TComYuv*[m_uhTotalDepth-1];
+#if H3D_IVRP
+  m_ppcResPredTmp  = new TComYuv*[m_uhTotalDepth-1];
+#endif
+  
+#if HHI_MPI
+  m_puhDepthSaved  = new UChar[1ll<<( ( m_uhTotalDepth - 1 )<<1 )];
+  m_puhWidthSaved  = new UChar[1ll<<( ( m_uhTotalDepth - 1 )<<1 )];
+  m_puhHeightSaved = new UChar[1ll<<( ( m_uhTotalDepth - 1 )<<1 )];
+#endif
+
+  UInt uiNumPartitions;
+  for( i=0 ; i<m_uhTotalDepth-1 ; i++)
+  {
+    uiNumPartitions = 1<<( ( m_uhTotalDepth - i - 1 )<<1 );
+    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_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);
+#if H3D_IVRP
+    m_ppcResPredTmp [i] = new TComYuv; m_ppcResPredTmp [i]->create(uiWidth, uiHeight);
+#endif
+  }
+  
+  m_bEncodeDQP = false;
+  m_checkBurstIPCMFlag = false;
+
+  // 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 );
+  initMotionReferIdx ( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
+}
+
+Void TEncCu::destroy()
+{
+  Int i;
+  
+#if HHI_MPI
+  delete[] m_puhDepthSaved;  m_puhDepthSaved  = NULL;
+  delete[] m_puhWidthSaved;  m_puhWidthSaved  = NULL;
+  delete[] m_puhHeightSaved; m_puhHeightSaved = NULL;
+#endif
+  for( i=0 ; i<m_uhTotalDepth-1 ; i++)
+  {
+    if(m_ppcBestCU[i])
+    {
+      m_ppcBestCU[i]->destroy();      delete m_ppcBestCU[i];      m_ppcBestCU[i] = NULL;
+    }
+    if(m_ppcTempCU[i])
+    {
+      m_ppcTempCU[i]->destroy();      delete m_ppcTempCU[i];      m_ppcTempCU[i] = NULL;
+    }
+    if(m_ppcPredYuvBest[i])
+    {
+      m_ppcPredYuvBest[i]->destroy(); delete m_ppcPredYuvBest[i]; m_ppcPredYuvBest[i] = NULL;
+    }
+    if(m_ppcResiYuvBest[i])
+    {
+      m_ppcResiYuvBest[i]->destroy(); delete m_ppcResiYuvBest[i]; m_ppcResiYuvBest[i] = NULL;
+    }
+    if(m_ppcRecoYuvBest[i])
+    {
+      m_ppcRecoYuvBest[i]->destroy(); delete m_ppcRecoYuvBest[i]; m_ppcRecoYuvBest[i] = NULL;
+    }
+    if(m_ppcPredYuvTemp[i])
+    {
+      m_ppcPredYuvTemp[i]->destroy(); delete m_ppcPredYuvTemp[i]; m_ppcPredYuvTemp[i] = NULL;
+    }
+    if(m_ppcResiYuvTemp[i])
+    {
+      m_ppcResiYuvTemp[i]->destroy(); delete m_ppcResiYuvTemp[i]; m_ppcResiYuvTemp[i] = NULL;
+    }
+    if(m_ppcRecoYuvTemp[i])
+    {
+      m_ppcRecoYuvTemp[i]->destroy(); delete m_ppcRecoYuvTemp[i]; m_ppcRecoYuvTemp[i] = NULL;
+    }
+    if(m_ppcOrigYuv[i])
+    {
+      m_ppcOrigYuv[i]->destroy();     delete m_ppcOrigYuv[i];     m_ppcOrigYuv[i] = NULL;
+    }
+#if H3D_IVRP
+    if(m_ppcResPredTmp[i])
+    {
+      m_ppcResPredTmp [i]->destroy(); delete m_ppcResPredTmp[i];  m_ppcResPredTmp[i] = NULL;
+    }
+#endif
+  }
+  if(m_ppcBestCU)
+  {
+    delete [] m_ppcBestCU;
+    m_ppcBestCU = NULL;
+  }
+  if(m_ppcTempCU)
+  {
+    delete [] m_ppcTempCU;
+    m_ppcTempCU = NULL;
+  }
+  
+  if(m_ppcPredYuvBest)
+  {
+    delete [] m_ppcPredYuvBest;
+    m_ppcPredYuvBest = NULL;
+  }
+  if(m_ppcResiYuvBest)
+  {
+    delete [] m_ppcResiYuvBest;
+    m_ppcResiYuvBest = NULL;
+  }
+  if(m_ppcRecoYuvBest)
+  {
+    delete [] m_ppcRecoYuvBest;
+    m_ppcRecoYuvBest = NULL;
+  }
+  if(m_ppcPredYuvTemp)
+  {
+    delete [] m_ppcPredYuvTemp;
+    m_ppcPredYuvTemp = NULL;
+  }
+  if(m_ppcResiYuvTemp)
+  {
+    delete [] m_ppcResiYuvTemp;
+    m_ppcResiYuvTemp = NULL;
+  }
+  if(m_ppcRecoYuvTemp)
+  {
+    delete [] m_ppcRecoYuvTemp;
+    m_ppcRecoYuvTemp = NULL;
+  }
+  if(m_ppcOrigYuv)
+  {
+    delete [] m_ppcOrigYuv;
+    m_ppcOrigYuv = NULL;
+  }
+#if H3D_IVRP
+  if(m_ppcResPredTmp)
+  {
+    delete [] m_ppcResPredTmp;
+    m_ppcResPredTmp = NULL;
+  }
+#endif
+}
+
+/** \param    pcEncTop      pointer of encoder class
+ */
+Void TEncCu::init( TEncTop* pcEncTop )
+{
+  m_pcEncCfg           = pcEncTop;
+  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_bUseSBACRD        = pcEncTop->getUseSBACRD();
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  rpcCU pointer of CU data class
+ */
+Void TEncCu::compressCU( TComDataCU*& rpcCU )
+{
+  // initialize CU data
+  m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+  m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+
+  // analysis of CU
+  xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 );
+
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcEncCfg->getUseAdaptQpSelect() )
+  {
+    if(rpcCU->getSlice()->getSliceType()!=I_SLICE) //IIII
+    {
+      xLcuCollectARLStats( rpcCU);
+    }
+  }
+#endif
+}
+/** \param  pcCU  pointer of CU data class, bForceTerminate when set to true terminates slice (default is false).
+ */
+Void TEncCu::encodeCU ( TComDataCU* pcCU, Bool bForceTerminate )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    setdQPFlag(true);
+  }
+
+  TComPic* pcPic = pcCU->getPic();
+  Bool checkBurstIPCMFlag = (pcPic->getSlice(0)->getSPS()->getUsePCM())? true : false;
+
+  setCheckBurstIPCMFlag( checkBurstIPCMFlag );
+
+  pcCU->setNumSucIPCM(0);
+  pcCU->setLastCUSucIPCMFlag(false);
+
+  // Encode CU data
+  xEncodeCU( pcCU, 0, 0 );
+  
+  bool bTerminateSlice = bForceTerminate;
+  UInt uiCUAddr = pcCU->getAddr();
+    /* If at the end of an LCU line but not at the end of a substream, perform CABAC flush */
+    if (!bTerminateSlice && pcCU->getSlice()->getPPS()->getNumSubstreams() > 1)
+    {
+      Int iNumSubstreams = pcCU->getSlice()->getPPS()->getNumSubstreams();
+      UInt uiWidthInLCUs = pcCU->getPic()->getPicSym()->getFrameWidthInCU();
+      UInt uiCol     = uiCUAddr % uiWidthInLCUs;
+      UInt uiLin     = uiCUAddr / uiWidthInLCUs;
+      UInt uiTileStartLCU = pcCU->getPic()->getPicSym()->getTComTile(pcCU->getPic()->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+      UInt uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+      UInt uiTileLCUY = uiTileStartLCU / uiWidthInLCUs;
+      UInt uiTileWidth = pcCU->getPic()->getPicSym()->getTComTile(pcCU->getPic()->getPicSym()->getTileIdxMap(uiCUAddr))->getTileWidth();
+      UInt uiTileHeight = pcCU->getPic()->getPicSym()->getTComTile(pcCU->getPic()->getPicSym()->getTileIdxMap(uiCUAddr))->getTileHeight();
+      Int iNumSubstreamsPerTile = iNumSubstreams;
+      if (pcCU->getSlice()->getPPS()->getNumSubstreams() > 1)
+      {
+        iNumSubstreamsPerTile /= pcCU->getPic()->getPicSym()->getNumTiles();
+      }
+      if ((uiCol == uiTileLCUX+uiTileWidth-1) && (uiLin+iNumSubstreamsPerTile < uiTileLCUY+uiTileHeight))
+      {
+        m_pcEntropyCoder->encodeFlush();
+      }
+    }
+}
+
+// ====================================================================================================================
+// 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 
+*/
+#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)
+#endif
+{
+  if ( rpcBestCU->getPartitionSize(0) == SIZE_2NxN )
+  {
+    bTestAMP_Hor = true;
+  }
+  else if ( rpcBestCU->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;          
+  }
+
+#if AMP_MRG
+  //! 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 )
+    {
+      bTestMergeAMP_Hor = true;
+    }
+    else if ( rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+    {
+      bTestMergeAMP_Ver = true;
+    }
+  }
+
+  if ( rpcBestCU->getPartitionSize(0) == SIZE_2Nx2N && rpcBestCU->isSkipped(0) == false )
+  {
+    bTestMergeAMP_Hor = true;          
+    bTestMergeAMP_Ver = true;          
+  }
+
+  if ( rpcBestCU->getWidth(0) == 64 )
+  { 
+    bTestAMP_Hor = false;
+    bTestAMP_Ver = false;
+  }    
+#else
+  //! Utilizing the partition size of parent PU        
+  if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
+  { 
+    bTestAMP_Hor = true;
+    bTestAMP_Ver = true;
+  }
+
+  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
+*/
+#if AMP_ENC_SPEEDUP
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth, PartSize eParentPartSize )
+#else
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+#endif
+{
+  TComPic* pcPic = rpcBestCU->getPic();
+
+#if H3D_QTL
+  TComSPS *sps         = pcPic->getSlice(0)->getSPS();
+  TComPic *pcTexture   = rpcBestCU->getSlice()->getTexturePic();
+
+  Bool  depthMapDetect    = (pcTexture != NULL);
+  Bool  bIntraSliceDetect = (rpcBestCU->getSlice()->getSliceType() == I_SLICE);
+
+  Bool rapPic     = (rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA);
+
+  Bool bTry2NxN = true;
+  Bool bTryNx2N = true;
+#endif
+
+  // get Original YUV data from picture
+  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+
+  // variables for fast encoder decision
+  Bool    bEarlySkip  = false;
+  Bool    bTrySplit   = true;
+  Double  fRD_Skip    = MAX_DOUBLE;
+
+  // variable for Early CU determination
+  Bool    bSubBranch = true;
+
+  // variable for Cbf fast mode PU decision
+  Bool    doNotBlockPu = true;
+
+  Bool    bTrySplitDQP  = true;
+
+  static  Double  afCost [ MAX_CU_DEPTH ];
+  static  Int      aiNum [ MAX_CU_DEPTH ];
+
+  if ( rpcBestCU->getAddr() == 0 )
+  {
+    ::memset( afCost, 0, sizeof( afCost ) );
+    ::memset( aiNum,  0, sizeof( aiNum  ) );
+  }
+
+  Bool bBoundary = false;
+  UInt uiLPelX   = rpcBestCU->getCUPelX();
+  UInt uiRPelX   = uiLPelX + rpcBestCU->getWidth(0)  - 1;
+  UInt uiTPelY   = rpcBestCU->getCUPelY();
+  UInt uiBPelY   = uiTPelY + rpcBestCU->getHeight(0) - 1;
+
+#if LGE_ILLUCOMP_B0045
+  Bool bICEnabled = (
+#if !LGE_ILLUCOMP_DEPTH_C0046
+      !rpcTempCU->getSlice()->getIsDepth() && 
+#endif
+      rpcTempCU->getSlice()->getViewId());
+
+  bICEnabled = bICEnabled && rpcTempCU->getSlice()->getApplyIC();
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  Bool bFullyRenderedSec = true ;
+  if( m_pcEncCfg->getInterViewSkip() )
+  {
+    Pel* pUsedSamples ;
+    UInt uiStride ;
+    pUsedSamples =  pcPic->getUsedPelsMap()->getLumaAddr( rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+    uiStride = pcPic->getUsedPelsMap()->getStride();
+
+    for ( Int y=0; y<m_ppcOrigYuv[uiDepth]->getHeight(); y++)
+    {
+      for ( Int x=0; x<m_ppcOrigYuv[uiDepth]->getWidth(); x++)
+      {
+        if( pUsedSamples[x] !=0 )
+        {
+          bFullyRenderedSec = false ;
+          break ;
+        }
+      }
+      if ( !bFullyRenderedSec )
+      {
+        break;
+      }
+      pUsedSamples += uiStride ;
+    }
+  }
+  else
+  {
+    bFullyRenderedSec = false ;
+  }
+
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  if( bFullyRenderedSec )
+  {
+    m_pcRdCost->setLambdaScale( m_pcEncCfg->getInterViewSkipLambdaScale() );
+  }
+  else
+  {
+    m_pcRdCost->setLambdaScale( 1 );
+  }
+  rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+#endif
+
+#endif
+  Int iBaseQP = xComputeQP( rpcBestCU, uiDepth );
+  Int iMinQP;
+  Int iMaxQP;
+#if LOSSLESS_CODING
+  Bool isAddLowestQP = false;
+  Int lowestQP = -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY();
+#endif
+
+  if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    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 );
+#if LOSSLESS_CODING
+    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
+    {
+      isAddLowestQP = true; 
+      iMinQP = iMinQP - 1;
+
+    }
+#endif
+  }
+  else
+  {
+    iMinQP = rpcTempCU->getQP(0);
+    iMaxQP = rpcTempCU->getQP(0);
+  }
+
+  // If slice start or slice end is within this cu...
+  TComSlice * pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
+  Bool bSliceStart = pcSlice->getEntropySliceCurStartCUAddr()>rpcTempCU->getSCUAddr()&&pcSlice->getEntropySliceCurStartCUAddr()<rpcTempCU->getSCUAddr()+rpcTempCU->getTotalNumPart();
+  Bool bSliceEnd = (pcSlice->getEntropySliceCurEndCUAddr()>rpcTempCU->getSCUAddr()&&pcSlice->getEntropySliceCurEndCUAddr()<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 )
+  {
+    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+    {
+#if LOSSLESS_CODING
+      if (isAddLowestQP && (iQP == iMinQP))
+      {
+        iQP = lowestQP;
+      }
+#endif
+      // variables for fast encoder decision
+      bEarlySkip  = false;
+      bTrySplit   = true;
+      fRD_Skip    = MAX_DOUBLE;
+
+      rpcTempCU->initEstData( uiDepth, iQP );
+
+#if H3D_QTL
+      //logic for setting bTrySplit using the partition information that is stored of the texture colocated CU
+
+      if(depthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTLPC())
+      {
+        TComDataCU* pcTextureCU = pcTexture->getCU( rpcBestCU->getAddr() ); //Corresponding texture LCU
+        UInt uiCUIdx            = rpcBestCU->getZorderIdxInCU();
+        assert(pcTextureCU->getDepth(uiCUIdx) >= uiDepth); //Depth cannot be more partitionned than the texture.
+        if (pcTextureCU->getDepth(uiCUIdx) > uiDepth || pcTextureCU->getPartitionSize(uiCUIdx) == SIZE_NxN) //Texture was split.
+        {
+          bTrySplit = true;
+          bTryNx2N  = true;
+          bTry2NxN  = true;
+        }
+        else
+        {
+          bTrySplit = false;
+          bTryNx2N  = false;
+          bTry2NxN  = false;
+        }
+      }
+#endif
+
+      // do inter modes, SKIP and 2Nx2N
+      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+      {
+#if H3D_IVRP
+        Bool  bResPredAvailable   = false;
+        UInt uiResPrdId = 0; 
+        {
+          Bool bResPredFlag  = ( uiResPrdId > 0 );
+#if LGE_ILLUCOMP_B0045
+          for(UInt uiICId = 0; uiICId < (bICEnabled ? 2 : 1); uiICId++)
+          {
+            Bool bICFlag = (uiICId ? true : false);
+            rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#endif
+#if H3D_IVRP
+          rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+          // SKIP
+#if HHI_INTERVIEW_SKIP
+          xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, bFullyRenderedSec );
+#else
+          xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU );
+#endif
+          rpcTempCU->initEstData( uiDepth, iQP );
+
+          // fast encoder decision for early skip
+          if ( m_pcEncCfg->getUseFastEnc() )
+          {
+            Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
+            if ( aiNum [ iIdx ] > 5 && fRD_Skip < EARLY_SKIP_THRES*afCost[ iIdx ]/aiNum[ iIdx ] )
+            {
+              bEarlySkip = true;
+              bTrySplit  = false;
+            }
+          }
+#if LGE_ILLUCOMP_B0045
+          if(bICFlag && rpcBestCU->getMergeFlag(0) && !rpcBestCU->getICFlag(0))
+          {
+             bICEnabled = false;
+             break;
+          }
+#endif
+          // 2Nx2N, NxN
+          if ( !bEarlySkip )
+          {
+#if H3D_IVRP
+            rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+            rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFullyRenderedSec );
+
+#else
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+#endif
+            rpcTempCU->initEstData( uiDepth, iQP );
+            if(m_pcEncCfg->getUseCbfFastMode())
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+#if LGE_ILLUCOMP_B0045
+         }
+#endif
+#if H3D_IVRP
+        } // uiResPrdId
+#endif
+      } // != I_SLICE
+
+#if LGE_ILLUCOMP_B0045
+    bICEnabled = rpcBestCU->getICFlag(0);
+#endif
+
+#if H3D_QTL
+
+      if(depthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTLPC())
+      {
+        bTrySplitDQP = bTrySplit;
+      }
+      else
+      {
+#endif
+        if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+        {
+          if(iQP == iBaseQP)
+          {
+            bTrySplitDQP = bTrySplit;
+          }
+        }
+        else
+        {
+          bTrySplitDQP = bTrySplit;
+        }
+#if H3D_QTL
+      }
+#endif
+
+#if LOSSLESS_CODING
+      if (isAddLowestQP && (iQP == lowestQP))
+      {
+        iQP = iMinQP;
+      }
+#endif
+    }  // end for iMinQP to iMaxQP
+
+
+    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+    {
+#if LOSSLESS_CODING
+      if (isAddLowestQP && (iQP == iMinQP))
+      {
+        iQP = lowestQP;
+      }
+#endif
+      rpcTempCU->initEstData( uiDepth, iQP );
+
+      // do inter modes, NxN, 2NxN, and Nx2N
+      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+      {
+#if H3D_IVRP
+        Bool  bResPredAvailable   = false;
+        UInt uiResPrdId = 0; 
+        {
+          Bool bResPredFlag  = ( uiResPrdId > 0 );
+#if LGE_ILLUCOMP_B0045
+          for(UInt uiICId = 0; uiICId < (bICEnabled ? 2 : 1); uiICId++)
+          {
+            Bool bICFlag = (uiICId ? true : false);
+            rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#endif
+          // 2Nx2N, NxN
+          if ( !bEarlySkip )
+          {
+
+            if(!( rpcBestCU->getSlice()->getSPS()->getDisInter4x4()  && (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
+            {
+              if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && doNotBlockPu)
+              {
+#if H3D_QTL //try InterNxN
+                if(bTrySplit)
+                {
+#endif
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN, bFullyRenderedSec   );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+#if H3D_QTL
+                }
+#endif
+              } 
+            }
+          }
+
+          { // 2NxN, Nx2N
+#if H3D_QTL //try Nx2N
+            if(bTryNx2N)
+            {
+#endif
+              if(doNotBlockPu)
+              {
+#if H3D_IVRP
+                rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N, bFullyRenderedSec   );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N  );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+#if H3D_QTL
+            }
+#endif
+
+#if H3D_QTL //try 2NxN
+            if(bTry2NxN)
+            {
+#endif
+              if(doNotBlockPu)
+              {
+#if H3D_IVRP
+                rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxN, bFullyRenderedSec   );
+#else
+                xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN  );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxN)
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+#if H3D_QTL
+            }
+#endif
+          }
+
+#if 1
+          //! Try AMP (SIZE_2NxnU, SIZE_2NxnD, SIZE_nLx2N, SIZE_nRx2N)
+          if( pcPic->getSlice(0)->getSPS()->getAMPAcc(uiDepth) )
+          {
+#if AMP_ENC_SPEEDUP        
+            Bool bTestAMP_Hor = false, bTestAMP_Ver = false;
+
+#if AMP_MRG
+            Bool bTestMergeAMP_Hor = false, bTestMergeAMP_Ver = false;
+
+            deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver, bTestMergeAMP_Hor, bTestMergeAMP_Ver);
+#else
+            deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver);
+#endif
+
+            //! Do horizontal AMP
+            if ( bTestAMP_Hor )
+            {
+#if H3D_QTL //try 2NxnU & 2NxnD
+              if(bTry2NxN)
+              {
+#endif
+                if(doNotBlockPu)
+                {
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                  rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFullyRenderedSec );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                  if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+                  {
+                    doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                  }
+                }
+                if(doNotBlockPu)
+                {
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                  rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFullyRenderedSec );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                  if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
+                  {
+                    doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                  }
+                }
+#if H3D_QTL
+              }
+#endif
+            }
+#if AMP_MRG
+            else if ( bTestMergeAMP_Hor ) 
+            {
+#if H3D_QTL //try 2NxnU & 2NxnD Merge
+              if(bTry2NxN)
+              {
+#endif
+                if(doNotBlockPu)
+                {
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                  rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFullyRenderedSec, true );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, true );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                  if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+                  {
+                    doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                  }
+                }
+                if(doNotBlockPu)
+                {
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                  rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFullyRenderedSec, true );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, true );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                  if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
+                  {
+                    doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                  }
+                }
+#if H3D_QTL
+              }
+#endif
+            }
+#endif
+
+            //! Do horizontal AMP
+            if ( bTestAMP_Ver )
+            {
+#if H3D_QTL //try nLx2N & nRx2N
+              if(bTryNx2N)
+              {
+#endif
+                if(doNotBlockPu)
+                {
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                  rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFullyRenderedSec );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                  if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+                  {
+                    doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                  }
+                }
+                if(doNotBlockPu)
+                {
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                  rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFullyRenderedSec );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                }
+#if H3D_QTL
+              }
+#endif
+            }
+#if AMP_MRG
+            else if ( bTestMergeAMP_Ver )
+            {
+#if H3D_QTL //try nLx2N & nRx2N (Merge)
+              if(bTryNx2N)
+              {
+#endif
+                if(doNotBlockPu)
+                {
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                  rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFullyRenderedSec, true );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, true );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                  if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+                  {
+                    doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                  }
+                }
+                if(doNotBlockPu)
+                {
+#if H3D_IVRP
+                  rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if LGE_ILLUCOMP_B0045
+                  rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if HHI_INTERVIEW_SKIP
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFullyRenderedSec, true );
+#else
+                  xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, true );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                }
+#if H3D_QTL
+              }
+#endif
+            }
+#endif
+
+#else
+#if H3D_IVRP
+            rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFullyRenderedSec );
+#else
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+#endif
+            rpcTempCU->initEstData( uiDepth, iQP );
+#if H3D_IVRP
+            rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFullyRenderedSec );
+#else
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+#endif
+            rpcTempCU->initEstData( uiDepth, iQP );
+#if H3D_IVRP
+            rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFullyRenderedSec );
+#else
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+#endif
+            rpcTempCU->initEstData( uiDepth, iQP );
+#if H3D_IVRP
+            rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFullyRenderedSec );
+#else
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+#endif
+            rpcTempCU->initEstData( uiDepth, iQP );
+
+#endif
+          } //! Try AMP (SIZE_2NxnU, SIZE_2NxnD, SIZE_nLx2N, SIZE_nRx2N)
+#endif
+#if LGE_ILLUCOMP_B0045
+         }
+#endif
+#if H3D_IVRP
+        } // uiResPrdId
+#endif
+      } // != I_SLICE
+
+      // initialize PCM flag
+      rpcTempCU->setIPCMFlag( 0, false);
+      rpcTempCU->setIPCMFlagSubParts ( false, 0, uiDepth); //SUB_LCU_DQP
+
+      // do normal intra modes
+      if ( !bEarlySkip 
+#if HHI_DEPTH_INTRA_SEARCH_RAU_C0160
+        || ((rpcBestCU->getSlice()->getIsDepth() == true) && (rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+#endif
+        )
+      {
+        // speedup for inter frames
+#if HHI_INTERVIEW_SKIP
+        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 
+#if HHI_DEPTH_INTRA_SEARCH_RAU_C0160
+          || ((rpcBestCU->getSlice()->getIsDepth() == true) && (rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+#endif            
+          ) && !bFullyRenderedSec ) // avoid very complex intra if it is unlikely
+#else
+        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     
+#if HHI_DEPTH_INTRA_SEARCH_RAU_C0160
+          || ((rpcBestCU->getSlice()->getIsDepth() == true) && (rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+#endif     
+          ) // avoid very complex intra if it is unlikely
+#endif
+        {
+#if LGE_ILLUCOMP_B0045
+          rpcTempCU->setICFlagSubParts(false, 0, 0, uiDepth);
+#endif
+          xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+          rpcTempCU->initEstData( uiDepth, iQP );
+          if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+          {
+#if H3D_QTL //Try IntraNxN
+            if(bTrySplit)
+            {
+#endif
+              if( rpcTempCU->getWidth(0) > ( 1 << rpcTempCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() ) )
+              {
+#if LGE_ILLUCOMP_B0045
+                rpcTempCU->setICFlagSubParts(false, 0, 0, uiDepth);
+#endif
+                xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN   );
+                rpcTempCU->initEstData( uiDepth, iQP );
+              }
+#if H3D_QTL
+            }
+#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()) )
+      {
+        UInt uiRawBits = (g_uiBitDepth * rpcBestCU->getWidth(0) * rpcBestCU->getHeight(0) * 3 / 2);
+        UInt uiBestBits = rpcBestCU->getTotalBits();
+#if HHI_VSO
+        Double dRDCostTemp = m_pcRdCost->getUseVSO() ? 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
+        {
+#if LGE_ILLUCOMP_B0045
+          rpcTempCU->setICFlagSubParts(false, 0, 0, uiDepth);
+#endif
+          xCheckIntraPCM (rpcBestCU, rpcTempCU);
+          rpcTempCU->initEstData( uiDepth, iQP );
+        }
+      }
+#if HHI_MPI
+      if( rpcBestCU->getSlice()->getSPS()->getUseMVI() && rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+      {
+#if LGE_ILLUCOMP_DEPTH_C0046
+        for(UInt uiICId = 0; uiICId < (bICEnabled ? 2 : 1); uiICId++)
+        {
+          Bool bICFlag = (uiICId ? true : false);
+          rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+        xCheckRDCostMvInheritance( rpcBestCU, rpcTempCU, uiDepth, false, false );
+        rpcTempCU->initEstData( uiDepth, iQP );
+#if FIX_ILLUCOMP_DEPTH
+        rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+        xCheckRDCostMvInheritance( rpcBestCU, rpcTempCU, uiDepth, true, false );
+        rpcTempCU->initEstData( uiDepth, iQP );
+#if LGE_ILLUCOMP_DEPTH_C0046
+        }
+#endif
+      }
+#endif
+#if LOSSLESS_CODING
+      if (isAddLowestQP && (iQP == lowestQP))
+      {
+        iQP = iMinQP;
+      }
+#endif
+    }
+
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
+    rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+    if(m_pcEncCfg->getUseSBACRD())
+    {
+      rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+    }
+
+#if HHI_VSO    
+    if ( m_pcRdCost->getUseVSO() )
+    {
+      rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
+    }
+    else
+#endif
+    {
+      rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
+    }
+
+    // accumulate statistics for early skip
+    if ( m_pcEncCfg->getUseFastEnc() )
+    {
+      if ( rpcBestCU->isSkipped(0) )
+      {
+        Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
+        afCost[ iIdx ] += rpcBestCU->getTotalCost();
+        aiNum [ iIdx ] ++;
+      }
+    }
+
+    // Early CU determination
+    if( m_pcEncCfg->getUseEarlyCU() && ((*rpcBestCU->getPredictionMode()) == 0) )
+    {
+      bSubBranch = false;
+    }
+    else
+    {
+      bSubBranch = true;
+    }
+#if HHI_INTERVIEW_SKIP
+    rpcBestCU->setRenderableSubParts(bFullyRenderedSec,0,rpcBestCU->getDepth( 0 )) ;
+#endif
+  }
+  else if(!(bSliceEnd && bInsidePicture))
+  {
+    bBoundary = true;
+  }
+
+#if LOSSLESS_CODING 
+  // copy orginal YUV samples to PCM buffer
+  if( rpcBestCU->isLosslessCoded(0) && (rpcBestCU->getIPCMFlag(0) == false))
+  {
+    xFillPCMBuffer(rpcBestCU, m_ppcOrigYuv[uiDepth]);
+  }
+#endif
+  if( (g_uiMaxCUWidth>>uiDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    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 );
+#if LOSSLESS_CODING
+    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
+    {
+      isAddLowestQP = true;
+      iMinQP = iMinQP - 1;      
+    }
+#endif
+  }
+  else if( (g_uiMaxCUWidth>>uiDepth) > rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    iMinQP = iBaseQP;
+    iMaxQP = iBaseQP;
+  }
+  else
+  {
+    Int iStartQP;
+    if( pcPic->getCU( rpcTempCU->getAddr() )->getEntropySliceStartCU(rpcTempCU->getZorderIdxInCU()) == pcSlice->getEntropySliceCurStartCUAddr())
+    {
+      iStartQP = rpcTempCU->getQP(0);
+    }
+    else
+    {
+      UInt uiCurSliceStartPartIdx = pcSlice->getEntropySliceCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
+      iStartQP = rpcTempCU->getQP(uiCurSliceStartPartIdx);
+    }
+    iMinQP = iStartQP;
+    iMaxQP = iStartQP;
+  }
+
+  for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+  {
+#if LOSSLESS_CODING
+    if (isAddLowestQP && (iQP == iMinQP))
+    {
+      iQP = lowestQP;
+    }
+#endif
+    rpcTempCU->initEstData( uiDepth, iQP );
+
+    // further split
+    if( bSubBranch && bTrySplitDQP && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+#if HHI_VSO
+      // 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();
+        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];
+
+      for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
+      {
+        pcSubBestPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
+        pcSubTempPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
+
+        Bool bInSlice = pcSubBestPartCU->getSCUAddr()+pcSubBestPartCU->getTotalNumPart()>pcSlice->getEntropySliceCurStartCUAddr()&&pcSubBestPartCU->getSCUAddr()<pcSlice->getEntropySliceCurEndCUAddr();
+        if(bInSlice && ( pcSubBestPartCU->getCUPelX() < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+        {
+          if( m_bUseSBACRD )
+          {
+            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) )
+          {
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth, SIZE_NONE );
+          }
+          else
+          {
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth, rpcBestCU->getPartitionSize(0) );
+          }
+#else
+          xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth );
+#endif
+
+          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );         // Keep best part data to current temporary data.
+          xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
+
+#if HHI_VSO
+#endif
+        }
+        else if (bInSlice)
+        {
+          pcSubBestPartCU->copyToPic( uhNextDepth );
+          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );
+        }
+      }
+
+      if( !bBoundary )
+      {
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeSplitFlag( rpcTempCU, 0, uiDepth, true );
+
+        rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+        if(m_pcEncCfg->getUseSBACRD())
+        {
+          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+        }
+      }
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+      if( bFullyRenderedSec )
+      {
+        m_pcRdCost->setLambdaScale( m_pcEncCfg->getInterViewSkipLambdaScale() );
+      }
+      else
+      {
+        m_pcRdCost->setLambdaScale( 1 );
+      }
+#endif
+
+#if HHI_VSO
+      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())
+      {
+        Bool bHasRedisual = false;
+        for( UInt uiBlkIdx = 0; uiBlkIdx < rpcTempCU->getTotalNumPart(); uiBlkIdx ++)
+        {
+          if( ( pcPic->getCU( rpcTempCU->getAddr() )->getEntropySliceStartCU(uiBlkIdx+rpcTempCU->getZorderIdxInCU()) == rpcTempCU->getSlice()->getEntropySliceCurStartCUAddr() ) && 
+            ( rpcTempCU->getCbf( uiBlkIdx, TEXT_LUMA ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_U ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_V ) ) )
+          {
+            bHasRedisual = true;
+            break;
+          }
+        }
+
+        UInt uiTargetPartIdx;
+        if ( pcPic->getCU( rpcTempCU->getAddr() )->getEntropySliceStartCU(rpcTempCU->getZorderIdxInCU()) != pcSlice->getEntropySliceCurStartCUAddr() )
+        {
+          uiTargetPartIdx = pcSlice->getEntropySliceCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
+        }
+        else
+        {
+          uiTargetPartIdx = 0;
+        }
+        if ( bHasRedisual )
+        {
+#if !RDO_WITHOUT_DQP_BITS
+          m_pcEntropyCoder->resetBits();
+          m_pcEntropyCoder->encodeQP( rpcTempCU, uiTargetPartIdx, false );
+          rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+          if(m_pcEncCfg->getUseSBACRD())
+          {
+            rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+          }
+#if HHI_VSO
+          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
+        }
+        else
+        {
+#if LOSSLESS_CODING
+          if (((rpcTempCU->getQP(uiTargetPartIdx) != rpcTempCU->getRefQP(uiTargetPartIdx)) ) && (rpcTempCU->getSlice()->getSPS()->getUseLossless()))
+          {
+            rpcTempCU->getTotalCost() = MAX_DOUBLE;
+          }
+#endif
+          rpcTempCU->setQPSubParts( rpcTempCU->getRefQP( uiTargetPartIdx ), 0, uiDepth ); // set QP to default QP
+        }
+      }
+
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+      }
+      Bool bEntropyLimit=false;
+      Bool bSliceLimit=false;
+      bSliceLimit=rpcBestCU->getSlice()->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE&&(rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getSliceArgument()<<3);
+      if(rpcBestCU->getSlice()->getEntropySliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE&&m_pcEncCfg->getUseSBACRD())
+      {
+        if(rpcBestCU->getTotalBins()>rpcBestCU->getSlice()->getEntropySliceArgument())
+        {
+          bEntropyLimit=true;
+        }
+      }
+      else if(rpcBestCU->getSlice()->getEntropySliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE)
+      {
+        if(rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getEntropySliceArgument())
+        {
+          bEntropyLimit=true;
+        }
+      }
+      if(rpcBestCU->getDepth(0)>=rpcBestCU->getSlice()->getPPS()->getSliceGranularity())
+      {
+        bSliceLimit=false;
+        bEntropyLimit=false;
+      }
+      if(bSliceLimit||bEntropyLimit)
+      {
+        rpcBestCU->getTotalCost()=rpcTempCU->getTotalCost()+1;
+      }
+      xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth);                                  // RD compare current larger prediction
+    }                                                                                  // with sub partitioned prediction.
+#if LOSSLESS_CODING
+    if (isAddLowestQP && (iQP == lowestQP))
+    {
+      iQP = iMinQP;
+    }
+#endif
+  } // SPLIT- QP Loop
+
+#if HHI_VSO
+  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  ( );
+    m_pcRdCost->setRenModelData( rpcBestCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+  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))
+  {
+    return;
+  }
+
+  // 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 );
+}
+
+/** finish encoding a cu and handle end-of-slice conditions
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth 
+ * \returns Void
+ */
+Void TEncCu::finishCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComPic* pcPic = pcCU->getPic();
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+
+  //Calculate end address
+  UInt uiCUAddr = pcCU->getSCUAddr()+uiAbsPartIdx;
+
+  UInt uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getEntropySliceCurEndCUAddr()-1) % pcPic->getNumPartInCU();
+  UInt uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getEntropySliceCurEndCUAddr()-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>>(pcSlice->getPPS()->getSliceGranularity());
+  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 && (!(pcCU->getIPCMFlag(uiAbsPartIdx) && ( pcCU->getNumSucIPCM() > 1 ))))
+  {
+    // 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.
+  unsigned iGranularitySize = pcCU->getPic()->getNumPartInCU()>>(pcSlice->getPPS()->getSliceGranularity()<<1);
+  int iGranularityEnd = ((pcCU->getSCUAddr()+uiAbsPartIdx)/iGranularitySize)*iGranularitySize;
+  if(iGranularityEnd<=pcSlice->getEntropySliceCurStartCUAddr()) 
+  {
+    iGranularityEnd+=max(iGranularitySize,(pcCU->getPic()->getNumPartInCU()>>(uiDepth<<1)));
+  }
+  // Set slice end parameter
+  if(pcSlice->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE&&!pcSlice->getFinalized()&&pcSlice->getSliceBits()+numberOfWrittenBits>pcSlice->getSliceArgument()<<3) 
+  {
+    pcSlice->setEntropySliceCurEndCUAddr(iGranularityEnd);
+    pcSlice->setSliceCurEndCUAddr(iGranularityEnd);
+    return;
+  }
+  // Set entropy slice end parameter
+  if(m_pcEncCfg->getUseSBACRD()) 
+  {
+    TEncBinCABAC *pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+    UInt uiBinsCoded = pppcRDSbacCoder->getBinsCoded();
+    if(pcSlice->getEntropySliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE&&!pcSlice->getFinalized()&&pcSlice->getEntropySliceCounter()+uiBinsCoded>pcSlice->getEntropySliceArgument())
+    {
+      pcSlice->setEntropySliceCurEndCUAddr(iGranularityEnd);
+      return;
+    }
+  }
+  else
+  {
+    if(pcSlice->getEntropySliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE&&!pcSlice->getFinalized()&&pcSlice->getEntropySliceCounter()+numberOfWrittenBits>pcSlice->getEntropySliceArgument()) 
+    {
+      pcSlice->setEntropySliceCurEndCUAddr(iGranularityEnd);
+      return;
+    }
+  }
+  if(granularityBoundary)
+  {
+    pcSlice->setSliceBits( (UInt)(pcSlice->getSliceBits() + numberOfWrittenBits) );
+    if(m_pcEncCfg->getUseSBACRD()) 
+    {
+      TEncBinCABAC *pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+      pcSlice->setEntropySliceCounter(pcSlice->getEntropySliceCounter()+pppcRDSbacCoder->getBinsCoded());
+      pppcRDSbacCoder->setBinsCoded( 0 );
+    }
+    else 
+    {
+      pcSlice->setEntropySliceCounter(pcSlice->getEntropySliceCounter()+numberOfWrittenBits);
+    }
+    if (m_pcBitCounter)
+    {
+      m_pcEntropyCoder->resetBits();      
+    }
+  }
+}
+
+/** Compute QP for each CU
+ * \param pcCU Target CU
+ * \param uiDepth CU depth
+ * \returns quantization parameter
+ */
+Int TEncCu::xComputeQP( TComDataCU* pcCU, UInt uiDepth )
+{
+  Int iBaseQp = pcCU->getSlice()->getSliceQp();
+  Int iQpOffset = 0;
+  if ( m_pcEncCfg->getUseAdaptiveQP() )
+  {
+    TEncPic* pcEPic = dynamic_cast<TEncPic*>( pcCU->getPic() );
+    UInt uiAQDepth = min( uiDepth, pcEPic->getMaxAQDepth()-1 );
+    TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer( uiAQDepth );
+    UInt uiAQUPosX = pcCU->getCUPelX() / pcAQLayer->getAQPartWidth();
+    UInt uiAQUPosY = pcCU->getCUPelY() / pcAQLayer->getAQPartHeight();
+    UInt uiAQUStride = pcAQLayer->getAQPartStride();
+    TEncQPAdaptationUnit* acAQU = pcAQLayer->getQPAdaptationUnit();
+
+    Double dMaxQScale = pow(2.0, m_pcEncCfg->getQPAdaptationRange()/6.0);
+    Double dAvgAct = pcAQLayer->getAvgActivity();
+    Double dCUAct = acAQU[uiAQUPosY * uiAQUStride + uiAQUPosX].getActivity();
+    Double dNormAct = (dMaxQScale*dCUAct + dAvgAct) / (dCUAct + dMaxQScale*dAvgAct);
+    Double dQpOffset = log(dNormAct) / log(2.0) * 6.0;
+    iQpOffset = Int(floor( dQpOffset + 0.49999 ));
+  }
+  return Clip3(-pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQp+iQpOffset );
+}
+
+/** encode a CU block recursively
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \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;
+  
+  if( getCheckBurstIPCMFlag() )
+  {
+    pcCU->setLastCUSucIPCMFlag( checkLastCUSucIPCM( pcCU, uiAbsPartIdx ));
+    pcCU->setNumSucIPCM( countNumSucIPCM ( pcCU, uiAbsPartIdx ) );
+  }
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  // If slice start is within this cu...
+  Bool bSliceStart = pcSlice->getEntropySliceCurStartCUAddr() > pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getEntropySliceCurStartCUAddr() < 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 HHI_MPI
+    if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 || uiDepth < pcCU->getTextureModeDepth( uiAbsPartIdx ) )
+    {
+#endif
+
+    m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+
+#if HHI_MPI
+    }
+#endif
+  }
+  else
+  {
+    bBoundary = true;
+  }
+  
+#if HHI_MPI
+  if( uiDepth == pcCU->getTextureModeDepth( uiAbsPartIdx ) )
+  {
+    xSaveDepthWidthHeight( pcCU );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+
+    if( ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+    {
+      m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+    }
+
+    if( !pcCU->getSlice()->isIntra() )
+    {
+      m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
+    }
+
+    if( pcCU->isSkipped( uiAbsPartIdx ) )
+    {
+      m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx, 0 );
+#if LGE_ILLUCOMP_DEPTH_C0046
+      m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx, false, uiDepth );
+#endif
+      finishCU(pcCU,uiAbsPartIdx,uiDepth);
+      xRestoreDepthWidthHeight( pcCU );
+      return;
+    }
+
+    m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
+
+    m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+
+    // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
+    m_pcEntropyCoder->encodePredInfo( pcCU, uiAbsPartIdx );
+#if LGE_ILLUCOMP_DEPTH_C0046
+    m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx, false, uiDepth );
+#endif
+    xRestoreDepthWidthHeight( pcCU );
+  }
+#endif
+
+  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())
+    {
+      setdQPFlag(true);
+    }
+    pcCU->setNumSucIPCM(0);
+    pcCU->setLastCUSucIPCMFlag(false);
+    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->getEntropySliceCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getEntropySliceCurEndCUAddr();
+      if(bInSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xEncodeCU( pcCU, uiAbsPartIdx, uiDepth+1 );
+      }
+    }
+    return;
+  }
+  
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    setdQPFlag(true);
+  }
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 )
+{
+#endif
+  if( !pcCU->getSlice()->isIntra() )
+  {
+    m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
+  }
+#if HHI_MPI
+}
+#endif
+  
+  if( pcCU->isSkipped( uiAbsPartIdx ) )
+  {
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx, 0 );
+#if LGE_ILLUCOMP_B0045
+    m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx
+#if LGE_ILLUCOMP_DEPTH_C0046
+        , false, uiDepth
+#endif
+        );
+#endif
+    finishCU(pcCU,uiAbsPartIdx,uiDepth);
+    return;
+  }
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 )
+  {
+#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))
+    {
+      // Encode slice finish
+      finishCU(pcCU,uiAbsPartIdx,uiDepth);
+      return;
+    }
+  }
+
+  // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
+  m_pcEntropyCoder->encodePredInfo( pcCU, uiAbsPartIdx );
+#if LGE_ILLUCOMP_B0045
+    m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx
+#if LGE_ILLUCOMP_DEPTH_C0046
+        ,false, uiDepth
+#endif
+        );
+#endif
+#if HHI_MPI
+  }
+#endif
+  
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, pcCU->getWidth (uiAbsPartIdx), pcCU->getHeight(uiAbsPartIdx), bCodeDQP );
+  setdQPFlag( bCodeDQP );
+
+  // --- write terminating bit ---
+  finishCU(pcCU,uiAbsPartIdx,uiDepth);
+}
+
+/** check RD costs for a CU block encoded with merge
+ * \param rpcBestCU
+ * \param rpcTempCU
+ * \returns Void
+ */
+#if HHI_INTERVIEW_SKIP
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool bSkipRes )
+#else
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
+#endif
+{
+  assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
+#if H3D_IVMP
+  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+#else
+  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+#endif
+  Int numValidMergeCand = 0;
+
+#if LGE_ILLUCOMP_B0045
+  Bool  bICFlag = rpcTempCU->getICFlag(0);
+#endif
+
+#if H3D_IVMP
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS_MEM; ++ui )
+#else
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+#endif
+  {
+    uhInterDirNeighbours[ui] = 0;
+  }
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+
+#if HHI_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();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+#if MERL_VSP_C0152
+  Int iVSPIndexTrue[3] = {-1, -1, -1};
+  rpcTempCU->getInterMergeCandidates( 0, 0, uhDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, iVSPIndexTrue );
+#else
+  rpcTempCU->getInterMergeCandidates( 0, 0, uhDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+#endif
+#if H3D_IVRP
+  Bool bResPredAvail = rpcTempCU->getResPredAvail(0);
+#endif
+
+  Bool bestIsSkip = false;
+  
+  for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+  {
+    {
+      TComYuv* pcPredYuvTemp = NULL;
+#if LOSSLESS_CODING
+      UInt iteration;
+      if ( rpcTempCU->isLosslessCoded(0))
+      {
+        iteration = 1;
+      }
+      else 
+      {
+        iteration = 2;
+      }
+
+#if HHI_INTERVIEW_SKIP
+    for( UInt uiNoResidual = (bSkipRes ? 1:0); uiNoResidual < iteration; ++uiNoResidual )
+#else
+      for( UInt uiNoResidual = 0; uiNoResidual < iteration; ++uiNoResidual )
+#endif
+#else
+#if HHI_INTERVIEW_SKIP
+    for( UInt uiNoResidual = (bSkipRes ? 1:0); uiNoResidual < 2; ++uiNoResidual )
+#else
+      for( UInt uiNoResidual = 0; uiNoResidual < 2; ++uiNoResidual )
+#endif
+#endif
+      {
+        if( !(bestIsSkip && uiNoResidual == 0) )
+        {
+          // set MC parameters
+          rpcTempCU->setPredModeSubParts( MODE_SKIP, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to LCU level
+#if MERL_VSP_C0152
+          {
+            Int iVSPIdx = 0;
+            Int numVSPIdx;
+            numVSPIdx = 3;
+            for (Int i = 0; i < numVSPIdx; i++)
+            {
+              if (iVSPIndexTrue[i] == uiMergeCand)
+                {
+                  iVSPIdx = i+1;
+                  break;
+                }
+            }
+            rpcTempCU->setVSPIndexSubParts( iVSPIdx, 0, 0, uhDepth );
+          }
+#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
+
+#if H3D_IVRP
+          rpcTempCU->setResPredAvailSubParts(bResPredAvail, 0, 0, uhDepth);
+#endif
+#if LGE_ILLUCOMP_B0045
+          rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uhDepth);
+#endif
+
+          // do MC
+#if HHI_INTERVIEW_SKIP
+      if ( (uiNoResidual == 0) || bSkipRes )
+#else
+      if ( uiNoResidual == 0 )
+#endif
+        {
+#if MERL_VSP_C0152
+            m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth],  rpcTempCU->getZorderIdxInCU() );
+#else
+            m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+#endif
+#if H3D_IVRP
+            if (uiMergeCand == 0 && rpcTempCU->getResPredAvail(0))
+            {
+              m_pcPredSearch->residualPrediction(rpcTempCU, m_ppcPredYuvTemp[uhDepth], m_ppcResPredTmp [uhDepth]);
+            }
+#endif
+            // save pred adress
+            pcPredYuvTemp = m_ppcPredYuvTemp[uhDepth];
+
+          }
+          else
+          {
+            if( bestIsSkip)
+            {
+#if MERL_VSP_C0152
+              m_pcPredSearch->motionCompensation( rpcTempCU, m_ppcPredYuvTemp[uhDepth], rpcTempCU->getZorderIdxInCU() );
+#else
+              m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+#endif
+#if H3D_IVRP
+              if (uiMergeCand == 0 && rpcTempCU->getResPredAvail(0))
+              {
+                m_pcPredSearch->residualPrediction(rpcTempCU, m_ppcPredYuvTemp[uhDepth], m_ppcResPredTmp [uhDepth]);
+              }
+#endif
+              // save pred adress
+              pcPredYuvTemp = m_ppcPredYuvTemp[uhDepth];
+            }
+            else
+            {
+              if ( pcPredYuvTemp != m_ppcPredYuvTemp[uhDepth])
+              {
+                //adress changes take best (old temp)
+                pcPredYuvTemp = m_ppcPredYuvBest[uhDepth];
+              }
+            }
+          }
+#if HHI_VSO
+          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   ();
+            m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+          }
+#endif
+          // estimate residual and encode everything
+          m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+            m_ppcOrigYuv    [uhDepth],
+            pcPredYuvTemp,
+            m_ppcResiYuvTemp[uhDepth],
+            m_ppcResiYuvBest[uhDepth],
+            m_ppcRecoYuvTemp[uhDepth],
+#if H3D_IVRP
+                                                     m_ppcResPredTmp [uhDepth],
+#endif
+            (uiNoResidual? true:false) );     
+          Bool bQtRootCbf = rpcTempCU->getQtRootCbf(0) == 1;
+
+          Int orgQP = rpcTempCU->getQP( 0 );
+          xCheckDQP( rpcTempCU );
+          xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+          rpcTempCU->initEstData( uhDepth, orgQP );
+
+          if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
+          {
+            bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
+          }
+
+          if (!bQtRootCbf)
+            break;
+        }
+      }
+    }
+  }
+}
+
+#if AMP_MRG
+#if HHI_INTERVIEW_SKIP
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bSkipRes, Bool bUseMRG)
+#else
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG)
+#endif
+#else
+#if HHI_INTERVIEW_SKIP
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bSkipRes)
+#else
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize )
+#endif
+#endif
+{
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  
+#if HHI_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();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif  
+
+  rpcTempCU->setDepthSubParts( uhDepth, 0 );
+  
+#if H3D_IVRP
+  Bool  bResPrdAvail  = rpcTempCU->getResPredAvail( 0 );
+  Bool  bResPrdFlag   = rpcTempCU->getResPredFlag ( 0 );
+#endif
+  
+  rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
+
+#if H3D_IVRP
+  rpcTempCU->setResPredAvailSubParts( bResPrdAvail, 0, 0, uhDepth );
+  rpcTempCU->setResPredFlagSubParts ( bResPrdFlag,  0, 0, uhDepth );
+#endif
+  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+
+#if AMP_MRG
+  rpcTempCU->setMergeAMP (true);
+  #if HHI_INTERVIEW_SKIP
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], bSkipRes, bUseMRG  );
+#else
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], false, bUseMRG );
+#endif
+#else
+  #if HHI_INTERVIEW_SKIP
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], bSkipRes );
+#else  
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
+#endif
+#endif
+
+#if AMP_MRG
+  if ( !rpcTempCU->getMergeAMP() )
+  {
+    return;
+  }
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+                                             m_ppcOrigYuv[uhDepth],
+                                             m_ppcPredYuvTemp[uhDepth],
+                                             m_ppcResiYuvTemp[uhDepth],
+                                             m_ppcResiYuvBest[uhDepth],
+                                             m_ppcRecoYuvTemp[uhDepth],
+#if H3D_IVRP
+                                             m_ppcResPredTmp [uhDepth],
+#endif
+                                             bSkipRes );
+#else
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+                                             m_ppcOrigYuv[uhDepth],
+                                             m_ppcPredYuvTemp[uhDepth],
+                                             m_ppcResiYuvTemp[uhDepth],
+                                             m_ppcResiYuvBest[uhDepth],
+                                             m_ppcRecoYuvTemp[uhDepth],
+#if H3D_IVRP
+                                             m_ppcResPredTmp [uhDepth],
+#endif
+                                             false );
+#endif
+#if HHI_VSO
+  if( m_pcRdCost->getUseLambdaScaleVSO() )
+  {
+    rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  }
+  else
+#endif
+  {
+  rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  }
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+}
+
+Void TEncCu::xCheckRDCostIntra( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize )
+{
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+  
+#if HHI_VSO
+  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  ();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+  rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+  
+  Bool bSeparateLumaChroma = true; // choose estimation mode
+  Dist uiPreCalcDistC      = 0;
+  if( !bSeparateLumaChroma )
+  {
+    m_pcPredSearch->preestChromaPredMode( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth] );
+  }
+  m_pcPredSearch  ->estIntraPredQT      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, bSeparateLumaChroma );
+
+  m_ppcRecoYuvTemp[uiDepth]->copyToPicLuma(rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getAddr(), rpcTempCU->getZorderIdxInCU() );
+  
+#if RWTH_SDC_DLT_B0036
+  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();
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+  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 );
+
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, rpcTempCU->getWidth (0), rpcTempCU->getHeight(0), bCodeDQP );
+  setdQPFlag( bCodeDQP );
+  
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  if(m_pcEncCfg->getUseSBACRD())
+  {
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  }
+#if HHI_VSO
+  if( m_pcRdCost->getUseLambdaScaleVSO())
+  {
+    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  }
+  else
+#endif
+  {
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  }
+  
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth);
+}
+
+/** 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.
+ */
+Void TEncCu::xCheckIntraPCM( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
+{
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+
+  rpcTempCU->setIPCMFlag(0, true);
+  rpcTempCU->setIPCMFlagSubParts (true, 0, rpcTempCU->getDepth(0));
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+
+  m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
+
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
+  m_pcEntropyCoder->resetBits();
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePredMode ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize ( rpcTempCU, 0, uiDepth, true );
+  m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
+
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  if(m_pcEncCfg->getUseSBACRD())
+  {
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  }
+#if HHI_VSO
+  if ( m_pcRdCost->getUseVSO() )
+  {
+    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  }
+  else
+#endif
+  {  
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  }
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth );
+}
+
+// check whether current try is the best
+Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
+{
+  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
+  {
+    TComYuv* pcYuv;
+    UChar uhDepth = rpcBestCU->getDepth(0);
+
+    // Change Information data
+    TComDataCU* pcCU = rpcBestCU;
+    rpcBestCU = rpcTempCU;
+    rpcTempCU = pcCU;
+    
+    // Change Prediction data
+    pcYuv = m_ppcPredYuvBest[uhDepth];
+    m_ppcPredYuvBest[uhDepth] = m_ppcPredYuvTemp[uhDepth];
+    m_ppcPredYuvTemp[uhDepth] = pcYuv;
+    
+    // Change Reconstruction data
+    pcYuv = m_ppcRecoYuvBest[uhDepth];
+    m_ppcRecoYuvBest[uhDepth] = m_ppcRecoYuvTemp[uhDepth];
+    m_ppcRecoYuvTemp[uhDepth] = pcYuv;
+    
+    pcYuv = NULL;
+    pcCU  = NULL;
+    
+    if( m_bUseSBACRD )  // store temp best CI for next CU coding
+      m_pppcRDSbacCoder[uhDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uhDepth][CI_NEXT_BEST]);
+  }
+}
+
+/** check whether current try is the best with identifying the depth of current try
+ * \param rpcBestCU
+ * \param rpcTempCU
+ * \returns Void
+ */
+Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+{
+  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
+  {
+    TComYuv* pcYuv;
+    // Change Information data
+    TComDataCU* pcCU = rpcBestCU;
+    rpcBestCU = rpcTempCU;
+    rpcTempCU = pcCU;
+
+    // Change Prediction data
+    pcYuv = m_ppcPredYuvBest[uiDepth];
+    m_ppcPredYuvBest[uiDepth] = m_ppcPredYuvTemp[uiDepth];
+    m_ppcPredYuvTemp[uiDepth] = pcYuv;
+
+    // Change Reconstruction data
+    pcYuv = m_ppcRecoYuvBest[uiDepth];
+    m_ppcRecoYuvBest[uiDepth] = m_ppcRecoYuvTemp[uiDepth];
+    m_ppcRecoYuvTemp[uiDepth] = pcYuv;
+
+    pcYuv = NULL;
+    pcCU  = NULL;
+
+    if( m_bUseSBACRD )  // store temp best CI for next CU coding
+      m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
+  }
+}
+
+Void TEncCu::xCheckDQP( TComDataCU* pcCU )
+{
+  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
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeQP( pcCU, 0, false );
+      pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+      if(m_pcEncCfg->getUseSBACRD())
+      {
+        pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+      }
+
+      // GT: Change here??
+#if HHI_VSO
+      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
+    }
+    else
+    {
+#if LOSSLESS_CODING
+      if ((  ( pcCU->getRefQP( 0 ) != pcCU->getQP( 0 )) ) && (pcCU->getSlice()->getSPS()->getUseLossless()))
+      {
+        pcCU->getTotalCost() = MAX_DOUBLE;
+      }
+#endif
+      pcCU->setQPSubParts( pcCU->getRefQP( 0 ), 0, uiDepth ); // set QP to default QP
+    }
+  }
+}
+
+/** Check whether the last CU shares the same root as the current CU and is IPCM or not.  
+ * \param pcCU
+ * \param uiCurAbsPartIdx
+ * \returns Bool
+ */
+Bool TEncCu::checkLastCUSucIPCM( TComDataCU* pcCU, UInt uiCurAbsPartIdx )
+{
+  Bool lastCUSucIPCMFlag = false;
+
+  UInt curDepth = pcCU->getDepth(uiCurAbsPartIdx);
+  UInt shift = ((pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx())->getSPS()->getMaxCUDepth() - curDepth)<<1);
+  UInt startPartUnitIdx = ((uiCurAbsPartIdx&(0x03<<shift))>>shift);
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  if( pcSlice->getEntropySliceCurStartCUAddr() == ( pcCU->getSCUAddr() + uiCurAbsPartIdx ) )
+  {
+    return false;
+  }
+
+  if(curDepth > 0 && startPartUnitIdx > 0)
+  {
+    Int lastValidPartIdx = pcCU->getLastValidPartIdx((Int) uiCurAbsPartIdx );
+
+    if( lastValidPartIdx >= 0 )
+    {
+      if(( pcCU->getSliceStartCU( uiCurAbsPartIdx ) == pcCU->getSliceStartCU( (UInt) lastValidPartIdx ))
+        && 
+        ( pcCU->getDepth( uiCurAbsPartIdx ) == pcCU->getDepth( (UInt) lastValidPartIdx )) 
+        && 
+        pcCU->getIPCMFlag( (UInt) lastValidPartIdx ) )
+      {
+        lastCUSucIPCMFlag = true;
+      }
+    }
+  }
+
+  return  lastCUSucIPCMFlag;
+}
+
+/** Count the number of successive IPCM CUs sharing the same root.
+ * \param pcCU
+ * \param uiCurAbsPartIdx
+ * \returns Int
+ */
+Int TEncCu::countNumSucIPCM ( TComDataCU* pcCU, UInt uiCurAbsPartIdx )
+{
+  Int numSucIPCM = 0;
+  UInt CurDepth = pcCU->getDepth(uiCurAbsPartIdx);
+
+  if( pcCU->getIPCMFlag(uiCurAbsPartIdx) )
+  {
+    if(CurDepth == 0)
+    {
+       numSucIPCM = 1;
+    }
+    else 
+    {
+      TComPic* pcPic = pcCU->getPic();
+      TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+      UInt qNumParts = ( pcPic->getNumPartInCU() >> ((CurDepth-1)<<1) )>>2;
+
+      Bool continueFlag = true;
+      UInt absPartIdx = uiCurAbsPartIdx;
+      UInt shift = ((pcSlice->getSPS()->getMaxCUDepth() - CurDepth)<<1);
+      UInt startPartUnitIdx = ((uiCurAbsPartIdx&(0x03<<shift))>>shift);
+
+      for ( UInt partUnitIdx = startPartUnitIdx; partUnitIdx < 4 && continueFlag; partUnitIdx++, absPartIdx+=qNumParts )
+      {
+        UInt lPelX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[absPartIdx] ];
+        UInt tPelY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[absPartIdx] ];
+        Bool inSliceFlag = ( pcCU->getSCUAddr()+absPartIdx+qNumParts>pcSlice->getEntropySliceCurStartCUAddr() ) && ( pcCU->getSCUAddr()+absPartIdx < pcSlice->getEntropySliceCurEndCUAddr());
+
+        if( inSliceFlag && ( lPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( tPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+        {
+          UInt uiDepth = pcCU->getDepth(absPartIdx);
+
+          if( ( CurDepth == uiDepth) && pcCU->getIPCMFlag( absPartIdx ) )
+          {
+            numSucIPCM++;
+          }
+          else
+          {
+            continueFlag = false;
+          }
+        }
+      }
+    }
+  }
+
+  return numSucIPCM;
+}
+
+Void TEncCu::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
+{
+  pDst->iN = pSrc->iN;
+  for (Int i = 0; i < pSrc->iN; i++)
+  {
+    pDst->m_acMvCand[i] = pSrc->m_acMvCand[i];
+  }
+}
+Void TEncCu::xCopyYuv2Pic(TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth, TComDataCU* pcCU, UInt uiLPelX, UInt uiTPelY )
+{
+  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->getEntropySliceCurStartCUAddr() > rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getEntropySliceCurStartCUAddr() < rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) );
+  Bool bSliceEnd   = pcSlice->getEntropySliceCurEndCUAddr() > rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getEntropySliceCurEndCUAddr() < 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->getEntropySliceCurStartCUAddr() && 
+        rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx < pcSlice->getEntropySliceCurEndCUAddr();
+      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
+      }
+    }
+  }
+}
+
+Void TEncCu::xCopyYuv2Tmp( UInt uiPartUnitIdx, UInt uiNextDepth )
+{
+  UInt uiCurrDepth = uiNextDepth - 1;
+  m_ppcRecoYuvBest[uiNextDepth]->copyToPartYuv( m_ppcRecoYuvTemp[uiCurrDepth], uiPartUnitIdx );
+}
+
+#if LOSSLESS_CODING 
+/** 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
+ */
+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;
+  }
+}
+#endif
+
+#if ADAPTIVE_QP_SELECTION
+/** Collect ARL statistics from one block
+  */
+Int TEncCu::xTuCollectARLStats(TCoeff* rpcCoeff, Int* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples )
+{
+  for( Int n = 0; n < NumCoeffInCU; n++ )
+  {
+    Int u = abs( rpcCoeff[ n ] );
+    Int absc = rpcArlCoeff[ n ];
+
+    if( u != 0 )
+    {
+      if( u < LEVEL_RANGE )
+      {
+        cSum[ u ] += ( Double )absc;
+        numSamples[ u ]++;
+      }
+      else 
+      {
+        cSum[ LEVEL_RANGE ] += ( Double )absc - ( Double )( u << ARL_C_PRECISION );
+        numSamples[ LEVEL_RANGE ]++;
+      }
+    }
+  }
+
+  return 0;
+}
+
+/** Collect ARL statistics from one LCU
+ * \param pcCU
+ */
+Void TEncCu::xLcuCollectARLStats(TComDataCU* rpcCU )
+{
+  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;
+
+  memset( cSum, 0, sizeof( Double )*(LEVEL_RANGE+1) );
+  memset( numSamples, 0, sizeof( UInt )*(LEVEL_RANGE+1) );
+
+  // 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 ) )
+    {
+      xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
+    }//Note that only InterY is processed. QP rounding is based on InterY data only.
+   
+    pCoeffY  += uiMinNumCoeffInCU;
+    pArlCoeffY  += uiMinNumCoeffInCU;
+  }
+
+  for(Int u=1; u<LEVEL_RANGE;u++)
+  {
+    m_pcTrQuant->getSliceSumC()[u] += cSum[ u ] ;
+    m_pcTrQuant->getSliceNSamples()[u] += numSamples[ u ] ;
+  }
+  m_pcTrQuant->getSliceSumC()[LEVEL_RANGE] += cSum[ LEVEL_RANGE ] ;
+  m_pcTrQuant->getSliceNSamples()[LEVEL_RANGE] += numSamples[ LEVEL_RANGE ] ;
+}
+#endif
+
+#if HHI_MPI
+Void TEncCu::xCheckRDCostMvInheritance( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UChar uhTextureModeDepth, Bool bSkipResidual, Bool bRecursiveCall )
+{
+  assert( rpcTempCU->getSlice()->getIsDepth() );
+  TComDataCU *pcTextureCU = rpcTempCU->getSlice()->getTexturePic()->getCU( rpcTempCU->getAddr() );
+
+  const UChar uhDepth  = rpcTempCU->getDepth( 0 );
+  const Int   iQP      = rpcTempCU->getQP( 0 );
+  assert( bRecursiveCall == ( uhDepth != uhTextureModeDepth ) );
+
+#if !MTK_UNCONSTRAINED_MVI_B0083
+  if( uhDepth == uhTextureModeDepth )
+  {
+    for( UInt ui = 0; ui < rpcTempCU->getTotalNumPart(); ui++ )
+    {
+      if( pcTextureCU->isIntra( rpcTempCU->getZorderIdxInCU() + ui ) )
+      {
+        return;
+      }
+    }
+  }
+#endif
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseRenModel() && !bRecursiveCall)
+  {
+    UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth   ();
+    UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight  ();
+    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr();
+    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride  ();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+  Bool bSplit = uhDepth < pcTextureCU->getDepth( rpcTempCU->getZorderIdxInCU() );
+  if( bSplit )
+  {
+    const UChar       uhNextDepth   = uhDepth+1;
+    TComDataCU* pcSubBestPartCU     = m_ppcBestCU[uhNextDepth];
+    TComDataCU* pcSubTempPartCU     = m_ppcTempCU[uhNextDepth];
+
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
+    {
+      pcSubBestPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
+      pcSubTempPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
+
+      TComSlice * pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
+      Bool bInSlice = pcSubBestPartCU->getSCUAddr()+pcSubBestPartCU->getTotalNumPart()>pcSlice->getEntropySliceCurStartCUAddr()&&pcSubBestPartCU->getSCUAddr()<pcSlice->getEntropySliceCurEndCUAddr();
+      if(bInSlice && ( pcSubBestPartCU->getCUPelX() < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        if( m_bUseSBACRD )
+        {
+          if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
+          {
+            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhDepth][CI_CURR_BEST]);
+          }
+          else
+          {
+            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+          }
+        }
+
+        xCheckRDCostMvInheritance( pcSubBestPartCU, pcSubTempPartCU, uhTextureModeDepth, bSkipResidual, true );
+
+        rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );         // Keep best part data to current temporary data.
+        xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
+      }
+      else if (bInSlice)
+      {
+        pcSubBestPartCU->copyToPic( uhNextDepth );
+        rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );
+      }
+    }
+
+    if( uhDepth == uhTextureModeDepth )
+    {
+      xAddMVISignallingBits( rpcTempCU );
+    }
+
+    // DQP stuff
+    {
+      if( (g_uiMaxCUWidth>>uhDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() && rpcTempCU->getSlice()->getPPS()->getUseDQP())
+      {
+        TComPic *pcPic = rpcTempCU->getPic();
+        TComSlice *pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
+        Bool bHasRedisual = false;
+        for( UInt uiBlkIdx = 0; uiBlkIdx < rpcTempCU->getTotalNumPart(); uiBlkIdx ++)
+        {
+          if( ( pcPic->getCU( rpcTempCU->getAddr() )->getEntropySliceStartCU(uiBlkIdx+rpcTempCU->getZorderIdxInCU()) == rpcTempCU->getSlice()->getEntropySliceCurStartCUAddr() ) &&
+              ( rpcTempCU->getCbf( uiBlkIdx, TEXT_LUMA ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_U ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_V ) ) )
+          {
+            bHasRedisual = true;
+            break;
+          }
+        }
+
+        UInt uiTargetPartIdx;
+        if ( pcPic->getCU( rpcTempCU->getAddr() )->getEntropySliceStartCU(rpcTempCU->getZorderIdxInCU()) != pcSlice->getEntropySliceCurStartCUAddr() )
+        {
+          uiTargetPartIdx = pcSlice->getEntropySliceCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
+        }
+        else
+        {
+          uiTargetPartIdx = 0;
+        }
+        if ( ! bHasRedisual )
+        {
+  #if LOSSLESS_CODING
+          if (((rpcTempCU->getQP(uiTargetPartIdx) != rpcTempCU->getRefQP(uiTargetPartIdx)) ) && (rpcTempCU->getSlice()->getSPS()->getUseLossless()))
+          {
+            rpcTempCU->getTotalCost() = MAX_DOUBLE;
+          }
+  #endif
+          rpcTempCU->setQPSubParts( rpcTempCU->getRefQP( uiTargetPartIdx ), 0, uhDepth ); // set QP to default QP
+        }
+      }
+    }
+
+    if( m_bUseSBACRD )
+    {
+      m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uhDepth][CI_TEMP_BEST]);
+    }
+  }
+  else
+  {
+    rpcTempCU->setTextureModeDepthSubParts( uhTextureModeDepth, 0, uhDepth );
+    rpcTempCU->copyTextureMotionDataFrom( pcTextureCU, uhDepth, rpcTempCU->getZorderIdxInCU() );
+#if FIX_MPI_B0065
+    UInt uiAbsPartIdx = rpcTempCU->getZorderIdxInCU();
+    if( rpcTempCU->getDepth(0) > pcTextureCU->getDepth(uiAbsPartIdx))
+    {
+      rpcTempCU->setPartSizeSubParts( SIZE_NxN, 0, uhDepth );
+    }
+    else
+    {
+      PartSize partSize = pcTextureCU->getPartitionSize(uiAbsPartIdx);
+      rpcTempCU->setPartSizeSubParts( partSize, 0, uhDepth );
+    }
+#else
+    rpcTempCU->setPartSizeSubParts( SIZE_NxN, 0, uhDepth );
+#endif
+    for( UInt ui = 0; ui < rpcTempCU->getTotalNumPart(); ui++ )
+    {
+      assert( rpcTempCU->getInterDir( ui ) != 0 );
+      assert( rpcTempCU->getPredictionMode( ui ) != MODE_NONE );
+#if MERL_VSP_C0152
+      Int vspIdx = pcTextureCU->getVSPIndex( rpcTempCU->getZorderIdxInCU() + ui);
+      rpcTempCU->setVSPIndex( ui , vspIdx);
+#endif
+    }
+
+    rpcTempCU->setPredModeSubParts( bSkipResidual ? MODE_SKIP : MODE_INTER, 0, uhDepth );
+#if MERL_VSP_C0152
+    m_pcPredSearch->motionCompensation( rpcTempCU, m_ppcPredYuvTemp[uhDepth], rpcTempCU->getZorderIdxInCU()  );
+#else
+    m_pcPredSearch->motionCompensation( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+#endif
+    // get Original YUV data from picture
+    m_ppcOrigYuv[uhDepth]->copyFromPicYuv( rpcBestCU->getPic()->getPicYuvOrg(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+    m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+                                               m_ppcOrigYuv[uhDepth],
+                                               m_ppcPredYuvTemp[uhDepth],
+                                               m_ppcResiYuvTemp[uhDepth],
+                                               m_ppcResiYuvBest[uhDepth],
+                                               m_ppcRecoYuvTemp[uhDepth],
+#if H3D_IVRP
+                                               m_ppcResPredTmp [uhDepth],
+#endif
+                                               bSkipResidual );
+
+    if( uhDepth == uhTextureModeDepth )
+    {
+      xAddMVISignallingBits( rpcTempCU );
+    }
+    xCheckDQP( rpcTempCU );
+  }
+
+#if HHI_VSO
+  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( rpcTempCU->getPredictionMode( 0 ) == MODE_SKIP && uhDepth == uhTextureModeDepth )
+  {
+    if( rpcTempCU->getSlice()->getPPS()->getUseDQP() && (g_uiMaxCUWidth>>uhDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+      rpcTempCU->setQPSubParts( rpcTempCU->getRefQP( 0 ), 0, uhDepth ); // set QP to default QP
+  }
+  xCheckBestMode( rpcBestCU, rpcTempCU, uhDepth );
+  rpcBestCU->copyToPic(uhDepth);                                                     // Copy Best data to Picture for next partition prediction.
+
+#if HHI_VSO
+  if( !bSplit && bRecursiveCall && m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = m_ppcRecoYuvBest[uhDepth]->getWidth   (   );
+    UInt  uiHeight    = m_ppcRecoYuvBest[uhDepth]->getHeight  (   );
+    UInt  uiSrcStride = m_ppcRecoYuvBest[uhDepth]->getStride  (   );
+    Pel*  piSrc       = m_ppcRecoYuvBest[uhDepth]->getLumaAddr( 0 );
+    m_pcRdCost->setRenModelData( rpcBestCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+}
+
+Void TEncCu::xAddMVISignallingBits( TComDataCU* pcCU )
+{
+  const UChar uhDepth = pcCU->getTextureModeDepth( 0 );
+  m_pcEntropyCoder->resetBits();
+  xSaveDepthWidthHeight( pcCU );
+  pcCU->setSizeSubParts( g_uiMaxCUWidth>>uhDepth, g_uiMaxCUHeight>>uhDepth, 0, uhDepth );
+  pcCU->setDepthSubParts( uhDepth, 0 );
+  pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth );
+  pcCU->setMergeFlagSubParts( true, 0, 0, uhDepth );
+  pcCU->setMergeIndexSubParts( HHI_MPI_MERGE_POS, 0, 0, uhDepth );
+
+  // check for skip mode
+  {
+    Bool bAllZero = true;
+    for( UInt ui = 0; ui < pcCU->getTotalNumPart(); ui++ )
+    {
+      if( pcCU->getCbf( ui, TEXT_LUMA ) || pcCU->getCbf( ui, TEXT_CHROMA_U ) || pcCU->getCbf( ui, TEXT_CHROMA_V ) )
+      {
+        bAllZero = false;
+        break;
+      }
+    }
+    if( bAllZero )
+      pcCU->setPredModeSubParts( MODE_SKIP, 0, uhDepth );
+  }
+
+
+  m_pcEntropyCoder->encodeSplitFlag( pcCU, 0, uhDepth, true );
+  m_pcEntropyCoder->encodeSkipFlag( pcCU, 0, true );
+
+  if( pcCU->isSkipped( 0 ) )
+  {
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, 0, 0, true );
+#if LGE_ILLUCOMP_B0045
+    m_pcEntropyCoder->encodeICFlag( pcCU, 0, true
+#if LGE_ILLUCOMP_DEPTH_C0046
+        , uhDepth
+#endif
+        );
+#endif
+  }
+  else
+  {
+    m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+    m_pcEntropyCoder->encodePartSize( pcCU, 0, uhDepth, true );
+    // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
+    m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+#if LGE_ILLUCOMP_B0045
+    m_pcEntropyCoder->encodeICFlag( pcCU, 0,          true 
+#if LGE_ILLUCOMP_DEPTH_C0046
+        , uhDepth
+#endif
+        );
+#endif
+  }
+  xRestoreDepthWidthHeight( pcCU );
+
+  pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits();
+}
+
+Void TEncCu::xSaveDepthWidthHeight( TComDataCU* pcCU )
+{
+  const Int iSizeInUchar  = sizeof( UChar ) * pcCU->getTotalNumPart();
+  memcpy( m_puhDepthSaved, pcCU->getDepth(), iSizeInUchar );
+  memcpy( m_puhWidthSaved, pcCU->getWidth(), iSizeInUchar );
+  memcpy( m_puhHeightSaved, pcCU->getHeight(), iSizeInUchar );
+}
+
+Void TEncCu::xRestoreDepthWidthHeight( TComDataCU* pcCU )
+{
+  const Int iSizeInUchar  = sizeof( UChar ) * pcCU->getTotalNumPart();
+  memcpy( pcCU->getDepth(), m_puhDepthSaved, iSizeInUchar );
+  memcpy( pcCU->getWidth(), m_puhWidthSaved, iSizeInUchar );
+  memcpy( pcCU->getHeight(), m_puhHeightSaved, iSizeInUchar );
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCu.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncCu.h	(revision 341)
@@ -0,0 +1,206 @@
+/* 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-2012, 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     TEncCu.h
+    \brief    Coding Unit (CU) encoder class (header)
+*/
+
+#ifndef __TENCCU__
+#define __TENCCU__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComYuv.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComDataCU.h"
+
+#include "TEncEntropy.h"
+#include "TEncSearch.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+class TEncSbac;
+class TEncCavlc;
+class TEncSlice;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU encoder class
+class TEncCu
+{
+private:
+  
+  TComDataCU**            m_ppcBestCU;      ///< Best CUs in each depth
+  TComDataCU**            m_ppcTempCU;      ///< Temporary CUs in each depth
+  UChar                   m_uhTotalDepth;
+  
+  TComYuv**               m_ppcPredYuvBest; ///< Best Prediction Yuv for each depth
+  TComYuv**               m_ppcResiYuvBest; ///< Best Residual Yuv for each depth
+  TComYuv**               m_ppcRecoYuvBest; ///< Best Reconstruction Yuv for each depth
+  TComYuv**               m_ppcPredYuvTemp; ///< Temporary Prediction Yuv for each depth
+  TComYuv**               m_ppcResiYuvTemp; ///< Temporary Residual Yuv for each depth
+  TComYuv**               m_ppcRecoYuvTemp; ///< Temporary Reconstruction Yuv for each depth
+  TComYuv**               m_ppcOrigYuv;     ///< Original Yuv for each depth
+#if H3D_IVRP
+  TComYuv**               m_ppcResPredTmp;  ///< Temporary residual prediction for each depth
+#endif
+
+  //  Data : encoder control
+  Bool                    m_bEncodeDQP;
+  Bool                    m_checkBurstIPCMFlag;
+
+  //  Access channel
+  TEncCfg*                m_pcEncCfg;
+  TComPrediction*         m_pcPrediction;
+  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;
+  Bool                    m_bUseSBACRD;
+  
+#if HHI_MPI
+  UChar *m_puhDepthSaved;
+  UChar *m_puhWidthSaved;
+  UChar *m_puhHeightSaved;
+#endif
+
+public:
+  /// copy parameters from encoder class
+  Void  init                ( TEncTop* pcEncTop );
+  
+  /// create internal buffers
+  Void  create              ( UChar uhTotalDepth, UInt iMaxWidth, UInt iMaxHeight );
+  
+  /// destroy internal buffers
+  Void  destroy             ();
+
+  /// CU analysis function
+  Void  compressCU          ( TComDataCU*&  rpcCU );
+  
+  /// CU encoding function
+  Void  encodeCU            ( TComDataCU*    pcCU, Bool bForceTerminate = false  );
+  
+  Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
+protected:
+  Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
+#if AMP_ENC_SPEEDUP
+  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth, PartSize eParentPartSize = SIZE_NONE );
+#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        );
+  
+#if HHI_INTERVIEW_SKIP
+  Void xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool bFullyRendered ) ;
+#else
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU                  );
+#endif
+#if AMP_MRG
+#if HHI_INTERVIEW_SKIP
+  Void xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bFullyRendered, Bool bUseMRG = false  ) ;
+#else
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG = false  );
+#endif
+//  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG = false  );
+#else
+#if HHI_INTERVIEW_SKIP
+  Void xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bFullyRendered ) ;
+#else
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#endif
+//  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#endif
+  Void  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+  Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU                      );
+  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  xCopyYuv2Tmp        ( UInt uhPartUnitIdx, UInt uiDepth );
+
+  Bool getdQPFlag           ()                        { return m_bEncodeDQP;        }
+  Void setdQPFlag           ( Bool b )                { m_bEncodeDQP = b;           }
+
+  Bool getCheckBurstIPCMFlag()                        { return m_checkBurstIPCMFlag;   }
+  Void setCheckBurstIPCMFlag( Bool b )                { m_checkBurstIPCMFlag = b;      }
+
+  Bool checkLastCUSucIPCM   ( TComDataCU* pcCU, UInt uiCurAbsPartIdx );
+  Int  countNumSucIPCM      ( TComDataCU* pcCU, UInt uiCurAbsPartIdx );
+
+#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 
+#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
+
+#if LOSSLESS_CODING 
+  Void  xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv ); 
+#endif
+#if HHI_MPI
+  Void  xCheckRDCostMvInheritance( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UChar uhTextureModeDepth, Bool bSkipResidual, Bool bRecursiveCall );
+  Void  xSaveDepthWidthHeight( TComDataCU* pcCU );
+  Void  xRestoreDepthWidthHeight( TComDataCU* pcCU );
+  Void  xAddMVISignallingBits( TComDataCU* pcCU );
+#endif
+};
+
+//! \}
+
+#endif // __TENCMB__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 341)
@@ -0,0 +1,1760 @@
+/* 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-2012, 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     TEncEntropy.cpp
+    \brief    entropy encoder class
+*/
+
+#include "TEncEntropy.h"
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+Void TEncEntropy::setEntropyCoder ( TEncEntropyIf* e, TComSlice* pcSlice )
+{
+  m_pcEntropyCoderIf = e;
+  m_pcEntropyCoderIf->setSlice ( pcSlice );
+}
+
+Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
+{
+  if (pcSlice->getSPS()->getUseSAO())
+  {
+    pcSlice->setSaoInterleavingFlag(pcSlice->getAPS()->getSaoInterleavingFlag());
+    pcSlice->setSaoEnabledFlag     (pcSlice->getAPS()->getSaoParam()->bSaoFlag[0]);
+    if (pcSlice->getAPS()->getSaoInterleavingFlag())
+    {
+      pcSlice->setSaoEnabledFlagCb   (pcSlice->getAPS()->getSaoParam()->bSaoFlag[1]);
+      pcSlice->setSaoEnabledFlagCr   (pcSlice->getAPS()->getSaoParam()->bSaoFlag[2]);
+    }
+    else
+    {
+      pcSlice->setSaoEnabledFlagCb   (0);
+      pcSlice->setSaoEnabledFlagCr   (0);
+    }
+  }
+
+  m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
+  return;
+}
+
+Void  TEncEntropy::encodeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  m_pcEntropyCoderIf->codeTilesWPPEntryPoint( pSlice );
+}
+
+Void TEncEntropy::encodeTerminatingBit      ( UInt uiIsLast )
+{
+  m_pcEntropyCoderIf->codeTerminatingBit( uiIsLast );
+  
+  return;
+}
+
+Void TEncEntropy::encodeSliceFinish()
+{
+  m_pcEntropyCoderIf->codeSliceFinish();
+}
+
+Void TEncEntropy::encodeFlush()
+{
+  m_pcEntropyCoderIf->codeFlush();
+}
+Void TEncEntropy::encodeStart()
+{
+  m_pcEntropyCoderIf->encodeStart();
+}
+
+Void TEncEntropy::encodeSEI(const SEI& sei)
+{
+  m_pcEntropyCoderIf->codeSEI(sei);
+  return;
+}
+
+Void TEncEntropy::encodePPS( TComPPS* pcPPS )
+{
+  m_pcEntropyCoderIf->codePPS( pcPPS );
+  return;
+}
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+Void TEncEntropy::encodeVPS( TComVPS* pcVPS )
+{
+  m_pcEntropyCoderIf->codeVPS( pcVPS );
+  return;
+}
+#endif
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+Void  codeVPS                 ( TComVPS* pcVPS );
+#endif
+
+#if HHI_MPI || H3D_QTL 
+Void TEncEntropy::encodeSPS( TComSPS* pcSPS, Bool bIsDepth )
+{
+  m_pcEntropyCoderIf->codeSPS( pcSPS, bIsDepth );
+  return;
+}
+#else
+Void TEncEntropy::encodeSPS( TComSPS* pcSPS )
+{
+  m_pcEntropyCoderIf->codeSPS( pcSPS );
+  return;
+}
+#endif
+
+Void TEncEntropy::encodeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+  m_pcEntropyCoderIf->codeSkipFlag( pcCU, uiAbsPartIdx );
+}
+
+#if LGE_ILLUCOMP_B0045
+Void TEncEntropy::encodeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD 
+#if LGE_ILLUCOMP_DEPTH_C0046
+    , UInt uiDepth
+#endif
+    )
+{
+  if (pcCU->isIntra(uiAbsPartIdx) || (pcCU->getSlice()->getViewId() == 0)
+#if !LGE_ILLUCOMP_DEPTH_C0046
+      || pcCU->getSlice()->getSPS()->isDepth()
+#endif
+      )
+  {
+    return;
+  }
+
+  if(!pcCU->getSlice()->getApplyIC())
+    return;
+
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+
+  if(pcCU->isICFlagRequired(uiAbsPartIdx
+#if LGE_ILLUCOMP_DEPTH_C0046
+      , uiDepth //This modification is not needed after integrating JCT3V-C0137
+#endif
+      ))
+    m_pcEntropyCoderIf->codeICFlag( pcCU, uiAbsPartIdx );
+}
+#endif
+
+Void TEncEntropy::codeFiltCountBit(ALFParam* pAlfParam, Int64* ruiRate)
+{
+  resetEntropy();
+  resetBits();
+  codeFilt(pAlfParam);
+  *ruiRate = getNumberOfWrittenBits();
+  resetEntropy();
+  resetBits();
+}
+
+Void TEncEntropy::codeAuxCountBit(ALFParam* pAlfParam, Int64* ruiRate)
+{
+  resetEntropy();
+  resetBits();
+  codeAux(pAlfParam);
+  *ruiRate = getNumberOfWrittenBits();
+  resetEntropy();
+  resetBits();
+}
+
+Void TEncEntropy::codeAux(ALFParam* pAlfParam)
+{
+  //  m_pcEntropyCoderIf->codeAlfUvlc(pAlfParam->realfiltNo); 
+
+  Int noFilters = min(pAlfParam->filters_per_group-1, 2);
+  m_pcEntropyCoderIf->codeAlfUvlc(noFilters);
+
+  if(noFilters == 1)
+  {
+    m_pcEntropyCoderIf->codeAlfUvlc(pAlfParam->startSecondFilter);
+  }
+  else if (noFilters == 2)
+  {
+    Int numMergeFlags = 16;
+    for (Int i=1; i<numMergeFlags; i++) 
+    {
+      m_pcEntropyCoderIf->codeAlfFlag (pAlfParam->filterPattern[i]);
+    }
+  }
+}
+
+Int TEncEntropy::lengthGolomb(int coeffVal, int k)
+{
+  int m = 2 << (k - 1);
+  int q = coeffVal / m;
+  if(coeffVal != 0)
+  {
+    return(q + 2 + k);
+  }
+  else
+  {
+    return(q + 1 + k);
+  }
+}
+
+Int TEncEntropy::codeFilterCoeff(ALFParam* ALFp)
+{
+  Int filters_per_group = ALFp->filters_per_group;
+  int sqrFiltLength = ALFp->num_coeff;
+  int i, k, kMin, kStart, minBits, ind, scanPos, maxScanVal, coeffVal, len = 0,
+    *pDepthInt=NULL, kMinTab[MAX_SCAN_VAL], bitsCoeffScan[MAX_SCAN_VAL][MAX_EXP_GOLOMB],
+    minKStart, minBitsKStart, bitsKStart;
+  
+  pDepthInt = pDepthIntTabShapes[ALFp->filter_shape];
+  maxScanVal = 0;
+  int minScanVal = MIN_SCAN_POS_CROSS;
+
+  for(i = 0; i < sqrFiltLength; i++)
+  {
+    maxScanVal = max(maxScanVal, pDepthInt[i]);
+  }
+  
+  // vlc for all
+  memset(bitsCoeffScan, 0, MAX_SCAN_VAL * MAX_EXP_GOLOMB * sizeof(int));
+  for(ind=0; ind<filters_per_group; ++ind)
+  {
+    for(i = 0; i < sqrFiltLength; i++)
+    {
+      scanPos=pDepthInt[i]-1;
+      coeffVal=abs(ALFp->coeffmulti[ind][i]);
+      for (k=1; k<15; k++)
+      {
+        bitsCoeffScan[scanPos][k]+=lengthGolomb(coeffVal, k);
+      }
+    }
+  }
+  
+  minBitsKStart = 0;
+  minKStart = -1;
+  for(k = 1; k < 8; k++)
+  { 
+    bitsKStart = 0; 
+    kStart = k;
+    for(scanPos = minScanVal; scanPos < maxScanVal; scanPos++)
+    {
+      kMin = kStart; 
+      minBits = bitsCoeffScan[scanPos][kMin];
+      
+      if(bitsCoeffScan[scanPos][kStart+1] < minBits)
+      {
+        kMin = kStart + 1; 
+        minBits = bitsCoeffScan[scanPos][kMin];
+      }
+      kStart = kMin;
+      bitsKStart += minBits;
+    }
+    if((bitsKStart < minBitsKStart) || (k == 1))
+    {
+      minBitsKStart = bitsKStart;
+      minKStart = k;
+    }
+  }
+  
+  kStart = minKStart; 
+  for(scanPos = minScanVal; scanPos < maxScanVal; scanPos++)
+  {
+    kMin = kStart; 
+    minBits = bitsCoeffScan[scanPos][kMin];
+    
+    if(bitsCoeffScan[scanPos][kStart+1] < minBits)
+    {
+      kMin = kStart + 1; 
+      minBits = bitsCoeffScan[scanPos][kMin];
+    }
+    
+    kMinTab[scanPos] = kMin;
+    kStart = kMin;
+  }
+  
+  // Coding parameters
+  ALFp->minKStart = minKStart;
+  for(scanPos = minScanVal; scanPos < maxScanVal; scanPos++)
+  {
+    ALFp->kMinTab[scanPos] = kMinTab[scanPos];
+  }
+
+  if (ALFp->filters_per_group == 1)
+  {
+    len += writeFilterCoeffs(sqrFiltLength, filters_per_group, pDepthInt, ALFp->coeffmulti, kTableTabShapes[ALF_CROSS9x7_SQUARE3x3]);
+  }
+  else
+  {
+  len += writeFilterCodingParams(minKStart, minScanVal, maxScanVal, kMinTab);
+
+  // Filter coefficients
+  len += writeFilterCoeffs(sqrFiltLength, filters_per_group, pDepthInt, ALFp->coeffmulti, kMinTab);
+  }
+  
+  return len;
+}
+
+Int TEncEntropy::writeFilterCodingParams(int minKStart, int minScanVal, int maxScanVal, int kMinTab[])
+{
+  int scanPos;
+  int golombIndexBit;
+  int kMin;
+
+  // Golomb parameters
+  m_pcEntropyCoderIf->codeAlfUvlc(minKStart - 1);
+  
+  kMin = minKStart; 
+  for(scanPos = minScanVal; scanPos < maxScanVal; scanPos++)
+  {
+    golombIndexBit = (kMinTab[scanPos] != kMin)? 1: 0;
+    
+    assert(kMinTab[scanPos] <= kMin + 1);
+    
+    m_pcEntropyCoderIf->codeAlfFlag(golombIndexBit);
+    kMin = kMinTab[scanPos];
+  }    
+  
+  return 0;
+}
+
+Int TEncEntropy::writeFilterCoeffs(int sqrFiltLength, int filters_per_group, int pDepthInt[], 
+                                   int **FilterCoeff, int kMinTab[])
+{
+  int ind, scanPos, i;
+  
+  for(ind = 0; ind < filters_per_group; ++ind)
+  {
+    for(i = 0; i < sqrFiltLength; i++)
+    {
+      scanPos = pDepthInt[i] - 1;
+      Int k = (filters_per_group == 1) ? kMinTab[i] : kMinTab[scanPos];
+      golombEncode(FilterCoeff[ind][i], k);
+    }
+  }
+  return 0;
+}
+
+Int TEncEntropy::golombEncode(int coeff, int k)
+{
+  int q, i;
+  int symbol = abs(coeff);
+  
+  q = symbol >> k;
+  
+  for (i = 0; i < q; i++)
+  {
+    m_pcEntropyCoderIf->codeAlfFlag(1);
+  }
+  m_pcEntropyCoderIf->codeAlfFlag(0);
+  // write one zero
+  
+  for(i = 0; i < k; i++)
+  {
+    m_pcEntropyCoderIf->codeAlfFlag(symbol & 0x01);
+    symbol >>= 1;
+  }
+  
+  if(coeff != 0)
+  {
+    int sign = (coeff > 0)? 1: 0;
+    m_pcEntropyCoderIf->codeAlfFlag(sign);
+  }
+  return 0;
+}
+
+Void TEncEntropy::codeFilt(ALFParam* pAlfParam)
+{
+  if(pAlfParam->filters_per_group > 1)
+  {
+    m_pcEntropyCoderIf->codeAlfFlag (pAlfParam->predMethod);
+  }
+  for(Int ind = 0; ind < pAlfParam->filters_per_group; ++ind)
+  {
+    m_pcEntropyCoderIf->codeAlfFlag (pAlfParam->nbSPred[ind]);
+  }
+  codeFilterCoeff (pAlfParam);
+}
+
+/** encode merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiPUIdx
+ * \returns Void
+ */
+Void TEncEntropy::encodeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx )
+{ 
+  // at least one merge candidate exists
+  m_pcEntropyCoderIf->codeMergeFlag( pcCU, uiAbsPartIdx );
+}
+
+/** encode merge index
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiPUIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  }
+
+  UInt uiNumCand = MRG_MAX_NUM_CANDS;
+  if ( uiNumCand > 1 )
+  {
+    m_pcEntropyCoderIf->codeMergeIndex( pcCU, uiAbsPartIdx );
+  }
+}
+
+
+/** parse the fixed length code (smaller than one max value) in ALF
+ * \param run: coded value
+ * \param rx: cur addr
+ * \param numLCUInWidth: # of LCU in one LCU 
+ * \returns Void
+ */
+Void TEncEntropy::encodeAlfFixedLengthRun(UInt run, UInt rx, UInt numLCUInWidth)
+{
+  assert(numLCUInWidth > rx);
+  UInt maxValue = numLCUInWidth - rx - 1;
+  m_pcEntropyCoderIf->codeAlfFixedLengthIdx(run, maxValue);
+}
+
+/** parse the fixed length code (smaller than one max value) in ALF
+ * \param idx: coded value
+ * \param numFilterSetsInBuffer: max value 
+ * \returns Void
+ */
+Void TEncEntropy::encodeAlfStoredFilterSetIdx(UInt idx, UInt numFilterSetsInBuffer)
+{
+  assert(numFilterSetsInBuffer > 0);
+  UInt maxValue = numFilterSetsInBuffer - 1;
+  m_pcEntropyCoderIf->codeAlfFixedLengthIdx(idx, maxValue);
+}
+
+Void TEncEntropy::encodeAlfParam(AlfParamSet* pAlfParamSet, Bool bSentInAPS, Int firstLCUAddr, Bool alfAcrossSlice)
+{
+  Bool isEnabled[NUM_ALF_COMPONENT];
+  Bool isUniParam[NUM_ALF_COMPONENT];
+
+  isEnabled[ALF_Y] = true;
+  isEnabled[ALF_Cb]= pAlfParamSet->isEnabled[ALF_Cb];
+  isEnabled[ALF_Cr]= pAlfParamSet->isEnabled[ALF_Cr];
+
+  isUniParam[ALF_Y]= pAlfParamSet->isUniParam[ALF_Y];
+  isUniParam[ALF_Cb]= pAlfParamSet->isUniParam[ALF_Cb];
+  isUniParam[ALF_Cr]= pAlfParamSet->isUniParam[ALF_Cr]; 
+
+
+  //alf_cb_enable_flag
+  m_pcEntropyCoderIf->codeAlfFlag(isEnabled[ALF_Cb]?1:0);
+  //alf_cr_enable_flag
+  m_pcEntropyCoderIf->codeAlfFlag(isEnabled[ALF_Cr]?1:0);  
+
+  for(Int compIdx = 0; compIdx< NUM_ALF_COMPONENT; compIdx++)
+  {
+    if(isEnabled[compIdx])
+    {
+      //alf_one_{luma, cb, cr}_unit_per_slice_flag
+      m_pcEntropyCoderIf->codeAlfFlag(isUniParam[compIdx]?1:0);
+    }
+  }
+  if(bSentInAPS)
+  {
+    //alf_num_lcu_in_width_minus1
+    m_pcEntropyCoderIf->codeAlfUvlc(pAlfParamSet->numLCUInWidth-1);
+    //alf_num_lcu_in_height_minus1
+    m_pcEntropyCoderIf->codeAlfUvlc(pAlfParamSet->numLCUInHeight-1);
+  }
+  else //sent in slice header
+  {
+    //alf_num_lcu_in_slice_minus1
+    m_pcEntropyCoderIf->codeAlfUvlc(pAlfParamSet->numLCU-1);
+  }
+
+
+  encodeAlfParamSet(pAlfParamSet, pAlfParamSet->numLCUInWidth, pAlfParamSet->numLCU, firstLCUAddr, alfAcrossSlice, 0, (Int)NUM_ALF_COMPONENT-1);
+
+}
+
+Bool TEncEntropy::getAlfRepeatRowFlag(Int compIdx, AlfParamSet* pAlfParamSet
+                                    , Int lcuIdxInSlice, Int lcuPos
+                                    , Int startlcuPosX, Int endlcuPosX
+                                    , Int numLCUInWidth
+                                    )
+{
+  assert(startlcuPosX == 0); //only the beginning of one LCU row needs to send repeat_row_flag
+  
+  Int len = endlcuPosX - startlcuPosX +1;
+  Bool isRepeatRow = true;
+  Int curPos;
+
+  for(Int i= 0; i < len; i++)
+  {
+    curPos = lcuIdxInSlice +i;
+    AlfUnitParam& alfUnitParam = pAlfParamSet->alfUnitParam[compIdx][curPos];
+    AlfUnitParam& alfUpUnitParam = pAlfParamSet->alfUnitParam[compIdx][curPos-numLCUInWidth];
+
+    if ( !(alfUnitParam == alfUpUnitParam) )
+    {
+      isRepeatRow = false;
+      break;
+    }
+  }
+
+  return isRepeatRow;
+}
+
+
+Int TEncEntropy::getAlfRun(Int compIdx, AlfParamSet* pAlfParamSet
+                          , Int lcuIdxInSlice, Int lcuPos
+                          , Int startlcuPosX, Int endlcuPosX
+                          )
+{
+  Int alfRun = 0;
+  Int len = endlcuPosX - startlcuPosX +1;
+  AlfUnitParam& alfLeftUnitParam = pAlfParamSet->alfUnitParam[compIdx][lcuIdxInSlice];
+
+
+
+  for(Int i= 1; i < len; i++)
+  {
+    AlfUnitParam& alfUnitParam = pAlfParamSet->alfUnitParam[compIdx][lcuIdxInSlice+ i];
+
+    if (alfUnitParam == alfLeftUnitParam)
+    {
+      alfRun++;
+    }
+    else
+    {
+      break;
+    }
+  }
+
+  return alfRun;
+
+}
+
+
+
+Void TEncEntropy::encodeAlfParamSet(AlfParamSet* pAlfParamSet, Int numLCUInWidth, Int numLCU, Int firstLCUAddr, Bool alfAcrossSlice, Int startCompIdx, Int endCompIdx)
+{
+  Int endLCUY       = (numLCU -1 + firstLCUAddr)/numLCUInWidth;
+  Int endLCUX       = (numLCU -1 + firstLCUAddr)%numLCUInWidth;
+
+  static Bool isRepeatedRow   [NUM_ALF_COMPONENT];
+  static Int  numStoredFilters[NUM_ALF_COMPONENT];
+  static Int* run             [NUM_ALF_COMPONENT];
+
+  for(Int compIdx =startCompIdx; compIdx <= endCompIdx; compIdx++)
+  {
+    isRepeatedRow[compIdx]    = false;
+    numStoredFilters[compIdx] = 0;
+
+    run[compIdx] = new Int[numLCU+1];
+    run[compIdx][0] = -1; 
+  }
+
+  Int  ry, rx, addrUp, endrX, lcuPos;
+
+  for(Int i=0; i< numLCU; i++)
+  {
+    lcuPos= firstLCUAddr+ i;
+    rx    = lcuPos% numLCUInWidth;
+    ry    = lcuPos/ numLCUInWidth;
+    endrX = ( ry == endLCUY)?( endLCUX ):(numLCUInWidth-1);
+
+    for(Int compIdx =startCompIdx; compIdx <= endCompIdx; compIdx++)
+    {
+      AlfUnitParam& alfUnitParam = pAlfParamSet->alfUnitParam[compIdx][i];
+      if(pAlfParamSet->isEnabled[compIdx])
+      {
+        if(!pAlfParamSet->isUniParam[compIdx])
+        {
+          addrUp = i-numLCUInWidth;
+          if(rx ==0 && addrUp >=0)
+          {
+            isRepeatedRow[compIdx] = getAlfRepeatRowFlag(compIdx, pAlfParamSet, i, lcuPos, rx, endrX, numLCUInWidth);
+
+            //alf_repeat_row_flag
+            m_pcEntropyCoderIf->codeAlfFlag(isRepeatedRow[compIdx]?1:0);
+          }
+
+          if(isRepeatedRow[compIdx])
+          {
+            assert(addrUp >=0);
+            run[compIdx][i] = run[compIdx][addrUp];
+          }
+          else
+          {
+            if(rx == 0 || run[compIdx][i] < 0)
+            {             
+              run[compIdx][i] = getAlfRun(compIdx, pAlfParamSet, i, lcuPos, rx, endrX);
+
+              if(addrUp < 0)
+              {
+                //alf_run_diff u(v)
+                encodeAlfFixedLengthRun(run[compIdx][i], rx, numLCUInWidth);                
+              }
+              else
+              {
+                //alf_run_diff s(v)
+                m_pcEntropyCoderIf->codeAlfSvlc(run[compIdx][i]- run[compIdx][addrUp]);
+
+              }
+
+              if(ry > 0 && (addrUp >=0 || alfAcrossSlice))
+              {
+                //alf_merge_up_flag
+                m_pcEntropyCoderIf->codeAlfFlag(  (alfUnitParam.mergeType == ALF_MERGE_UP)?1:0   );  
+              }
+
+              if(alfUnitParam.mergeType != ALF_MERGE_UP)
+              {
+                assert(alfUnitParam.mergeType == ALF_MERGE_DISABLED);
+
+                //alf_lcu_enable_flag
+                m_pcEntropyCoderIf->codeAlfFlag(alfUnitParam.isEnabled ? 1 : 0);
+
+                if(alfUnitParam.isEnabled)
+                {
+                  if(numStoredFilters[compIdx] > 0)
+                  {
+                    //alf_new_filter_set_flag
+                    m_pcEntropyCoderIf->codeAlfFlag(alfUnitParam.isNewFilt ? 1:0);
+
+                    if(!alfUnitParam.isNewFilt)
+                    {
+                      //alf_stored_filter_set_idx
+                      encodeAlfStoredFilterSetIdx(alfUnitParam.storedFiltIdx, numStoredFilters[compIdx]);
+
+                    }
+                  }
+                  else
+                  {
+                    assert(alfUnitParam.isNewFilt);
+                  }
+
+                  if(alfUnitParam.isNewFilt)
+                  {
+                    assert(alfUnitParam.alfFiltParam->alf_flag == 1);
+                    encodeAlfParam(alfUnitParam.alfFiltParam);
+                    numStoredFilters[compIdx]++;
+                  }
+                }
+
+              }
+            }
+
+            run[compIdx][i+1] = run[compIdx][i] -1;
+          }
+
+        }
+        else // uni-param
+        {
+          if(i == 0)
+          {
+            //alf_lcu_enable_flag
+            m_pcEntropyCoderIf->codeAlfFlag(alfUnitParam.isEnabled?1:0);
+            if(alfUnitParam.isEnabled)
+            {
+              encodeAlfParam(alfUnitParam.alfFiltParam);
+            }
+          }
+        }
+      } // component enabled/disable
+    } //comp
+
+  }
+
+  for(Int compIdx =startCompIdx; compIdx <= endCompIdx; compIdx++)
+  {
+    delete[] run[compIdx];
+  }
+
+}
+
+
+Void TEncEntropy::encodeAlfParam(ALFParam* pAlfParam)
+{
+  const Int numCoeff = (Int)ALF_MAX_NUM_COEF;
+
+  switch(pAlfParam->componentID)
+  {
+  case ALF_Cb:
+  case ALF_Cr:
+    {
+      for(Int pos=0; pos< numCoeff; pos++)
+      {
+        m_pcEntropyCoderIf->codeAlfSvlc(  pAlfParam->coeffmulti[0][pos]);
+
+      }
+    }
+    break;
+  case ALF_Y:
+    {
+      codeAux(pAlfParam);
+      codeFilt(pAlfParam);
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+Void TEncEntropy::encodeAlfCtrlFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  m_pcEntropyCoderIf->codeAlfCtrlFlag( pcCU, uiAbsPartIdx );
+}
+
+
+/** Encode ALF CU control flag
+ * \param uiFlag ALF CU control flag: 0 or 1
+ */
+Void TEncEntropy::encodeAlfCtrlFlag(UInt uiFlag)
+{
+  assert(uiFlag == 0 || uiFlag == 1);
+  m_pcEntropyCoderIf->codeAlfCtrlFlag( uiFlag );
+}
+
+
+/** Encode ALF CU control flag parameters
+ * \param pAlfParam ALF parameters
+ */
+Void TEncEntropy::encodeAlfCtrlParam(AlfCUCtrlInfo& cAlfParam, Int iNumCUsInPic)
+{
+  // region control parameters for luma
+  m_pcEntropyCoderIf->codeAlfFlag(cAlfParam.cu_control_flag);
+
+  if (cAlfParam.cu_control_flag == 0)
+  { 
+    return;
+  }
+
+  m_pcEntropyCoderIf->codeAlfCtrlDepth();
+
+  Int iSymbol    = ((Int)cAlfParam.num_alf_cu_flag - iNumCUsInPic);
+  m_pcEntropyCoderIf->codeAlfSvlc(iSymbol);
+
+  for(UInt i=0; i< cAlfParam.num_alf_cu_flag; i++)
+  {
+    m_pcEntropyCoderIf->codeAlfCtrlFlag( cAlfParam.alf_cu_flag[i] );
+  }
+}
+
+/** encode prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+
+#if !RWTH_SDC_DLT_B0036
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+#endif
+
+  m_pcEntropyCoderIf->codePredMode( pcCU, uiAbsPartIdx );
+  
+#if RWTH_SDC_DLT_B0036
+  // if B-Slice, code SDC flag later
+  if( !pcCU->getSlice()->isInterB() && pcCU->getSlice()->getSPS()->isDepth() && pcCU->isIntra(uiAbsPartIdx) )
+  {
+    // encode SDC flag
+    encodeSDCFlag(pcCU, uiAbsPartIdx, bRD);
+  }
+#endif
+}
+
+// Split mode
+Void TEncEntropy::encodeSplitFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+
+  m_pcEntropyCoderIf->codeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** encode partition size
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( !bRD )
+  {
+    if( pcCU->getLastCUSucIPCMFlag() && pcCU->getIPCMFlag(uiAbsPartIdx) )
+    {
+      return;
+    }
+  }
+#if RWTH_SDC_DLT_B0036
+  if( !pcCU->getSlice()->isInterB() && pcCU->isIntra(uiAbsPartIdx) && pcCU->getSDCFlag(uiAbsPartIdx)  )
+  {
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+    return;
+  }
+#endif
+  
+  m_pcEntropyCoderIf->codePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  
+#if RWTH_SDC_DLT_B0036
+  // code SDC flag now!
+  if( pcCU->getSlice()->isInterB() && pcCU->isIntra(uiAbsPartIdx) && pcCU->getSlice()->getSPS()->isDepth() )
+  {
+    // encode SDC flag
+    encodeSDCFlag(pcCU, uiAbsPartIdx, bRD);
+    
+    if( pcCU->getSDCFlag(uiAbsPartIdx) )
+    {
+      // part size is also known for SDC intra
+      assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+    }
+  }
+#endif
+}
+
+/** Encode I_PCM information. 
+ * \param pcCU pointer to CU 
+ * \param uiAbsPartIdx CU index
+ * \param bRD flag indicating estimation or encoding
+ * \returns Void
+ */
+Void TEncEntropy::encodeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if(!pcCU->getSlice()->getSPS()->getUsePCM()
+    || pcCU->getWidth(uiAbsPartIdx) > (1<<pcCU->getSlice()->getSPS()->getPCMLog2MaxSize())
+    || pcCU->getWidth(uiAbsPartIdx) < (1<<pcCU->getSlice()->getSPS()->getPCMLog2MinSize()))
+  {
+    return;
+  }
+  
+#if RWTH_SDC_DLT_B0036
+  if( pcCU->getSDCFlag(uiAbsPartIdx) )
+  {
+    return;
+  }
+#endif
+  
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  Int numIPCM = 0;
+  Bool firstIPCMFlag = false;
+
+  if( pcCU->getIPCMFlag(uiAbsPartIdx) )
+  {
+    numIPCM = 1;
+    firstIPCMFlag = true;
+
+    if( !bRD )
+    {
+      numIPCM = pcCU->getNumSucIPCM();
+      firstIPCMFlag = !pcCU->getLastCUSucIPCMFlag();
+    }
+  }
+  m_pcEntropyCoderIf->codeIPCMInfo ( pcCU, uiAbsPartIdx, numIPCM, firstIPCMFlag);
+
+}
+
+Void TEncEntropy::xEncodeTransform( TComDataCU* pcCU,UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt absTUPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, UInt uiInnerQuadIdx, UInt& uiYCbfFront3, UInt& uiUCbfFront3, UInt& uiVCbfFront3, Bool& bCodeDQP )
+{
+  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(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 );
+    }
+  }
+  {//CABAC
+    if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && 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) )
+    {
+      if ( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+      {
+        assert( uiSubdiv );
+      }
+      else
+      {
+        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) );
+      m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSubdiv, uiDepth );
+    }
+  }
+
+  {
+    if( uiLog2TrafoSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+    {
+      const UInt uiTrDepthCurr = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+      const Bool bFirstCbfOfCU = uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() || uiTrDepthCurr == 0;
+      if( bFirstCbfOfCU || uiLog2TrafoSize > 2 )
+      {
+        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) )
+        {
+          if ( uiInnerQuadIdx == 3 && uiUCbfFront3 == 0 && uiLog2TrafoSize < pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+          {
+            uiUCbfFront3++;
+          }
+          else
+          {
+            m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr );
+            uiUCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr );
+          }
+        }
+        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) )
+        {
+          if ( uiInnerQuadIdx == 3 && uiVCbfFront3 == 0 && uiLog2TrafoSize < pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize()  )
+          {
+            uiVCbfFront3++;
+          }
+          else
+          {
+            m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr );
+            uiVCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr );
+          }
+        }
+      }
+      else if( uiLog2TrafoSize == 2 )
+      {
+        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 ) );
+        
+        uiUCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr );
+        uiVCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr );
+      }
+    }
+    
+    if( uiSubdiv )
+    {
+      UInt size;
+      width  >>= 1;
+      height >>= 1;
+      size = width*height;
+      uiTrIdx++;
+      ++uiDepth;
+      const UInt partNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+      
+      UInt uiCurrentCbfY = 0;
+      UInt uiCurrentCbfU = 0;
+      UInt uiCurrentCbfV = 0;
+      
+      UInt nsAddr = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, 0, uiDepth - pcCU->getDepth( uiAbsPartIdx ) );
+      xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, 0, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV, bCodeDQP );
+
+      uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, 1, uiDepth - pcCU->getDepth( uiAbsPartIdx ) );
+      xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, 1, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV, bCodeDQP );
+
+      uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, 2, uiDepth - pcCU->getDepth( uiAbsPartIdx ) );
+      xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, 2, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV, bCodeDQP );
+
+      uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrafoSize-1, uiAbsPartIdx, absTUPartIdx, 3, uiDepth - pcCU->getDepth( uiAbsPartIdx ) );
+      xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, nsAddr, uiDepth, width, height, uiTrIdx, 3, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV, bCodeDQP );      
+      
+      uiYCbfFront3 += uiCurrentCbfY;
+      uiUCbfFront3 += uiCurrentCbfU;
+      uiVCbfFront3 += uiCurrentCbfV;
+    }
+    else
+    {
+      {
+        DTRACE_CABAC_VL( g_nSymbolCounter++ );
+        DTRACE_CABAC_T( "\tTrIdx: abspart=" );
+        DTRACE_CABAC_V( uiAbsPartIdx );
+        DTRACE_CABAC_T( "\tdepth=" );
+        DTRACE_CABAC_V( uiDepth );
+        DTRACE_CABAC_T( "\ttrdepth=" );
+        DTRACE_CABAC_V( pcCU->getTransformIdx( uiAbsPartIdx ) );
+        DTRACE_CABAC_T( "\n" );
+      }
+      UInt uiLumaTrMode, uiChromaTrMode;
+      pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx( uiAbsPartIdx ), uiLumaTrMode, uiChromaTrMode );
+      if(pcCU->getPredictionMode( uiAbsPartIdx ) == MODE_INTER && pcCU->useNonSquarePU( uiAbsPartIdx ) )
+      {
+        pcCU->setNSQTIdxSubParts( uiLog2TrafoSize, uiAbsPartIdx, absTUPartIdx, uiLumaTrMode );
+      }
+      if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
+      {
+        assert( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, 0 ) );
+        //      printf( "saved one bin! " );
+      }
+      else
+      {
+        const UInt uiLog2CUSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - pcCU->getDepth( uiAbsPartIdx );
+        if ( pcCU->getPredictionMode( uiAbsPartIdx ) != MODE_INTRA && uiInnerQuadIdx == 3 && uiYCbfFront3 == 0 && uiUCbfFront3 == 0 && uiVCbfFront3 == 0
+            && ( uiLog2CUSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() + 1 || uiLog2TrafoSize < pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() ) )
+        {      
+          uiYCbfFront3++;
+        }    
+        else
+        {
+          m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode );
+          uiYCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode );
+        }
+      }
+      
+      if ( cbfY || cbfU || cbfV )
+      {
+        // dQP: only for LCU once
+        if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+        {
+          if ( bCodeDQP )
+          {
+            encodeQP( pcCU, m_bakAbsPartIdxCU );
+            bCodeDQP = false;
+          }
+        }
+      }
+      if( cbfY )
+      {
+        Int trWidth = width;
+        Int trHeight = height;
+        pcCU->getNSQTSize( uiTrIdx, uiAbsPartIdx, trWidth, trHeight );
+        m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffY()+offsetLuma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
+      }
+      if( uiLog2TrafoSize > 2 )
+      {
+        Int trWidth = width >> 1;
+        Int trHeight = height >> 1;
+        pcCU->getNSQTSize( uiTrIdx, uiAbsPartIdx, trWidth, trHeight );
+        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;
+          pcCU->getNSQTSize( uiTrIdx - 1, uiAbsPartIdx, trWidth, trHeight );
+          if( cbfU )
+          {
+            m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCb()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+          }
+          if( cbfV )
+          {
+            m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCr()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+          }
+        }
+      }
+    }
+  }
+}
+
+
+// Intra direction for Luma
+Void TEncEntropy::encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  m_pcEntropyCoderIf->codeIntraDirLumaAng( pcCU, uiAbsPartIdx );
+}
+
+// Intra direction for Chroma
+Void TEncEntropy::encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  m_pcEntropyCoderIf->codeIntraDirChroma( pcCU, uiAbsPartIdx );
+}
+
+Void TEncEntropy::encodePredInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+
+#if RWTH_SDC_DLT_B0036
+  if( pcCU->getSDCFlag(uiAbsPartIdx) )
+  {
+    encodeSDCPredMode(pcCU, uiAbsPartIdx, bRD);
+    return;
+  }
+#endif
+
+  PartSize eSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  
+  if( pcCU->isIntra( uiAbsPartIdx ) )                                 // If it is Intra mode, encode intra prediction mode.
+  {
+    if( eSize == SIZE_NxN )                                         // if it is NxN size, encode 4 intra directions.
+    {
+      UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+      // if it is NxN size, this size might be the smallest partition size.
+      encodeIntraDirModeLuma( pcCU, uiAbsPartIdx                  );
+      encodeIntraDirModeLuma( pcCU, uiAbsPartIdx + uiPartOffset   );
+      encodeIntraDirModeLuma( pcCU, uiAbsPartIdx + uiPartOffset*2 );
+      encodeIntraDirModeLuma( pcCU, uiAbsPartIdx + uiPartOffset*3 );
+      encodeIntraDirModeChroma( pcCU, uiAbsPartIdx, bRD );
+    }
+    else                                                              // if it is not NxN size, encode 1 intra directions
+    {
+      encodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx );
+      encodeIntraDirModeChroma( pcCU, uiAbsPartIdx, bRD );
+    }
+  }
+  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;
+  }
+  
+  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;
+
+  for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
+  {
+    encodeMergeFlag( pcCU, uiSubPartIdx, uiPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      encodeMergeIndex( pcCU, uiSubPartIdx, uiPartIdx );
+    }
+    else
+    {
+      encodeInterDirPU( pcCU, uiSubPartIdx );
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {
+        if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+        {
+          encodeRefFrmIdxPU ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+          encodeMvdPU       ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+          encodeMVPIdxPU    ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+        }
+      }
+    }
+  }
+
+  return;
+}
+
+Void TEncEntropy::encodeInterDirPU( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( !pcCU->getSlice()->isInterB() )
+  {
+    return;
+  }
+
+  m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+  return;
+}
+
+/** encode reference frame index for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param eRefList
+ * \returns Void
+ */
+Void TEncEntropy::encodeRefFrmIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+
+  if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C)>0 && pcCU->getInterDir( uiAbsPartIdx ) != 3)
+  {
+    if ((eRefList== REF_PIC_LIST_1) || ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C ) == 1 ) )
+    {
+      return;
+    }
+
+    if ( pcCU->getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 1 )
+    {
+      m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, RefPicList(pcCU->getInterDir( uiAbsPartIdx )-1) );
+    }
+
+  }
+  else
+  {
+    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
+ */
+Void TEncEntropy::encodeMvdPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+
+  if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+  {
+    m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+  }
+  return;
+}
+
+Void TEncEntropy::encodeMVPIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+  {
+#if H3D_IVMP
+    const Int iNumCands = AMVP_MAX_NUM_CANDS + ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() ? 1 : 0 );
+    m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList, iNumCands );
+#else
+    m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+#endif
+  }
+
+  return;
+}
+
+Void TEncEntropy::encodeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, eType, uiTrDepth );
+}
+
+Void TEncEntropy::encodeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSymbol, uiCtx );
+}
+
+Void TEncEntropy::encodeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  m_pcEntropyCoderIf->codeQtRootCbf( pcCU, uiAbsPartIdx );
+}
+
+// dQP
+Void TEncEntropy::encodeQP( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    m_pcEntropyCoderIf->codeDeltaQP( pcCU, uiAbsPartIdx );
+  }
+}
+
+
+// texture
+
+/** encode coefficients
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param uiWidth
+ * \param uiHeight
+ */
+Void TEncEntropy::encodeCoeff( 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;
+  
+  UInt uiLumaTrMode, uiChromaTrMode;
+  pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx(uiAbsPartIdx), uiLumaTrMode, uiChromaTrMode );
+  
+#if RWTH_SDC_DLT_B0036
+  if( pcCU->getSDCFlag( uiAbsPartIdx ) )
+  {
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+    assert( pcCU->getTransformIdx(uiAbsPartIdx) == 0 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA) == 1 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
+    
+    encodeSDCResidualData(pcCU, uiAbsPartIdx);
+    return;
+  }
+#endif
+  
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
+    DTRACE_CABAC_V( uiDepth )
+    DTRACE_CABAC_T( "\n" )
+  }
+  else
+  {
+    {
+#if HHI_MPI
+      if( !(pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N &&
+            ( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 || uiDepth == pcCU->getTextureModeDepth( uiAbsPartIdx ) ) ) )
+#else
+      if( !(pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N ) )
+#endif
+      {
+        m_pcEntropyCoderIf->codeQtRootCbf( pcCU, uiAbsPartIdx );
+      }
+      if ( !pcCU->getQtRootCbf( uiAbsPartIdx ) )
+      {
+#if 1 // MW Bug Fix
+        pcCU->setCbfSubParts( 0, 0, 0, uiAbsPartIdx, uiDepth );
+        pcCU->setTrIdxSubParts( 0 , uiAbsPartIdx, uiDepth );
+#endif
+        pcCU->setNSQTIdxSubParts( uiAbsPartIdx, uiDepth );
+        return;
+      }
+    }
+  }
+  
+#if FIX_MPI_B0065
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getMergeIndex( uiAbsPartIdx ) == 0 && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N && pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1 )
+  {
+    TComDataCU *pcTextureCU = pcCU->getSlice()->getTexturePic()->getCU( pcCU->getAddr() );
+    if( uiDepth == pcTextureCU->getDepth(uiAbsPartIdx))
+    {
+      PartSize partSize = pcTextureCU->getPartitionSize(uiAbsPartIdx);
+      pcCU->setPartSizeSubParts( partSize, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setPartSizeSubParts( SIZE_NxN, uiAbsPartIdx, uiDepth );
+    }
+  }
+#endif
+
+  UInt temp = 0;
+  UInt temp1 = 0;
+  UInt temp2 = 0;
+  xEncodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, 0, temp, temp1, temp2, bCodeDQP );
+
+#if FIX_MPI_B0065
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getMergeIndex( uiAbsPartIdx ) == 0 && pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N &&  pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1 )
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );  
+  }
+#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 );
+}
+
+/** Encode SAO Offset
+ * \param  saoLcuParam SAO LCU paramters
+ */
+Void TEncEntropy::encodeSaoOffset(SaoLcuParam* saoLcuParam)
+{
+  UInt uiSymbol;
+  Int i;
+
+  uiSymbol = saoLcuParam->typeIdx + 1;
+  m_pcEntropyCoderIf->codeSaoTypeIdx(uiSymbol);
+  if (uiSymbol)
+  {
+    if( saoLcuParam->typeIdx == SAO_BO )
+    {
+      // Code Left Band Index
+      uiSymbol = (UInt) (saoLcuParam->bandPosition);
+      m_pcEntropyCoderIf->codeSaoUflc(uiSymbol);
+      for( i=0; i< saoLcuParam->length; i++)
+      {
+        m_pcEntropyCoderIf->codeSaoSvlc(saoLcuParam->offset[i]);
+      }  
+    }
+    else
+      if( saoLcuParam->typeIdx < 4 )
+      {
+        m_pcEntropyCoderIf->codeSaoUvlc( saoLcuParam->offset[0]);
+        m_pcEntropyCoderIf->codeSaoUvlc( saoLcuParam->offset[1]);
+        m_pcEntropyCoderIf->codeSaoUvlc(-saoLcuParam->offset[2]);
+        m_pcEntropyCoderIf->codeSaoUvlc(-saoLcuParam->offset[3]);
+      }
+  }
+}
+/** Encode SAO unit
+* \param  rx
+* \param  ry
+* \param  iCompIdx
+* \param  pSaoParam
+* \param  bRepeatedRow
+ */
+Void TEncEntropy::encodeSaoUnit(Int rx, Int ry, Int compIdx, SAOParam* saoParam, Int repeatedRow )
+{
+  int addr, addrLeft; 
+  int numCuInWidth  = saoParam->numCuInWidth;
+  SaoLcuParam* saoOneLcu;
+  Int runLeft;
+
+  addr      =  rx + ry*numCuInWidth;
+  addrLeft  =  (addr%numCuInWidth == 0) ? -1 : addr - 1;
+
+  if (!repeatedRow)
+  {
+    saoOneLcu = &(saoParam->saoLcuParam[compIdx][addr]);    
+    runLeft = (addrLeft>=0 ) ? saoParam->saoLcuParam[compIdx][addrLeft].run : -1;
+    if (rx == 0 || runLeft==0)
+    {
+      if (ry == 0)
+      {
+        m_pcEntropyCoderIf->codeSaoRun(saoOneLcu->runDiff, numCuInWidth-rx-1); 
+        saoOneLcu->mergeUpFlag = 0;
+      }
+      else 
+      {
+        m_pcEntropyCoderIf->codeSaoSvlc(saoOneLcu->runDiff); 
+        m_pcEntropyCoderIf->codeSaoFlag(saoOneLcu->mergeUpFlag);  
+      }
+      if (!saoOneLcu->mergeUpFlag)
+      {
+        encodeSaoOffset(saoOneLcu);
+      }
+    }
+  }
+}
+
+/** Encode SAO unit interleaving
+* \param  rx
+* \param  ry
+* \param  pSaoParam
+* \param  pcCU
+* \param  iCUAddrInSlice
+* \param  iCUAddrUpInSlice
+* \param  bLFCrossSliceBoundaryFlag
+ */
+Void TEncEntropy::encodeSaoUnitInterleaving(Int rx, Int ry, SAOParam* saoParam, TComDataCU* cu, Int cuAddrInSlice, Int cuAddrUpInSlice, Bool lfCrossSliceBoundaryFlag)
+{
+  Int addr = cu->getAddr();
+  for (Int compIdx=0; compIdx<3; compIdx++)
+  {
+    if (saoParam->bSaoFlag[compIdx])
+    {
+      if (rx>0 && cuAddrInSlice!=0)
+      {
+      m_pcEntropyCoderIf->codeSaoMergeLeft(saoParam->saoLcuParam[compIdx][addr].mergeLeftFlag,compIdx);
+      }
+      else
+      {
+        saoParam->saoLcuParam[compIdx][addr].mergeLeftFlag = 0;
+      }
+      if (saoParam->saoLcuParam[compIdx][addr].mergeLeftFlag == 0)
+      {
+        if ( (ry > 0) && (cuAddrUpInSlice>0||lfCrossSliceBoundaryFlag))
+        {
+          m_pcEntropyCoderIf->codeSaoMergeUp(saoParam->saoLcuParam[compIdx][addr].mergeUpFlag);
+        }
+        else
+        {
+          saoParam->saoLcuParam[compIdx][addr].mergeUpFlag = 0;
+        }
+        if (!saoParam->saoLcuParam[compIdx][addr].mergeUpFlag)
+        {
+          encodeSaoOffset(&(saoParam->saoLcuParam[compIdx][addr]));
+        }
+      }
+    }
+  }
+}
+
+/** Encode SAO parameter
+* \param  pcAPS
+ */
+Void TEncEntropy::encodeSaoParam(TComAPS* aps)
+{
+  SaoLcuParam* psSaoOneLcu;
+  int i,j,k, compIdx; 
+  int numCuInWidth  ;
+  int numCuInHeight ;
+  Bool repeatedRow[3];
+  Int addr;
+  m_pcEntropyCoderIf->codeSaoFlag(aps->getSaoInterleavingFlag());  
+  if(!aps->getSaoInterleavingFlag())
+  {
+    m_pcEntropyCoderIf->codeSaoFlag(aps->getSaoEnabled());  
+    if (aps->getSaoEnabled())
+    {
+      SAOParam* pSaoParam = aps->getSaoParam();
+      numCuInWidth  = pSaoParam->numCuInWidth;
+      numCuInHeight = pSaoParam->numCuInHeight;
+      m_pcEntropyCoderIf->codeSaoFlag(pSaoParam->bSaoFlag[1]); 
+      m_pcEntropyCoderIf->codeSaoFlag(pSaoParam->bSaoFlag[2]); 
+      m_pcEntropyCoderIf->codeSaoUvlc(numCuInWidth-1); 
+      m_pcEntropyCoderIf->codeSaoUvlc(numCuInHeight-1); 
+      for (compIdx=0;compIdx<3;compIdx++)
+      {
+        if (pSaoParam->bSaoFlag[compIdx])
+        {
+          m_pcEntropyCoderIf->codeSaoFlag(pSaoParam->oneUnitFlag[compIdx]); 
+          if (pSaoParam->oneUnitFlag[compIdx])
+          {
+            psSaoOneLcu = &(pSaoParam->saoLcuParam[compIdx][0]);   
+            encodeSaoOffset(psSaoOneLcu);
+          }
+        }
+      }
+
+      for (j=0;j<numCuInHeight;j++)
+      {
+        for (compIdx=0; compIdx<3; compIdx++)
+        {
+          repeatedRow[compIdx] = true;
+          for (k=0;k<numCuInWidth;k++)
+          {
+            addr       =  k + j*numCuInWidth;
+            psSaoOneLcu = &(pSaoParam->saoLcuParam[compIdx][addr]);    
+            if (!psSaoOneLcu->mergeUpFlag || psSaoOneLcu->runDiff)
+            {
+              repeatedRow[compIdx] = false;
+              break;
+            }
+          }
+        }
+        for (i=0;i<numCuInWidth;i++)
+        {
+          for (compIdx=0; compIdx<3; compIdx++)
+          {
+            if (pSaoParam->bSaoFlag[compIdx]  && !pSaoParam->oneUnitFlag[compIdx]) 
+            {
+              if (j>0 && i==0) 
+              {
+                m_pcEntropyCoderIf->codeSaoFlag(repeatedRow[compIdx]); 
+              }
+              encodeSaoUnit (i,j, compIdx, pSaoParam, repeatedRow[compIdx]);
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
+{
+  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 );
+}
+
+Void TEncEntropy::encodeDFParams(TComAPS* pcAPS)
+{
+  m_pcEntropyCoderIf->codeDFFlag(pcAPS->getLoopFilterDisable(), "loop_filter_disable");
+
+  if (!pcAPS->getLoopFilterDisable())
+  {
+    m_pcEntropyCoderIf->codeDFSvlc(pcAPS->getLoopFilterBetaOffset(), "beta_offset_div2");
+    m_pcEntropyCoderIf->codeDFSvlc(pcAPS->getLoopFilterTcOffset(), "tc_offset_div2");
+  }
+}
+
+#if RWTH_SDC_DLT_B0036
+Void TEncEntropy::encodeSDCPredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  m_pcEntropyCoderIf->codeSDCPredMode(pcCU, uiAbsPartIdx);
+}
+
+Void TEncEntropy::encodeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  m_pcEntropyCoderIf->codeSDCFlag(pcCU, uiAbsPartIdx);
+}
+
+Void TEncEntropy::encodeSDCResidualData( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  assert( pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA) == 1 );
+  assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
+  assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
+  assert( pcCU->getTransformIdx(uiAbsPartIdx) == 0 );
+  
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  // number of segments depends on prediction mode for INTRA
+  UInt uiNumSegments = 2;
+  UInt uiLumaPredMode = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  if( uiLumaPredMode == DC_IDX || uiLumaPredMode == PLANAR_IDX )
+    uiNumSegments = 1;
+  
+  // encode residual data for each segment
+  for( UInt uiSeg = 0; uiSeg < uiNumSegments; uiSeg++ )
+    m_pcEntropyCoderIf->codeSDCResidualData(pcCU, uiAbsPartIdx, uiSeg);
+}
+#endif
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncEntropy.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncEntropy.h	(revision 341)
@@ -0,0 +1,324 @@
+/* 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-2012, 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     TEncEntropy.h
+    \brief    entropy encoder class (header)
+*/
+
+#ifndef __TENCENTROPY__
+#define __TENCENTROPY__
+
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComDataCU.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComAdaptiveLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+class TEncSbac;
+class TEncCavlc;
+class SEI;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// entropy encoder pure class
+class TEncEntropyIf
+{
+public:
+  virtual Bool getAlfCtrl()                = 0;
+  virtual UInt getMaxAlfCtrlDepth()                = 0;
+  virtual Void setAlfCtrl(Bool bAlfCtrl)                = 0;
+  virtual Void setMaxAlfCtrlDepth(UInt uiMaxAlfCtrlDepth)                = 0;
+  
+  virtual Void  resetEntropy          ()                = 0;
+#if CABAC_INIT_FLAG
+  virtual Void  determineCabacInitIdx ()                = 0;
+#endif
+  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;
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  virtual Void  codeVPS                 ( TComVPS* pcVPS )                                      = 0;
+#endif
+
+#if HHI_MPI || H3D_QTL 
+  virtual Void  codeSPS                 ( TComSPS* pcSPS, Bool bIsDepth )                       = 0;
+#else
+  virtual Void  codeSPS                 ( TComSPS* pcSPS )                                      = 0;
+#endif
+  virtual Void  codePPS                 ( TComPPS* pcPPS )                                      = 0;
+  virtual void codeSEI(const SEI&) = 0;
+  virtual Void  codeSliceHeader         ( TComSlice* pcSlice )                                  = 0;
+  virtual Void codeTileMarkerFlag      ( TComSlice* pcSlice )                                  = 0;
+
+  virtual Void  codeTilesWPPEntryPoint  ( TComSlice* pSlice )     = 0;
+  virtual Void  codeTerminatingBit      ( UInt uilsLast )                                       = 0;
+  virtual Void  codeSliceFinish         ()                                                      = 0;
+  virtual Void  codeFlush               ()                                                      = 0;
+  virtual Void  encodeStart             ()                                                      = 0;
+  
+  virtual Void codeAlfCtrlDepth() = 0;
+#if H3D_IVMP
+  virtual Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Int iNum ) = 0;
+#else
+  virtual Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) = 0;
+#endif
+  virtual Void codeScalingList   ( TComScalingList* scalingList )      = 0;
+  
+public:
+  virtual Void codeAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeApsExtensionFlag () = 0;
+  
+  virtual Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#if LGE_ILLUCOMP_B0045
+  virtual Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+  virtual Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#if H3D_IVRP
+  virtual Void codeResPredFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#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;
+  
+#if RWTH_SDC_DLT_B0036
+  virtual Void codeSDCFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeSDCResidualData  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment ) = 0;
+  virtual Void codeSDCPredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+  
+  virtual Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag) = 0;
+
+  virtual Void codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx ) = 0;
+  virtual Void codeQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth ) = 0;
+  virtual Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 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 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 codeAlfFlag          ( UInt uiCode ) = 0;
+  virtual Void codeAlfUvlc          ( UInt uiCode ) = 0;
+  virtual Void codeAlfSvlc          ( Int   iCode ) = 0;
+  virtual Void codeAlfFixedLengthIdx( UInt idx, UInt numFilterSetsInBuffer) = 0;
+  virtual Void codeAPSAlflag(UInt uiCode) = 0;
+  /// set slice granularity
+  virtual Void setSliceGranularity(Int iSliceGranularity) = 0;
+
+  /// get slice granularity
+  virtual Int  getSliceGranularity()                      = 0;
+
+  virtual Void codeAlfCtrlFlag      ( UInt uiSymbol ) = 0;
+  virtual Void codeSaoFlag          ( UInt uiCode ) = 0;
+  virtual Void codeSaoUvlc          ( UInt uiCode ) = 0;
+  virtual Void codeSaoSvlc          ( Int   iCode ) = 0;
+  virtual Void codeSaoRun          ( UInt   uiCode, UInt uiMaxValue  ) = 0;
+  virtual Void codeSaoMergeLeft    ( UInt   uiCode, UInt uiCompIdx  ) = 0;
+  virtual Void codeSaoMergeUp      ( UInt   uiCode) = 0;
+  virtual Void codeSaoTypeIdx      ( UInt   uiCode) = 0;
+  virtual Void codeSaoUflc         ( UInt   uiCode) = 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 writeTileMarker             ( UInt uiTileIdx, UInt uiBitsUsed ) = 0;
+
+  virtual Void codeAPSInitInfo  (TComAPS* pcAPS)= 0;
+  virtual Void codeFinish       (Bool bEnd)= 0;
+
+  virtual Void codeDFFlag (UInt uiCode, const Char *pSymbolName) = 0;
+  virtual Void codeDFSvlc (Int iCode, const Char *pSymbolName)   = 0;
+
+  virtual ~TEncEntropyIf() {}
+
+};
+
+/// entropy encoder class
+class TEncEntropy
+{
+private:
+  UInt    m_uiBakAbsPartIdx;
+  UInt    m_uiBakChromaOffset;
+  UInt    m_bakAbsPartIdxCU;
+
+public:
+  Void    setEntropyCoder           ( TEncEntropyIf* e, TComSlice* pcSlice );
+  Void    setBitstream              ( TComBitIf* p )          { m_pcEntropyCoderIf->setBitstream(p);  }
+  Void    resetBits                 ()                        { m_pcEntropyCoderIf->resetBits();      }
+  Void    resetCoeffCost            ()                        { m_pcEntropyCoderIf->resetCoeffCost(); }
+  UInt    getNumberOfWrittenBits    ()                        { return m_pcEntropyCoderIf->getNumberOfWrittenBits(); }
+  UInt    getCoeffCost              ()                        { return  m_pcEntropyCoderIf->getCoeffCost(); }
+  Void    resetEntropy              ()                        { m_pcEntropyCoderIf->resetEntropy();  }
+#if CABAC_INIT_FLAG
+  Void    determineCabacInitIdx     ()                        { m_pcEntropyCoderIf->determineCabacInitIdx(); }
+#endif
+  
+  Void    encodeSliceHeader         ( TComSlice* pcSlice );
+  Void    encodeTileMarkerFlag       (TComSlice* pcSlice) {m_pcEntropyCoderIf->codeTileMarkerFlag(pcSlice);}
+  Void    encodeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void    encodeTerminatingBit      ( UInt uiIsLast );
+  Void    encodeSliceFinish         ();
+  Void    encodeFlush               ();
+  Void    encodeStart               ();
+  Void encodeAlfFlag(UInt code) {m_pcEntropyCoderIf->codeAlfFlag(code);}
+  Void encodeAlfStoredFilterSetIdx(UInt idx, UInt numFilterSetsInBuffer);
+  Void encodeAlfFixedLengthRun(UInt run, UInt rx, UInt numLCUInWidth);
+  Void encodeAlfParam(AlfParamSet* pAlfParamSet, Bool bSentInAPS = true, Int firstLCUAddr = 0, Bool alfAcrossSlice= true);
+  Void encodeAlfParamSet(AlfParamSet* pAlfParamSet, Int numLCUInWidth, Int numLCU, Int firstLCUAddr, Bool alfAcrossSlice, Int startCompIdx, Int endCompIdx);
+  Bool getAlfRepeatRowFlag(Int compIdx, AlfParamSet* pAlfParamSet, Int lcuIdx, Int lcuPos, Int startlcuPosX, Int endlcuPosX, Int numLCUInWidth);
+  Int  getAlfRun(Int compIdx, AlfParamSet* pAlfParamSet, Int lcuIdxInSlice, Int lcuPos, Int startlcuPosX, Int endlcuPosX);
+  Void encodeAPSAlfFlag(UInt code) {m_pcEntropyCoderIf->codeAPSAlflag(code);}
+  Void encodeAlfParam(ALFParam* pAlfParam);
+  
+  TEncEntropyIf*      m_pcEntropyCoderIf;
+  
+public:
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void encodeVPS               ( TComVPS* pcVPS);
+#endif
+  // SPS
+#if HHI_MPI || H3D_QTL 
+  Void encodeSPS               ( TComSPS* pcSPS, Bool bIsDepth );
+#else
+  Void encodeSPS               ( TComSPS* pcSPS );
+#endif
+  Void encodePPS               ( TComPPS* pcPPS );
+  void encodeSEI(const SEI&);
+  Bool getAlfCtrl() {return m_pcEntropyCoderIf->getAlfCtrl();}
+  UInt getMaxAlfCtrlDepth() {return m_pcEntropyCoderIf->getMaxAlfCtrlDepth();}
+  Void setAlfCtrl(Bool bAlfCtrl) {m_pcEntropyCoderIf->setAlfCtrl(bAlfCtrl);}
+  Void setMaxAlfCtrlDepth(UInt uiMaxAlfCtrlDepth) {m_pcEntropyCoderIf->setMaxAlfCtrlDepth(uiMaxAlfCtrlDepth);}
+  
+  Void encodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD = false );
+#if LGE_ILLUCOMP_B0045
+  Void encodeICFlag            ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false 
+#if LGE_ILLUCOMP_DEPTH_C0046
+      , UInt uiDepth = 0
+#endif
+      );
+#endif
+  Void encodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeInterDirPU   ( TComDataCU* pcSubCU, UInt uiAbsPartIdx  );
+  Void encodeRefFrmIdxPU  ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMvdPU        ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMVPIdxPU     ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx );
+  Void encodeMergeIndex   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx, Bool bRD = false );
+  Void encodeAlfCtrlFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+
+  /// set slice granularity
+  Void setSliceGranularity (Int iSliceGranularity) {m_pcEntropyCoderIf->setSliceGranularity(iSliceGranularity);}
+
+  /// encode ALF CU control flag
+  Void encodeAlfCtrlFlag(UInt uiFlag);
+  
+  Void encodeApsExtensionFlag() {m_pcEntropyCoderIf->codeApsExtensionFlag();};
+
+  Void encodeAlfCtrlParam(AlfCUCtrlInfo& cAlfParam, Int iNumCUsInPic);
+
+  Void encodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  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 encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  
+  Void encodeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
+  Void encodeQtCbf             ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  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 writeTileMarker              ( UInt uiTileIdx, UInt uiBitsUsed ) { m_pcEntropyCoderIf->writeTileMarker( uiTileIdx, uiBitsUsed ); }
+  
+  Void encodeAPSInitInfo          (TComAPS* pcAPS) {m_pcEntropyCoderIf->codeAPSInitInfo(pcAPS);}
+  Void encodeFinish               (Bool bEnd) {m_pcEntropyCoderIf->codeFinish(bEnd);}
+  Void encodeScalingList       ( TComScalingList* scalingList );
+  Void encodeDFParams          (TComAPS* pcAPS);
+  
+#if RWTH_SDC_DLT_B0036
+  Void encodeSDCFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeSDCResidualData  ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeSDCPredMode   ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+#endif
+
+private:
+  Void xEncodeTransform        ( TComDataCU* pcCU,UInt offsetLumaOffset, UInt offsetChroma, UInt uiAbsPartIdx, UInt absTUPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, UInt uiInnerQuadIdx, UInt& uiYCbfFront3, UInt& uiUCbfFront3, UInt& uiVCbfFront3, Bool& bCodeDQP );
+public:
+  Void encodeCoeff             ( TComDataCU* pcCU,                 UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
+  
+  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);
+  
+  // ALF-related
+  Void codeAuxCountBit(ALFParam* pAlfParam, Int64* ruiRate);
+  Void codeFiltCountBit(ALFParam* pAlfParam, Int64* ruiRate);
+  Void codeAux (ALFParam* pAlfParam);
+  Void codeFilt (ALFParam* pAlfParam);
+  Int codeFilterCoeff(ALFParam* ALFp);
+  Int writeFilterCodingParams(int minKStart, int minScanVal, int maxScanVal, int kMinTab[]);
+
+  Int writeFilterCoeffs(int sqrFiltLength, int filters_per_group, int pDepthInt[], 
+                        int **FilterCoeff, int kMinTab[]);
+  Int golombEncode(int coeff, int k);
+  Int lengthGolomb(int coeffVal, int k);
+  Void    encodeSaoUnit(Int rx, Int ry, Int compIdx, SAOParam* saoParam, Int repeatedRow);
+  Void    encodeSaoOffset(SaoLcuParam* saoLcuParam);
+  Void    encodeSaoUnitInterleaving(Int rx, Int ry, SAOParam* saoParam, TComDataCU* cu, Int cuAddrInSlice, Int cuAddrUpInSlice, Bool lfCrossSliceBoundaryFlag);
+  Void    encodeSaoParam         (TComAPS*  aps);
+
+  static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
+
+};// END CLASS DEFINITION TEncEntropy
+
+//! \}
+
+#endif // __TENCENTROPY__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 341)
@@ -0,0 +1,2272 @@
+/* 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-2012, 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     TEncGOP.cpp
+    \brief    GOP encoder class
+*/
+
+#include <list>
+#include <algorithm>
+
+#include "TEncTop.h"
+#include "TEncGOP.h"
+#include "TEncAnalyze.h"
+#include "libmd5/MD5.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/NAL.h"
+#include "NALwrite.h"
+#include "../../App/TAppEncoder/TAppEncTop.h"
+
+#include <time.h>
+#include <math.h>
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TEncGOP::TEncGOP()
+{
+  m_iLastIDR            = 0;
+  m_iGopSize            = 0;
+  m_iNumPicCoded        = 0; //Niko
+  m_bFirst              = true;
+  
+  m_pcCfg               = NULL;
+  m_pcSliceEncoder      = NULL;
+  m_pcListPic           = NULL;
+  
+  m_pcEntropyCoder      = NULL;
+  m_pcCavlcCoder        = NULL;
+  m_pcSbacCoder         = NULL;
+  m_pcBinCABAC          = NULL;
+#if DEPTH_MAP_GENERATION
+  m_pcDepthMapGenerator = NULL;
+#endif
+#if H3D_IVRP
+  m_pcResidualGenerator = NULL;
+#endif
+  
+  m_bSeqFirst           = true;
+  
+  m_bRefreshPending     = 0;
+  m_pocCRA              = 0;
+
+  return;
+}
+
+TEncGOP::~TEncGOP()
+{
+}
+
+/** Create list to contain pointers to LCU start addresses of slice.
+ * \param iWidth, iHeight are picture width, height. iMaxCUWidth, iMaxCUHeight are LCU width, height.
+ */
+Void  TEncGOP::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight )
+{
+  UInt uiWidthInCU       = ( iWidth %iMaxCUWidth  ) ? iWidth /iMaxCUWidth  + 1 : iWidth /iMaxCUWidth;
+  UInt uiHeightInCU      = ( iHeight%iMaxCUHeight ) ? iHeight/iMaxCUHeight + 1 : iHeight/iMaxCUHeight;
+  UInt uiNumCUsInFrame   = uiWidthInCU * uiHeightInCU;
+  m_uiStoredStartCUAddrForEncodingSlice = new UInt [uiNumCUsInFrame*(1<<(g_uiMaxCUDepth<<1))+1];
+  m_uiStoredStartCUAddrForEncodingEntropySlice = new UInt [uiNumCUsInFrame*(1<<(g_uiMaxCUDepth<<1))+1];
+  m_bLongtermTestPictureHasBeenCoded = 0;
+  m_bLongtermTestPictureHasBeenCoded2 = 0;
+}
+
+Void  TEncGOP::destroy()
+{
+  delete [] m_uiStoredStartCUAddrForEncodingSlice; m_uiStoredStartCUAddrForEncodingSlice = NULL;
+  delete [] m_uiStoredStartCUAddrForEncodingEntropySlice; m_uiStoredStartCUAddrForEncodingEntropySlice = NULL;
+}
+
+Void TEncGOP::init ( TEncTop* pcTEncTop )
+{
+  m_pcEncTop     = pcTEncTop;
+  m_pcCfg                = pcTEncTop;
+  m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
+  m_pcListPic            = pcTEncTop->getListPic();
+  
+  m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
+  m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
+  m_pcSbacCoder          = pcTEncTop->getSbacCoder();
+  m_pcBinCABAC           = pcTEncTop->getBinCABAC();
+  m_pcLoopFilter         = pcTEncTop->getLoopFilter();
+  m_pcBitCounter         = pcTEncTop->getBitCounter();
+  
+#if DEPTH_MAP_GENERATION
+  m_pcDepthMapGenerator  = pcTEncTop->getDepthMapGenerator();
+#endif
+#if H3D_IVRP
+  m_pcResidualGenerator  = pcTEncTop->getResidualGenerator();
+#endif
+  
+  // Adaptive Loop filter
+  m_pcAdaptiveLoopFilter = pcTEncTop->getAdaptiveLoopFilter();
+  //--Adaptive Loop filter
+  m_pcSAO                = pcTEncTop->getSAO();
+  m_pcRdCost             = pcTEncTop->getRdCost();
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncGOP::initGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+{
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
+  m_iNumPicCoded = 0;
+}
+
+Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid)
+{
+  TComPic*        pcPic;
+  TComPicYuv*     pcPicYuvRecOut;
+  TComSlice*      pcSlice;
+  TComOutputBitstream  *pcBitstreamRedirect;
+  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;
+
+  {
+      UInt uiColDir = 1;
+      //-- 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;
+      }
+
+      /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
+      UInt uiPOCCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
+      Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+      if(iPOCLast == 0)
+      {
+        uiPOCCurr=0;
+        iTimeOffset = 1;
+      }
+      if(uiPOCCurr>=m_pcCfg->getFrameToBeEncoded())
+      {
+        return;
+      }        
+      if( getNalUnitTypeBaseViewMvc( uiPOCCurr ) == NAL_UNIT_CODED_SLICE_IDR )
+      {
+        m_iLastIDR = uiPOCCurr;
+      }        
+
+      /* 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, uiPOCCurr );
+      
+      //  Slice data initialization
+      pcPic->clearSliceBuffer();
+      assert(pcPic->getNumAllocatedSlice() == 1);
+      m_pcSliceEncoder->setSliceIdx(0);
+      pcPic->setCurrSliceIdx(0);
+
+      std::vector<TComAPS>& vAPS = m_pcEncTop->getAPS();
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, uiPOCCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getEncTop()->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), m_pcEncTop->getIsDepth() );
+#else
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, uiPOCCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getEncTop()->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
+#endif
+#else
+      m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, uiPOCCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
+#endif
+      pcSlice->setLastIDR(m_iLastIDR);
+      pcSlice->setSliceIdx(0);
+      pcSlice->setViewId( m_pcEncTop->getViewId() );
+      pcSlice->setIsDepth( m_pcEncTop->getIsDepth() );
+#if INTER_VIEW_VECTOR_SCALING_C0115
+      pcSlice->setIVScalingFlag( m_pcEncTop->getUseIVS() );
+#endif
+
+      m_pcEncTop->getSPS()->setDisInter4x4(m_pcEncTop->getDisInter4x4());
+      pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
+      if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
+      {
+        m_pcEncTop->getTrQuant()->setFlatScalingList();
+        m_pcEncTop->getTrQuant()->setUseScalingList(false);
+      }
+      else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
+      {
+        pcSlice->setDefaultScalingList ();
+        pcSlice->getScalingList()->setScalingListPresentFlag(true);
+        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();
+        pcSlice->getScalingList()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
+        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 HHI_INTERVIEW_SKIP
+      if ( m_pcEncTop->getInterViewSkip() )
+      {
+        m_pcEncTop->getEncTop()->getUsedPelsMap( pcPic->getViewId(), pcPic->getPOC(), pcPic->getUsedPelsMap() );
+      }
+#endif
+      //  Slice info. refinement
+      if( pcSlice->getSliceType() == B_SLICE )
+      {
+#if QC_REM_IDV_B0046
+      if( m_pcCfg->getGOPEntry(pcSlice->getSPS()->getViewId() && ((getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR) || (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_CRA))? MAX_GOP : iGOPid ).m_sliceType == 'P' ) { pcSlice->setSliceType( P_SLICE ); }
+#else
+      if( m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) { pcSlice->setSliceType( P_SLICE ); }
+#endif
+    }
+
+      // Set the nal unit type
+      pcSlice->setNalUnitType( getNalUnitType(uiPOCCurr) );
+      pcSlice->setNalUnitTypeBaseViewMvc( getNalUnitTypeBaseViewMvc(uiPOCCurr) );
+
+      // Do decoding refresh marking if any 
+      pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+
+      if ( !pcSlice->getPPS()->getEnableTMVPFlag() && pcPic->getTLayer() == 0 )
+      {
+        pcSlice->decodingMarkingForNoTMVP( rcListPic, pcSlice->getPOC() );
+      }
+
+      m_pcEncTop->selectReferencePictureSet(pcSlice, uiPOCCurr, iGOPid,rcListPic);
+      pcSlice->getRPS()->setNumberOfLongtermPictures(0);
+
+      if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
+      {
+         pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
+      }
+      pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
+
+#if H0566_TLA_SET_FOR_SWITCHING_POINTS
+      if(pcSlice->getTLayer() > 0)
+      {
+        if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic, pcSlice->getRPS()))
+        {
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA);
+        }
+      }
+#endif
+
+#if !QC_REM_IDV_B0046
+      pcSlice->setNumRefIdx( REF_PIC_LIST_0, min( m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid ).m_numRefPicsActive, (pcSlice->getRPS()->getNumberOfPictures() + pcSlice->getSPS()->getNumberOfUsableInterViewRefs()) ) );
+      pcSlice->setNumRefIdx( REF_PIC_LIST_1, min( m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid ).m_numRefPicsActive, (pcSlice->getRPS()->getNumberOfPictures() + pcSlice->getSPS()->getNumberOfUsableInterViewRefs()) ) );
+#else
+
+      Bool bNalRAP = ((getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_CRA) || (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR)) && (pcSlice->getSPS()->getViewId())  ? 1: 0;
+      pcSlice->setNumRefIdx( REF_PIC_LIST_0, min( m_pcCfg->getGOPEntry( bNalRAP ? MAX_GOP : iGOPid ).m_numRefPicsActive, (pcSlice->getRPS()->getNumberOfPictures() + pcSlice->getSPS()->getNumberOfUsableInterViewRefs()) ) );
+      pcSlice->setNumRefIdx( REF_PIC_LIST_1, min( m_pcCfg->getGOPEntry( bNalRAP ? MAX_GOP : iGOPid ).m_numRefPicsActive, (pcSlice->getRPS()->getNumberOfPictures() + pcSlice->getSPS()->getNumberOfUsableInterViewRefs()) ) );
+#endif
+      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+      refPicListModification->setRefPicListModificationFlagL0( false );
+      refPicListModification->setRefPicListModificationFlagL1( false );
+      xSetRefPicListModificationsMvc( pcSlice, uiPOCCurr, iGOPid );
+
+#if ADAPTIVE_QP_SELECTION
+      pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
+#endif      
+      //  Set reference list
+      TAppEncTop* tAppEncTop = m_pcEncTop->getEncTop();
+      assert( tAppEncTop != NULL );
+
+
+#if FLEX_CODING_ORDER_M23723
+      TComPic * pcTexturePic; 
+      if(m_pcEncTop->getIsDepth() == 1)
+      {
+        TComPicYuv * recText;
+        recText = tAppEncTop->getPicYuvFromView(m_pcEncTop->getViewId(), pcSlice->getPOC(), false ,true);
+        if(recText == NULL)
+        {
+           pcSlice->setTexturePic(NULL);
+        }
+        else
+        {
+           pcTexturePic = m_pcEncTop->getIsDepth() ? tAppEncTop->getPicFromView( m_pcEncTop->getViewId(), pcSlice->getPOC(), false ) : NULL;
+           pcSlice->setTexturePic( pcTexturePic );
+        }
+      }
+      else
+    {
+        pcTexturePic = m_pcEncTop->getIsDepth() ? tAppEncTop->getPicFromView( m_pcEncTop->getViewId(), pcSlice->getPOC(), false ) : NULL;
+        assert( !m_pcEncTop->getIsDepth() || pcTexturePic != NULL );
+          pcSlice->setTexturePic( pcTexturePic );
+      }
+
+#else
+      TComPic * const pcTexturePic = m_pcEncTop->getIsDepth() ? tAppEncTop->getPicFromView( m_pcEncTop->getViewId(), pcSlice->getPOC(), false ) : NULL;
+      assert( !m_pcEncTop->getIsDepth() || pcTexturePic != NULL );
+      pcSlice->setTexturePic( pcTexturePic );
+
+#endif 
+      std::vector<TComPic*> apcInterViewRefPics = tAppEncTop->getInterViewRefPics( m_pcEncTop->getViewId(), pcSlice->getPOC(), m_pcEncTop->getIsDepth(), pcSlice->getSPS() );
+      pcSlice->setRefPicListMvc( rcListPic, apcInterViewRefPics );
+
+      //  Slice info. refinement
+      if( pcSlice->getSliceType() == B_SLICE )
+      {
+#if !QC_REM_IDV_B0046
+        if( m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) { pcSlice->setSliceType( P_SLICE ); }
+#else
+      Bool bRAP = ((getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_CRA) || (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR)) && (pcSlice->getSPS()->getViewId())  ? 1: 0;
+      if( m_pcCfg->getGOPEntry( bRAP ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) { pcSlice->setSliceType( P_SLICE ); }
+#endif
+      }
+      
+      if (pcSlice->getSliceType() != B_SLICE || !pcSlice->getSPS()->getUseLComb())
+      {
+        pcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
+        pcSlice->setRefPicListCombinationFlag(false);
+        pcSlice->setRefPicListModificationFlagLC(false);
+      }
+      else
+      {
+        pcSlice->setRefPicListCombinationFlag(pcSlice->getSPS()->getUseLComb());
+        pcSlice->setRefPicListModificationFlagLC(pcSlice->getSPS()->getLCMod());
+        pcSlice->setNumRefIdx(REF_PIC_LIST_C, pcSlice->getNumRefIdx(REF_PIC_LIST_0));
+      }
+      
+      if (pcSlice->getSliceType() == B_SLICE)
+      {
+        pcSlice->setColDir(uiColDir);
+        Bool bLowDelay = true;
+        Int  iCurrPOC  = pcSlice->getPOC();
+        Int iRefIdx = 0;
+
+        for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
+        {
+          if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
+          {
+            bLowDelay = false;
+          }
+        }
+        for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
+        {
+          if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
+          {
+            bLowDelay = false;
+          }
+        }
+
+        pcSlice->setCheckLDC(bLowDelay);  
+      }
+      
+      uiColDir = 1-uiColDir;
+      
+      //-------------------------------------------------------------
+      pcSlice->setRefPOCnViewListsMvc();
+      
+      pcSlice->setNoBackPredFlag( false );
+      if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
+      {
+        if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
+        {
+          pcSlice->setNoBackPredFlag( true );
+          int i;
+          for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
+          {
+            if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+            {
+              pcSlice->setNoBackPredFlag( false );
+              break;
+            }
+          }
+        }
+      }
+
+      if(pcSlice->getNoBackPredFlag())
+      {
+        pcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
+      }
+      pcSlice->generateCombinedList();
+      
+#if HHI_VSO
+  Bool bUseVSO = m_pcEncTop->getUseVSO();
+  m_pcRdCost->setUseVSO( bUseVSO );
+#if SAIT_VSO_EST_A0033
+  m_pcRdCost->setUseEstimatedVSD( m_pcEncTop->getUseEstimatedVSD() );
+#endif
+
+  if ( bUseVSO )
+  {
+    Int iVSOMode = m_pcEncTop->getVSOMode();
+    m_pcRdCost->setVSOMode( iVSOMode  );
+
+#if HHI_VSO_DIST_INT
+    m_pcRdCost->setAllowNegDist( m_pcEncTop->getAllowNegDist() );
+#endif
+
+
+#if SAIT_VSO_EST_A0033
+#ifdef FLEX_CODING_ORDER_M23723    
+{
+  Bool flagRec;
+  flagRec =  ((m_pcEncTop->getEncTop()->getPicYuvFromView( pcSlice->getViewId(), pcSlice->getPOC(), false, true) == NULL) ? false: true);
+  m_pcRdCost->setVideoRecPicYuv( m_pcEncTop->getEncTop()->getPicYuvFromView( pcSlice->getViewId(), pcSlice->getPOC(), false, flagRec ) );
+  m_pcRdCost->setDepthPicYuv   ( m_pcEncTop->getEncTop()->getPicYuvFromView( pcSlice->getViewId(), pcSlice->getPOC(), true, false ) );
+}
+#else
+  m_pcRdCost->setVideoRecPicYuv( m_pcEncTop->getEncTop()->getPicYuvFromView( pcSlice->getViewId(), pcSlice->getPOC(), false, true ) );
+  m_pcRdCost->setDepthPicYuv   ( m_pcEncTop->getEncTop()->getPicYuvFromView( pcSlice->getViewId(), pcSlice->getPOC(), true, false ) );
+#endif
+#endif
+#if LGE_WVSO_A0119
+    Bool bUseWVSO  = m_pcEncTop->getUseWVSO();
+    m_pcRdCost->setUseWVSO( bUseWVSO );
+#endif
+
+  }
+#endif
+      /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
+      //  Slice compression
+      if (m_pcCfg->getUseASR())
+      {
+        m_pcSliceEncoder->setSearchRange(pcSlice);
+      }
+
+      Bool bGPBcheck=false;
+      if ( pcSlice->getSliceType() == B_SLICE)
+      {
+        if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
+        {
+          bGPBcheck=true;
+          int i;
+          for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
+          {
+            if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+            {
+              bGPBcheck=false;
+              break;
+            }
+          }
+        }
+      }
+      if(bGPBcheck)
+      {
+        pcSlice->setMvdL1ZeroFlag(true);
+      }
+      else
+      {
+        pcSlice->setMvdL1ZeroFlag(false);
+      }
+      pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
+
+      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;
+
+    UInt uiCummulativeTileWidth;
+    UInt uiCummulativeTileHeight;
+    Int  p, j;
+    UInt uiEncCUAddr;
+    
+
+    if( pcSlice->getPPS()->getColumnRowInfoPresent() == 1 )    //derive the tile parameters from PPS
+    {
+      //set NumColumnsMinus1 and NumRowsMinus1
+      pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
+      pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
+
+      //create the TComTileArray
+      pcPic->getPicSym()->xCreateTComTileArray();
+
+      if( pcSlice->getPPS()->getUniformSpacingIdr() == 1 )
+      {
+        //set the width for each tile
+        for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+        {
+          for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
+          {
+            pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
+              setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
+              - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
+          }
+        }
+
+        //set the height for each tile
+        for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+        {
+          for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
+          {
+            pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
+              setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
+              - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
+          }
+        }
+      }
+      else
+      {
+        //set the width for each tile
+        for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+        {
+          uiCummulativeTileWidth = 0;
+          for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
+          {
+            pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getPPS()->getColumnWidth(p) );
+            uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(p);
+          }
+          pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
+        }
+
+        //set the height for each tile
+        for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+        {
+          uiCummulativeTileHeight = 0;
+          for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
+          {
+            pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getPPS()->getRowHeight(p) );
+            uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(p);
+          }
+          pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
+        }
+      }
+    }
+    else //derive the tile parameters from SPS
+    {
+      //set NumColumnsMins1 and NumRowsMinus1
+      pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getSPS()->getNumColumnsMinus1() );
+      pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getSPS()->getNumRowsMinus1() );
+
+      //create the TComTileArray
+      pcPic->getPicSym()->xCreateTComTileArray();
+
+      if( pcSlice->getSPS()->getUniformSpacingIdr() == 1 )
+      {
+        //set the width for each tile
+        for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+        {
+          for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
+          {
+            pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
+              setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
+              - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
+          }
+        }
+
+        //set the height for each tile
+        for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+        {
+          for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
+          {
+            pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
+              setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
+              - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
+          }
+        }
+      }
+
+      else
+      {
+        //set the width for each tile
+        for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+        {
+          uiCummulativeTileWidth = 0;
+          for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
+          {
+            pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getSPS()->getColumnWidth(p) );
+            uiCummulativeTileWidth += pcSlice->getSPS()->getColumnWidth(p);
+          }
+          pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
+        }
+
+        //set the height for each tile
+        for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+        {
+          uiCummulativeTileHeight = 0;
+          for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
+          {
+            pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getSPS()->getRowHeight(p) );
+            uiCummulativeTileHeight += pcSlice->getSPS()->getRowHeight(p);
+          }
+          pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
+        }
+      }
+    }
+
+    //initialize each tile of the current picture
+    pcPic->getPicSym()->xInitTiles();
+
+    // 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());
+    if (pcSlice->getPPS()->getEntropyCodingMode())
+    {
+      // Allocate some coders, now we know how many tiles there are.
+      m_pcEncTop->createWPPCoders(iNumSubstreams);
+      pcSbacCoders = m_pcEncTop->getSbacCoders();
+      pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
+    }
+
+      UInt uiStartCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
+      UInt uiStartCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
+      pcSlice->setSliceCurStartCUAddr( uiStartCUAddrSlice ); // Setting "start CU addr" for current slice
+      memset(m_uiStoredStartCUAddrForEncodingSlice, 0, sizeof(UInt) * (pcPic->getPicSym()->getNumberOfCUsInFrame()*pcPic->getNumPartInCU()+1));
+
+      UInt uiStartCUAddrEntropySliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
+      UInt uiStartCUAddrEntropySlice    = 0; // used to keep track of current Entropy slice's starting CU addr.
+      pcSlice->setEntropySliceCurStartCUAddr( uiStartCUAddrEntropySlice ); // Setting "start CU addr" for current Entropy slice
+      
+      memset(m_uiStoredStartCUAddrForEncodingEntropySlice, 0, sizeof(UInt) * (pcPic->getPicSym()->getNumberOfCUsInFrame()*pcPic->getNumPartInCU()+1));
+      UInt uiNextCUAddr = 0;
+      m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx++]                = uiNextCUAddr;
+      m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = uiNextCUAddr;
+
+#if FCO_DVP_REFINE_C0132_C0170
+      pcPic->setDepthCoded(false);
+
+      if(pcSlice->getViewId() != 0)
+      {
+        if(pcSlice->getSPS()->isDepth() == 0 )
+        {
+          TComPic * recDepthMapBuffer;
+          recDepthMapBuffer = m_pcEncTop->getEncTop()->getPicFromView( pcSlice->getViewId(), pcSlice->getPOC(), true );
+          pcSlice->getPic()->setRecDepthMap(recDepthMapBuffer);
+          if(recDepthMapBuffer->getReconMark())
+          {
+            pcPic->setDepthCoded(true);
+          }
+        }
+      }
+#endif
+
+#if DEPTH_MAP_GENERATION
+      // init view component and predict virtual depth map
+      m_pcDepthMapGenerator->initViewComponent( pcPic );
+#if !H3D_NBDV
+      m_pcDepthMapGenerator->predictDepthMap  ( pcPic );
+#endif
+#endif
+#if H3D_IVMP
+      m_pcDepthMapGenerator->covertOrgDepthMap( pcPic );
+#endif
+#if H3D_IVRP
+      m_pcResidualGenerator->initViewComponent( pcPic );
+#endif
+
+#if H3D_NBDV
+      if(pcSlice->getViewId() && pcSlice->getSPS()->getMultiviewMvPredMode())
+      {
+        Int iColPoc = pcSlice->getRefPOC(RefPicList(pcSlice->getColDir()), pcSlice->getColRefIdx());
+        pcPic->setRapbCheck(pcPic->getDisCandRefPictures(iColPoc));
+      }
+#endif
+      while(uiNextCUAddr<uiRealEndAddress) // determine slice boundaries
+      {
+        pcSlice->setNextSlice       ( false );
+        pcSlice->setNextEntropySlice( false );
+        assert(pcPic->getNumAllocatedSlice() == uiStartCUAddrSliceIdx);
+        m_pcSliceEncoder->precompressSlice( pcPic );
+        m_pcSliceEncoder->compressSlice   ( pcPic );
+
+        Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextEntropySlice());
+        if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE))
+        {
+          uiStartCUAddrSlice                                              = pcSlice->getSliceCurEndCUAddr();
+          // Reconstruction slice
+          m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx++]  = uiStartCUAddrSlice;
+          // Entropy slice
+          if (uiStartCUAddrEntropySliceIdx>0 && m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx-1] != uiStartCUAddrSlice)
+          {
+            m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = uiStartCUAddrSlice;
+          }
+          
+          if (uiStartCUAddrSlice < uiRealEndAddress)
+          {
+            pcPic->allocateNewSlice();          
+            pcPic->setCurrSliceIdx                  ( uiStartCUAddrSliceIdx-1 );
+            m_pcSliceEncoder->setSliceIdx           ( uiStartCUAddrSliceIdx-1 );
+            pcSlice = pcPic->getSlice               ( uiStartCUAddrSliceIdx-1 );
+            pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
+            pcSlice->setSliceIdx                    ( uiStartCUAddrSliceIdx-1 );
+            pcSlice->setSliceCurStartCUAddr         ( uiStartCUAddrSlice      );
+            pcSlice->setEntropySliceCurStartCUAddr  ( uiStartCUAddrSlice      );
+            pcSlice->setSliceBits(0);
+            uiNumSlices ++;
+          }
+        }
+        else if (pcSlice->isNextEntropySlice() || (bNoBinBitConstraintViolated && m_pcCfg->getEntropySliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE))
+        {
+          uiStartCUAddrEntropySlice                                                     = pcSlice->getEntropySliceCurEndCUAddr();
+          m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = uiStartCUAddrEntropySlice;
+          pcSlice->setEntropySliceCurStartCUAddr( uiStartCUAddrEntropySlice );
+        }
+        else
+        {
+          uiStartCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
+          uiStartCUAddrEntropySlice                                                     = pcSlice->getEntropySliceCurEndCUAddr();
+        }        
+
+        uiNextCUAddr = (uiStartCUAddrSlice > uiStartCUAddrEntropySlice) ? uiStartCUAddrSlice : uiStartCUAddrEntropySlice;
+      }
+      m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx++]                = pcSlice->getSliceCurEndCUAddr();
+      m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = pcSlice->getSliceCurEndCUAddr();
+      
+      pcSlice = pcPic->getSlice(0);
+
+#if H3D_IVRP
+      // set residual picture
+      m_pcResidualGenerator->setRecResidualPic( pcPic );
+#endif
+#if DEPTH_MAP_GENERATION
+#if !H3D_NBDV
+      // update virtual depth map
+      m_pcDepthMapGenerator->updateDepthMap( pcPic );
+#endif
+#endif
+
+      //-- Loop filter
+      Bool bLFCrossTileBoundary = (pcSlice->getPPS()->getTileBehaviorControlPresentFlag() == 1)?
+                                  (pcSlice->getPPS()->getLFCrossTileBoundaryFlag()):(pcSlice->getPPS()->getSPS()->getLFCrossTileBoundaryFlag());
+      m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresent(), pcSlice->getLoopFilterDisable(), pcSlice->getLoopFilterBetaOffset(), pcSlice->getLoopFilterTcOffset(), bLFCrossTileBoundary);
+      m_pcLoopFilter->loopFilterPic( pcPic );
+
+      pcSlice = pcPic->getSlice(0);
+      if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+      {
+        Int sliceGranularity = pcSlice->getPPS()->getSliceGranularity();
+        pcPic->createNonDBFilterInfo(m_uiStoredStartCUAddrForEncodingSlice, uiNumSlices, sliceGranularity, pcSlice->getSPS()->getLFCrossSliceBoundaryFlag(),pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
+      }
+
+
+      pcSlice = pcPic->getSlice(0);
+
+      if(pcSlice->getSPS()->getUseSAO())
+      {
+        m_pcSAO->createPicSaoInfo(pcPic, uiNumSlices);
+      }
+
+      AlfParamSet* alfSliceParams = NULL;
+      std::vector<AlfCUCtrlInfo>* alfCUCtrlParam = NULL;
+      pcSlice = pcPic->getSlice(0);
+
+      if(pcSlice->getSPS()->getUseALF())
+      {
+        m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic, uiNumSlices, pcSlice->getSliceQp());
+        m_pcAdaptiveLoopFilter->initALFEnc(m_pcCfg->getALFParamInSlice(), m_pcCfg->getALFPicBasedEncode(), uiNumSlices, alfSliceParams, alfCUCtrlParam);
+      }
+
+      /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
+      // Set entropy coder
+      m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+
+      /* write various header sets. */
+      if ( m_bSeqFirst )
+      {
+#if QC_MVHEVC_B0046
+      if(!m_pcEncTop->getLayerId())
+      {
+#endif
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+        {
+          OutputNALUnit nalu(NAL_UNIT_VPS, true, m_pcEncTop->getLayerId());
+          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+          m_pcEntropyCoder->encodeVPS(m_pcEncTop->getEncTop()->getVPS());
+          writeRBSPTrailingBits(nalu.m_Bitstream);
+          accessUnit.push_back(new NALUnitEBSP(nalu));
+        }
+#endif
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+        OutputNALUnit nalu(NAL_UNIT_SPS, true, m_pcEncTop->getLayerId());
+#else
+        OutputNALUnit nalu(NAL_UNIT_SPS, true, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
+#endif
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+        pcSlice->getSPS()->setNumSubstreams( pcSlice->getPPS()->getNumSubstreams() );
+#if HHI_MPI || H3D_QTL
+        m_pcEntropyCoder->encodeSPS(pcSlice->getSPS(), m_pcEncTop->getIsDepth());
+#else
+        m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
+#endif
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046 
+#if QC_MVHEVC_B0046
+        nalu = NALUnit(NAL_UNIT_PPS, true, m_pcEncTop->getLayerId());
+#else
+        nalu = NALUnit(NAL_UNIT_PPS, true, m_pcEncTop->getLayerId());
+#endif
+#else
+        nalu = NALUnit(NAL_UNIT_PPS, true, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
+#endif
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+        m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+#if QC_MVHEVC_B0046
+      }
+#endif
+      m_bSeqFirst = false;
+    }
+
+      /* use the main bitstream buffer for storing the marshalled picture */
+      m_pcEntropyCoder->setBitstream(NULL);
+
+      uiStartCUAddrSliceIdx = 0;
+      uiStartCUAddrSlice    = 0; 
+
+      uiStartCUAddrEntropySliceIdx = 0;
+      uiStartCUAddrEntropySlice    = 0; 
+      uiNextCUAddr                 = 0;
+      pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
+
+      Int processingState = (pcSlice->getSPS()->getUseALF() || pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getScalingListFlag() || pcSlice->getSPS()->getUseDF())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
+
+      static Int iCurrAPSIdx = 0;
+      Int iCodedAPSIdx = 0;
+      TComSlice* pcSliceForAPS = NULL;
+
+      bool skippedSlice=false;
+      while (uiNextCUAddr < uiRealEndAddress) // Iterate over all slices
+      {
+        switch(processingState)
+        {
+        case ENCODE_SLICE:
+          {
+        pcSlice->setNextSlice       ( false );
+        pcSlice->setNextEntropySlice( false );
+        if (uiNextCUAddr == m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx])
+        {
+          pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
+#if COLLOCATED_REF_IDX
+          if(uiStartCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
+          {
+            pcSlice->checkColRefIdx(uiStartCUAddrSliceIdx, pcPic);
+          }
+#endif
+          pcPic->setCurrSliceIdx(uiStartCUAddrSliceIdx);
+          m_pcSliceEncoder->setSliceIdx(uiStartCUAddrSliceIdx);
+          assert(uiStartCUAddrSliceIdx == pcSlice->getSliceIdx());
+          // Reconstruction slice
+          pcSlice->setSliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
+          pcSlice->setSliceCurEndCUAddr  ( m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx+1 ] );
+          // Entropy slice
+          pcSlice->setEntropySliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
+          pcSlice->setEntropySliceCurEndCUAddr  ( m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx+1 ] );
+
+          pcSlice->setNextSlice       ( true );
+
+          uiStartCUAddrSliceIdx++;
+          uiStartCUAddrEntropySliceIdx++;
+        } 
+        else if (uiNextCUAddr == m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx])
+        {
+          // Entropy slice
+          pcSlice->setEntropySliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
+          pcSlice->setEntropySliceCurEndCUAddr  ( m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx+1 ] );
+
+          pcSlice->setNextEntropySlice( true );
+
+          uiStartCUAddrEntropySliceIdx++;
+        }
+
+      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->getEntropySliceCurEndCUAddr()-1) % pcPic->getNumPartInCU();
+        uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getEntropySliceCurEndCUAddr()-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 uiEndAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
+        if(uiEndAddress<=pcSlice->getEntropySliceCurStartCUAddr()) {
+          UInt uiBoundingAddrSlice, uiBoundingAddrEntropySlice;
+          uiBoundingAddrSlice        = m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];          
+          uiBoundingAddrEntropySlice = m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx];          
+          uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrEntropySlice);
+          if(pcSlice->isNextSlice())
+          {
+            skippedSlice=true;
+          }
+          continue;
+        }
+        if(skippedSlice) 
+        {
+          pcSlice->setNextSlice       ( true );
+          pcSlice->setNextEntropySlice( false );
+        }
+        skippedSlice=false;
+        if (pcSlice->getPPS()->getEntropyCodingMode())
+        {
+          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 */
+        OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->isReferenced(),
+#if !VIDYO_VPS_INTEGRATION &!QC_MVHEVC_B0046
+                           m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth(), pcSlice->getTLayer() );
+#else
+                           m_pcEncTop->getLayerId(), pcSlice->getTLayer() );
+#endif
+            
+        Bool bEntropySlice = (!pcSlice->isNextSlice());
+        if (!bEntropySlice)
+        {
+          uiOneBitstreamPerSliceLength = 0; // start of a new slice
+        }
+
+        // used while writing slice header
+        Int iTransmitLWHeader = (m_pcCfg->getTileMarkerFlag()==0) ? 0 : 1;
+        pcSlice->setTileMarkerFlag ( iTransmitLWHeader );
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if !CABAC_INIT_FLAG
+        pcSlice->setCABACinitIDC(pcSlice->getSliceType());
+#endif
+
+        m_pcEntropyCoder->encodeSliceHeader(pcSlice);
+
+        if(pcSlice->isNextSlice())
+        {
+          if (pcSlice->getSPS()->getUseALF())
+          {
+            if(pcSlice->getAlfEnabledFlag())
+            {
+
+              if( pcSlice->getSPS()->getUseALFCoefInSlice())
+              {
+                Int iNumSUinLCU    = 1<< (g_uiMaxCUDepth << 1); 
+                Int firstLCUAddr   = pcSlice->getSliceCurStartCUAddr() / iNumSUinLCU;  
+                Bool isAcrossSlice = pcSlice->getSPS()->getLFCrossSliceBoundaryFlag();
+                m_pcEntropyCoder->encodeAlfParam( &(alfSliceParams[pcSlice->getSliceIdx()]), false, firstLCUAddr, isAcrossSlice);
+              }
+
+              if( !pcSlice->getSPS()->getUseALFCoefInSlice())
+              {
+                AlfCUCtrlInfo& cAlfCUCtrlParam = (*alfCUCtrlParam)[pcSlice->getSliceIdx()];
+              if(cAlfCUCtrlParam.cu_control_flag)
+              {
+                m_pcEntropyCoder->setAlfCtrl( true );
+                m_pcEntropyCoder->setMaxAlfCtrlDepth(cAlfCUCtrlParam.alf_max_depth);
+                m_pcCavlcCoder->setAlfCtrl(true);
+                m_pcCavlcCoder->setMaxAlfCtrlDepth(cAlfCUCtrlParam.alf_max_depth); 
+              }
+              else
+              {
+                m_pcEntropyCoder->setAlfCtrl(false);
+              }
+              m_pcEntropyCoder->encodeAlfCtrlParam(cAlfCUCtrlParam, m_pcAdaptiveLoopFilter->getNumCUsInPic());
+            
+              }
+            }
+          }
+        }
+        m_pcEntropyCoder->encodeTileMarkerFlag(pcSlice);
+
+        // is it needed?
+        {
+          if (!bEntropySlice)
+          {
+            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 (!bEntropySlice)
+          {
+            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 );
+        if (!bEntropySlice)
+        {
+          pcSlice->setTileLocationCount ( 0 );
+          m_pcSliceEncoder->encodeSlice(pcPic, pcBitstreamRedirect, pcSubstreamsOut); // redirect is only used for CAVLC tile position info.
+        }
+        else
+        {
+          m_pcSliceEncoder->encodeSlice(pcPic, &nalu.m_Bitstream, pcSubstreamsOut); // nalu.m_Bitstream is only used for CAVLC tile position info.
+        }
+
+        {
+          // 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].write( 1, 1 ); // stop bit.
+            pcSubstreamsOut[ui].writeAlignZero();
+            // 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)
+              {
+                // byte align.
+                while (uiTotalCodedSize&0x7)
+                {
+                  pcSubstreamsOut[ui].write(0, 1);
+                  uiTotalCodedSize++;
+                }
+              }
+              Bool bRecordOffsetNext = m_pcCfg->getTileLocationInSliceHeaderFlag()
+                                            && bNextSubstreamInNewTile;
+              if (bRecordOffsetNext)
+                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
+            }
+            if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
+              puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits();
+          }
+          // Complete the slice header info.
+          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+          if (m_pcCfg->getTileLocationInSliceHeaderFlag()==0) 
+          {
+            pcSlice->setTileLocationCount( 0 );
+          }
+          m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
+          // Substreams...
+          TComOutputBitstream *pcOut = pcBitstreamRedirect;
+          // xWriteTileLocation will perform byte-alignment...
+          {
+            if (bEntropySlice)
+            {
+              // In these cases, padding is necessary here.
+              pcOut = &nalu.m_Bitstream;
+              pcOut->writeAlignOne();
+            }
+          }
+          UInt uiAccumulatedLength = 0;
+          for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams(); ui++ )
+          {
+            pcOut->addSubstream(&pcSubstreamsOut[ui]);
+
+            // Update tile marker location information
+            for (Int uiMrkIdx = 0; uiMrkIdx < pcSubstreamsOut[ui].getTileMarkerLocationCount(); uiMrkIdx++)
+            {
+              UInt uiBottom = pcOut->getTileMarkerLocationCount();
+              pcOut->setTileMarkerLocation      ( uiBottom, uiAccumulatedLength + pcSubstreamsOut[ui].getTileMarkerLocation( uiMrkIdx ) );
+              pcOut->setTileMarkerLocationCount ( uiBottom + 1 );
+            }
+            uiAccumulatedLength = (pcOut->getNumberOfWrittenBits() >> 3);
+          }
+        }
+
+        UInt uiBoundingAddrSlice, uiBoundingAddrEntropySlice;
+        uiBoundingAddrSlice        = m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];          
+        uiBoundingAddrEntropySlice = m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx];          
+        uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrEntropySlice);
+        // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple entropy 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.
+        xWriteTileLocationToSliceHeader(nalu, pcBitstreamRedirect, pcSlice);
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+        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
+        }
+
+
+        processingState = ENCODE_SLICE;
+          }
+          break;
+        case EXECUTE_INLOOPFILTER:
+          {
+            TComAPS cAPS;
+            allocAPS(&cAPS, pcSlice->getSPS());
+            cAPS.setSaoInterleavingFlag(m_pcCfg->getSaoInterleavingFlag());
+            // set entropy coder for RD
+            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+
+            if ( pcSlice->getSPS()->getUseSAO() )
+            {
+              m_pcEntropyCoder->resetEntropy();
+              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
+              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), NULL);
+              SAOParam& cSaoParam = *(cAPS.getSaoParam());
+
+#if SAO_CHROMA_LAMBDA 
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
+#else
+#if ALF_CHROMA_LAMBDA
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma());
+#else
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
+#endif
+#endif
+              m_pcSAO->endSaoEnc();
+
+              m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
+            }
+
+            // adaptive loop filter
+            if ( pcSlice->getSPS()->getUseALF())
+            {
+              m_pcEntropyCoder->resetEntropy    ();
+              m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+              m_pcAdaptiveLoopFilter->startALFEnc(pcPic, m_pcEntropyCoder );
+              AlfParamSet* pAlfEncParam = (pcSlice->getSPS()->getUseALFCoefInSlice())?( alfSliceParams ):( cAPS.getAlfParam());
+#if ALF_CHROMA_LAMBDA 
+#if HHI_INTERVIEW_SKIP
+              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), m_pcEncTop->getInterViewSkip()  );
+#else
+              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma() );
+#endif
+#else
+#if SAO_CHROMA_LAMBDA
+#if HHI_INTERVIEW_SKIP
+              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), m_pcEncTop->getInterViewSkip());
+#else
+              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma());
+#endif
+#else
+#if HHI_INTERVIEW_SKIP
+              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambda(), m_pcEncTop->getInterViewSkip() );
+#else
+              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambda());
+#endif
+#endif
+#endif
+
+              m_pcAdaptiveLoopFilter->endALFEnc();
+
+              m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
+            }
+            iCodedAPSIdx = iCurrAPSIdx;  
+            pcSliceForAPS = pcSlice;
+
+            assignNewAPS(cAPS, iCodedAPSIdx, vAPS, pcSliceForAPS);
+            iCurrAPSIdx = (iCurrAPSIdx +1)%MAX_NUM_SUPPORTED_APS;
+            processingState = ENCODE_APS;
+
+            //set APS link to the slices
+            for(Int s=0; s< uiNumSlices; s++)
+            {
+              if (pcSlice->getSPS()->getUseALF())
+              {
+                pcPic->getSlice(s)->setAlfEnabledFlag(  (pcSlice->getSPS()->getUseALFCoefInSlice())?(alfSliceParams[s].isEnabled[ALF_Y]):(cAPS.getAlfEnabled())   );
+              }
+              if (pcSlice->getSPS()->getUseSAO())
+              {
+                pcPic->getSlice(s)->setSaoEnabledFlag((cAPS.getSaoParam()->bSaoFlag[0]==1)?true:false);
+              }
+              pcPic->getSlice(s)->setAPS(&(vAPS[iCodedAPSIdx]));
+              pcPic->getSlice(s)->setAPSId(iCodedAPSIdx);
+            }
+          }
+          break;
+        case ENCODE_APS:
+          {
+#if VIDYO_VPS_INTEGRATION | QC_MVHEVC_B0046
+            OutputNALUnit nalu(NAL_UNIT_APS, true, m_pcEncTop->getLayerId());
+#else
+            OutputNALUnit nalu(NAL_UNIT_APS, true, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
+#endif
+            encodeAPS(&(vAPS[iCodedAPSIdx]), nalu.m_Bitstream, pcSliceForAPS);
+            accessUnit.push_back(new NALUnitEBSP(nalu));
+
+            processingState = ENCODE_SLICE;
+          }
+          break;
+        default:
+          {
+            printf("Not a supported encoding state\n");
+            assert(0);
+            exit(-1);
+          }
+        }
+      } // end iteration over slices
+
+
+      if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+      {
+        if(pcSlice->getSPS()->getUseSAO())
+        {
+          m_pcSAO->destroyPicSaoInfo();
+        }
+
+        if(pcSlice->getSPS()->getUseALF())
+        {
+          m_pcAdaptiveLoopFilter->uninitALFEnc(alfSliceParams, alfCUCtrlParam);
+          m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
+        }
+
+        pcPic->destroyNonDBFilterInfo();
+      }
+
+#if HHI_INTERVIEW_SKIP
+      if (pcPic->getUsedPelsMap())
+        pcPic->removeUsedPelsMapBuffer() ;
+#endif
+#if H3D_IVMP
+      pcPic->removeOrgDepthMapBuffer();
+#endif
+   
+   //   pcPic->compressMotion(); 
+      m_pocLastCoded = pcPic->getPOC();
+      
+      //-- For time output for each slice
+      Double dEncTime = (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+
+      const char* digestStr = NULL;
+      if (m_pcCfg->getPictureDigestEnabled())
+      {
+        /* calculate MD5sum for entire reconstructed picture */
+        SEIpictureDigest sei_recon_picture_digest;
+        sei_recon_picture_digest.method = SEIpictureDigest::MD5;
+        calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
+        digestStr = digestToString(sei_recon_picture_digest.digest);
+
+#if VIDYO_VPS_INTEGRATION | QC_MVHEVC_B0046
+        OutputNALUnit nalu(NAL_UNIT_SEI, false, m_pcEncTop->getLayerId());
+#else
+        OutputNALUnit nalu(NAL_UNIT_SEI, false, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
+#endif
+
+        /* write the SEI messages */
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+        m_pcEntropyCoder->encodeSEI(sei_recon_picture_digest);
+        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 );
+      if (digestStr)
+        printf(" [MD5:%s]", digestStr);
+
+#if FIXED_ROUNDING_FRAME_MEMORY
+      /* TODO: this should happen after copyToPic(pcPicYuvRecOut) */
+      pcPic->getPicYuvRec()->xFixedRoundingPic();
+#endif
+      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
+      
+      pcPic->setReconMark   ( true );
+
+      pcPic->setUsedForTMVP ( true );
+
+      m_bFirst = false;
+      m_iNumPicCoded++;
+
+      /* logging: insert a newline at end of picture period */
+      printf("\n");
+      fflush(stdout);
+  }
+  
+  delete[] pcSubstreamsOut;
+  delete pcBitstreamRedirect;
+
+}
+
+/** Memory allocation for APS
+  * \param [out] pAPS APS pointer
+  * \param [in] pSPS SPS pointer
+  */
+Void TEncGOP::allocAPS (TComAPS* pAPS, TComSPS* pSPS)
+{
+  if(pSPS->getUseSAO())
+  {
+    pAPS->createSaoParam();
+    m_pcSAO->allocSaoParam(pAPS->getSaoParam());
+  }
+  if(pSPS->getUseALF())
+  {
+    pAPS->createAlfParam();
+    //alf Enabled flag in APS is false after pAPS->createAlfParam();
+    if(!pSPS->getUseALFCoefInSlice())
+    {
+      pAPS->getAlfParam()->create(m_pcAdaptiveLoopFilter->getNumLCUInPicWidth(), m_pcAdaptiveLoopFilter->getNumLCUInPicHeight(), m_pcAdaptiveLoopFilter->getNumCUsInPic());
+      pAPS->getAlfParam()->createALFParam();
+    }
+  }
+}
+
+/** Memory deallocation for APS
+  * \param [out] pAPS APS pointer
+  * \param [in] pSPS SPS pointer
+  */
+Void TEncGOP::freeAPS (TComAPS* pAPS, TComSPS* pSPS)
+{
+  if(pSPS->getUseSAO())
+  {
+    if(pAPS->getSaoParam() != NULL)
+    {
+      m_pcSAO->freeSaoParam(pAPS->getSaoParam());
+      pAPS->destroySaoParam();
+
+    }
+  }
+  if(pSPS->getUseALF())
+  {
+    if(pAPS->getAlfParam() != NULL)
+    {
+      if(!pSPS->getUseALFCoefInSlice())
+      {
+        pAPS->getAlfParam()->releaseALFParam();
+      }
+      pAPS->destroyAlfParam();
+    }
+  }
+}
+
+/** Assign APS object into APS container according to APS ID
+  * \param [in] cAPS APS object
+  * \param [in] apsID APS ID
+  * \param [in,out] vAPS APS container
+  * \param [in] pcSlice pointer to slice
+  */
+Void TEncGOP::assignNewAPS(TComAPS& cAPS, Int apsID, std::vector<TComAPS>& vAPS, TComSlice* pcSlice)
+{
+
+  cAPS.setAPSID(apsID);
+  if(pcSlice->getPOC() == 0)
+  {
+    cAPS.setScalingListEnabled(pcSlice->getSPS()->getScalingListFlag());
+  }
+  else
+  {
+    cAPS.setScalingListEnabled(false);
+  }
+
+  cAPS.setSaoEnabled(pcSlice->getSPS()->getUseSAO() ? (cAPS.getSaoParam()->bSaoFlag[0] ):(false));
+  cAPS.setAlfEnabled(pcSlice->getSPS()->getUseALF() ? (cAPS.getAlfParam()->isEnabled[0]):(false));
+  cAPS.setLoopFilterOffsetInAPS(m_pcCfg->getLoopFilterOffsetInAPS());
+  cAPS.setLoopFilterDisable(m_pcCfg->getLoopFilterDisable());
+  cAPS.setLoopFilterBetaOffset(m_pcCfg->getLoopFilterBetaOffset());
+  cAPS.setLoopFilterTcOffset(m_pcCfg->getLoopFilterTcOffset());
+
+  //assign new APS into APS container
+  Int apsBufSize= (Int)vAPS.size();
+
+  if(apsID >= apsBufSize)
+  {
+    vAPS.resize(apsID +1);
+  }
+
+  freeAPS(&(vAPS[apsID]), pcSlice->getSPS());
+  vAPS[apsID] = cAPS;
+}
+
+
+/** encode APS syntax elements
+  * \param [in] pcAPS APS pointer
+  * \param [in, out] APSbs bitstream
+  * \param [in] pointer to slice (just used for entropy coder initialization)
+  */
+Void TEncGOP::encodeAPS(TComAPS* pcAPS, TComOutputBitstream& APSbs, TComSlice* pcSlice)
+{
+  m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice);
+  m_pcEntropyCoder->resetEntropy      ();
+  m_pcEntropyCoder->setBitstream(&APSbs);
+
+  m_pcEntropyCoder->encodeAPSInitInfo(pcAPS);
+  if(pcAPS->getScalingListEnabled())
+  {
+    m_pcEntropyCoder->encodeScalingList( pcSlice->getScalingList() );
+  }
+  if(pcAPS->getLoopFilterOffsetInAPS())
+  {
+    m_pcEntropyCoder->encodeDFParams(pcAPS);
+  }
+  m_pcEntropyCoder->encodeSaoParam(pcAPS);
+  m_pcEntropyCoder->encodeAPSAlfFlag( pcAPS->getAlfEnabled()?1:0);
+  if(pcAPS->getAlfEnabled())
+  {
+    m_pcEntropyCoder->encodeAlfParam(pcAPS->getAlfParam());
+  }
+
+  m_pcEntropyCoder->encodeApsExtensionFlag();
+  //neither SAO and ALF is enabled
+  writeRBSPTrailingBits(APSbs);
+}
+
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
+{
+  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  Bool bCalcDist = false;
+  m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresent(), pcSlice->getLoopFilterDisable(), m_pcCfg->getLoopFilterBetaOffset(), m_pcCfg->getLoopFilterTcOffset(), m_pcCfg->getLFCrossTileBoundaryFlag());
+  m_pcLoopFilter->loopFilterPic( pcPic );
+  
+  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
+  m_pcEntropyCoder->resetEntropy    ();
+  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+  pcSlice = pcPic->getSlice(0);
+  if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+  {
+    pcPic->createNonDBFilterInfo();
+  }
+  
+  // Adaptive Loop filter
+  if( pcSlice->getSPS()->getUseALF() )
+  {
+    m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic);
+
+    AlfParamSet* alfParamSet;
+    std::vector<AlfCUCtrlInfo>* alfCUCtrlParam = NULL;
+    alfParamSet= new AlfParamSet;
+    alfParamSet->create( m_pcAdaptiveLoopFilter->getNumLCUInPicWidth(), m_pcAdaptiveLoopFilter->getNumLCUInPicHeight(), m_pcAdaptiveLoopFilter->getNumCUsInPic());
+    alfParamSet->createALFParam();
+    m_pcAdaptiveLoopFilter->initALFEnc(false, true, 1, alfParamSet, alfCUCtrlParam);
+    m_pcAdaptiveLoopFilter->startALFEnc(pcPic, m_pcEntropyCoder);
+    
+
+
+#if ALF_CHROMA_LAMBDA 
+#if HHI_INTERVIEW_SKIP
+    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), m_pcEncTop->getInterViewSkip()  );
+#else
+    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma() );
+#endif
+#else
+#if SAO_CHROMA_LAMBDA
+    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambdaLuma(), m_pcEncTop->getInterViewSkip());
+#if HHI_INTERVIEW_SKIP
+#else
+    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambdaLuma());
+#endif
+#else
+#if HHI_INTERVIEW_SKIP
+    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambda(), m_pcEncTop->getInterViewSkip());
+#else
+    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambda());
+#endif
+#endif
+#endif
+
+    m_pcAdaptiveLoopFilter->endALFEnc();
+
+    alfParamSet->releaseALFParam();
+    delete alfParamSet;
+    delete alfCUCtrlParam;
+    m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
+    m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
+  }
+  if( pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
+  {
+    pcPic->destroyNonDBFilterInfo();
+  }
+  
+  m_pcEntropyCoder->resetEntropy    ();
+  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  
+  if (!bCalcDist)
+    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
+{
+  assert( iNumPicRcvd > 0 );
+  //  Exception for the first frame
+  if ( iPOCLast == 0 )
+  {
+    m_iGopSize    = 1;
+  }
+  else
+    m_iGopSize    = m_pcCfg->getGOPSize();
+  
+  assert (m_iGopSize > 0); 
+
+  return;
+}
+
+Void TEncGOP::xGetBuffer( TComList<TComPic*>&       rcListPic,
+                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
+                         Int                       iNumPicRcvd,
+                         Int                       iTimeOffset,
+                         TComPic*&                 rpcPic,
+                         TComPicYuv*&              rpcPicYuvRecOut,
+                         UInt                      uiPOCCurr )
+{
+  Int i;
+  //  Rec. output
+  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
+  for ( i = 0; i < iNumPicRcvd - iTimeOffset + 1; i++ )
+  {
+    iterPicYuvRec--;
+  }
+  
+  rpcPicYuvRecOut = *(iterPicYuvRec);
+  
+  //  Current pic.
+  TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+  while (iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic);
+    rpcPic->setCurrSliceIdx(0);
+    if (rpcPic->getPOC() == (Int)uiPOCCurr)
+    {
+      break;
+    }
+    iterPic++;
+  }
+  
+  assert (rpcPic->getPOC() == (Int)uiPOCCurr);
+  
+  return;
+}
+
+UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
+{
+  Int     x, y;
+  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
+  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
+#if IBDI_DISTORTION
+  Int  iShift = g_uiBitIncrement;
+  Int  iOffset = 1<<(g_uiBitIncrement-1);
+#else
+  UInt  uiShift = g_uiBitIncrement<<1;
+#endif
+  Int   iTemp;
+  
+  Int   iStride = pcPic0->getStride();
+  Int   iWidth  = pcPic0->getWidth();
+  Int   iHeight = pcPic0->getHeight();
+  
+  UInt64  uiTotalDiff = 0;
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_DISTORTION
+      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
+#else
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+#endif
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  
+  pSrc0  = pcPic0->getCbAddr();
+  pSrc1  = pcPic1->getCbAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_DISTORTION
+      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
+#else
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+#endif
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  pSrc0  = pcPic0->getCrAddr();
+  pSrc1  = pcPic1->getCrAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+#if IBDI_DISTORTION
+      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
+#else
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+#endif
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  return uiTotalDiff;
+}
+
+#if VERBOSE_RATE
+static const char* nalUnitTypeToString(NalUnitType type)
+{
+  switch (type)
+  {
+  case NAL_UNIT_CODED_SLICE: return "SLICE";
+#if !QC_REM_IDV_B0046
+  case NAL_UNIT_CODED_SLICE_IDV: return "IDV";
+#endif
+  case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
+  case NAL_UNIT_CODED_SLICE_TLA: return "TLA";
+  case NAL_UNIT_CODED_SLICE_IDR: return "IDR";
+  case NAL_UNIT_SEI: return "SEI";
+  case NAL_UNIT_SPS: return "SPS";
+  case NAL_UNIT_PPS: return "PPS";
+  case NAL_UNIT_FILLER_DATA: return "FILLER";
+  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;
+  
+  //===== 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 HHI_VSO
+#if HHI_VSO_SYNTH_DIST_OUT
+  if ( m_pcRdCost->getUseRenModel() )
+  {
+    unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
+    Double fRefValueY = (double) maxval * maxval * iSize;
+    Double fRefValueC = fRefValueY / 4.0;
+    TRenModel*  pcRenModel = m_pcEncTop->getEncTop()->getRenModel();
+    Int64 iDistVSOY, iDistVSOU, iDistVSOV;
+    pcRenModel->getTotalSSE( iDistVSOY, iDistVSOU, iDistVSOV );
+    dYPSNR = ( iDistVSOY ? 10.0 * log10( fRefValueY / (Double) iDistVSOY ) : 99.99 );
+    dUPSNR = ( iDistVSOU ? 10.0 * log10( fRefValueC / (Double) iDistVSOU ) : 99.99 );
+    dVPSNR = ( iDistVSOV ? 10.0 * log10( fRefValueC / (Double) iDistVSOV ) : 99.99 );
+  }
+  else
+#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;
+  }
+  
+  unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
+  Double fRefValueY = (double) maxval * maxval * iSize;
+  Double fRefValueC = fRefValueY / 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 );
+  }
+  /* calculate the size of the access unit, excluding:
+   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
+   *  - SEI NAL units
+   */
+  unsigned numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+  {
+    unsigned numRBSPBytes_nal = unsigned((*it)->m_nalUnitData.str().size());
+#if VERBOSE_RATE
+    printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
+#endif
+    if ((*it)->m_nalUnitType != NAL_UNIT_SEI)
+      numRBSPBytes += numRBSPBytes_nal;
+  }
+
+  unsigned uibits = numRBSPBytes * 8;
+  m_vRVM_RP.push_back( uibits );
+
+  //===== add PSNR =====
+  m_pcEncTop->getAnalyzeAll()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  TComSlice*  pcSlice = pcPic->getSlice(0);
+  if (pcSlice->isIntra())
+  {
+    m_pcEncTop->getAnalyzeI()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if (pcSlice->isInterP())
+  {
+    m_pcEncTop->getAnalyzeP()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if (pcSlice->isInterB())
+  {
+    m_pcEncTop->getAnalyzeB()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+
+  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  if (!pcSlice->isReferenced()) c += 32;
+
+#if ADAPTIVE_QP_SELECTION
+  printf("%s   View %3d POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
+         pcSlice->getIsDepth() ? "Depth  " : "Texture",
+         pcSlice->getViewId(),
+         pcSlice->getPOC(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQpBase(),
+         pcSlice->getSliceQp(),
+         uibits );
+#else
+  printf("%s   View %3d POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
+         pcSlice->getIsDepth() ? "Depth  " : "Texture",
+         pcSlice->getViewId(),
+         pcSlice->getPOC()-pcSlice->getLastIDR(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQp(),
+         uibits );
+#endif
+
+  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
+  printf(" [ET %5.0f ]", dEncTime );
+  
+  for (Int iRefList = 0; iRefList < 2; iRefList++)
+  {
+    printf(" [L%d ", iRefList);
+    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
+    {
+      if( pcSlice->getViewId() != pcSlice->getRefViewId( RefPicList(iRefList), iRefIndex ) )
+      {
+        printf( "V%d ", pcSlice->getRefViewId( RefPicList(iRefList), iRefIndex ) );
+      }
+      else
+      {
+        printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
+      }
+    }
+    printf("]");
+  }
+  if(pcSlice->getNumRefIdx(REF_PIC_LIST_C)>0 && !pcSlice->getNoBackPredFlag())
+  {
+    printf(" [LC ");
+    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(REF_PIC_LIST_C); iRefIndex++)
+    {
+      if( pcSlice->getViewId() != pcSlice->getRefViewId( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) )
+      {
+        printf( "V%d ", pcSlice->getRefViewId( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) );
+      }
+      else
+      {
+        printf ("%d ", pcSlice->getRefPOC((RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex))-pcSlice->getLastIDR());
+      }
+    }
+    printf("]");
+  }
+}
+
+/** Function for deciding the nal_unit_type.
+ * \param uiPOCCurr POC of the current picture
+ * \returns the nal_unit type of the picture
+ * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
+ */
+NalUnitType TEncGOP::getNalUnitType(UInt uiPOCCurr)
+{
+  Bool bInterViewOnlySlice = ( m_pcCfg->getGOPEntry(MAX_GOP).m_POC == 0 && (m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType == 'P' || m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType == 'B') );
+
+  if (uiPOCCurr == 0)
+  {
+    if( bInterViewOnlySlice ) 
+    { 
+#if !QC_REM_IDV_B0046
+      return NAL_UNIT_CODED_SLICE_IDV; 
+#else
+      return NAL_UNIT_CODED_SLICE_IDR;
+#endif
+    }
+    else
+    { 
+      return NAL_UNIT_CODED_SLICE_IDR;
+    }
+  }
+  if (uiPOCCurr % m_pcCfg->getIntraPeriod() == 0)
+  {
+    if (m_pcCfg->getDecodingRefreshType() == 1)
+    {
+      if( bInterViewOnlySlice ) 
+      { 
+#if !QC_REM_IDV_B0046
+        return NAL_UNIT_CODED_SLICE_IDV; 
+#else
+        return NAL_UNIT_CODED_SLICE_CRA; 
+#endif
+      }
+      else
+      { 
+      return NAL_UNIT_CODED_SLICE_CRA;
+      }
+    }
+    else if (m_pcCfg->getDecodingRefreshType() == 2)
+    {
+      if( bInterViewOnlySlice ) 
+      { 
+#if !QC_REM_IDV_B0046
+        return NAL_UNIT_CODED_SLICE_IDV; 
+#else
+        return NAL_UNIT_CODED_SLICE_IDR;
+#endif
+      }
+      else
+      { 
+        return NAL_UNIT_CODED_SLICE_IDR;
+      }
+    }
+  }
+  return NAL_UNIT_CODED_SLICE;
+}
+
+NalUnitType TEncGOP::getNalUnitTypeBaseViewMvc(UInt uiPOCCurr)
+{
+  if( uiPOCCurr == 0 )
+  {
+    return NAL_UNIT_CODED_SLICE_IDR;
+  }
+  if( uiPOCCurr % m_pcCfg->getIntraPeriod() == 0 )
+  {
+    if( m_pcCfg->getDecodingRefreshType() == 1 )
+    {
+      return NAL_UNIT_CODED_SLICE_CRA;
+    }
+    else if( m_pcCfg->getDecodingRefreshType() == 2 )
+    {
+      return NAL_UNIT_CODED_SLICE_IDR;
+    }
+  }
+  return NAL_UNIT_CODED_SLICE;
+}
+
+Double TEncGOP::xCalculateRVM()
+{
+  Double dRVM = 0;
+  
+  if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFrameToBeEncoded() > RVM_VCEGAM10_M * 2 )
+  {
+    // calculate RVM only for lowdelay configurations
+    std::vector<Double> vRL , vB;
+    size_t N = m_vRVM_RP.size();
+    vRL.resize( N );
+    vB.resize( N );
+    
+    Int i;
+    Double dRavg = 0 , dBavg = 0;
+    vB[RVM_VCEGAM10_M] = 0;
+    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
+    {
+      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];
+      dRavg += m_vRVM_RP[i];
+      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++ )
+    {
+      Double tmp = vB[i] - dBavg;
+      dSigamB += tmp * tmp;
+    }
+    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 );
+}
+
+/** Determine the difference between consecutive tile sizes (in bytes) and writes it to  bistream rNalu [slice header]
+ * \param rpcBitstreamRedirect contains the bitstream to be concatenated to rNalu. rpcBitstreamRedirect contains slice payload. rpcSlice contains tile location information.
+ * \returns Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
+ */
+Void TEncGOP::xWriteTileLocationToSliceHeader (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect, TComSlice*& rpcSlice)
+{
+  {
+  }
+
+  // Byte-align
+  rNalu.m_Bitstream.writeAlignOne();
+
+  // Update tile marker locations
+  TComOutputBitstream *pcOut = &rNalu.m_Bitstream;
+  UInt uiAccumulatedLength   = pcOut->getNumberOfWrittenBits() >> 3;
+  for (Int uiMrkIdx = 0; uiMrkIdx < rpcBitstreamRedirect->getTileMarkerLocationCount(); uiMrkIdx++)
+  {
+    UInt uiBottom = pcOut->getTileMarkerLocationCount();
+    pcOut->setTileMarkerLocation      ( uiBottom, uiAccumulatedLength + rpcBitstreamRedirect->getTileMarkerLocation( uiMrkIdx ) );
+    pcOut->setTileMarkerLocationCount ( uiBottom + 1 );
+  }
+
+  // Perform bitstream concatenation
+  if (rpcBitstreamRedirect->getNumberOfWrittenBits() > 0)
+  {
+    UInt uiBitCount  = rpcBitstreamRedirect->getNumberOfWrittenBits();
+    if (rpcBitstreamRedirect->getByteStreamLength()>0)
+    {
+      UChar *pucStart  =  reinterpret_cast<UChar*>(rpcBitstreamRedirect->getByteStream());
+      UInt uiWriteByteCount = 0;
+      while (uiWriteByteCount < (uiBitCount >> 3) )
+      {
+        UInt uiBits = (*pucStart);
+        rNalu.m_Bitstream.write(uiBits, 8);
+        pucStart++;
+        uiWriteByteCount++;
+      }
+    }
+    UInt uiBitsHeld = (uiBitCount & 0x07);
+    for (UInt uiIdx=0; uiIdx < uiBitsHeld; uiIdx++)
+    {
+      rNalu.m_Bitstream.write((rpcBitstreamRedirect->getHeldBits() & (1 << (7-uiIdx))) >> (7-uiIdx), 1);
+    }          
+  }
+
+  m_pcEntropyCoder->setBitstream(&rNalu.m_Bitstream);
+
+  delete rpcBitstreamRedirect;
+  rpcBitstreamRedirect = new TComOutputBitstream;
+}
+
+Void TEncGOP::xSetRefPicListModificationsMvc( TComSlice* pcSlice, UInt uiPOCCurr, UInt iGOPid )
+{
+  if( pcSlice->getSliceType() == I_SLICE || !(pcSlice->getSPS()->getListsModificationPresentFlag()) || pcSlice->getSPS()->getNumberOfUsableInterViewRefs() == 0 )
+  {
+    return;
+  }
+
+  // analyze inter-view modifications
+#if !QC_REM_IDV_B0046
+  GOPEntryMvc gem = m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid );
+#else
+  Bool bRAP = ((getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR) || (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_CRA)) && (pcSlice->getSPS()->getViewId()) ? 1:0;
+  GOPEntryMvc gem = m_pcCfg->getGOPEntry( bRAP ? MAX_GOP : iGOPid );
+#endif
+  Int numL0Modifications = 0;
+  Int numL1Modifications = 0;
+  for( Int k = 0; k < gem.m_numInterViewRefPics; k++ )
+  {
+    if( gem.m_interViewRefPosL0[k] > 0 ) { numL0Modifications++; }
+    if( gem.m_interViewRefPosL1[k] > 0 ) { numL1Modifications++; }
+  }
+
+  TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+  Int maxRefListSize = pcSlice->getNumPocTotalCurrMvc();
+  Int numTemporalRefs = pcSlice->getNumPocTotalCurr();
+
+  // set L0 inter-view modifications
+  if( (maxRefListSize > 1) && (numL0Modifications > 0) )
+  {
+    refPicListModification->setRefPicListModificationFlagL0( true );
+    Int tempListEntryL0[16];
+    for( Int k = 0; k < 16; k++ ) { tempListEntryL0[k] = -1; }
+    
+    Bool hasModification = false;
+    for( Int k = 0; k < gem.m_numInterViewRefPics; k++ )
+    {
+      if( gem.m_interViewRefPosL0[k] > 0 )
+      {
+        for( Int l = 0; l < pcSlice->getSPS()->getNumberOfUsableInterViewRefs(); l++ )
+        {
+          if( gem.m_interViewRefs[k] == pcSlice->getSPS()->getUsableInterViewRef( l ) && (gem.m_interViewRefPosL0[k] - 1) != (numTemporalRefs + l) )
+          {
+            tempListEntryL0[gem.m_interViewRefPosL0[k]-1] = numTemporalRefs + l;
+            hasModification = true;
+          }
+        }
+      }
+    }
+
+    if( hasModification )
+    {
+      Int temporalRefIdx = 0;
+      for( Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++ )
+      {
+        if( tempListEntryL0[i] >= 0 ) 
+        {
+          refPicListModification->setRefPicSetIdxL0( i, tempListEntryL0[i] );
+        }
+        else
+        {
+          refPicListModification->setRefPicSetIdxL0( i, temporalRefIdx );
+          temporalRefIdx++;
+        }
+      }
+    }
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL0( false );
+    }
+  }
+
+  // set L1 inter-view modifications
+  if( (maxRefListSize > 1) && (numL1Modifications > 0) )
+  {
+    refPicListModification->setRefPicListModificationFlagL1( true );
+    Int tempListEntryL1[16];
+    for( Int k = 0; k < 16; k++ ) { tempListEntryL1[k] = -1; }
+
+    Bool hasModification = false;
+    for( Int k = 0; k < gem.m_numInterViewRefPics; k++ )
+    {
+      if( gem.m_interViewRefPosL1[k] > 0 )
+      {
+        for( Int l = 0; l < pcSlice->getSPS()->getNumberOfUsableInterViewRefs(); l++ )
+        {
+          if( gem.m_interViewRefs[k] == pcSlice->getSPS()->getUsableInterViewRef( l ) && (gem.m_interViewRefPosL1[k] - 1) != (numTemporalRefs + l) )
+          {
+            tempListEntryL1[gem.m_interViewRefPosL1[k]-1] = numTemporalRefs + l;
+            hasModification = true;
+          }
+        }
+      }
+    }
+
+    if( hasModification )
+    {
+      Int temporalRefIdx = 0;
+      for( Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++ )
+      {
+        if( tempListEntryL1[i] >= 0 ) 
+        {
+          refPicListModification->setRefPicSetIdxL1( i, tempListEntryL1[i] );
+        }
+        else
+        {
+          refPicListModification->setRefPicSetIdxL1( i, temporalRefIdx );
+          temporalRefIdx++;
+        }
+      }
+    } 
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL1( false );
+    }
+  }
+
+  return;
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncGOP.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncGOP.h	(revision 341)
@@ -0,0 +1,184 @@
+/* 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-2012, 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     TEncGOP.h
+    \brief    GOP encoder class (header)
+*/
+
+#ifndef __TENCGOP__
+#define __TENCGOP__
+
+#include <list>
+
+#include <stdlib.h>
+
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComLoopFilter.h"
+#include "TLibCommon/AccessUnit.h"
+#include "TLibCommon/TComDepthMapGenerator.h"
+#include "TLibCommon/TComResidualGenerator.h"
+#include "TEncAdaptiveLoopFilter.h"
+#include "TEncSampleAdaptiveOffset.h"
+#include "TEncSlice.h"
+#include "TEncEntropy.h"
+#include "TEncCavlc.h"
+#include "TEncSbac.h"
+
+#include "TEncAnalyze.h"
+
+#include <vector>
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP encoder class
+class TEncGOP
+{
+private:
+  //  Data
+  Bool                    m_bLongtermTestPictureHasBeenCoded;
+  Bool                    m_bLongtermTestPictureHasBeenCoded2;
+  Int                     m_iLastIDR;
+  Int                     m_iGopSize;
+  Int                     m_iNumPicCoded;
+  Bool                    m_bFirst;
+  
+  //  Access channel
+  TEncTop*                m_pcEncTop;
+  TEncCfg*                m_pcCfg;
+  TEncSlice*              m_pcSliceEncoder;
+  TComList<TComPic*>*     m_pcListPic;
+  
+  TEncEntropy*            m_pcEntropyCoder;
+  TEncCavlc*              m_pcCavlcCoder;
+  TEncSbac*               m_pcSbacCoder;
+  TEncBinCABAC*           m_pcBinCABAC;
+  TComLoopFilter*         m_pcLoopFilter;
+  
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator*  m_pcDepthMapGenerator;
+#endif
+#if H3D_IVRP
+  TComResidualGenerator*  m_pcResidualGenerator;
+#endif
+  Int                     m_pocLastCoded;
+
+  // Adaptive Loop filter
+  TEncAdaptiveLoopFilter* m_pcAdaptiveLoopFilter;
+  //--Adaptive Loop filter
+  TEncSampleAdaptiveOffset*  m_pcSAO;
+  TComBitCounter*         m_pcBitCounter;
+  TComRdCost*             m_pcRdCost;                           ///< RD cost computation
+  // indicate sequence first
+  Bool                    m_bSeqFirst;
+  
+  // clean decoding refresh
+  Bool                    m_bRefreshPending;
+  Int                     m_pocCRA;
+  UInt*                   m_uiStoredStartCUAddrForEncodingSlice;
+  UInt*                   m_uiStoredStartCUAddrForEncodingEntropySlice;
+
+  std::vector<Int> m_vRVM_RP;
+
+public:
+  TEncGOP();
+  virtual ~TEncGOP();
+  
+  Void  create      ( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight );
+  Void  destroy     ();
+  
+  Void  init        ( TEncTop* pcTEncTop );
+  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, Int iGOPid );
+  Void  xWriteTileLocationToSliceHeader (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect, TComSlice*& rpcSlice);
+
+  Int   getPocLastCoded()       { return  m_pocLastCoded; }
+  Int   getGOPSize()          { return  m_iGopSize;  }
+  
+  TComList<TComPic*>*   getListPic()      { return m_pcListPic; }
+  
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits );
+  TEncTop* getEncTop() { return m_pcEncTop; }
+  
+  TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
+  NalUnitType getNalUnitType( UInt uiPOCCurr );
+  NalUnitType getNalUnitTypeBaseViewMvc( UInt uiPOCCurr );
+  Void freeAPS     (TComAPS* pAPS, TComSPS* pSPS);
+  Void allocAPS    (TComAPS* pAPS, TComSPS* pSPS);
+protected:
+  Void encodeAPS   (TComAPS* pcAPS, TComOutputBitstream& APSbs, TComSlice* pcSlice);            //!< encode APS syntax elements
+  Void assignNewAPS(TComAPS& cAPS, Int apsID, std::vector<TComAPS>& vAPS, TComSlice* pcSlice);  //!< Assign APS object into APS container
+  
+
+protected:
+  Void  xInitGOP          ( Int iPOC, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, UInt uiPOCCurr );
+  
+  Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime );
+  
+  UInt64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
+
+  Double xCalculateRVM();
+
+  Void  xSetRefPicListModificationsMvc( TComSlice* pcSlice, UInt uiPOCCurr, UInt iGOPid );
+};// END CLASS DEFINITION TEncGOP
+
+// ====================================================================================================================
+// Enumeration
+// ====================================================================================================================
+enum PROCESSING_STATE
+{
+  EXECUTE_INLOOPFILTER,
+  ENCODE_APS,
+  ENCODE_SLICE
+};
+
+enum SCALING_LIST_PARAMETER
+{
+  SCALING_LIST_OFF,
+  SCALING_LIST_DEFAULT,
+  SCALING_LIST_FILE_READ
+};
+
+//! \}
+
+#endif // __TENCGOP__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPic.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPic.cpp	(revision 341)
@@ -0,0 +1,155 @@
+/* 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-2012, 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     TEncPic.cpp
+    \brief    class of picture which includes side information for encoder
+*/
+
+#include "TEncPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/** Constructor
+ */
+TEncQPAdaptationUnit::TEncQPAdaptationUnit()
+: m_dActivity(0.0)
+{
+}
+
+/** Destructor
+ */
+TEncQPAdaptationUnit::~TEncQPAdaptationUnit()
+{
+}
+
+/** Constructor
+ */
+TEncPicQPAdaptationLayer::TEncPicQPAdaptationLayer()
+: m_uiAQPartWidth(0)
+, m_uiAQPartHeight(0)
+, m_uiNumAQPartInWidth(0)
+, m_uiNumAQPartInHeight(0)
+, m_acTEncAQU(NULL)
+, m_dAvgActivity(0.0)
+{
+}
+
+/** Destructor
+ */
+TEncPicQPAdaptationLayer::~TEncPicQPAdaptationLayer()
+{
+  destroy();
+}
+
+/** Initialize member variables
+ * \param iWidth Picture width
+ * \param iHeight Picture height
+ * \param uiAQPartWidth Width of unit block for analyzing local image characteristics
+ * \param uiAQPartHeight Height of unit block for analyzing local image characteristics
+ * \return Void
+ */
+Void TEncPicQPAdaptationLayer::create( Int iWidth, Int iHeight, UInt uiAQPartWidth, UInt uiAQPartHeight )
+{
+  m_uiAQPartWidth = uiAQPartWidth;
+  m_uiAQPartHeight = uiAQPartHeight;
+  m_uiNumAQPartInWidth = (iWidth + m_uiAQPartWidth-1) / m_uiAQPartWidth;
+  m_uiNumAQPartInHeight = (iHeight + m_uiAQPartHeight-1) / m_uiAQPartHeight;
+  m_acTEncAQU = new TEncQPAdaptationUnit[ m_uiNumAQPartInWidth * m_uiNumAQPartInHeight ];
+}
+
+/** Clean up
+ * \return Void
+ */
+Void TEncPicQPAdaptationLayer::destroy()
+{
+  if (m_acTEncAQU)
+  {
+    delete[] m_acTEncAQU;
+    m_acTEncAQU = NULL;
+  }
+}
+
+/** Constructor
+ */
+TEncPic::TEncPic()
+: m_acAQLayer(NULL)
+, m_uiMaxAQDepth(0)
+{
+}
+
+/** Destructor
+ */
+TEncPic::~TEncPic()
+{
+  destroy();
+}
+
+/** 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 bIsVirtual
+ * \return Void
+ */
+Void TEncPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth, Bool bIsVirtual )
+{
+  TComPic::create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth, bIsVirtual );
+  m_uiMaxAQDepth = uiMaxAQDepth;
+  if ( uiMaxAQDepth > 0 )
+  {
+    m_acAQLayer = new TEncPicQPAdaptationLayer[ m_uiMaxAQDepth ]; 
+    for (UInt d = 0; d < m_uiMaxAQDepth; d++)
+    {
+      m_acAQLayer[d].create( iWidth, iHeight, uiMaxWidth>>d, uiMaxHeight>>d );
+    }
+  }
+}
+
+/** Clean up
+ * \return Void
+ */
+Void TEncPic::destroy()
+{
+  if (m_acAQLayer)
+  {
+    delete[] m_acAQLayer;
+    m_acAQLayer = NULL;
+  }
+  TComPic::destroy();
+}
+//! \}
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPic.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPic.h	(revision 341)
@@ -0,0 +1,114 @@
+/* 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-2012, 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     TEncPic.h
+    \brief    class of picture which includes side information for encoder (header)
+*/
+
+#ifndef __TENCPIC__
+#define __TENCPIC__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Unit block for storing image characteristics
+class TEncQPAdaptationUnit
+{
+private:
+  Double m_dActivity;
+
+public:
+  TEncQPAdaptationUnit();
+  ~TEncQPAdaptationUnit();
+
+  Void   setActivity( Double d ) { m_dActivity = d; }
+  Double getActivity()           { return m_dActivity; }
+};
+
+/// Local image characteristics for CUs on a specific depth
+class TEncPicQPAdaptationLayer
+{
+private:
+  UInt                  m_uiAQPartWidth;
+  UInt                  m_uiAQPartHeight;
+  UInt                  m_uiNumAQPartInWidth;
+  UInt                  m_uiNumAQPartInHeight;
+  TEncQPAdaptationUnit* m_acTEncAQU;
+  Double                m_dAvgActivity;
+
+public:
+  TEncPicQPAdaptationLayer();
+  virtual ~TEncPicQPAdaptationLayer();
+
+  Void  create( Int iWidth, Int iHeight, UInt uiAQPartWidth, UInt uiAQPartHeight );
+  Void  destroy();
+
+  UInt                   getAQPartWidth()        { return m_uiAQPartWidth;       }
+  UInt                   getAQPartHeight()       { return m_uiAQPartHeight;      }
+  UInt                   getNumAQPartInWidth()   { return m_uiNumAQPartInWidth;  }
+  UInt                   getNumAQPartInHeight()  { return m_uiNumAQPartInHeight; }
+  UInt                   getAQPartStride()       { return m_uiNumAQPartInWidth;  }
+  TEncQPAdaptationUnit*  getQPAdaptationUnit()   { return m_acTEncAQU;           }
+  Double                 getAvgActivity()        { return m_dAvgActivity;        }
+
+  Void                   setAvgActivity( Double d )  { m_dAvgActivity = d; }
+};
+
+/// Picture class including local image characteristics information for QP adaptation
+class TEncPic : public TComPic
+{
+private:
+  TEncPicQPAdaptationLayer* m_acAQLayer;
+  UInt                      m_uiMaxAQDepth;
+
+public:
+  TEncPic();
+  virtual ~TEncPic();
+
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth, Bool bIsVirtual = false );
+  virtual Void  destroy();
+
+  TEncPicQPAdaptationLayer* getAQLayer( UInt uiDepth )  { return &m_acAQLayer[uiDepth]; }
+  UInt                      getMaxAQDepth()             { return m_uiMaxAQDepth;        }
+};
+
+//! \}
+
+#endif // __TENCPIC__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 341)
@@ -0,0 +1,141 @@
+/* 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-2012, 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     TEncPreanalyzer.cpp
+    \brief    source picture analyzer class
+*/
+
+#include <cfloat>
+#include <algorithm>
+
+#include "TEncPreanalyzer.h"
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+/** Constructor
+ */
+TEncPreanalyzer::TEncPreanalyzer()
+{
+}
+
+/** Destructor
+ */
+TEncPreanalyzer::~TEncPreanalyzer()
+{
+}
+
+/** Analyze source picture and compute local image characteristics used for QP adaptation
+ * \param pcEPic Picture object to be analyzed
+ * \return Void
+ */
+Void TEncPreanalyzer::xPreanalyze( TEncPic* pcEPic )
+{
+  TComPicYuv* pcPicYuv = pcEPic->getPicYuvOrg();
+  const Int iWidth = pcPicYuv->getWidth();
+  const Int iHeight = pcPicYuv->getHeight();
+  const Int iStride = pcPicYuv->getStride();
+
+  for ( UInt d = 0; d < pcEPic->getMaxAQDepth(); d++ )
+  {
+    const Pel* pLineY = pcPicYuv->getLumaAddr();
+    TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer(d);
+    const UInt uiAQPartWidth = pcAQLayer->getAQPartWidth();
+    const UInt uiAQPartHeight = pcAQLayer->getAQPartHeight();
+    TEncQPAdaptationUnit* pcAQU = pcAQLayer->getQPAdaptationUnit();
+
+    Double dSumAct = 0.0;
+    for ( UInt y = 0; y < iHeight; y += uiAQPartHeight )
+    {
+      const UInt uiCurrAQPartHeight = min(uiAQPartHeight, iHeight-y);
+      for ( UInt x = 0; x < iWidth; x += uiAQPartWidth, pcAQU++ )
+      {
+        const UInt uiCurrAQPartWidth = min(uiAQPartWidth, iWidth-x);
+        const Pel* pBlkY = &pLineY[x];
+        UInt64 uiSum[4] = {0, 0, 0, 0};
+        UInt64 uiSumSq[4] = {0, 0, 0, 0};
+        UInt uiNumPixInAQPart = 0;
+        UInt by = 0;
+        for ( ; by < uiCurrAQPartHeight>>1; by++ )
+        {
+          UInt bx = 0;
+          for ( ; bx < uiCurrAQPartWidth>>1; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [0] += pBlkY[bx];
+            uiSumSq[0] += pBlkY[bx] * pBlkY[bx];
+          }
+          for ( ; bx < uiCurrAQPartWidth; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [1] += pBlkY[bx];
+            uiSumSq[1] += pBlkY[bx] * pBlkY[bx];
+          }
+          pBlkY += iStride;
+        }
+        for ( ; by < uiCurrAQPartHeight; by++ )
+        {
+          UInt bx = 0;
+          for ( ; bx < uiCurrAQPartWidth>>1; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [2] += pBlkY[bx];
+            uiSumSq[2] += pBlkY[bx] * pBlkY[bx];
+          }
+          for ( ; bx < uiCurrAQPartWidth; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [3] += pBlkY[bx];
+            uiSumSq[3] += pBlkY[bx] * pBlkY[bx];
+          }
+          pBlkY += iStride;
+        }
+
+        Double dMinVar = DBL_MAX;
+        for ( Int i=0; i<4; i++)
+        {
+          const Double dAverage = Double(uiSum[i]) / uiNumPixInAQPart;
+          const Double dVariance = Double(uiSumSq[i]) / uiNumPixInAQPart - dAverage * dAverage;
+          dMinVar = min(dMinVar, dVariance);
+        }
+        const Double dActivity = 1.0 + dMinVar;
+        pcAQU->setActivity( dActivity );
+        dSumAct += dActivity;
+      }
+      pLineY += iStride * uiCurrAQPartHeight;
+    }
+
+    const Double dAvgAct = dSumAct / (pcAQLayer->getNumAQPartInWidth() * pcAQLayer->getNumAQPartInHeight());
+    pcAQLayer->setAvgActivity( dAvgAct );
+  }
+}
+//! \}
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPreanalyzer.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 341)
@@ -0,0 +1,62 @@
+/* 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-2012, 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     TEncPreanalyzer.h
+    \brief    source picture analyzer class (header)
+*/
+
+#ifndef __TENCPREANALYZER__
+#define __TENCPREANALYZER__
+
+#include "TEncPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Source picture analyzer class
+class TEncPreanalyzer
+{
+public:
+  TEncPreanalyzer();
+  virtual ~TEncPreanalyzer();
+
+  Void xPreanalyze( TEncPic* pcPic );
+};
+
+//! \}
+
+#endif // __TENCPREANALYZER__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 341)
@@ -0,0 +1,1978 @@
+/* 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-2012, 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     TEncSampleAdaptiveOffset.cpp
+ \brief       estimation part of sample adaptive offset class
+ */
+#include "TEncSampleAdaptiveOffset.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
+{
+  m_pcEntropyCoder = NULL;
+  m_pppcRDSbacCoder = NULL;
+  m_pcRDGoOnSbacCoder = NULL;
+  m_pppcBinCoderCABAC = NULL;            
+  m_iCount = NULL;     
+  m_iOffset = NULL;      
+  m_iOffsetOrg = NULL;  
+  m_iRate = NULL;       
+  m_iDist = NULL;        
+  m_dCost = NULL;        
+  m_dCostPartBest = NULL; 
+  m_iDistOrg = NULL;      
+  m_iTypePartBest = NULL; 
+}
+TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
+{
+
+}
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+inline Double xRoundIbdi2(Double x)
+{
+#if FULL_NBIT
+  Int bitDepthMinus8 = g_uiBitDepth - 8;
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepthMinus8-1)))/(1<<bitDepthMinus8)) : ((Int)(((Int)(x)-(1<<(bitDepthMinus8-1)))/(1<<bitDepthMinus8)));
+#else
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(g_uiBitIncrement-1)))/(1<<g_uiBitIncrement)) : ((Int)(((Int)(x)-(1<<(g_uiBitIncrement-1)))/(1<<g_uiBitIncrement)));
+#endif
+}
+
+/** rounding with IBDI
+ * \param  x
+ */
+inline Double xRoundIbdi(Double x)
+{
+#if FULL_NBIT
+  return (g_uiBitDepth > 8 ? xRoundIbdi2((x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+#else
+  return (g_uiBitIncrement >0 ? xRoundIbdi2((x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+#endif
+}
+
+
+
+/** process SAO for one partition
+ * \param  *psQTPart, iPartIdx, dLambda
+ */
+Void TEncSampleAdaptiveOffset::rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda)
+{
+  Int iTypeIdx;
+  Int iNumTotalType = MAX_NUM_SAO_TYPE;
+  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
+
+  Int64 iEstDist;
+  Int64 iOffsetOrg;
+  Int64 iOffset;
+  Int64 iCount;
+  Int iClassIdx;
+  Int uiShift = g_uiBitIncrement << 1;
+  UInt uiDepth = pOnePart->PartLevel;
+
+  m_iDistOrg [iPartIdx] =  0;
+
+  Double  bestRDCostTableBo = MAX_DOUBLE;
+  Int     bestClassTableBo    = 0;
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+
+#if HHI_INTERVIEW_SKIP
+  Int iFrameWidthInCU = m_pcPic->getFrameWidthInCU();
+  Int LcuIdxX = psQTPart->StartCUX;
+  Int LcuIdxY = psQTPart->StartCUY;
+  Int iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+  TComDataCU *pcCU = m_pcPic->getCU(iAddr);
+  Bool bRenderable = pcCU->getRenderable(0) ;
+
+#endif
+  for (iTypeIdx=-1; iTypeIdx<iNumTotalType; iTypeIdx++)
+  {
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+      m_pcRDGoOnSbacCoder->resetBits();
+    }
+    else
+    {
+      m_pcEntropyCoder->resetEntropy();
+      m_pcEntropyCoder->resetBits();
+    }
+
+    iEstDist = 0;
+
+    m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoTypeIdx(iTypeIdx+1);
+
+    if (iTypeIdx>=0)
+    {
+
+      for(iClassIdx=1; iClassIdx < ( (iTypeIdx < SAO_BO) ?  m_iNumClass[iTypeIdx]+1 : SAO_MAX_BO_CLASSES+1); iClassIdx++)
+      {
+        if( iTypeIdx == SAO_BO)
+        {
+          currentDistortionTableBo[iClassIdx-1] = 0;
+          currentRdCostTableBo[iClassIdx-1] = dLambda;
+        }
+#if HHI_INTERVIEW_SKIP
+        if(m_iCount [iPartIdx][iTypeIdx][iClassIdx] && !bRenderable)
+#else
+        if(m_iCount [iPartIdx][iTypeIdx][iClassIdx])
+#endif
+        {
+#if FULL_NBIT
+          m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = (Int64) xRoundIbdi((Double)(m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx]<<g_uiBitDepth-8) / (Double)(m_iCount [iPartIdx][iTypeIdx][iClassIdx]<<m_uiSaoBitIncrease));
+#else
+          m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = (Int64) xRoundIbdi((Double)(m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx]<<g_uiBitIncrement) / (Double)(m_iCount [iPartIdx][iTypeIdx][iClassIdx]<<m_uiSaoBitIncrease));
+#endif
+          m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = Clip3(-m_iOffsetTh, m_iOffsetTh-1, (Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx]);
+
+          if (iTypeIdx < 4)
+          {
+            if ( m_iOffset[iPartIdx][iTypeIdx][iClassIdx]<0 && iClassIdx<3 )
+            {
+              m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = 0;
+            }
+            if ( m_iOffset[iPartIdx][iTypeIdx][iClassIdx]>0 && iClassIdx>=3)
+            {
+              m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = 0;
+            }
+          }
+          {
+            //Clean up, best_q_offset.
+            Int64 iIterOffset, iTempOffset;
+            Int64 iTempDist, iTempRate;
+            Double dTempCost, dTempMinCost;
+            UInt uiLength, uiTemp;
+
+            iIterOffset = m_iOffset[iPartIdx][iTypeIdx][iClassIdx];
+            m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = 0;
+            dTempMinCost = dLambda; // 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. 
+
+            while (iIterOffset != 0)
+            {
+              // Calculate the bits required for signalling the offset
+              uiLength = 1;
+              uiTemp = (UInt)((iIterOffset <= 0) ? ( (-iIterOffset<<1) + 1 ) : (iIterOffset<<1));
+              while( 1 != uiTemp )
+              {
+                uiTemp >>= 1;
+                uiLength += 2;
+              }
+              iTempRate = (uiLength >> 1) + ((uiLength+1) >> 1);
+
+              // Do the dequntization before distorion calculation
+              iTempOffset    =  iIterOffset << m_uiSaoBitIncrease;
+              iTempDist  = (( m_iCount [iPartIdx][iTypeIdx][iClassIdx]*iTempOffset*iTempOffset-m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx]*iTempOffset*2 ) >> uiShift);
+
+              dTempCost = ((Double)iTempDist + dLambda * (Double) iTempRate);
+              if(dTempCost < dTempMinCost)
+              {
+                dTempMinCost = dTempCost;
+                m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = iIterOffset;
+                if(iTypeIdx == SAO_BO)
+                {
+                  currentDistortionTableBo[iClassIdx-1] = (Int) iTempDist;
+                  currentRdCostTableBo[iClassIdx-1] = dTempCost;
+                }
+              }
+              iIterOffset = (iIterOffset > 0) ? (iIterOffset-1):(iIterOffset+1);
+            }
+
+          }
+        }
+        else
+        {
+          m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx] = 0;
+          m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = 0;
+        }
+        if( iTypeIdx != SAO_BO )
+        {
+          iCount     =  m_iCount [iPartIdx][iTypeIdx][iClassIdx];
+          iOffset    =  m_iOffset[iPartIdx][iTypeIdx][iClassIdx] << m_uiSaoBitIncrease;
+          iOffsetOrg =  m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx];
+          iEstDist   += (( iCount*iOffset*iOffset-iOffsetOrg*iOffset*2 ) >> uiShift);
+          if (iTypeIdx < 4)
+          {
+            if (iClassIdx<3)
+            {
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoUvlc((Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx]);
+            }
+            else
+            {
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoUvlc((Int)-m_iOffset[iPartIdx][iTypeIdx][iClassIdx]);
+            }
+          }
+          else
+          {
+            m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoSvlc((Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx]);
+          }
+        }
+      }
+
+      if( iTypeIdx == SAO_BO )
+      {
+        // Estimate Best Position
+        Double currentRDCost = 0.0;
+
+        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+        {
+          currentRDCost = 0.0;
+          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+          {
+            currentRDCost += currentRdCostTableBo[uj];
+          }
+
+          if( currentRDCost < bestRDCostTableBo)
+          {
+            bestRDCostTableBo = currentRDCost;
+            bestClassTableBo  = i;
+          }
+        }
+
+        // Re code all Offsets
+        // Code Center
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoUflc( (UInt) (bestClassTableBo) );
+
+        for(iClassIdx = bestClassTableBo; iClassIdx < bestClassTableBo+SAO_BO_LEN; iClassIdx++)
+        {
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoSvlc((Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx+1]);
+          iEstDist += currentDistortionTableBo[iClassIdx];
+        }
+      }
+
+      m_iDist[iPartIdx][iTypeIdx] = iEstDist;
+      m_iRate[iPartIdx][iTypeIdx] = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+      m_dCost[iPartIdx][iTypeIdx] = (Double)((Double)m_iDist[iPartIdx][iTypeIdx] + dLambda * (Double) m_iRate[iPartIdx][iTypeIdx]);
+
+      if(m_dCost[iPartIdx][iTypeIdx] < m_dCostPartBest[iPartIdx])
+      {
+        m_iDistOrg [iPartIdx] = 0;
+        m_dCostPartBest[iPartIdx] = m_dCost[iPartIdx][iTypeIdx];
+        m_iTypePartBest[iPartIdx] = iTypeIdx;
+        if( m_bUseSBACRD )
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
+      }
+    }
+    else
+    {
+      if(m_iDistOrg[iPartIdx] < m_dCostPartBest[iPartIdx] )
+      {
+        m_dCostPartBest[iPartIdx] = (Double) m_iDistOrg[iPartIdx] + m_pcEntropyCoder->getNumberOfWrittenBits()*dLambda ; 
+        m_iTypePartBest[iPartIdx] = -1;
+        if( m_bUseSBACRD )
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
+      }
+    }
+  }
+
+  pOnePart->bProcessed = true;
+  pOnePart->bSplit     = false;
+  pOnePart->iMinDist   =        m_iTypePartBest[iPartIdx] >= 0 ? m_iDist[iPartIdx][m_iTypePartBest[iPartIdx]] : m_iDistOrg[iPartIdx];
+  pOnePart->iMinRate   = (Int) (m_iTypePartBest[iPartIdx] >= 0 ? m_iRate[iPartIdx][m_iTypePartBest[iPartIdx]] : 0);
+  pOnePart->dMinCost   = pOnePart->iMinDist + dLambda * pOnePart->iMinRate;
+  pOnePart->iBestType  = m_iTypePartBest[iPartIdx];
+  if (pOnePart->iBestType != -1)
+  {
+    //     pOnePart->bEnableFlag =  1;
+    pOnePart->iLength = m_iNumClass[pOnePart->iBestType];
+    Int minIndex = 0;
+    if( pOnePart->iBestType == SAO_BO )
+    {
+      pOnePart->bandPosition = bestClassTableBo;
+      minIndex = pOnePart->bandPosition;
+    }
+    for (Int i=0; i< pOnePart->iLength ; i++)
+    {
+      pOnePart->iOffset[i] = (Int) m_iOffset[iPartIdx][pOnePart->iBestType][minIndex+i+1];
+    }
+
+  }
+  else
+  {
+    //     pOnePart->bEnableFlag = 0;
+    pOnePart->iLength     = 0;
+  }
+}
+
+/** Run partition tree disable
+ */
+Void TEncSampleAdaptiveOffset::disablePartTree(SAOQTPart *psQTPart, Int iPartIdx)
+{
+  SAOQTPart*  pOnePart= &(psQTPart[iPartIdx]);
+  pOnePart->bSplit      = false;
+  pOnePart->iLength     =  0;
+  pOnePart->iBestType   = -1;
+
+  if (pOnePart->PartLevel < m_uiMaxSplitLevel)
+  {
+    for (Int i=0; i<NUM_DOWN_PART; i++)
+    {
+      disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
+    }
+  }
+}
+
+/** Run quadtree decision function
+ * \param  iPartIdx, pcPicOrg, pcPicDec, pcPicRest, &dCostFinal
+ */
+Void TEncSampleAdaptiveOffset::runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda)
+{
+  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
+
+  UInt uiDepth = pOnePart->PartLevel;
+  UInt uhNextDepth = uiDepth+1;
+
+  if (iPartIdx == 0)
+  {
+    dCostFinal = 0;
+  }
+
+  //SAO for this part
+  if(!pOnePart->bProcessed)
+  {
+    rdoSaoOnePart (psQTPart, iPartIdx, dLambda);
+  }
+
+  //SAO for sub 4 parts
+  if (pOnePart->PartLevel < iMaxLevel)
+  {
+    Double      dCostNotSplit = dLambda + pOnePart->dMinCost;
+    Double      dCostSplit    = dLambda;
+
+    for (Int i=0; i< NUM_DOWN_PART ;i++)
+    {
+      if( m_bUseSBACRD )  
+      {
+        if ( 0 == i) //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]);
+        }
+      }  
+      runQuadTreeDecision(psQTPart, pOnePart->DownPartsIdx[i], dCostFinal, iMaxLevel, dLambda);
+      dCostSplit += dCostFinal;
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_TEMP_BEST]);
+      }
+    }
+
+    if(dCostSplit < dCostNotSplit)
+    {
+      dCostFinal = dCostSplit;
+      pOnePart->bSplit      = true;
+      pOnePart->iLength     =  0;
+      pOnePart->iBestType   = -1;
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+      }
+    }
+    else
+    {
+      dCostFinal = dCostNotSplit;
+      pOnePart->bSplit = false;
+      for (Int i=0; i<NUM_DOWN_PART; i++)
+      {
+        disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
+      }
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+      }
+    }
+  }
+  else
+  {
+    dCostFinal = pOnePart->dMinCost;
+  }
+}
+
+/** delete allocated memory of TEncSampleAdaptiveOffset class.
+ */
+Void TEncSampleAdaptiveOffset::destroyEncBuffer()
+{
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      if (m_iCount [i][j])
+      {
+        delete [] m_iCount [i][j]; 
+      }
+      if (m_iOffset[i][j])
+      {
+        delete [] m_iOffset[i][j]; 
+      }
+      if (m_iOffsetOrg[i][j])
+      {
+        delete [] m_iOffsetOrg[i][j]; 
+      }
+    }
+    if (m_iRate[i])
+    {
+      delete [] m_iRate[i];
+    }
+    if (m_iDist[i])
+    {
+      delete [] m_iDist[i]; 
+    }
+    if (m_dCost[i])
+    {
+      delete [] m_dCost[i]; 
+    }
+    if (m_iCount [i])
+    {
+      delete [] m_iCount [i]; 
+    }
+    if (m_iOffset[i])
+    {
+      delete [] m_iOffset[i]; 
+    }
+    if (m_iOffsetOrg[i])
+    {
+      delete [] m_iOffsetOrg[i]; 
+    }
+
+  }
+  if (m_iDistOrg)
+  {
+    delete [] m_iDistOrg ; m_iDistOrg = NULL;
+  }
+  if (m_dCostPartBest)
+  {
+    delete [] m_dCostPartBest ; m_dCostPartBest = NULL;
+  }
+  if (m_iTypePartBest)
+  {
+    delete [] m_iTypePartBest ; m_iTypePartBest = NULL;
+  }
+  if (m_iRate)
+  {
+    delete [] m_iRate ; m_iRate = NULL;
+  }
+  if (m_iDist)
+  {
+    delete [] m_iDist ; m_iDist = NULL;
+  }
+  if (m_dCost)
+  {
+    delete [] m_dCost ; m_dCost = NULL;
+  }
+  if (m_iCount)
+  {
+    delete [] m_iCount  ; m_iCount = NULL;
+  }
+  if (m_iOffset)
+  {
+    delete [] m_iOffset ; m_iOffset = NULL;
+  }
+  if (m_iOffsetOrg)
+  {
+    delete [] m_iOffsetOrg ; m_iOffsetOrg = NULL;
+  }
+
+  Int iMaxDepth = 4;
+  Int iDepth;
+  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+      delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+    }
+  }
+
+  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    delete [] m_pppcRDSbacCoder[iDepth];
+    delete [] m_pppcBinCoderCABAC[iDepth];
+  }
+
+  delete [] m_pppcRDSbacCoder;
+  delete [] m_pppcBinCoderCABAC;
+}
+
+/** create Encoder Buffer for SAO
+ * \param 
+ */
+Void TEncSampleAdaptiveOffset::createEncBuffer()
+{
+  m_iDistOrg = new Int64 [m_iNumTotalParts]; 
+  m_dCostPartBest = new Double [m_iNumTotalParts]; 
+  m_iTypePartBest = new Int [m_iNumTotalParts]; 
+
+  m_iRate = new Int64* [m_iNumTotalParts];
+  m_iDist = new Int64* [m_iNumTotalParts];
+  m_dCost = new Double*[m_iNumTotalParts];
+
+  m_iCount  = new Int64 **[m_iNumTotalParts];
+  m_iOffset = new Int64 **[m_iNumTotalParts];
+  m_iOffsetOrg = new Int64 **[m_iNumTotalParts];
+
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    m_iRate[i] = new Int64  [MAX_NUM_SAO_TYPE];
+    m_iDist[i] = new Int64  [MAX_NUM_SAO_TYPE]; 
+    m_dCost[i] = new Double [MAX_NUM_SAO_TYPE]; 
+
+    m_iCount [i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+    m_iOffset[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+    m_iOffsetOrg[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      m_iCount [i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
+      m_iOffset[i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
+      m_iOffsetOrg[i][j]= new Int64 [MAX_NUM_SAO_CLASS]; 
+    }
+  }
+
+  Int iMaxDepth = 4;
+  m_pppcRDSbacCoder = new TEncSbac** [iMaxDepth+1];
+#if FAST_BIT_EST
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter** [iMaxDepth+1];
+#else
+  m_pppcBinCoderCABAC = new TEncBinCABAC** [iMaxDepth+1];
+#endif
+
+  for ( Int iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
+#if FAST_BIT_EST
+    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;
+#if FAST_BIT_EST
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
+#else
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+#endif
+      m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
+    }
+  }
+}
+
+/** Start SAO encoder
+ * \param pcPic, pcEntropyCoder, pppcRDSbacCoder, pcRDGoOnSbacCoder 
+ */
+Void TEncSampleAdaptiveOffset::startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder)
+{
+  if( pcRDGoOnSbacCoder )
+    m_bUseSBACRD = true;
+  else
+    m_bUseSBACRD = false;
+
+  m_pcPic = pcPic;
+  m_pcEntropyCoder = pcEntropyCoder;
+
+  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
+  m_pcEntropyCoder->resetEntropy();
+  m_pcEntropyCoder->resetBits();
+
+  if( m_bUseSBACRD )
+  {
+    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
+  }
+}
+
+/** End SAO encoder
+ */
+Void TEncSampleAdaptiveOffset::endSaoEnc()
+{
+  m_pcPic = NULL;
+  m_pcEntropyCoder = NULL;
+}
+
+inline int xSign(int x)
+{
+  return ((x >> 31) | ((int)( (((unsigned int) -x)) >> 31)));
+}
+
+/** Calculate SAO statistics for non-cross-slice or non-cross-tile processing
+ * \param  pRecStart to-be-filtered block buffer pointer
+ * \param  pOrgStart original block buffer pointer
+ * \param  stride picture buffer stride
+ * \param  ppStat statistics buffer
+ * \param  ppCount counter buffer
+ * \param  width block width
+ * \param  height block height
+ * \param  pbBorderAvail availabilities of block border pixels
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail)
+{
+  Int64 *stats, *count;
+  Int classIdx, posShift, startX, endX, startY, endY, signLeft,signRight,signDown,signDown1;
+  Pel *pOrg, *pRec;
+  UInt edgeType;
+  Int x, y;
+
+  //--------- Band offset-----------//
+  stats = ppStats[SAO_BO];
+  count = ppCount[SAO_BO];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+  for (y=0; y< height; y++)
+  {
+    for (x=0; x< width; x++)
+    {
+      classIdx = m_lumaTableBo[pRec[x]];
+      if (classIdx)
+      {
+        stats[classIdx] += (pOrg[x] - pRec[x]); 
+        count[classIdx] ++;
+      }
+    }
+    pOrg += stride;
+    pRec += stride;
+  }
+  //---------- Edge offset 0--------------//
+  stats = ppStats[SAO_EO_0];
+  count = ppCount[SAO_EO_0];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+  for (y=0; y< height; y++)
+  {
+    signLeft = xSign(pRec[startX] - pRec[startX-1]);
+    for (x=startX; x< endX; x++)
+    {
+      signRight =  xSign(pRec[x] - pRec[x+1]); 
+      edgeType =  signRight + signLeft + 2;
+      signLeft  = -signRight;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+    pRec  += stride;
+    pOrg += stride;
+  }
+
+  //---------- Edge offset 1--------------//
+  stats = ppStats[SAO_EO_1];
+  count = ppCount[SAO_EO_1];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
+  endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
+  if (!pbBorderAvail[SGU_T])
+  {
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  for (x=0; x< width; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
+  }
+  for (y=startY; y<endY; y++)
+  {
+    for (x=0; x< width; x++)
+    {
+      signDown     =  xSign(pRec[x] - pRec[x+stride]); 
+      edgeType    =  signDown + m_iUpBuff1[x] + 2;
+      m_iUpBuff1[x] = -signDown;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+    pOrg += stride;
+    pRec += stride;
+  }
+  //---------- Edge offset 2--------------//
+  stats = ppStats[SAO_EO_2];
+  count = ppCount[SAO_EO_2];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  posShift= stride + 1;
+
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
+
+  //prepare 2nd line upper sign
+  pRec += stride;
+  for (x=startX; x< endX+1; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
+  }
+
+  //1st line
+  pRec -= stride;
+  if(pbBorderAvail[SGU_TL])
+  {
+    x= 0;
+    edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+  if(pbBorderAvail[SGU_T])
+  {
+    for(x= 1; x< endX; x++)
+    {
+      edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  pRec   += stride;
+  pOrg   += stride;
+
+  //middle lines
+  for (y= 1; y< height-1; y++)
+  {
+    for (x=startX; x<endX; x++)
+    {
+      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
+      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+
+      m_iUpBufft[x+1] = -signDown1; 
+    }
+    m_iUpBufft[startX] = xSign(pRec[stride+startX] - pRec[startX-1]);
+
+    ipSwap     = m_iUpBuff1;
+    m_iUpBuff1 = m_iUpBufft;
+    m_iUpBufft = ipSwap;
+
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  //last line
+  if(pbBorderAvail[SGU_B])
+  {
+    for(x= startX; x< width-1; x++)
+    {
+      edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  if(pbBorderAvail[SGU_BR])
+  {
+    x= width -1;
+    edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+
+  //---------- Edge offset 3--------------//
+
+  stats = ppStats[SAO_EO_3];
+  count = ppCount[SAO_EO_3];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  posShift     = stride - 1;
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+
+  //prepare 2nd line upper sign
+  pRec += stride;
+  for (x=startX-1; x< endX; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
+  }
+
+
+  //first line
+  pRec -= stride;
+  if(pbBorderAvail[SGU_T])
+  {
+    for(x= startX; x< width -1; x++)
+    {
+      edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  if(pbBorderAvail[SGU_TR])
+  {
+    x= width-1;
+    edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+  pRec  += stride;
+  pOrg  += stride;
+
+  //middle lines
+  for (y= 1; y< height-1; y++)
+  {
+    for(x= startX; x< endX; x++)
+    {
+      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
+      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+      m_iUpBuff1[x-1] = -signDown1; 
+
+    }
+    m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
+
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  //last line
+  if(pbBorderAvail[SGU_BL])
+  {
+    x= 0;
+    edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+
+  }
+  if(pbBorderAvail[SGU_B])
+  {
+    for(x= 1; x< endX; x++)
+    {
+      edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+}
+
+/** Calculate SAO statistics for current LCU
+ * \param  iAddr,  iPartIdx,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr)
+{
+  if(!m_bUseNIF)
+  {
+    calcSaoStatsCuOrg( iAddr, iPartIdx, iYCbCr);
+  }
+  else
+  {
+    Int64** ppStats = m_iOffsetOrg[iPartIdx];
+    Int64** ppCount = m_iCount    [iPartIdx];
+
+    //parameters
+    Int  isChroma = (iYCbCr != 0)? 1:0;
+    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
+    Pel* pPicOrg = getPicYuvAddr (m_pcPic->getPicYuvOrg(), iYCbCr);
+    Pel* pPicRec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
+
+    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
+
+    //variables
+    UInt  xPos, yPos, width, height;
+    Bool* pbBorderAvail;
+    UInt  posOffset;
+
+    for(Int i=0; i< vFilterBlocks.size(); i++)
+    {
+      xPos        = vFilterBlocks[i].posX   >> isChroma;
+      yPos        = vFilterBlocks[i].posY   >> isChroma;
+      width       = vFilterBlocks[i].width  >> isChroma;
+      height      = vFilterBlocks[i].height >> isChroma;
+      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
+
+      posOffset = (yPos* stride) + xPos;
+
+#if HHI_INTERVIEW_SKIP
+      if( !m_pcPic->getCU(iAddr)->getRenderable(0 ))
+      {
+      calcSaoStatsBlock(pPicRec+ posOffset, pPicOrg+ posOffset, stride, ppStats, ppCount,width, height, pbBorderAvail);
+      }
+#else
+      calcSaoStatsBlock(pPicRec+ posOffset, pPicOrg+ posOffset, stride, ppStats, ppCount,width, height, pbBorderAvail);
+#endif
+    }
+  }
+
+}
+
+/** Calculate SAO statistics for current LCU without non-crossing slice
+ * \param  iAddr,  iPartIdx,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr)
+{
+  Int x,y;
+  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
+  TComSPS *pTmpSPS =  m_pcPic->getSlice(0)->getSPS();
+
+  Pel* pOrg;
+  Pel* pRec;
+  Int iStride;
+  Int iLcuWidth  = pTmpSPS->getMaxCUHeight();
+  Int iLcuHeight = pTmpSPS->getMaxCUWidth();
+  UInt uiLPelX   = pTmpCu->getCUPelX();
+  UInt uiTPelY   = pTmpCu->getCUPelY();
+  UInt uiRPelX;
+  UInt uiBPelY;
+  Int64* iStats;
+  Int64* iCount;
+  Int iClassIdx;
+  Int iPicWidthTmp;
+  Int iPicHeightTmp;
+  Int iStartX;
+  Int iStartY;
+  Int iEndX;
+  Int iEndY;
+
+  Int iIsChroma = (iYCbCr!=0)? 1:0;
+  Int numSkipLine = iIsChroma? 2:4;
+  if (m_saoInterleavingFlag == 0)
+  {
+    numSkipLine = 0;
+  }
+
+  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
+  iPicHeightTmp = m_iPicHeight >> iIsChroma;
+  iLcuWidth     = iLcuWidth    >> iIsChroma;
+  iLcuHeight    = iLcuHeight   >> iIsChroma;
+  uiLPelX       = uiLPelX      >> iIsChroma;
+  uiTPelY       = uiTPelY      >> iIsChroma;
+  uiRPelX       = uiLPelX + iLcuWidth  ;
+  uiBPelY       = uiTPelY + iLcuHeight ;
+  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
+  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
+  iLcuWidth     = uiRPelX - uiLPelX;
+  iLcuHeight    = uiBPelY - uiTPelY;
+
+  iStride    =  (iYCbCr == 0)? m_pcPic->getStride(): m_pcPic->getCStride();
+
+//if(iSaoType == BO_0 || iSaoType == BO_1)
+#if HHI_INTERVIEW_SKIP
+  if( !m_pcPic->getCU(iAddr)->getRenderable(0) )
+#endif
+  {
+    iStats = m_iOffsetOrg[iPartIdx][SAO_BO];
+    iCount = m_iCount    [iPartIdx][SAO_BO];
+
+    pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+    pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+    iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight : iLcuHeight-numSkipLine;
+    for (y=0; y<iEndY; y++)
+    {
+      for (x=0; x<iLcuWidth; x++)
+      {
+        iClassIdx = m_lumaTableBo[pRec[x]];
+        if (iClassIdx)
+        {
+          iStats[iClassIdx] += (pOrg[x] - pRec[x]); 
+          iCount[iClassIdx] ++;
+        }
+      }
+      pOrg += iStride;
+      pRec += iStride;
+    }
+
+  }
+  Int iSignLeft;
+  Int iSignRight;
+  Int iSignDown;
+  Int iSignDown1;
+  Int iSignDown2;
+
+  UInt uiEdgeType;
+
+//if (iSaoType == EO_0  || iSaoType == EO_1 || iSaoType == EO_2 || iSaoType == EO_3)
+#if HHI_INTERVIEW_SKIP
+  if( !m_pcPic->getCU(iAddr)->getRenderable(0) )
+#endif
+  {
+  //if (iSaoType == EO_0)
+    {
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_0];
+      iCount = m_iCount    [iPartIdx][SAO_EO_0];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+      for (y=0; y<iLcuHeight-numSkipLine; y++)
+      {
+        iSignLeft = xSign(pRec[iStartX] - pRec[iStartX-1]);
+        for (x=iStartX; x< iEndX; x++)
+        {
+          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
+          uiEdgeType =  iSignRight + iSignLeft + 2;
+          iSignLeft  = -iSignRight;
+
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+
+  //if (iSaoType == EO_1)
+    {
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_1];
+      iCount = m_iCount    [iPartIdx][SAO_EO_1];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (uiTPelY == 0)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=0; x< iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        for (x=0; x<iLcuWidth; x++)
+        {
+          iSignDown     =  xSign(pRec[x] - pRec[x+iStride]); 
+          uiEdgeType    =  iSignDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x] = -iSignDown;
+
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+  //if (iSaoType == EO_2)
+    {
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_2];
+      iCount = m_iCount    [iPartIdx][SAO_EO_2];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (uiTPelY == 0)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=iStartX; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride-1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        iSignDown2 = xSign(pRec[iStride+iStartX] - pRec[iStartX-1]);
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBufft[x+1] = -iSignDown1; 
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        m_iUpBufft[iStartX] = iSignDown2;
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pRec += iStride;
+        pOrg += iStride;
+      }
+    } 
+  //if (iSaoType == EO_3  )
+    {
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_3];
+      iCount = m_iCount    [iPartIdx][SAO_EO_3];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (iStartY == 1)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=iStartX-1; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride+1]);
+      }
+
+      for (y=iStartY; y<iEndY; y++)
+      {
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x-1] = -iSignDown1; 
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
+
+        pRec += iStride;
+        pOrg += iStride;
+      } 
+    } 
+  }
+}
+
+/** get SAO statistics
+ * \param  *psQTPart,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::getSaoStats(SAOQTPart *psQTPart, Int iYCbCr)
+{
+  Int iLevelIdx, iPartIdx, iTypeIdx, iClassIdx;
+  Int i;
+  Int iNumTotalType = MAX_NUM_SAO_TYPE;
+  Int LcuIdxX;
+  Int LcuIdxY;
+  Int iAddr;
+  Int iFrameWidthInCU = m_pcPic->getFrameWidthInCU();
+  Int iDownPartIdx;
+  Int iPartStart;
+  Int iPartEnd;
+  SAOQTPart*  pOnePart; 
+
+  if (m_uiMaxSplitLevel == 0)
+  {
+    iPartIdx = 0;
+    pOnePart = &(psQTPart[iPartIdx]);
+    for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
+    {
+      for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
+      {
+        iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+        calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
+      }
+    }
+  }
+  else
+  {
+    for(iPartIdx=m_aiNumCulPartsLevel[m_uiMaxSplitLevel-1]; iPartIdx<m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; iPartIdx++)
+    {
+      pOnePart = &(psQTPart[iPartIdx]);
+      for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
+      {
+        for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
+        {
+          iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+          calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
+        }
+      }
+    }
+    for (iLevelIdx = m_uiMaxSplitLevel-1; iLevelIdx>=0; iLevelIdx-- )
+    {
+      iPartStart = (iLevelIdx > 0) ? m_aiNumCulPartsLevel[iLevelIdx-1] : 0;
+      iPartEnd   = m_aiNumCulPartsLevel[iLevelIdx];
+
+      for(iPartIdx = iPartStart; iPartIdx < iPartEnd; iPartIdx++)
+      {
+        pOnePart = &(psQTPart[iPartIdx]);
+        for (i=0; i< NUM_DOWN_PART; i++)
+        {
+          iDownPartIdx = pOnePart->DownPartsIdx[i];
+          for (iTypeIdx=0; iTypeIdx<iNumTotalType; iTypeIdx++)
+          {
+            for (iClassIdx=0; iClassIdx< (iTypeIdx < SAO_BO ? m_iNumClass[iTypeIdx] : SAO_MAX_BO_CLASSES) +1; iClassIdx++)
+            {
+              m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx] += m_iOffsetOrg[iDownPartIdx][iTypeIdx][iClassIdx];
+              m_iCount [iPartIdx][iTypeIdx][iClassIdx]    += m_iCount [iDownPartIdx][iTypeIdx][iClassIdx];
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+/** reset offset statistics 
+ * \param 
+ */
+Void TEncSampleAdaptiveOffset::resetStats()
+{
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    m_dCostPartBest[i] = MAX_DOUBLE;
+    m_iTypePartBest[i] = -1;
+    m_iDistOrg[i] = 0;
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      m_iDist[i][j] = 0;
+      m_iRate[i][j] = 0;
+      m_dCost[i][j] = 0;
+      for (Int k=0;k<MAX_NUM_SAO_CLASS;k++)
+      {
+        m_iCount [i][j][k] = 0;
+        m_iOffset[i][j][k] = 0;
+        m_iOffsetOrg[i][j][k] = 0;
+      }  
+    }
+  }
+}
+
+#if SAO_CHROMA_LAMBDA 
+/** Sample adaptive offset process
+ * \param pcSaoParam
+ * \param dLambdaLuma
+ * \param dLambdaChroma
+ */
+Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma)
+#else
+/** Sample adaptive offset process
+ * \param dLambda
+ */
+Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambda)
+#endif
+{
+
+  m_eSliceType          =  m_pcPic->getSlice(0)->getSliceType();
+  m_iPicNalReferenceIdc = (m_pcPic->getSlice(0)->isReferenced() ? 1 :0);
+
+#if SAO_CHROMA_LAMBDA 
+  m_dLambdaLuma    = dLambdaLuma;
+  m_dLambdaChroma  = dLambdaChroma;
+#else
+  m_dLambdaLuma    = dLambda;
+  m_dLambdaChroma  = dLambda;
+#endif
+
+  if(m_bUseNIF)
+  {
+    m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
+  }
+
+#if FULL_NBIT
+  m_uiSaoBitIncrease = g_uiBitDepth + (g_uiBitDepth-8) - min((Int)(g_uiBitDepth + (g_uiBitDepth-8)), 10);
+#else
+  m_uiSaoBitIncrease = g_uiBitDepth + g_uiBitIncrement - min((Int)(g_uiBitDepth + g_uiBitIncrement), 10);
+#endif
+
+  const Int iOffsetBitRange8Bit = 4;
+  Int iOffsetBitDepth = g_uiBitDepth + g_uiBitIncrement - m_uiSaoBitIncrease;
+  Int iOffsetBitRange = iOffsetBitRange8Bit + (iOffsetBitDepth - 8);
+  m_iOffsetTh = 1 << (iOffsetBitRange - 1);
+  resetSAOParam(pcSaoParam);
+  resetStats();
+
+  Int iY  = 0;
+  Double dCostFinal = 0;
+
+
+  if ( m_saoInterleavingFlag)
+  {
+    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma);
+  }
+  else
+  {
+    pcSaoParam->bSaoFlag[0] = 1;
+    pcSaoParam->bSaoFlag[1] = 0;
+    pcSaoParam->bSaoFlag[2] = 0;
+    for (Int compIdx=0;compIdx<3;compIdx++)
+    {
+      if (pcSaoParam->bSaoFlag[iY])
+      {
+        dCostFinal = 0;
+        Double lambdaRdo = (compIdx==0 ? dLambdaLuma: dLambdaChroma);
+        resetStats();
+        getSaoStats(pcSaoParam->psSaoPart[compIdx], compIdx);
+        runQuadTreeDecision(pcSaoParam->psSaoPart[compIdx], 0, dCostFinal, m_uiMaxSplitLevel, lambdaRdo);
+        pcSaoParam->bSaoFlag[compIdx] = dCostFinal < 0 ? 1:0;
+        if(pcSaoParam->bSaoFlag[compIdx])
+        {
+          convertQT2SaoUnit(pcSaoParam, 0, compIdx);
+          assignSaoUnitSyntax(pcSaoParam->saoLcuParam[compIdx],  pcSaoParam->psSaoPart[compIdx], pcSaoParam->oneUnitFlag[compIdx], compIdx);
+        }
+      }
+    }
+  }
+  for (Int compIdx=0;compIdx<3;compIdx++)
+  {
+    if (pcSaoParam->bSaoFlag[compIdx])
+    {
+      processSaoUnitAll( pcSaoParam->saoLcuParam[compIdx], pcSaoParam->oneUnitFlag[compIdx], compIdx);
+    }
+  }
+}
+/** Check merge SAO unit
+ * \param saoUnitCurr current SAO unit 
+ * \param saoUnitCheck SAO unit tobe check
+ * \param dir direction
+ */
+Void TEncSampleAdaptiveOffset::checkMerge(SaoLcuParam * saoUnitCurr, SaoLcuParam * saoUnitCheck, Int dir)
+{
+  Int i ;
+  Int countDiff = 0;
+  if (saoUnitCurr->partIdx != saoUnitCheck->partIdx)
+  {
+    if (saoUnitCurr->typeIdx !=-1)
+    {
+      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
+      {
+        for (i=0;i<saoUnitCurr->length;i++)
+        {
+          countDiff += (saoUnitCurr->offset[i] != saoUnitCheck->offset[i]);
+        }
+        countDiff += (saoUnitCurr->bandPosition != saoUnitCheck->bandPosition);
+        if (countDiff ==0)
+        {
+          saoUnitCurr->partIdx = saoUnitCheck->partIdx;
+          if (dir == 1)
+          {
+            saoUnitCurr->mergeUpFlag = 1;
+            saoUnitCurr->mergeLeftFlag = 0;
+          }
+          else
+          {
+            saoUnitCurr->mergeUpFlag = 0;
+            saoUnitCurr->mergeLeftFlag = 1;
+          }
+        }
+      }
+    }
+    else
+    {
+      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
+      {
+        saoUnitCurr->partIdx = saoUnitCheck->partIdx;
+        if (dir == 1)
+        {
+          saoUnitCurr->mergeUpFlag = 1;
+          saoUnitCurr->mergeLeftFlag = 0;
+        }
+        else
+        {
+          saoUnitCurr->mergeUpFlag = 0;
+          saoUnitCurr->mergeLeftFlag = 1;
+        }
+      }
+    }
+  }
+}
+/** Assign SAO unit syntax from picture-based algorithm
+ * \param saoLcuParam SAO LCU parameters
+ * \param saoPart SAO part
+ * \param oneUnitFlag SAO one unit flag
+ * \param iYCbCr color component Index
+ */
+Void TEncSampleAdaptiveOffset::assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr)
+{
+  if (saoPart->bSplit == 0)
+  {
+    oneUnitFlag = 1;
+  }
+  else
+  {
+    Int i,j, addr, addrUp, addrLeft,  idx, idxUp, idxLeft,  idxCount;
+    Int run;
+    Int runPartBeginAddr=0;
+    Int runPart;
+    Int runPartPrevious;
+
+    oneUnitFlag = 0;
+
+    idxCount = -1;
+    saoLcuParam[0].mergeUpFlag = 0;
+    saoLcuParam[0].mergeLeftFlag = 0;
+
+    for (j=0;j<m_iNumCuInHeight;j++)
+    {
+      run = 0;
+      runPartPrevious = -1;
+      for (i=0;i<m_iNumCuInWidth;i++)
+      {
+        addr     = i + j*m_iNumCuInWidth;
+        addrLeft = (addr%m_iNumCuInWidth == 0) ? -1 : addr - 1;
+        addrUp   = (addr<m_iNumCuInWidth)      ? -1 : addr - m_iNumCuInWidth;
+        idx      = saoLcuParam[addr].partIdxTmp;
+        idxLeft  = (addrLeft == -1) ? -1 : saoLcuParam[addrLeft].partIdxTmp;
+        idxUp    = (addrUp == -1)   ? -1 : saoLcuParam[addrUp].partIdxTmp;
+
+        if(idx!=idxLeft && idx!=idxUp)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 0; idxCount++;
+          saoLcuParam[addr].mergeLeftFlag = 0;
+          saoLcuParam[addr].partIdx = idxCount;
+        }
+        else if (idx==idxLeft)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 1;
+          saoLcuParam[addr].mergeLeftFlag = 1;
+          saoLcuParam[addr].partIdx = saoLcuParam[addrLeft].partIdx;
+        }
+        else if (idx==idxUp)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 1;
+          saoLcuParam[addr].mergeLeftFlag = 0;
+          saoLcuParam[addr].partIdx = saoLcuParam[addrUp].partIdx;
+        }
+        if (addrUp != -1)
+        {
+          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrUp], 1);
+        }
+        if (addrLeft != -1)
+        {
+          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrLeft], 0);
+        }
+        runPart = saoLcuParam[addr].partIdx;
+        if (runPart == runPartPrevious)
+        {
+          run ++;
+          saoLcuParam[addr].run = -1;
+          saoLcuParam[runPartBeginAddr].run = run;
+        }
+        else
+        {
+          runPartBeginAddr = addr;
+          run = 0;
+          saoLcuParam[addr].run = run;
+        }
+        runPartPrevious = runPart;
+      }
+    }
+
+    for (j=0;j<m_iNumCuInHeight;j++)
+    {
+      for (i=0;i<m_iNumCuInWidth;i++)
+      {
+        addr     =  i + j*m_iNumCuInWidth;
+        addrLeft =  (addr%m_iNumCuInWidth == 0) ? -1 : addr - 1;
+        addrUp  =  (addr<m_iNumCuInWidth)      ? -1 : addr - m_iNumCuInWidth;
+
+        if (saoLcuParam[addr].run == -1)
+        {
+          if (addrLeft != -1)
+          {
+            saoLcuParam[addr].run = saoLcuParam[addrLeft].run-1;
+          }
+        }
+        if (addrUp>=0)
+        {
+          saoLcuParam[addr].runDiff = saoLcuParam[addr].run - saoLcuParam[addrUp].run;
+        }
+        else
+        {
+          saoLcuParam[addr].runDiff = saoLcuParam[addr].run ;
+        }
+      }
+    }
+  }
+}
+/** rate distortion optimization of all SAO units
+ * \param saoParam SAO parameters
+ * \param lambda 
+ * \param lambdaChroma
+ */
+Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma)
+{
+
+  Int idxY;
+  Int idxX;
+  Int frameHeightInCU = saoParam->numCuInHeight;
+  Int frameWidthInCU  = saoParam->numCuInWidth;
+  Int j, k;
+  Int addr = 0;
+  Int addrUp = -1;
+  Int addrLeft = -1;
+  Int compIdx = 0;
+  Double lambdaComp;
+
+  saoParam->bSaoFlag[0] = true;
+  saoParam->bSaoFlag[1] = true;
+  saoParam->bSaoFlag[2] = true;
+  saoParam->oneUnitFlag[0] = false;
+  saoParam->oneUnitFlag[1] = false;
+  saoParam->oneUnitFlag[2] = false;
+
+
+  for (idxY = 0; idxY< frameHeightInCU; idxY++)
+  {
+    for (idxX = 0; idxX< frameWidthInCU; idxX++)
+    {
+      addr     = idxX  + frameWidthInCU*idxY;
+      addrUp   = addr < frameWidthInCU ? -1:idxX   + frameWidthInCU*(idxY-1);
+      addrLeft = idxX == 0               ? -1:idxX-1 + frameWidthInCU*idxY;
+      // reset stats Y, Cb, Cr
+      for ( compIdx=0;compIdx<3;compIdx++)
+      {
+        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
+        {
+          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
+          {
+            m_iCount    [compIdx][j][k] = 0;
+            m_iOffset   [compIdx][j][k] = 0;
+            m_iOffsetOrg[compIdx][j][k] = 0;
+          }  
+        }
+        saoParam->saoLcuParam[compIdx][addr].typeIdx       =  -1;
+        saoParam->saoLcuParam[compIdx][addr].mergeUpFlag   = 0;
+        saoParam->saoLcuParam[compIdx][addr].run           = 0;
+        saoParam->saoLcuParam[compIdx][addr].runDiff       = 0;
+        saoParam->saoLcuParam[compIdx][addr].mergeLeftFlag = 0;
+        saoParam->saoLcuParam[compIdx][addr].bandPosition  = 0;
+        lambdaComp = compIdx==0 ? lambda : lambdaChroma;
+        calcSaoStatsCu(addr, compIdx,  compIdx);
+        rdoSaoUnit (saoParam, addr, addrUp, addrLeft, compIdx,  lambdaComp);
+#if !REMOVE_SAO_LCU_ENC_CONSTRAINTS_3
+        if (compIdx!=0)
+        {
+          if ( saoParam->saoLcuParam[compIdx][0].typeIdx == -1 )
+          {
+            saoParam->bSaoFlag[compIdx] = false;
+          }
+        }
+#endif
+      }
+    }
+  }
+
+}
+/** rate distortion optimization of SAO unit 
+ * \param saoParam SAO parameters
+ * \param addr address 
+ * \param addrUp above address
+ * \param addrLeft left address 
+ * \param yCbCr color component index
+ * \param lambda 
+ */
+Void TEncSampleAdaptiveOffset::rdoSaoUnit(SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda)
+{
+  Int typeIdx;
+
+  Int64 estDist;
+  Int64 offsetOrg;
+  Int64 offset;
+  Int64 count;
+  Int classIdx;
+  Int shift = g_uiBitIncrement << 1;
+  //   Double dAreaWeight =  0;
+  Double complexityCost = 0;
+  SaoLcuParam*  saoLcuParam = NULL;   
+  SaoLcuParam*  saoLcuParamNeighbor = NULL; 
+  Int   merge_iOffset [33];
+  Int64 merge_iDist;
+  Int   merge_iRate;
+  Double merge_dCost;
+  Int offsetTh = m_iOffsetTh;
+
+  saoLcuParam = &(saoParam->saoLcuParam[yCbCr][addr]);
+
+  saoLcuParam->mergeUpFlag   = 0;
+  saoLcuParam->mergeLeftFlag = 0;
+  saoLcuParam->run    = 0;
+  saoLcuParam->runDiff= 0;
+
+
+  m_iTypePartBest[yCbCr] = -1;
+  m_dCostPartBest[yCbCr] = 0;
+  m_iDistOrg[yCbCr] = 0;
+
+  Double  bestRDCostTableBo = MAX_DOUBLE;
+  Int     bestClassTableBo    = 0;
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+  Int     bestClassTableBoMerge = 0;
+
+#if HHI_INTERVIEW_SKIP
+  Bool bRenderable = m_pcPic->getCU(addr)->getRenderable(0) ;
+#endif
+  for (typeIdx=-1; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
+  {
+    m_pcEntropyCoder->resetEntropy();
+    m_pcEntropyCoder->resetBits();
+
+    if (m_saoInterleavingFlag)
+    {
+#if !REMOVE_SAO_LCU_ENC_CONSTRAINTS_1
+      if(yCbCr>0 && typeIdx>3 )
+      {
+        continue;
+      }
+#endif
+#if !REMOVE_SAO_LCU_ENC_CONSTRAINTS_2
+      if (yCbCr>0 )
+      {
+        offsetTh = 2<<g_uiBitIncrement;
+      }
+      else
+#endif
+      {
+        offsetTh = m_iOffsetTh;
+      }
+    }
+
+    estDist = 0;
+    m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoTypeIdx(typeIdx+1);
+    if (typeIdx>=0)
+    {
+
+      for(classIdx=1; classIdx < ( (typeIdx < SAO_BO) ?  m_iNumClass[typeIdx]+1 : SAO_MAX_BO_CLASSES+1); classIdx++)
+      {
+        if( typeIdx == SAO_BO)
+        {
+          currentDistortionTableBo[classIdx-1] = 0;
+          currentRdCostTableBo[classIdx-1] = lambda;
+        }
+#if HHI_INTERVIEW_SKIP
+        if(m_iCount [yCbCr][typeIdx][classIdx] && !bRenderable)
+#else
+        if(m_iCount [yCbCr][typeIdx][classIdx])
+#endif
+        {
+          m_iOffset[yCbCr][typeIdx][classIdx] = (Int64) xRoundIbdi((Double)(m_iOffsetOrg[yCbCr][typeIdx][classIdx]<<g_uiBitIncrement) / (Double)(m_iCount [yCbCr][typeIdx][classIdx]<<m_uiSaoBitIncrease));
+          m_iOffset[yCbCr][typeIdx][classIdx] = Clip3(-offsetTh, offsetTh, (Int)m_iOffset[yCbCr][typeIdx][classIdx]);
+          if (typeIdx < 4)
+          {
+            if ( m_iOffset[yCbCr][typeIdx][classIdx]<0 && classIdx<3 )
+            {
+              m_iOffset[yCbCr][typeIdx][classIdx] = 0;
+            }
+            if ( m_iOffset[yCbCr][typeIdx][classIdx]>0 && classIdx>=3)
+            {
+              m_iOffset[yCbCr][typeIdx][classIdx] = 0;
+            }
+          }
+          {
+            //Clean up, best_q_offset.
+            Int64 iIterOffset, iTempOffset;
+            Int64 iTempDist, iTempRate;
+            Double dTempCost, dTempMinCost;
+            UInt uiLength, uiTemp;
+
+            iIterOffset = m_iOffset[yCbCr][typeIdx][classIdx];
+            m_iOffset[yCbCr][typeIdx][classIdx] = 0;
+            dTempMinCost = 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. 
+
+            while (iIterOffset != 0)
+            {
+              // Calculate the bits required for signalling the offset
+              uiLength = 1;
+              uiTemp = (UInt)((iIterOffset <= 0) ? ( (-iIterOffset<<1) + 1 ) : (iIterOffset<<1));
+              while( 1 != uiTemp )
+              {
+                uiTemp >>= 1;
+                uiLength += 2;
+              }
+              iTempRate = (uiLength >> 1) + ((uiLength+1) >> 1);
+
+              // Do the dequntization before distorion calculation
+              iTempOffset    =  iIterOffset << m_uiSaoBitIncrease;
+              iTempDist  = (( m_iCount [yCbCr][typeIdx][classIdx]*iTempOffset*iTempOffset-m_iOffsetOrg[yCbCr][typeIdx][classIdx]*iTempOffset*2 ) >> shift);
+              dTempCost = ((Double)iTempDist + lambda * (Double) iTempRate);
+              if(dTempCost < dTempMinCost)
+              {
+                dTempMinCost = dTempCost;
+                m_iOffset[yCbCr][typeIdx][classIdx] = iIterOffset;
+                if(typeIdx == SAO_BO)
+                {
+                  currentDistortionTableBo[classIdx-1] = (Int) iTempDist;
+                  currentRdCostTableBo[classIdx-1] = dTempCost;
+                }
+              }
+              iIterOffset = (iIterOffset > 0) ? (iIterOffset-1):(iIterOffset+1);
+            }
+          }
+
+        }
+        else
+        {
+          m_iOffsetOrg[yCbCr][typeIdx][classIdx] = 0;
+          m_iOffset[yCbCr][typeIdx][classIdx] = 0;
+        }
+        if( typeIdx != SAO_BO )
+        {
+          count     =  m_iCount [yCbCr][typeIdx][classIdx];
+          offset    =  m_iOffset[yCbCr][typeIdx][classIdx] << m_uiSaoBitIncrease;
+          offsetOrg =  m_iOffsetOrg[yCbCr][typeIdx][classIdx];
+#if HHI_INTERVIEW_SKIP
+          if (!bRenderable)
+          {
+          estDist   += (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
+          }
+#else
+          estDist   += (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
+#endif
+          if (typeIdx < 4)
+          {
+            if (classIdx<3)
+            {
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoUvlc((Int)m_iOffset[yCbCr][typeIdx][classIdx]);
+            }
+            else
+            {
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoUvlc((Int)-m_iOffset[yCbCr][typeIdx][classIdx]);
+            }
+          }
+          else
+          {
+            m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoSvlc((Int)m_iOffset[yCbCr][typeIdx][classIdx]);
+          }
+        }
+
+      }
+
+      if( typeIdx == SAO_BO )
+      {
+        // Estimate Best Position
+        Double currentRDCost = 0.0;
+
+        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+        {
+          currentRDCost = 0.0;
+          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+          {
+            currentRDCost += currentRdCostTableBo[uj];
+          }
+
+          if( currentRDCost < bestRDCostTableBo)
+          {
+            bestRDCostTableBo = currentRDCost;
+            bestClassTableBo  = i;
+          }
+        }
+
+        // Re code all Offsets
+        // Code Center
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoUflc( (UInt) (bestClassTableBo) );
+
+        for(classIdx = bestClassTableBo; classIdx < bestClassTableBo+SAO_BO_LEN; classIdx++)
+        {
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoSvlc((Int)m_iOffset[yCbCr][typeIdx][classIdx+1]);
+#if HHI_INTERVIEW_SKIP
+          if (!bRenderable)
+          {
+          estDist += currentDistortionTableBo[classIdx];
+          }
+#else
+          estDist += currentDistortionTableBo[classIdx];
+#endif
+        }
+      }
+
+      m_iDist[yCbCr][typeIdx] = estDist;
+      m_iRate[yCbCr][typeIdx] = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+      m_dCost[yCbCr][typeIdx] = (Double)((Double)m_iDist[yCbCr][typeIdx] + lambda * (Double) m_iRate[yCbCr][typeIdx]);
+
+      if(m_dCost[yCbCr][typeIdx] < m_dCostPartBest[yCbCr])
+      {
+        m_iDistOrg [yCbCr] = (Int64)complexityCost;
+        m_dCostPartBest[yCbCr] = m_dCost[yCbCr][typeIdx];
+        m_iTypePartBest[yCbCr] = typeIdx;
+      }
+    }
+    else
+    {
+      if(m_iDistOrg[yCbCr] < m_dCostPartBest[yCbCr])
+      {
+        m_dCostPartBest[yCbCr] = (Double) m_iDistOrg[yCbCr] + m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
+        m_iTypePartBest[yCbCr] = -1;
+      }
+    }
+  }
+
+  // merge left or merge up
+
+  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
+  {
+    saoLcuParamNeighbor = NULL;
+    if (addrLeft>=0 && idxNeighbor ==0)
+    {
+      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrLeft]);
+    }
+    else if (addrUp>=0 && idxNeighbor ==1)
+    {
+      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrUp]);
+    }
+    if (saoLcuParamNeighbor!=NULL)
+    {
+      if (saoLcuParamNeighbor->typeIdx>=0) //new
+      {
+        m_pcEntropyCoder->resetEntropy();
+        m_pcEntropyCoder->resetBits();
+
+        estDist = 0;
+        typeIdx = saoLcuParamNeighbor->typeIdx;
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoFlag(1);
+        if (saoLcuParamNeighbor->typeIdx == SAO_BO)
+        {
+          for(classIdx = saoLcuParamNeighbor->bandPosition+1; classIdx < saoLcuParamNeighbor->bandPosition+SAO_BO_LEN+1; classIdx++)
+          {
+            merge_iOffset[classIdx] = saoLcuParamNeighbor->offset[classIdx-1-saoLcuParamNeighbor->bandPosition];
+
+            count     =  m_iCount [yCbCr][typeIdx][classIdx];
+            offset    =  merge_iOffset[classIdx];
+            offsetOrg =  m_iOffsetOrg[yCbCr][typeIdx][classIdx];
+#if HHI_INTERVIEW_SKIP
+          if (!bRenderable)
+          {
+            estDist   += (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
+          }
+#else
+          estDist   += (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
+#endif
+          }
+        }
+        else
+        {
+          for(classIdx=1; classIdx < m_iNumClass[typeIdx]+1; classIdx++)
+          {
+            merge_iOffset[classIdx] = saoLcuParamNeighbor->offset[classIdx-1];
+
+            count     =  m_iCount [yCbCr][typeIdx][classIdx];
+            offset    =  merge_iOffset[classIdx];
+            offsetOrg =  m_iOffsetOrg[yCbCr][typeIdx][classIdx];
+#if HHI_INTERVIEW_SKIP
+          if (!bRenderable)
+          {
+            estDist   += (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
+          }
+#else
+          estDist   += (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
+#endif
+          }
+        }
+        merge_iDist = estDist;
+        merge_iRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+        merge_dCost = (Double)((Double)merge_iDist + m_dLambdaLuma * (Double) merge_iRate) ;
+
+        if(merge_dCost < m_dCostPartBest[yCbCr])
+        {
+          m_iDistOrg [yCbCr] = (Int64)complexityCost;
+          m_dCostPartBest[yCbCr] = merge_dCost;
+          m_iTypePartBest[yCbCr] = typeIdx;
+          if (typeIdx == SAO_BO)
+          {
+            bestClassTableBoMerge   = saoLcuParamNeighbor->bandPosition;
+            for(classIdx = saoLcuParamNeighbor->bandPosition+1; classIdx < saoLcuParamNeighbor->bandPosition+SAO_BO_LEN+1; classIdx++)
+            {
+              m_iOffset[yCbCr][typeIdx][classIdx] = merge_iOffset[classIdx];
+            }
+          }
+          else  
+          {
+            for(classIdx=1; classIdx < m_iNumClass[typeIdx]+1; classIdx++)
+            {
+              m_iOffset[yCbCr][typeIdx][classIdx] = merge_iOffset[classIdx];
+            }
+          }
+          saoLcuParam->mergeUpFlag   = idxNeighbor;
+          saoLcuParam->mergeLeftFlag = !idxNeighbor;
+        }
+      }
+    }
+  } 
+
+  saoLcuParam->typeIdx  = m_iTypePartBest[yCbCr];
+  if (saoLcuParam->typeIdx != -1)
+  {
+    saoLcuParam->length = m_iNumClass[saoLcuParam->typeIdx];
+    Int minIndex = 0;
+    if( saoLcuParam->typeIdx == SAO_BO )
+    {
+      if ((saoLcuParam->mergeUpFlag )||(saoLcuParam->mergeLeftFlag)) 
+      {
+        saoLcuParam->bandPosition = bestClassTableBoMerge;
+      }
+      else
+      {
+        saoLcuParam->bandPosition = bestClassTableBo;
+      }
+      minIndex = saoLcuParam->bandPosition;
+    }
+    for (Int i=0; i< saoLcuParam->length ; i++)
+    {
+      saoLcuParam->offset[i] = (Int) m_iOffset[yCbCr][saoLcuParam->typeIdx][minIndex+i+1];
+    }
+  }
+  else
+  {
+    saoLcuParam->length = 0;
+  }
+
+  if (addrUp>=0)
+  {
+    if (saoLcuParam->typeIdx == -1 && saoParam->saoLcuParam[yCbCr][addrUp].typeIdx == -1)
+    {
+      saoLcuParam->mergeUpFlag   = 1;
+      saoLcuParam->mergeLeftFlag = 0;
+    }
+  }
+  if (addrLeft>=0)
+  {
+    if (saoLcuParam->typeIdx == -1 && saoParam->saoLcuParam[yCbCr][addrLeft].typeIdx == -1)
+    {
+      saoLcuParam->mergeUpFlag   = 0;
+      saoLcuParam->mergeLeftFlag = 1;
+    }
+  }
+
+}
+
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 341)
@@ -0,0 +1,113 @@
+/* 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-2012, 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     TEncAdaptiveLoopFilter.h
+ \brief    estimation part of sample adaptive offset class (header)
+ */
+
+#ifndef __TENCSAMPLEADAPTIVEOFFSET__
+#define __TENCSAMPLEADAPTIVEOFFSET__
+
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComPic.h"
+
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TLibCommon/TComBitCounter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+private:
+  Double            m_dLambdaLuma;
+  Double            m_dLambdaChroma;
+
+  TEncEntropy*      m_pcEntropyCoder;
+  TEncSbac***       m_pppcRDSbacCoder;              ///< for CABAC
+  TEncSbac*         m_pcRDGoOnSbacCoder;
+#if FAST_BIT_EST
+  TEncBinCABACCounter*** m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+#else
+  TEncBinCABAC***   m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+#endif
+  
+  Int64  ***m_iCount;      //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  ***m_iOffset;     //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  ***m_iOffsetOrg;  //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Int64  **m_iRate;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Int64  **m_iDist;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Double **m_dCost;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Double *m_dCostPartBest; //[MAX_NUM_SAO_PART]; 
+  Int64  *m_iDistOrg;      //[MAX_NUM_SAO_PART]; 
+  Int    *m_iTypePartBest; //[MAX_NUM_SAO_PART]; 
+  Int     m_iOffsetTh;
+  Bool    m_bUseSBACRD;
+
+public:
+  TEncSampleAdaptiveOffset         ();
+  virtual ~TEncSampleAdaptiveOffset();
+
+  Void startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder);
+  Void endSaoEnc();
+  Void resetStats();
+#if SAO_CHROMA_LAMBDA
+  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma);
+#else
+  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda);
+#endif
+  Void runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda);
+  Void rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda);
+  Void disablePartTree(SAOQTPart *psQTPart, Int iPartIdx);
+  Void getSaoStats(SAOQTPart *psQTPart, Int iYCbCr);
+  Void calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr);
+  Void calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail);
+  Void calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);
+  Void destroyEncBuffer();
+  Void createEncBuffer();
+  Void assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr);
+  Void checkMerge(SaoLcuParam * lcuParamCurr,SaoLcuParam * lcuParamCheck, Int dir);
+  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma);
+  Void rdoSaoUnit(SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda);
+  Void setMaxNumOffsetsPerPic(Int iVal) {m_maxNumOffsetsPerPic = iVal; }
+  Int  getMaxNumOffsetsPerPic() {return m_maxNumOffsetsPerPic; }
+};
+
+//! \}
+
+#endif
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 341)
@@ -0,0 +1,2479 @@
+/* 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-2012, 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     TEncSbac.cpp
+    \brief    SBAC encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSbac.h"
+
+#include <map>
+#include <algorithm>
+
+#if RWTH_SDC_DLT_B0036
+#define GetNumDepthValues()     (pcCU->getSlice()->getSPS()->getNumDepthValues())
+#define GetBitsPerDepthValue()  (pcCU->getSlice()->getSPS()->getBitsPerDepthValue())
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSbac::TEncSbac()
+// new structure here
+: m_pcBitIf                   ( NULL )
+, m_pcSlice                   ( NULL )
+, m_pcBinIf                   ( NULL )
+, m_bAlfCtrl                  ( false )
+, m_uiCoeffCost               ( 0 )
+, m_uiMaxAlfCtrlDepth         ( 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)
+#if LGE_ILLUCOMP_B0045
+, m_cCUICFlagSCModel          ( 1,             1,               NUM_IC_FLAG_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 H3D_IVRP
+, m_cResPredFlagSCModel       ( 1,             1,               NUM_RES_PRED_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_cCUAlfCtrlFlagSCModel     ( 1,             1,               NUM_ALF_CTRL_FLAG_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_cALFFlagSCModel           ( 1,             1,               NUM_ALF_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFUvlcSCModel           ( 1,             1,               NUM_ALF_UVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cALFSvlcSCModel           ( 1,             1,               NUM_ALF_SVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoFlagSCModel           ( 1,             1,               NUM_SAO_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoUvlcSCModel           ( 1,             1,               NUM_SAO_UVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoSvlcSCModel           ( 1,             1,               NUM_SAO_SVLC_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeLeftSCModel      ( 1,             1,               NUM_SAO_MERGE_LEFT_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeUpSCModel        ( 1,             1,               NUM_SAO_MERGE_UP_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+, m_cDmmFlagSCModel           ( 1,             1,               NUM_DMM_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDmmModeSCModel           ( 1,             1,               NUM_DMM_MODE_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDmmDataSCModel           ( 1,             1,               NUM_DMM_DATA_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if LGE_EDGE_INTRA_A0070
+, m_cEdgeIntraSCModel         ( 1,             1,               NUM_EDGE_INTRA_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+#if LGE_EDGE_INTRA_DELTA_DC
+, m_cEdgeIntraDeltaDCSCModel  ( 1,             1,               NUM_EDGE_INTRA_DELTA_DC_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#endif
+#if RWTH_SDC_DLT_B0036
+, m_cSDCFlagSCModel             ( 1,             1,                 SDC_NUM_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCResidualFlagSCModel     ( 1,             2,  SDC_NUM_RESIDUAL_FLAG_CTX  , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCResidualSignFlagSCModel ( 1,             2,  SDC_NUM_SIGN_FLAG_CTX      , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCResidualSCModel         ( 1,             2,  SDC_NUM_RESIDUAL_CTX       , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCPredModeSCModel             ( 1,             3,                 SDC_NUM_PRED_MODE_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+{
+  assert( m_numContextModels <= MAX_NUM_CTX_MOD );
+  m_iSliceGranularity = 0;
+}
+
+TEncSbac::~TEncSbac()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncSbac::resetEntropy           ()
+{
+  Int  iQp              = m_pcSlice->getSliceQp();
+  SliceType eSliceType  = m_pcSlice->getSliceType();
+  
+#if CABAC_INIT_FLAG
+  Int  encCABACTableIdx = m_pcSlice->getPPS()->getEncCABACTableIdx();
+  if (!m_pcSlice->isIntra() && (encCABACTableIdx==B_SLICE || encCABACTableIdx==P_SLICE) && m_pcSlice->getPPS()->getCabacInitPresentFlag())
+  {
+    eSliceType = (SliceType) encCABACTableIdx;
+  }
+#endif
+
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+#if LGE_ILLUCOMP_B0045
+  m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_ALF_CTRL_FLAG );
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
+#if H3D_IVRP
+  m_cResPredFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_RES_PRED_FLAG );
+#endif
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  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_cALFFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_SVLC );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cSaoFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_FLAG );
+  m_cSaoUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_UVLC );
+  m_cSaoSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_SVLC );
+  m_cSaoMergeLeftSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+  m_cSaoMergeUpSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  m_cDmmFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_FLAG );
+  m_cDmmModeSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_MODE );
+  m_cDmmDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_DATA );
+#endif
+#if LGE_EDGE_INTRA_A0070
+  m_cEdgeIntraSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_EDGE_INTRA );
+#if LGE_EDGE_INTRA_DELTA_DC
+  m_cEdgeIntraDeltaDCSCModel.initBuffer  ( eSliceType, iQp, (UChar*)INIT_EDGE_INTRA_DELTA_DC );
+#endif
+#endif
+#if RWTH_SDC_DLT_B0036
+  m_cSDCFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
+  m_cSDCResidualFlagSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
+  m_cSDCResidualSignFlagSCModel.initBuffer  ( eSliceType, iQp, (UChar*)INIT_SDC_SIGN_FLAG );
+  m_cSDCPredModeSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_PRED_MODE );
+#endif
+
+  // new structure
+  m_uiLastQp = iQp;
+  
+  m_pcBinIf->start();
+  
+  return;
+}
+
+#if CABAC_INIT_FLAG
+/** 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 LGE_ILLUCOMP_B0045
+      curCost += m_cCUICFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_IC_FLAG );
+#endif
+      curCost += m_cCUAlfCtrlFlagSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_ALF_CTRL_FLAG );
+      curCost += m_cCUMergeFlagExtSCModel.calcCost    ( curSliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT);
+      curCost += m_cCUMergeIdxExtSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT);
+#if H3D_IVRP
+      curCost += m_cResPredFlagSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_RES_PRED_FLAG);
+#endif
+      curCost += m_cCUPartSizeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
+      curCost += m_cCUAMPSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CU_AMP_POS );
+      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_cALFFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_ALF_FLAG );
+      curCost += m_cALFUvlcSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_ALF_UVLC );
+      curCost += m_cALFSvlcSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_ALF_SVLC );
+      curCost += m_cCUTransSubdivFlagSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+      curCost += m_cSaoFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_SAO_FLAG );
+      curCost += m_cSaoUvlcSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_SAO_UVLC );
+      curCost += m_cSaoSvlcSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_SAO_SVLC );
+      curCost += m_cSaoMergeLeftSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+      curCost += m_cSaoMergeUpSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+      curCost += m_cSaoTypeIdxSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+
+      if (curCost < bestCost)
+      {
+        bestSliceType = curSliceType;
+        bestCost      = curCost;
+      }
+    }
+    m_pcSlice->getPPS()->setEncCABACTableIdx( bestSliceType );
+  }
+  else
+  {
+    m_pcSlice->getPPS()->setEncCABACTableIdx( I_SLICE );
+  }  
+
+  #if CABAC_INIT_FLAG && FIX_POZNAN_CABAC_INIT_FLAG
+    m_pcSlice->getPPS()->setEncPrevPOC( m_pcSlice->getPOC() );
+  #endif
+}
+#endif
+
+
+/** 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 LGE_ILLUCOMP_B0045
+  m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_ALF_CTRL_FLAG );
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
+#if H3D_IVRP
+  m_cResPredFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_RES_PRED_FLAG );
+#endif
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  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_cALFFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_ALF_SVLC );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cSaoFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_FLAG );
+  m_cSaoUvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_UVLC );
+  m_cSaoSvlcSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_SAO_SVLC );
+  m_cSaoMergeLeftSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_LEFT_FLAG );
+  m_cSaoMergeUpSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_UP_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  m_cDmmFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_FLAG );
+  m_cDmmModeSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_MODE );
+  m_cDmmDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DMM_DATA );
+#endif
+#if RWTH_SDC_DLT_B0036
+  m_cSDCFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
+  m_cSDCResidualFlagSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
+  m_cSDCResidualSignFlagSCModel.initBuffer  ( eSliceType, iQp, (UChar*)INIT_SDC_SIGN_FLAG );
+  m_cSDCPredModeSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_PRED_MODE );
+#endif
+  
+  m_pcBinIf->start();
+}
+
+Void TEncSbac::writeTileMarker( UInt uiTileIdx, UInt uiBitsUsed )
+{
+  for (Int iShift=uiBitsUsed-1; iShift>=0; iShift--)
+  {
+    m_pcBinIf->encodeBinEP ( (uiTileIdx & (1 << iShift)) >> iShift );
+  }
+}
+
+void TEncSbac::codeSEI(const SEI&)
+{
+  assert(0);
+}
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+Void TEncSbac::codeVPS( TComVPS* pcVPS )
+{
+  assert (0);
+  return;
+}
+#endif
+
+#if HHI_MPI || H3D_QTL 
+Void TEncSbac::codeSPS( TComSPS* pcSPS, Bool bIsDepth )
+#else
+Void TEncSbac::codeSPS( TComSPS* pcSPS )
+#endif
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codePPS( TComPPS* pcPPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeSliceHeader( TComSlice* pcSlice )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeTerminatingBit( UInt uilsLast )
+{
+  m_pcBinIf->encodeBinTrm( uilsLast );
+}
+
+Void TEncSbac::codeSliceFinish()
+{
+  m_pcBinIf->finish();
+}
+
+Void TEncSbac::codeFlush()
+{
+  m_pcBinIf->flush();
+}
+
+Void TEncSbac::encodeStart()
+{
+  m_pcBinIf->start();
+}
+
+Void TEncSbac::xWriteUnarySymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset )
+{
+  m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[0] );
+  
+  if( 0 == uiSymbol)
+  {
+    return;
+  }
+  
+  while( uiSymbol-- )
+  {
+    m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ iOffset ] );
+  }
+  
+  return;
+}
+
+Void TEncSbac::xWriteUnaryMaxSymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    return;
+  }
+  
+  m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ 0 ] );
+  
+  if ( uiSymbol == 0 )
+  {
+    return;
+  }
+  
+  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
+  
+  while( --uiSymbol )
+  {
+    m_pcBinIf->encodeBin( 1, pcSCModel[ iOffset ] );
+  }
+  if( bCodeLast )
+  {
+    m_pcBinIf->encodeBin( 0, pcSCModel[ iOffset ] );
+  }
+  
+  return;
+}
+
+Void TEncSbac::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
+{
+  UInt bins = 0;
+  Int numBins = 0;
+  
+  while( uiSymbol >= (UInt)(1<<uiCount) )
+  {
+    bins = 2 * bins + 1;
+    numBins++;
+    uiSymbol -= 1 << uiCount;
+    uiCount  ++;
+  }
+  bins = 2 * bins + 0;
+  numBins++;
+  
+  bins = (bins << uiCount) | uiSymbol;
+  numBins += uiCount;
+  
+  assert( numBins <= 32 );
+  m_pcBinIf->encodeBinsEP( bins, numBins );
+}
+
+/** Coding of coeff_abs_level_minus3
+ * \param uiSymbol value of coeff_abs_level_minus3
+ * \param ruiGoRiceParam reference to Rice parameter
+ * \returns Void
+ */
+Void TEncSbac::xWriteGoRiceExGolomb( UInt uiSymbol, UInt &ruiGoRiceParam )
+{
+  UInt uiMaxVlc     = g_auiGoRiceRange[ ruiGoRiceParam ];
+  Bool bExGolomb    = ( uiSymbol > uiMaxVlc );
+  UInt uiCodeWord   = min<UInt>( uiSymbol, ( uiMaxVlc + 1 ) );
+  UInt uiQuotient   = uiCodeWord >> ruiGoRiceParam;
+  UInt uiMaxPreLen  = g_auiGoRicePrefixLen[ ruiGoRiceParam ];
+  
+  UInt binValues;
+  Int numBins;
+  
+  if ( uiQuotient >= uiMaxPreLen )
+  {
+    numBins = uiMaxPreLen;
+    binValues = ( 1 << numBins ) - 1;
+  }
+  else
+  {
+    numBins = uiQuotient + 1;
+    binValues = ( 1 << numBins ) - 2;
+  }
+  
+  m_pcBinIf->encodeBinsEP( ( binValues << ruiGoRiceParam ) + uiCodeWord - ( uiQuotient << ruiGoRiceParam ), numBins + ruiGoRiceParam );
+  
+  ruiGoRiceParam = g_aauiGoRiceUpdate[ ruiGoRiceParam ][ min<UInt>( uiSymbol, 23 ) ];
+  
+  if( bExGolomb )
+  {
+    uiSymbol -= uiMaxVlc + 1;
+    xWriteEpExGolomb( uiSymbol, 0 );
+  }
+}
+
+// SBAC RD
+Void  TEncSbac::load ( TEncSbac* pSrc)
+{
+  this->xCopyFrom(pSrc);
+}
+
+Void  TEncSbac::loadIntraDirModeLuma( TEncSbac* pSrc)
+{
+  m_pcBinIf->copyState( pSrc->m_pcBinIf );
+  
+  this->m_cCUIntraPredSCModel      .copyFrom( &pSrc->m_cCUIntraPredSCModel       );
+}
+
+
+Void  TEncSbac::store( TEncSbac* pDest)
+{
+  pDest->xCopyFrom( this );
+}
+
+
+Void TEncSbac::xCopyFrom( 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 ) );
+}
+
+#if H3D_IVMP
+Void TEncSbac::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Int iNum )
+#else
+Void TEncSbac::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+#endif
+{
+  Int iSymbol = pcCU->getMVPIdx(eRefList, uiAbsPartIdx);
+#if H3D_IVMP
+#else
+  Int iNum = AMVP_MAX_NUM_CANDS;
+#endif
+
+  xWriteUnaryMaxSymbol(iSymbol, m_cMVPIdxSCModel.get(0), 1, iNum-1);
+}
+
+Void TEncSbac::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
+
+#if H3D_QTL
+  TComSPS *sps           = pcCU->getPic()->getSlice(0)->getSPS();
+  TComPic *pcTexture     = pcCU->getSlice()->getTexturePic();
+  Bool bDepthMapDetect   = (pcTexture != NULL);
+  Bool bIntraSliceDetect = (pcCU->getSlice()->getSliceType() == I_SLICE);
+ 
+  Bool rapPic     = (pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA);
+  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTLPC() && pcCU->getPic()->getReduceBitsFlag())
+  {
+    TComDataCU *pcTextureCU = pcTexture->getCU(pcCU->getAddr());
+    UInt uiCUIdx            = (pcCU->getZorderIdxInCU() == 0) ? uiAbsPartIdx : pcCU->getZorderIdxInCU();
+    assert(pcTextureCU->getDepth(uiCUIdx) >= uiDepth);
+    if (pcTextureCU->getDepth(uiCUIdx) == uiDepth && pcTextureCU->getPartitionSize( uiCUIdx ) != SIZE_NxN)
+    {
+      assert( eSize == SIZE_2Nx2N );
+      return;
+    }
+  }
+#endif
+
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      m_pcBinIf->encodeBin( eSize == SIZE_2Nx2N? 1 : 0, m_cCUPartSizeSCModel.get( 0, 0, 0 ) );
+    }
+    return;
+  }
+  
+  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()->getAMPAcc( uiDepth ) )
+      {
+        if (eSize == SIZE_2NxN)
+        {
+          m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 ));
+        }
+        else
+        {
+          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));          
+          m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
+        }
+      }
+      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 == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getSlice()->getSPS()->getDisInter4x4() && 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_cCUAMPSCModel.get( 0, 0, 0 ));
+        }
+        else
+        {
+          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
+        }
+      }
+      break;
+    }
+  case SIZE_NxN:
+    {
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getSlice()->getSPS()->getDisInter4x4() && 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);
+    }
+  }
+}
+
+/** code prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx  
+ * \returns Void
+ */
+Void TEncSbac::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if RWTH_SDC_DLT_B0036
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    assert( pcCU->isIntra(uiAbsPartIdx) );
+    return;
+  }
+#endif
+  
+  // get context function is here
+  Int iPredMode = pcCU->getPredictionMode( uiAbsPartIdx );
+  m_pcBinIf->encodeBin( iPredMode == MODE_INTER ? 0 : 1, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+}
+
+Void TEncSbac::codeAlfCtrlFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if (!m_bAlfCtrl)
+    return;
+  
+  if( pcCU->getDepth(uiAbsPartIdx) > m_uiMaxAlfCtrlDepth && !pcCU->isFirstAbsZorderIdxInDepth(uiAbsPartIdx, m_uiMaxAlfCtrlDepth))
+  {
+    return;
+  }
+  
+  const UInt uiSymbol = pcCU->getAlfCtrlFlag( uiAbsPartIdx ) ? 1 : 0;
+  m_pcBinIf->encodeBin( uiSymbol, *m_cCUAlfCtrlFlagSCModel.get( 0 ) );
+}
+
+Void TEncSbac::codeAlfCtrlDepth()
+{
+  if (!m_bAlfCtrl)
+    return;
+  
+  UInt uiDepth = m_uiMaxAlfCtrlDepth;
+  xWriteUnaryMaxSymbol(uiDepth, m_cALFUvlcSCModel.get(0), 1, g_uiMaxCUDepth-1);
+}
+
+/** code skip flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  UInt uiSymbol = pcCU->isSkipped( uiAbsPartIdx ) ? 1 : 0;
+  UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx ) ;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tSkipFlag" );
+  DTRACE_CABAC_T( "\tuiCtxSkip: ");
+  DTRACE_CABAC_V( uiCtxSkip );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+}
+
+#if LGE_ILLUCOMP_B0045
+/** code Illumination Compensation flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  UInt uiSymbol = pcCU->getICFlag( uiAbsPartIdx ) ? 1 : 0;
+  UInt uiCtxIC  = pcCU->getCtxICFlag( uiAbsPartIdx ) ;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUICFlagSCModel.get( 0, 0, uiCtxIC ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tICFlag" );
+  DTRACE_CABAC_T( "\tuiCtxIC: ");
+  DTRACE_CABAC_V( uiCtxIC );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+}
+#endif
+
+/** code merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  const UInt uiSymbol = pcCU->getMergeFlag( uiAbsPartIdx ) ? 1 : 0;
+  m_pcBinIf->encodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tMergeFlag: " );
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\tAddress: " );
+  DTRACE_CABAC_V( pcCU->getAddr() );
+  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
+  DTRACE_CABAC_V( uiAbsPartIdx );
+  DTRACE_CABAC_T( "\n" );
+}
+
+/** code merge index
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiNumCand = MRG_MAX_NUM_CANDS;
+  UInt uiUnaryIdx = pcCU->getMergeIndex( uiAbsPartIdx );
+  uiNumCand = pcCU->getSlice()->getMaxNumMergeCand();
+#if HHI_MPI
+  const Bool bMVIAvailable = pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE;
+  if( bMVIAvailable )
+  {
+    const Bool bUseMVI = pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1;
+    if( bUseMVI )
+    {
+      uiUnaryIdx = (UInt)HHI_MPI_MERGE_POS;
+    }
+    else if( (Int)uiUnaryIdx >= (Int)HHI_MPI_MERGE_POS )
+    {
+      uiUnaryIdx++;
+    }
+  }
+#endif
+  if ( uiNumCand > 1 )
+  {
+    for( UInt ui = 0; ui < uiNumCand - 1; ++ui )
+    {
+      const UInt uiSymbol = ui == uiUnaryIdx ? 0 : 1;
+      if ( ui==0 )
+      {
+        m_pcBinIf->encodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) );
+      }
+      else
+      {
+        m_pcBinIf->encodeBinEP( uiSymbol );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+  }
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tparseMergeIndex()" );
+  DTRACE_CABAC_T( "\tuiMRGIdx= " );
+  DTRACE_CABAC_V( pcCU->getMergeIndex( uiAbsPartIdx ) );
+  DTRACE_CABAC_T( "\n" );
+}
+
+#if H3D_IVRP
+Void
+TEncSbac::codeResPredFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt  uiCtx     = pcCU->getCtxResPredFlag( uiAbsPartIdx );
+  UInt  uiSymbol  = ( pcCU->getResPredFlag( uiAbsPartIdx ) ? 1 : 0 );
+  m_pcBinIf->encodeBin( uiSymbol, m_cResPredFlagSCModel.get( 0, 0, uiCtx ) );
+}
+#endif
+
+Void TEncSbac::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    return;
+  
+  UInt uiCtx           = pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth );
+  UInt uiCurrSplitFlag = ( pcCU->getDepth( uiAbsPartIdx ) > uiDepth ) ? 1 : 0;
+  
+  assert( uiCtx < 3 );
+
+#if H3D_QTL
+  Bool bCodeSplitFlag    = true;
+
+  TComSPS *sps           = pcCU->getPic()->getSlice(0)->getSPS();
+  TComPic *pcTexture     = pcCU->getSlice()->getTexturePic();
+  Bool bDepthMapDetect   = (pcTexture != NULL);
+  Bool bIntraSliceDetect = (pcCU->getSlice()->getSliceType() == I_SLICE);
+
+  Bool rapPic     = (pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA);
+  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTLPC() && pcCU->getPic()->getReduceBitsFlag())
+  {
+    TComDataCU *pcTextureCU = pcTexture->getCU(pcCU->getAddr());
+    UInt uiCUIdx            = (pcCU->getZorderIdxInCU() == 0) ? uiAbsPartIdx : pcCU->getZorderIdxInCU();
+    assert(pcTextureCU->getDepth(uiCUIdx) >= uiDepth);
+    bCodeSplitFlag          = (pcTextureCU->getDepth(uiCUIdx) > uiDepth);
+  }
+
+  if(!bCodeSplitFlag)
+  {
+    assert(uiCurrSplitFlag == 0);
+    return;
+  }
+#endif
+
+  m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tSplitFlag\n" )
+  return;
+}
+
+Void TEncSbac::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiSymbol )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\n" )
+}
+
+#if LGE_EDGE_INTRA_A0070
+Void TEncSbac::xCodeEdgeIntraInfo( TComDataCU* pcCU, UInt uiPartIdx )
+{
+  UInt   uiDepth        = pcCU->getDepth( uiPartIdx ) + (pcCU->getPartitionSize( uiPartIdx ) == SIZE_NxN ? 1 : 0);
+  UInt   uiCtxEdgeIntra = pcCU->getCtxEdgeIntra( uiPartIdx );
+  UChar* pucSymbolList  = pcCU->getEdgeCode( uiPartIdx );
+  UChar  ucEdgeNumber   = pcCU->getEdgeNumber( uiPartIdx );
+  Bool   bLeft          = pcCU->getEdgeLeftFirst( uiPartIdx );
+  UChar  ucStart        = pcCU->getEdgeStartPos( uiPartIdx );
+  UInt   uiSymbol;
+
+  // 1. Top(0) or Left(1)
+  uiSymbol = (bLeft == false) ? 0 : 1;
+  m_pcBinIf->encodeBinEP( uiSymbol );
+
+  // 2. Start position (lowest bit first)
+  uiSymbol = ucStart;
+  for( UInt ui = 6; ui > uiDepth; ui-- ) // 64(0)->6, 32(1)->5, 16(2)->4, 8(3)->3, 4(4)->2
+  {
+    m_pcBinIf->encodeBinEP( uiSymbol & 0x1 );
+    uiSymbol >>= 1;
+  }
+
+  // 3. Number of edges
+  uiSymbol = ucEdgeNumber > 0 ? ucEdgeNumber - 1 : 0;
+  for( UInt ui = 7; ui > uiDepth; ui-- ) // 64(0)->7, 32(1)->6, 16(2)->5, 8(3)->4, 4(4)->3
+  {
+    m_pcBinIf->encodeBinEP( uiSymbol & 0x1 );
+    uiSymbol >>= 1;
+  }
+
+  if(uiSymbol != 0)
+  {
+    printf(" ucEdgeNumber %d at depth %d\n",ucEdgeNumber, uiDepth);
+    assert(false);
+  }
+
+  // 4. Edges
+  for( Int iPtr2 = 0; iPtr2 < ucEdgeNumber; iPtr2++ )
+  {
+    UInt uiReorderSymbol = pucSymbolList[iPtr2];
+
+    //printf ("Ptr = %d, Symbol = %d\n", iPtr2, uiSymbol);
+
+    // Left-friendly direction (Top start)
+    // 0 (   0deg) => 0
+    // 1 (  45deg) => 10
+    // 2 ( -45deg) => 110
+    // 3 (  90deg) => 1110
+    // 4 ( -90deg) => 11110
+    // 5 ( 135deg) => 111110
+    // 6 (-135deg) => 111111
+    // Right-friendly direction (Left start)
+    // 0 (   0deg) => 0
+    // 2 ( -45deg) => 10
+    // 1 (  45deg) => 110
+    // 4 ( -90deg) => 1110
+    // 3 (  90deg) => 11110
+    // 6 (-135deg) => 111110
+    // 5 ( 135deg) => 111111
+
+    // refer to a paper "An efficient chain code with Huffman coding"
+
+    for( UInt ui = 0; ui < uiReorderSymbol; ui++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cEdgeIntraSCModel.get( 0, 0, uiCtxEdgeIntra ) );
+    }
+
+    if( uiReorderSymbol != 6 )
+      m_pcBinIf->encodeBin( 0, m_cEdgeIntraSCModel.get( 0, 0, uiCtxEdgeIntra ) );
+  }
+}
+#endif
+
+Void TEncSbac::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiDir         = pcCU->getLumaIntraDir( uiAbsPartIdx );
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( pcCU->getSlice()->getSPS()->getUseDMM() && pcCU->getWidth( uiAbsPartIdx ) <= DMM_WEDGEMODEL_MAX_SIZE )
+  {
+#if LGE_EDGE_INTRA_A0070
+    m_pcBinIf->encodeBin( uiDir >= NUM_INTRA_MODE && uiDir < EDGE_INTRA_IDX, m_cDmmFlagSCModel.get(0, 0, 0) );
+#else
+    m_pcBinIf->encodeBin( uiDir >= NUM_INTRA_MODE, m_cDmmFlagSCModel.get(0, 0, 0) );
+#endif
+  }
+#if LGE_EDGE_INTRA_A0070
+  if( uiDir >= NUM_INTRA_MODE && uiDir < EDGE_INTRA_IDX )
+#else
+  if( uiDir >= NUM_INTRA_MODE )
+#endif
+  {
+    assert( pcCU->getWidth( uiAbsPartIdx ) <= DMM_WEDGEMODEL_MAX_SIZE );
+    UInt uiDMMode = uiDir - NUM_INTRA_MODE;
+
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+    m_pcBinIf->encodeBin( (uiDMMode & 0x01),      m_cDmmModeSCModel.get(0, 0, 0) );
+    m_pcBinIf->encodeBin( (uiDMMode & 0x02) >> 1, m_cDmmModeSCModel.get(0, 0, 0) );
+
+    if( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && pcCU->getWidth( uiAbsPartIdx ) > 4 )
+    {
+      m_pcBinIf->encodeBin( (uiDMMode & 0x04) >> 2, m_cDmmModeSCModel.get(0, 0, 0) );
+    }
+#else
+    m_pcBinIf->encodeBin( (uiDMMode & 0x01),      m_cDmmModeSCModel.get(0, 0, 0) );
+
+    if( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && pcCU->getWidth( uiAbsPartIdx ) > 4 )
+    {
+      m_pcBinIf->encodeBin( (uiDMMode & 0x02) >> 1, m_cDmmModeSCModel.get(0, 0, 0) );
+    }
+#endif
+#if HHI_DMM_WEDGE_INTRA
+    if( uiDir == DMM_WEDGE_FULL_IDX )          { xCodeWedgeFullInfo          ( pcCU, uiAbsPartIdx ); }
+    if( uiDir == DMM_WEDGE_FULL_D_IDX )        { xCodeWedgeFullDeltaInfo     ( pcCU, uiAbsPartIdx ); }
+    if( uiDir == DMM_WEDGE_PREDDIR_IDX )       { xCodeWedgePredDirInfo       ( pcCU, uiAbsPartIdx ); }
+    if( uiDir == DMM_WEDGE_PREDDIR_D_IDX )     { xCodeWedgePredDirDeltaInfo  ( pcCU, uiAbsPartIdx ); }
+#endif
+#if HHI_DMM_PRED_TEX
+
+#if FLEX_CODING_ORDER_M23723
+    if ( !pcCU->getSlice()->getSPS()->getUseDMM34() )
+    {
+      assert( uiDir != DMM_WEDGE_PREDTEX_D_IDX );
+      assert( uiDir != DMM_CONTOUR_PREDTEX_D_IDX );
+    }
+#endif
+
+    if( uiDir == DMM_WEDGE_PREDTEX_D_IDX )     { xCodeWedgePredTexDeltaInfo  ( pcCU, uiAbsPartIdx ); }
+#if LGE_DMM3_SIMP_C0044
+    if( uiDir == DMM_WEDGE_PREDTEX_IDX )       { xCodeWedgePredTexInfo       ( pcCU, uiAbsPartIdx ); }
+#endif
+    if( uiDir == DMM_CONTOUR_PREDTEX_D_IDX )   { xCodeContourPredTexDeltaInfo( pcCU, uiAbsPartIdx ); }
+#endif
+  }
+  else
+#if LGE_EDGE_INTRA_A0070
+    if ( uiDir >= EDGE_INTRA_IDX)
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+      m_pcBinIf->encodeBinsEP( 63, 6 );
+      xCodeEdgeIntraInfo( pcCU, uiAbsPartIdx );
+#if LGE_EDGE_INTRA_DELTA_DC
+      m_pcBinIf->encodeBin( (uiDir == EDGE_INTRA_DELTA_IDX), m_cEdgeIntraDeltaDCSCModel.get(0, 0, 0) );
+      if( uiDir == EDGE_INTRA_DELTA_IDX )
+      {
+        Int iDeltaDC0 = pcCU->getEdgeDeltaDC0( uiAbsPartIdx );
+        Int iDeltaDC1 = pcCU->getEdgeDeltaDC1( uiAbsPartIdx );
+
+        xWriteExGolombLevel( UInt( abs( iDeltaDC0 ) ), m_cEdgeIntraDeltaDCSCModel.get(0, 0, 1) );
+        if ( iDeltaDC0 != 0 )
+        {
+          UInt uiSign = iDeltaDC0 > 0 ? 0 : 1;
+          m_pcBinIf->encodeBinEP( uiSign );
+        }
+        xWriteExGolombLevel( UInt( abs( iDeltaDC1 ) ), m_cEdgeIntraDeltaDCSCModel.get(0, 0, 1) );
+        if ( iDeltaDC1 != 0 )
+        {
+          UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+          m_pcBinIf->encodeBinEP( uiSign );
+        }
+      }
+#endif
+    }
+    else
+#endif // LGE_EDGE_INTRA
+  {
+#endif
+#if LGE_EDGE_INTRA_A0070
+  Bool bCodeEdgeIntra = false;
+  if( pcCU->getSlice()->getSPS()->isDepth() )
+  {
+    UInt uiPUWidth = pcCU->getWidth( uiAbsPartIdx ) >> (pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN ? 1 : 0);
+    if( uiPUWidth <= LGE_EDGE_INTRA_MAX_SIZE && uiPUWidth >= LGE_EDGE_INTRA_MIN_SIZE )
+      bCodeEdgeIntra = true;
+  }
+#endif
+  
+  Int uiPreds[3] = {-1, -1, -1};
+  Int uiPredNum = pcCU->getIntraDirLumaPredictor(uiAbsPartIdx, uiPreds);  
+
+  Int uiPredIdx = -1;
+
+  for(UInt i = 0; i < uiPredNum; i++)
+  {
+    if(uiDir == uiPreds[i])
+    {
+      uiPredIdx = i;
+    }
+  }
+ 
+  if(uiPredIdx != -1)
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+    m_pcBinIf->encodeBinEP( uiPredIdx ? 1 : 0 );
+    if (uiPredIdx)
+    {
+      m_pcBinIf->encodeBinEP( uiPredIdx-1 );
+    }
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+  
+    if (uiPreds[0] > uiPreds[1])
+    { 
+      std::swap(uiPreds[0], uiPreds[1]); 
+    }
+    if (uiPreds[0] > uiPreds[2])
+    {
+      std::swap(uiPreds[0], uiPreds[2]);
+    }
+    if (uiPreds[1] > uiPreds[2])
+    {
+      std::swap(uiPreds[1], uiPreds[2]);
+    }
+
+    for(Int i = (uiPredNum - 1); i >= 0; i--)
+    {
+      uiDir = uiDir > uiPreds[i] ? uiDir - 1 : uiDir;
+    }
+
+    m_pcBinIf->encodeBinsEP( uiDir, 5 );
+#if LGE_EDGE_INTRA_A0070
+  if (bCodeEdgeIntra)
+    if (uiDir == 31) m_pcBinIf->encodeBinsEP(0,1);
+#endif
+   }
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  }
+#endif
+  return;
+}
+
+Void TEncSbac::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiIntraDirChroma = pcCU->getChromaIntraDir( uiAbsPartIdx );
+
+  if( uiIntraDirChroma == DM_CHROMA_IDX ) 
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+  } 
+  else if( uiIntraDirChroma == LM_CHROMA_IDX )
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 1 ) );
+  }
+  else
+  { 
+    UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
+    pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
+
+    for( Int i = 0; i < NUM_CHROMA_MODE - 2; i++ )
+    {
+      if( uiIntraDirChroma == uiAllowedChromaDir[i] )
+      {
+        uiIntraDirChroma = i;
+        break;
+      }
+    }
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+
+    if (pcCU->getSlice()->getSPS()->getUseLMChroma())
+    {
+      m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 1 ));
+    }
+    m_pcBinIf->encodeBinsEP( uiIntraDirChroma, 2 );
+  }
+  return;
+}
+
+Void TEncSbac::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  const UInt uiInterDir = pcCU->getInterDir( uiAbsPartIdx ) - 1;
+  const UInt uiCtx      = pcCU->getCtxInterDir( uiAbsPartIdx );
+  ContextModel *pCtx    = m_cCUInterDirSCModel.get( 0 );
+  m_pcBinIf->encodeBin( uiInterDir == 2 ? 1 : 0, *( pCtx + uiCtx ) );
+
+  return;
+}
+
+Void TEncSbac::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getInterDir( uiAbsPartIdx ) != 3)
+  {
+    Int iRefFrame = pcCU->getSlice()->getRefIdxOfLC(eRefList, pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx ));
+
+    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+    m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), *pCtx );
+
+    if( iRefFrame > 0 )
+    {
+      xWriteUnaryMaxSymbol( iRefFrame - 1, pCtx + 1, 1, pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C )-2 );
+    }
+#if MERL_VSP_C0152
+    else if (iRefFrame < 0) // NOT_VALID
+    {
+      assert(0);
+    }
+#endif
+  }
+  else
+  {
+    Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
+    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+    m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), *pCtx );
+    
+    if( iRefFrame > 0 )
+    {
+      xWriteUnaryMaxSymbol( iRefFrame - 1, pCtx + 1, 1, pcCU->getSlice()->getNumRefIdx( eRefList )-2 );
+    }
+#if MERL_VSP_C0152
+    else if (iRefFrame < 0) // NOT_VALID
+    {
+      assert(0);
+    }
+#endif
+  }
+  return;
+}
+
+Void TEncSbac::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefList == REF_PIC_LIST_1 && pcCU->getInterDir(uiAbsPartIdx)==3)
+  {
+    return;
+  }
+
+  const TComCUMvField* pcCUMvField = pcCU->getCUMvField( eRefList );
+  const Int iHor = pcCUMvField->getMvd( uiAbsPartIdx ).getHor();
+  const Int iVer = pcCUMvField->getMvd( uiAbsPartIdx ).getVer();
+  ContextModel* pCtx = m_cCUMvdSCModel.get( 0 );
+
+  m_pcBinIf->encodeBin( iHor != 0 ? 1 : 0, *pCtx );
+  m_pcBinIf->encodeBin( iVer != 0 ? 1 : 0, *pCtx );
+
+  const Bool bHorAbsGr0 = iHor != 0;
+  const Bool bVerAbsGr0 = iVer != 0;
+  const UInt uiHorAbs   = 0 > iHor ? -iHor : iHor;
+  const UInt uiVerAbs   = 0 > iVer ? -iVer : iVer;
+  pCtx++;
+
+  if( bHorAbsGr0 )
+  {
+    m_pcBinIf->encodeBin( uiHorAbs > 1 ? 1 : 0, *pCtx );
+  }
+
+  if( bVerAbsGr0 )
+  {
+    m_pcBinIf->encodeBin( uiVerAbs > 1 ? 1 : 0, *pCtx );
+  }
+
+  if( bHorAbsGr0 )
+  {
+    if( uiHorAbs > 1 )
+    {
+      xWriteEpExGolomb( uiHorAbs-2, 1 );
+    }
+
+    m_pcBinIf->encodeBinEP( 0 > iHor ? 1 : 0 );
+  }
+
+  if( bVerAbsGr0 )
+  {
+    if( uiVerAbs > 1 )
+    {
+      xWriteEpExGolomb( uiVerAbs-2, 1 );
+    }
+
+    m_pcBinIf->encodeBinEP( 0 > iVer ? 1 : 0 );
+  }
+  
+  return;
+}
+
+Void TEncSbac::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
+  
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
+
+  if ( iDQp == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUDeltaQpSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUDeltaQpSCModel.get( 0, 0, 0 ) );
+   
+    UInt uiSign = (iDQp > 0 ? 0 : 1);
+
+    m_pcBinIf->encodeBinEP(uiSign);
+
+    assert(iDQp >= -(26+(qpBdOffsetY/2)));
+    assert(iDQp <=  (25+(qpBdOffsetY/2)));
+
+    UInt uiMaxAbsDQpMinus1 = 24 + (qpBdOffsetY/2) + (uiSign);
+    UInt uiAbsDQpMinus1 = (UInt)((iDQp > 0)? iDQp  : (-iDQp)) - 1;
+    xWriteUnaryMaxSymbol( uiAbsDQpMinus1, &m_cCUDeltaQpSCModel.get( 0, 0, 1 ), 1, uiMaxAbsDQpMinus1);
+  }
+  
+  return;
+}
+
+Void TEncSbac::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  UInt uiCbf = pcCU->getCbf     ( uiAbsPartIdx, eType, uiTrDepth );
+  UInt uiCtx = pcCU->getCtxQtCbf( uiAbsPartIdx, eType, uiTrDepth );
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) );
+  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" )
+}
+
+/** Code I_PCM information. 
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param numIPCM the number of succesive IPCM blocks with the same size 
+ * \param firstIPCMFlag 
+ * \returns Void
+ */
+Void TEncSbac::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag)
+{
+  UInt uiIPCM = (pcCU->getIPCMFlag(uiAbsPartIdx) == true)? 1 : 0;
+
+  Bool writePCMSampleFlag = pcCU->getIPCMFlag(uiAbsPartIdx);
+
+  if( uiIPCM == 0 || firstIPCMFlag)
+  {
+    m_pcBinIf->encodeBinTrm (uiIPCM);
+
+    if ( firstIPCMFlag )
+    {
+      m_pcBinIf->encodeNumSubseqIPCM( numIPCM - 1 );
+      m_pcBinIf->encodePCMAlignBits();
+    }
+  }
+
+  if (writePCMSampleFlag)
+  {
+    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;
+    }
+
+    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 = piPCMSample[uiX];
+
+        m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
+      }
+      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;
+    }
+    numIPCM--;
+    if(numIPCM == 0)
+    {
+      m_pcBinIf->resetBac();
+    }
+  }
+}
+
+Void TEncSbac::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiCbf = pcCU->getQtRootCbf( uiAbsPartIdx );
+  UInt uiCtx = 0;
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtRootCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiCbf )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+}
+
+/** 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)
+ * 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 )
+{  
+  // swap
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosX, uiPosY );
+  }
+
+  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 ];
+
+  // posX
+  Int widthCtx = eTType? 4: width;
+  const UInt *puiCtxIdxX = g_uiLastCtx + ( g_aucConvertToBit[ widthCtx ] * ( g_aucConvertToBit[ widthCtx ] + 3 ) );
+  for( uiCtxLast = 0; uiCtxLast < uiGroupIdxX; uiCtxLast++ )
+  {
+    if (eTType)
+    {
+      m_pcBinIf->encodeBin( 1, *( pCtxX + (uiCtxLast>>g_aucConvertToBit[ width ]) ) );
+    }
+    else
+    {
+      m_pcBinIf->encodeBin( 1, *( pCtxX + puiCtxIdxX[ uiCtxLast ] ) );
+    }
+  }
+  if( uiGroupIdxX < g_uiGroupIdx[ width - 1 ])
+  {
+    if ( eTType )
+    {
+      m_pcBinIf->encodeBin( 0, *( pCtxX + (uiCtxLast>>g_aucConvertToBit[ width ]) ) );
+    }
+    else
+    {
+      m_pcBinIf->encodeBin( 0, *( pCtxX + puiCtxIdxX[ uiCtxLast ] ) );
+    }
+  }
+
+  // posY
+  Int heightCtx = eTType? 4: height;
+  const UInt *puiCtxIdxY = g_uiLastCtx + ( g_aucConvertToBit[ heightCtx ] * ( g_aucConvertToBit[ heightCtx ] + 3 ) );
+  for( uiCtxLast = 0; uiCtxLast < uiGroupIdxY; uiCtxLast++ )
+  {
+    if (eTType)
+    {
+      m_pcBinIf->encodeBin( 1, *( pCtxY + (uiCtxLast>>g_aucConvertToBit[ height ])));
+    }
+    else
+    {
+      m_pcBinIf->encodeBin( 1, *( pCtxY + puiCtxIdxY[ uiCtxLast ] ) );
+    }
+  }
+  if( uiGroupIdxY < g_uiGroupIdx[ height - 1 ])
+  {
+    if (eTType)
+    {
+      m_pcBinIf->encodeBin( 0, *( pCtxY + (uiCtxLast>>g_aucConvertToBit[ height ]) ) );
+    }
+    else
+    {
+      m_pcBinIf->encodeBin( 0, *( pCtxY + puiCtxIdxY[ uiCtxLast ] ) );
+    }
+    }
+  if ( uiGroupIdxX > 3 )
+  {      
+    UInt uiCount = ( uiGroupIdxX - 2 ) >> 1;
+    uiPosX       = uiPosX - g_uiMinInGroup[ uiGroupIdxX ];
+    for (Int i = uiCount - 1 ; i >= 0; i-- )
+    {
+      m_pcBinIf->encodeBinEP( ( uiPosX >> i ) & 1 );
+    }
+  }
+  if ( uiGroupIdxY > 3 )
+  {      
+    UInt uiCount = ( uiGroupIdxY - 2 ) >> 1;
+    uiPosY       = uiPosY - g_uiMinInGroup[ uiGroupIdxY ];
+    for ( Int i = uiCount - 1 ; i >= 0; i-- )
+    {
+      m_pcBinIf->encodeBinEP( ( uiPosY >> i ) & 1 );
+    }
+  }
+}
+
+Void TEncSbac::codeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\twidth=" )
+  DTRACE_CABAC_V( uiWidth )
+  DTRACE_CABAC_T( "\theight=" )
+  DTRACE_CABAC_V( uiHeight )
+  DTRACE_CABAC_T( "\tdepth=" )
+  DTRACE_CABAC_V( uiDepth )
+  DTRACE_CABAC_T( "\tabspartidx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\ttoCU-X=" )
+  DTRACE_CABAC_V( pcCU->getCUPelX() )
+  DTRACE_CABAC_T( "\ttoCU-Y=" )
+  DTRACE_CABAC_V( pcCU->getCUPelY() )
+  DTRACE_CABAC_T( "\tCU-addr=" )
+  DTRACE_CABAC_V(  pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tinCU-X=" )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tinCU-Y=" )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tpredmode=" )
+  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
+  DTRACE_CABAC_T( "\n" )
+
+  if( uiWidth > m_pcSlice->getSPS()->getMaxTrSize() )
+  {
+    uiWidth  = m_pcSlice->getSPS()->getMaxTrSize();
+    uiHeight = m_pcSlice->getSPS()->getMaxTrSize();
+  }
+  
+  UInt uiNumSig = 0;
+  
+  // compute number of significant coefficients
+  uiNumSig = TEncEntropy::countNonZeroCoeffs(pcCoef, uiWidth * uiHeight);
+  
+  if ( uiNumSig == 0 )
+    return;
+  
+  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : ( eTType == TEXT_NONE ? TEXT_NONE : TEXT_CHROMA );
+  
+  //----- encode significance map -----
+  const UInt   uiLog2BlockSize   = g_aucConvertToBit[ uiWidth ] + 2;
+  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+  if (uiScanIdx == SCAN_ZIGZAG)
+  {
+    // Map zigzag to diagonal scan
+    uiScanIdx = SCAN_DIAG;
+  }
+  Int blockType = uiLog2BlockSize;
+  if (uiWidth != uiHeight)
+  {
+    uiScanIdx = SCAN_DIAG;
+    blockType = 4;
+  }
+  
+  const UInt * scan;
+  if (uiWidth == uiHeight)
+  {
+    scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize - 1 ];
+  }
+  else
+  {
+    scan = g_sigScanNSQT[ uiLog2BlockSize - 2 ];
+  }
+  
+  UInt const tsig = pcCU->getSlice()->getPPS()->getTSIG();
+#if LOSSLESS_CODING
+  Bool beValid; 
+  if (pcCU->isLosslessCoded(uiAbsPartIdx))
+  {
+    beValid = false;
+  }
+  else 
+  {
+    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+  }
+#else
+  Bool beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+#endif
+
+  // Find position of last coefficient
+  Int scanPosLast = -1;
+  Int posLast;
+
+  const UInt * scanCG;
+  if (uiWidth == uiHeight)
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0 ];
+    if( uiLog2BlockSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlockSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+  else
+  {
+    scanCG = g_sigCGScanNSQT[ uiLog2BlockSize - 2 ];
+  }
+  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 ];
+
+      // get L1 sig map
+      UInt uiPosY    = posLast >> uiLog2BlockSize;
+      UInt uiPosX    = posLast - ( uiPosY << uiLog2BlockSize );
+      UInt uiBlkIdx  = uiNumBlkSide * (uiPosY >> uiShift) + (uiPosX >> uiShift);
+      if( uiWidth == 8 && uiHeight == 8 && (uiScanIdx == SCAN_HOR || uiScanIdx == SCAN_VER) )
+      {
+        if( uiScanIdx == SCAN_HOR )
+        {
+          uiBlkIdx = uiPosY >> 1;
+        }
+        else if( uiScanIdx == SCAN_VER )
+        {
+          uiBlkIdx = uiPosX >> 1;
+        }
+      }
+      if( pcCoef[ posLast ] )
+      {
+        uiSigCoeffGroupFlag[ uiBlkIdx ] = 1;
+      }
+
+      uiNumSig -= ( pcCoef[ posLast ] != 0 );
+    }
+    while ( uiNumSig > 0 );
+
+  // Code position of last coefficient
+  Int posLastY = posLast >> uiLog2BlockSize;
+  Int posLastX = posLast - ( posLastY << uiLog2BlockSize );
+  codeLastSignificantXY(posLastX, posLastY, uiWidth, uiHeight, eTType, uiScanIdx);
+  
+  //===== 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 uiNumOne                = 0;
+  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];
+    UInt coeffSigns = 0;
+
+    Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE;
+
+    if( iScanPosSig == scanPosLast )
+    {
+      absCoeff[ 0 ] = abs( pcCoef[ posLast ] );
+      coeffSigns    = ( pcCoef[ posLast ] < 0 );
+      numNonZero    = 1;
+      lastNZPosInCG  = iScanPosSig;
+      firstNZPosInCG = iScanPosSig;
+      iScanPosSig--;
+    }
+
+      // encode significant_coeffgroup_flag
+      Int iCGBlkPos = scanCG[ iSubSet ];
+      Int iCGPosY   = iCGBlkPos / uiNumBlkSide;
+      Int iCGPosX   = iCGBlkPos - (iCGPosY * uiNumBlkSide);
+      if( uiWidth == 8 && uiHeight == 8 && (uiScanIdx == SCAN_HOR || uiScanIdx == SCAN_VER) )
+      {
+        iCGPosY = (uiScanIdx == SCAN_HOR ? iCGBlkPos : 0);
+        iCGPosX = (uiScanIdx == SCAN_VER ? iCGBlkPos : 0);
+      }
+      if( iSubSet == iLastScanSet || iSubSet == 0)
+      {
+        uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+      }
+      else
+      {
+          UInt uiSigCoeffGroup   = (uiSigCoeffGroupFlag[ iCGBlkPos ] != 0);
+          UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiScanIdx, uiWidth, uiHeight );
+          m_pcBinIf->encodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+      }
+      
+      // encode significant_coeff_flag
+      if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+      {
+        UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig;
+        for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+        {
+          uiBlkPos  = scan[ iScanPosSig ]; 
+          uiPosY    = uiBlkPos >> uiLog2BlockSize;
+          uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+          uiSig     = (pcCoef[ uiBlkPos ] != 0);
+          if( iScanPosSig > iSubPos || iSubSet == 0 || numNonZero )
+          {
+            uiCtxSig  = TComTrQuant::getSigCtxInc( pcCoef, uiPosX, uiPosY, blockType, uiWidth, uiHeight, eTType );
+            m_pcBinIf->encodeBin( uiSig, baseCtx[ uiCtxSig ] );
+          }
+          if( uiSig )
+          {
+            absCoeff[ numNonZero ] = abs( pcCoef[ uiBlkPos ] );
+            coeffSigns = 2 * coeffSigns + ( pcCoef[ uiBlkPos ] < 0 );
+            numNonZero++;
+            if( lastNZPosInCG == -1 )
+            {
+              lastNZPosInCG = iScanPosSig;
+            }
+            firstNZPosInCG = iScanPosSig;
+          }
+        }
+      }
+      else
+      {
+        iScanPosSig = iSubPos - 1;
+      }
+
+    if( numNonZero > 0 )
+    {
+      Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= (Int)tsig );
+
+      UInt c1 = 1;
+      UInt uiCtxSet = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0;
+      
+      if( uiNumOne > 0 )
+      {
+        uiCtxSet++;
+      }
+      
+      uiNumOne       >>= 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 numC1Flag = min(numNonZero, C1FLAG_NUMBER);
+      Int firstC2FlagIdx = -1;
+      for( Int idx = 0; idx < numC1Flag; idx++ )
+      {
+        UInt uiSymbol = absCoeff[ idx ] > 1;
+        m_pcBinIf->encodeBin( uiSymbol, baseCtxMod[c1] );
+        if( uiSymbol )
+        {
+          c1 = 0;
+
+          if (firstC2FlagIdx == -1)
+          {
+            firstC2FlagIdx = idx;
+          }
+        }
+        else if( (c1 < 3) && (c1 > 0) )
+        {
+          c1++;
+        }
+      }
+      
+      if (c1 == 0)
+      {
+
+        baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUAbsSCModel.get( 0, 0 ) + uiCtxSet : m_cCUAbsSCModel.get( 0, 0 ) + NUM_ABS_FLAG_CTX_LUMA + uiCtxSet;
+        if ( firstC2FlagIdx != -1)
+        {
+          UInt symbol = absCoeff[ firstC2FlagIdx ] > 2;
+          m_pcBinIf->encodeBin( symbol, baseCtxMod[0] );
+        }
+      }
+      
+      if( beValid && signHidden )
+      {
+        m_pcBinIf->encodeBinsEP( (coeffSigns >> 1), numNonZero-1 );
+      }
+      else
+      {
+        m_pcBinIf->encodeBinsEP( coeffSigns, numNonZero );
+      }
+      
+      Int iFirstCoeff2 = 1;    
+      if (c1 == 0 || numNonZero > C1FLAG_NUMBER)
+      {
+        for ( Int idx = 0; idx < numNonZero; idx++ )
+        {
+          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2 ) : 1;
+
+          if( absCoeff[ idx ] >= baseLevel)
+          {
+            xWriteGoRiceExGolomb( absCoeff[ idx ] - baseLevel, uiGoRiceParam ); 
+          }
+          if(absCoeff[ idx ] >= 2)  
+          {
+            iFirstCoeff2 = 0;
+            uiNumOne++;
+          }
+        }        
+      }
+    }
+    else
+    {
+      uiNumOne >>= 1;
+    }
+  }
+
+  return;
+}
+
+Void TEncSbac::codeAlfFlag       ( UInt uiCode )
+{
+  UInt uiSymbol = ( ( uiCode == 0 ) ? 0 : 1 );
+  m_pcBinIf->encodeBin( uiSymbol, m_cALFFlagSCModel.get( 0, 0, 0 ) );
+}
+
+Void TEncSbac::codeAlfCtrlFlag( UInt uiSymbol )
+{
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUAlfCtrlFlagSCModel.get( 0, 0, 0) );
+}
+
+Void TEncSbac::codeAlfUvlc       ( UInt uiCode )
+{
+  Int i;
+  
+  if ( uiCode == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cALFUvlcSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cALFUvlcSCModel.get( 0, 0, 0 ) );
+    for ( i=0; i<uiCode-1; i++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cALFUvlcSCModel.get( 0, 0, 1 ) );
+    }
+    m_pcBinIf->encodeBin( 0, m_cALFUvlcSCModel.get( 0, 0, 1 ) );
+  }
+}
+
+Void TEncSbac::codeAlfSvlc       ( Int iCode )
+{
+  Int i;
+  
+  if ( iCode == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cALFSvlcSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cALFSvlcSCModel.get( 0, 0, 0 ) );
+    
+    // write sign
+    if ( iCode > 0 )
+    {
+      m_pcBinIf->encodeBin( 0, m_cALFSvlcSCModel.get( 0, 0, 1 ) );
+    }
+    else
+    {
+      m_pcBinIf->encodeBin( 1, m_cALFSvlcSCModel.get( 0, 0, 1 ) );
+      iCode = -iCode;
+    }
+    
+    // write magnitude
+    for ( i=0; i<iCode-1; i++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cALFSvlcSCModel.get( 0, 0, 2 ) );
+    }
+    m_pcBinIf->encodeBin( 0, m_cALFSvlcSCModel.get( 0, 0, 2 ) );
+  }
+}
+
+Void TEncSbac::codeSaoFlag       ( UInt uiCode )
+{
+  UInt uiSymbol = ( ( uiCode == 0 ) ? 0 : 1 );
+  m_pcBinIf->encodeBin( uiSymbol, m_cSaoFlagSCModel.get( 0, 0, 0 ) );
+}
+
+Void TEncSbac::codeSaoUvlc       ( UInt uiCode )
+{
+  Int i;
+
+  if ( uiCode == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cSaoUvlcSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cSaoUvlcSCModel.get( 0, 0, 0 ) );
+    for ( i=0; i<uiCode-1; i++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cSaoUvlcSCModel.get( 0, 0, 1 ) );
+    }
+    m_pcBinIf->encodeBin( 0, m_cSaoUvlcSCModel.get( 0, 0, 1 ) );
+  }
+}
+
+Void TEncSbac::codeSaoSvlc       ( Int iCode )
+{
+  Int i;
+
+  if ( iCode == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cSaoSvlcSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cSaoSvlcSCModel.get( 0, 0, 0 ) );
+
+    // write sign
+    if ( iCode > 0 )
+    {
+      m_pcBinIf->encodeBin( 0, m_cSaoSvlcSCModel.get( 0, 0, 1 ) );
+    }
+    else
+    {
+      m_pcBinIf->encodeBin( 1, m_cSaoSvlcSCModel.get( 0, 0, 1 ) );
+      iCode = -iCode;
+    }
+
+    // write magnitude
+    for ( i=0; i<iCode-1; i++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cSaoSvlcSCModel.get( 0, 0, 2 ) );
+    }
+    m_pcBinIf->encodeBin( 0, m_cSaoSvlcSCModel.get( 0, 0, 2 ) );
+  }
+}
+/** Code SAO band position 
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoUflc       ( UInt uiCode )
+{
+  for (Int i=0;i<5;i++)
+  {
+    m_pcBinIf->encodeBinEP ( (uiCode>>i) &0x01 );
+  }
+}
+/** Code SAO merge left flag 
+ * \param uiCode
+ * \param uiCompIdx
+ */
+Void TEncSbac::codeSaoMergeLeft       ( UInt uiCode, UInt uiCompIdx )
+{
+  if (uiCode == 0)
+  {
+    m_pcBinIf->encodeBin(0,  m_cSaoMergeLeftSCModel.get( 0, 0, uiCompIdx ));
+  }
+  else
+  {
+    m_pcBinIf->encodeBin(1,  m_cSaoMergeLeftSCModel.get( 0, 0, uiCompIdx ));
+  }
+}
+/** Code SAO merge up flag 
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoMergeUp       ( UInt uiCode)
+{
+  if (uiCode == 0)
+  {
+    m_pcBinIf->encodeBin(0,  m_cSaoMergeUpSCModel.get( 0, 0, 0 ));
+  }
+  else
+  {
+    m_pcBinIf->encodeBin(1,  m_cSaoMergeUpSCModel.get( 0, 0, 0 ));
+  }
+}
+/** Code SAO type index 
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoTypeIdx       ( UInt uiCode)
+{
+  Int i;
+  if ( uiCode == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+    for ( i=0; i<uiCode-1; i++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 1 ) );
+    }
+    m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 1 ) );
+  }
+}
+/*!
+ ****************************************************************************
+ * \brief
+ *   estimate bit cost for CBP, significant map and significant coefficients
+ ****************************************************************************
+ */
+Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType )
+{
+  estCBFBit( pcEstBitsSbac, 0, eTType );
+
+  estSignificantCoeffGroupMapBit( pcEstBitsSbac, 0, eTType );
+  
+  // encode significance map
+  estSignificantMapBit( pcEstBitsSbac, width, height, eTType );
+  
+  // encode significant coefficients
+  estSignificantCoefficientsBit( pcEstBitsSbac, 0, eTType );
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost for each CBP bit
+ ****************************************************************************
+ */
+Void TEncSbac::estCBFBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType )
+{
+  ContextModel *pCtx = m_cCUQtCbfSCModel.get( 0 );
+
+  for( UInt uiCtxInc = 0; uiCtxInc < 3*NUM_QT_CBF_CTX; uiCtxInc++ )
+  {
+    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
+    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 );
+  }
+
+  pCtx = m_cCUQtRootCbfSCModel.get( 0 );
+  
+  for( UInt uiCtxInc = 0; uiCtxInc < 4; uiCtxInc++ )
+  {
+    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
+    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 );
+  }
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate SAMBAC bit cost for significant coefficient group map
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType )
+{
+  Int firstCtx = 0, numCtx = NUM_SIG_CG_FLAG_CTX;
+
+  for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+  {
+    for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+    {
+      pcEstBitsSbac->significantCoeffGroupBits[ ctxIdx ][ uiBin ] = m_cCUSigCoeffGroupSCModel.get(  0, eTType, ctxIdx ).getEntropyBits( uiBin );
+    }
+  }
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate SAMBAC bit cost for significant coefficient map
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType )
+{
+  Int firstCtx = 0, numCtx = (eTType == TEXT_LUMA) ? 9 : 6;
+  if (std::max(width, height) >= 16)
+  {
+    firstCtx = (eTType == TEXT_LUMA) ? 20 : 17;
+    numCtx = (eTType == TEXT_LUMA) ? 7 : 4;    
+  }
+  else if (width == 8)
+  {
+    firstCtx = (eTType == TEXT_LUMA) ? 9 : 6;
+    numCtx = 11;
+  }
+  
+  if (eTType == TEXT_LUMA )
+  {
+    for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+    {
+      for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+      {
+        pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, ctxIdx ).getEntropyBits( uiBin );
+      }
+    }
+  }
+  else
+  {
+    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;
+  const UInt *puiCtxIdx;
+  Int ctx;
+  Int widthCtx = eTType? 4 : width;
+  puiCtxIdx = g_uiLastCtx + (g_aucConvertToBit[ widthCtx ]*(g_aucConvertToBit[ widthCtx ]+3));
+  ContextModel *pCtxX      = m_cCuCtxLastX.get( 0, eTType );
+  for (ctx = 0; ctx < g_uiGroupIdx[ width - 1 ]; ctx++)
+  {
+    Int ctxOffset = puiCtxIdx[ ctx ];
+    if (eTType)
+    {
+      Int ctxOffsetC =  ctx>>g_aucConvertToBit[ width ];
+      pcEstBitsSbac->lastXBits[ ctx ] = iBitsX + pCtxX[ ctxOffsetC ].getEntropyBits( 0 );
+      iBitsX += pCtxX[ ctxOffsetC].getEntropyBits( 1 );
+    }
+    else
+    {
+      pcEstBitsSbac->lastXBits[ ctx ] = iBitsX + pCtxX[ ctxOffset ].getEntropyBits( 0 );
+      iBitsX += pCtxX[ ctxOffset ].getEntropyBits( 1 );
+    }
+    }
+  pcEstBitsSbac->lastXBits[ctx] = iBitsX;
+
+  Int heightCtx = eTType? 4 : height;
+  puiCtxIdx = g_uiLastCtx + (g_aucConvertToBit[ heightCtx ]*(g_aucConvertToBit[ heightCtx ]+3));
+  ContextModel *pCtxY      = m_cCuCtxLastY.get( 0, eTType );
+  for (ctx = 0; ctx < g_uiGroupIdx[ height - 1 ]; ctx++)
+  {
+    Int ctxOffset = puiCtxIdx[ ctx ];
+    if (eTType)
+    {
+      Int ctxOffsetC =  ctx>>g_aucConvertToBit[ height ];
+      pcEstBitsSbac->lastYBits[ ctx ] = iBitsY + pCtxY[ ctxOffsetC ].getEntropyBits( 0 );
+      iBitsY += pCtxY[ctxOffsetC].getEntropyBits( 1 );
+    }
+    else
+    {
+      pcEstBitsSbac->lastYBits[ ctx ] = iBitsY + pCtxY[ ctxOffset ].getEntropyBits( 0 );
+      iBitsY += pCtxY[ ctxOffset ].getEntropyBits( 1 );
+    }
+    }
+  pcEstBitsSbac->lastYBits[ctx] = iBitsY;
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost of significant coefficient
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, 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 );    
+    }
+  }
+}
+
+/**
+ - Initialize our context information from the nominated source.
+ .
+ \param pSrc From where to copy context information.
+ */
+Void TEncSbac::xCopyContextsFrom( TEncSbac* pSrc )
+{  
+  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
+}
+
+Void  TEncSbac::loadContexts ( TEncSbac* pScr)
+{
+  this->xCopyContextsFrom(pScr);
+}
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX || (LGE_EDGE_INTRA_A0070 && LGE_EDGE_INTRA_DELTA_DC)
+Void TEncSbac::xWriteExGolombLevel( UInt uiSymbol, ContextModel& rcSCModel  )
+{
+  if( uiSymbol )
+  {
+    m_pcBinIf->encodeBin( 1, rcSCModel );
+    UInt uiCount = 0;
+    Bool bNoExGo = (uiSymbol < 13);
+
+    while( --uiSymbol && ++uiCount < 13 )
+    {
+      m_pcBinIf->encodeBin( 1, rcSCModel );
+    }
+    if( bNoExGo )
+    {
+      m_pcBinIf->encodeBin( 0, rcSCModel );
+    }
+    else
+    {
+      xWriteEpExGolomb( uiSymbol, 0 );
+    }
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 0, rcSCModel );
+  }
+
+  return;
+}
+#endif
+#if HHI_DMM_WEDGE_INTRA
+Void TEncSbac::xCodeWedgeFullInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+  Int iBits = g_aucWedgeFullBitsListIdx[iIntraIdx];
+
+  UInt uiTabIdx = pcCU->getWedgeFullTabIdx( uiAbsPartIdx );
+
+  for ( Int i = 0; i < iBits; i++ )
+  {
+    m_pcBinIf->encodeBin( ( uiTabIdx >> i ) & 1, m_cDmmDataSCModel.get(0, 0, 0) );
+  }
+}
+
+Void TEncSbac::xCodeWedgeFullDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+  Int iBits = g_aucWedgeFullBitsListIdx[iIntraIdx];
+
+  UInt uiTabIdx = pcCU->getWedgeFullTabIdx( uiAbsPartIdx );
+
+  for ( Int i = 0; i < iBits; i++ )
+  {
+    m_pcBinIf->encodeBin( ( uiTabIdx >> i ) & 1, m_cDmmDataSCModel.get(0, 0, 0) );
+  }
+
+  Int iDeltaDC1 = pcCU->getWedgeFullDeltaDC1( uiAbsPartIdx );
+  Int iDeltaDC2 = pcCU->getWedgeFullDeltaDC2( uiAbsPartIdx );
+
+  xWriteExGolombLevel( UInt( abs( iDeltaDC1 ) ), m_cDmmDataSCModel.get(0, 0, 1) );
+  if ( iDeltaDC1 != 0 )
+  {
+    UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+  xWriteExGolombLevel( UInt( abs( iDeltaDC2 ) ), m_cDmmDataSCModel.get(0, 0, 1) );
+  if ( iDeltaDC2 != 0 )
+  {
+    UInt uiSign = iDeltaDC2 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+}
+
+Void TEncSbac::xCodeWedgePredDirInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if( DMM_WEDGE_PREDDIR_DELTAEND_MAX > 0 )
+  {
+    Int iDeltaEnd = pcCU->getWedgePredDirDeltaEnd( uiAbsPartIdx );
+    m_pcBinIf->encodeBin( (iDeltaEnd!=0), m_cDmmDataSCModel.get(0, 0, 2) );
+
+    if( iDeltaEnd != 0 )
+    {
+      UInt uiAbsValMinus1 = abs(iDeltaEnd)-1;
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x01),      m_cDmmDataSCModel.get(0, 0, 2) );
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x02) >> 1, m_cDmmDataSCModel.get(0, 0, 2) );
+
+      UInt uiSign = iDeltaEnd > 0 ? 0 : 1;
+      m_pcBinIf->encodeBinEP( uiSign );
+    }
+  }
+}
+
+Void TEncSbac::xCodeWedgePredDirDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if( DMM_WEDGE_PREDDIR_DELTAEND_MAX > 0 )
+  {
+    Int iDeltaEnd = pcCU->getWedgePredDirDeltaEnd( uiAbsPartIdx );
+    m_pcBinIf->encodeBin( (iDeltaEnd!=0), m_cDmmDataSCModel.get(0, 0, 2) );
+
+    if( iDeltaEnd != 0 )
+    {
+      UInt uiAbsValMinus1 = abs(iDeltaEnd)-1;
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x01),      m_cDmmDataSCModel.get(0, 0, 2) );
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x02) >> 1, m_cDmmDataSCModel.get(0, 0, 2) );
+
+      UInt uiSign = iDeltaEnd > 0 ? 0 : 1;
+      m_pcBinIf->encodeBinEP( uiSign );
+    }
+  }
+
+  Int iDeltaDC1 = pcCU->getWedgePredDirDeltaDC1( uiAbsPartIdx );
+  Int iDeltaDC2 = pcCU->getWedgePredDirDeltaDC2( uiAbsPartIdx );
+
+  xWriteExGolombLevel( UInt( abs( iDeltaDC1 ) ), m_cDmmDataSCModel.get(0, 0, 1) );
+  if ( iDeltaDC1 != 0 )
+  {
+    UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+  xWriteExGolombLevel( UInt( abs( iDeltaDC2 ) ), m_cDmmDataSCModel.get(0, 0, 1) );
+  if ( iDeltaDC2 != 0 )
+  {
+    UInt uiSign = iDeltaDC2 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+}
+#endif
+#if HHI_DMM_PRED_TEX
+#if LGE_DMM3_SIMP_C0044
+Void TEncSbac::xCodeWedgePredTexInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+  Int iBits = g_aucWedgeTexPredBitsListIdx[iIntraIdx];
+
+  UInt uiTabIdx = pcCU->getWedgePredTexIntraTabIdx( uiAbsPartIdx );
+
+  for ( Int i = 0; i < iBits; i++ )
+  {
+    m_pcBinIf->encodeBin( ( uiTabIdx >> i ) & 1, m_cDmmDataSCModel.get(0, 0, 3) );
+  }
+}
+#endif
+
+Void TEncSbac::xCodeWedgePredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if LGE_DMM3_SIMP_C0044
+  xCodeWedgePredTexInfo( pcCU, uiAbsPartIdx );
+#endif
+  Int iDeltaDC1 = pcCU->getWedgePredTexDeltaDC1( uiAbsPartIdx );
+  Int iDeltaDC2 = pcCU->getWedgePredTexDeltaDC2( uiAbsPartIdx );
+
+  xWriteExGolombLevel( UInt( abs( iDeltaDC1 ) ), m_cDmmDataSCModel.get(0, 0, 1) );
+  if ( iDeltaDC1 != 0 )
+  {
+    UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+  xWriteExGolombLevel( UInt( abs( iDeltaDC2 ) ), m_cDmmDataSCModel.get(0, 0, 1) );
+  if ( iDeltaDC2 != 0 )
+  {
+    UInt uiSign = iDeltaDC2 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+}
+
+Void TEncSbac::xCodeContourPredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDeltaDC1 = pcCU->getContourPredTexDeltaDC1( uiAbsPartIdx );
+  Int iDeltaDC2 = pcCU->getContourPredTexDeltaDC2( uiAbsPartIdx );
+
+  xWriteExGolombLevel( UInt( abs( iDeltaDC1 ) ), m_cDmmDataSCModel.get(0, 0, 1) );
+  if ( iDeltaDC1 != 0 )
+  {
+    UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+  xWriteExGolombLevel( UInt( abs( iDeltaDC2 ) ), m_cDmmDataSCModel.get(0, 0, 1) );
+  if ( iDeltaDC2 != 0 )
+  {
+    UInt uiSign = iDeltaDC2 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+}
+#endif
+
+#if RWTH_SDC_DLT_B0036
+Void TEncSbac::codeSDCPredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  assert( pcCU->getSDCFlag(uiAbsPartIdx) );
+  
+  UInt uiPredMode     = pcCU->getLumaIntraDir(uiAbsPartIdx);
+  UInt uiCtx          = 0;
+  
+  UInt uiMPModeIdx    = 0;
+  
+  for(Int i=0; i<RWTH_SDC_NUM_PRED_MODES-1; i++)
+  {
+    UInt uiBit = (uiPredMode == g_auiSDCPredModes[uiMPModeIdx]) ? 1 : 0;
+    m_pcBinIf->encodeBin( uiBit, m_cSDCPredModeSCModel.get( 0, i, uiCtx ) );
+    
+    // if mode is most probable mode, we are done here
+    if ( uiBit == 1 )
+      break;
+    
+    // else: get next most probable pred mode
+    uiMPModeIdx = (uiMPModeIdx+1)%RWTH_SDC_NUM_PRED_MODES;
+  }
+  
+#if HHI_DMM_WEDGE_INTRA
+  if( uiPredMode == DMM_WEDGE_FULL_IDX )          { xCodeWedgeFullInfo          ( pcCU, uiAbsPartIdx ); }
+  if( uiPredMode == DMM_WEDGE_PREDDIR_IDX )       { xCodeWedgePredDirInfo       ( pcCU, uiAbsPartIdx ); }
+#endif
+  
+  AOF(uiPredMode == g_auiSDCPredModes[uiMPModeIdx]);
+}
+
+Void TEncSbac::codeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  UInt uiSymbol = pcCU->getSDCFlag( uiAbsPartIdx ) ? 1 : 0;
+  UInt uiCtxSDCFlag = pcCU->getCtxSDCFlag( uiAbsPartIdx );
+  m_pcBinIf->encodeBin( uiSymbol, m_cSDCFlagSCModel.get( 0, 0, uiCtxSDCFlag ) );
+  
+}
+
+Void TEncSbac::codeSDCResidualData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment )
+{
+  assert( pcCU->getSlice()->getSPS()->isDepth() );
+  assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  assert( pcCU->getSDCFlag(uiAbsPartIdx) );
+  assert( uiSegment < 2 );
+  
+  Pel segmentDCOffset = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+  
+  UInt uiResidual = segmentDCOffset == 0 ? 0 : 1;
+  UInt uiSign     = segmentDCOffset < 0 ? 1 : 0;
+  UInt uiAbsIdx   = abs(segmentDCOffset);
+  UInt uiBit = 0;
+  
+  UInt uiMaxResidualBits  = GetBitsPerDepthValue();
+  assert( uiMaxResidualBits <= g_uiBitDepth );
+  
+  // residual flag
+  m_pcBinIf->encodeBin( uiResidual, m_cSDCResidualFlagSCModel.get( 0, uiSegment, 0 ) ); //TODO depthmap: more sophisticated context selection
+  
+  if (uiResidual)
+  {
+    // encode sign bit of residual
+    m_pcBinIf->encodeBin( uiSign, m_cSDCResidualSignFlagSCModel.get( 0, uiSegment, 0 ) ); //TODO depthmap: more sophisticated context selection
+        
+    assert(uiAbsIdx < GetNumDepthValues());
+    
+    // encode residual magnitude
+    uiAbsIdx -= 1;
+    for (Int i=0; i<uiMaxResidualBits; i++)
+    {
+      uiBit = (uiAbsIdx & (1<<i))>>i;
+      
+      m_pcBinIf->encodeBin( uiBit, m_cSDCResidualSCModel.get( 0, uiSegment, i ) ); //TODO depthmap: more sophisticated context selection
+    }
+    
+  }
+}
+#endif
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSbac.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSbac.h	(revision 341)
@@ -0,0 +1,326 @@
+/* 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-2012, 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     TEncSbac.h
+    \brief    Context-adaptive entropy encoder class (header)
+*/
+
+#ifndef __TENCSBAC__
+#define __TENCSBAC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/ContextTables.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/ContextModel3DBuffer.h"
+#include "TEncEntropy.h"
+#include "TEncBinCoder.h"
+#include "TEncBinCoderCABAC.h"
+#if FAST_BIT_EST
+#include "TEncBinCoderCABACCounter.h"
+#endif
+
+class TEncTop;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// SBAC encoder class
+class TEncSbac : public TEncEntropyIf
+{
+public:
+  TEncSbac();
+  virtual ~TEncSbac();
+  
+  Void  init                   ( TEncBinIf* p )  { m_pcBinIf = p; }
+  Void  uninit                 ()                { m_pcBinIf = 0; }
+  
+  //  Virtual list
+  Void  resetEntropy           ();
+#if CABAC_INIT_FLAG
+  Void  determineCabacInitIdx  ();
+#endif
+  Void  setBitstream           ( TComBitIf* p )  { m_pcBitIf = p; m_pcBinIf->init( p ); }
+  Void  setSlice               ( TComSlice* p )  { m_pcSlice = p;                       }
+  
+  Bool  getAlfCtrl             ()                         { return m_bAlfCtrl;          }
+  UInt  getMaxAlfCtrlDepth     ()                         { return m_uiMaxAlfCtrlDepth; }
+  Void  setAlfCtrl             ( Bool bAlfCtrl          ) { m_bAlfCtrl          = bAlfCtrl;          }
+  Void  setMaxAlfCtrlDepth     ( UInt uiMaxAlfCtrlDepth ) { m_uiMaxAlfCtrlDepth = uiMaxAlfCtrlDepth; }
+  
+  // SBAC RD
+  Void  resetCoeffCost         ()                { m_uiCoeffCost = 0;  }
+  UInt  getCoeffCost           ()                { return  m_uiCoeffCost;  }
+  
+  Void  load                   ( TEncSbac* pScr  );
+  Void  loadIntraDirModeLuma   ( TEncSbac* pScr  );
+  Void  store                  ( TEncSbac* pDest );
+  Void  loadContexts           ( TEncSbac* pScr  );
+  Void  resetBits              ()                { m_pcBinIf->resetBits(); m_pcBitIf->resetBits(); }
+  UInt  getNumberOfWrittenBits ()                { return m_pcBinIf->getNumWrittenBits(); }
+  //--SBAC RD
+
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  Void  codeVPS                 ( TComVPS* pcVPS );
+#endif
+  
+#if HHI_MPI || H3D_QTL 
+  Void  codeSPS                 ( TComSPS* pcSPS, Bool bIsDepth );
+#else
+  Void  codeSPS                 ( TComSPS* pcSPS     );
+#endif
+  Void  codePPS                 ( TComPPS* pcPPS     );
+  void codeSEI(const SEI&);
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+  Void codeTileMarkerFlag(TComSlice* pcSlice) {printf("Not supported\n"); assert(0); exit(1);}
+  Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast      );
+  Void  codeSliceFinish         ();
+  Void  codeFlush               ();
+  Void  encodeStart             ();
+  
+  Void  codeAlfFlag       ( UInt uiCode );
+  Void  codeAlfUvlc       ( UInt uiCode );
+  Void  codeAlfSvlc       ( Int  uiCode );
+  Void  codeAlfCtrlDepth  ();
+  Void codeAPSAlflag(UInt uiCode) {assert (0);  return;}
+  Void codeAlfFixedLengthIdx( UInt idx, UInt maxValue){ assert (0);  return;}
+
+  Void codeAlfCtrlFlag       ( UInt uiSymbol );
+  Void  codeApsExtensionFlag () { assert (0); return; };
+  Void  codeSaoFlag       ( UInt uiCode );
+  Void  codeSaoUvlc       ( UInt uiCode );
+  Void  codeSaoSvlc       ( Int  uiCode );
+  Void  codeSaoRun        ( UInt  uiCode, UInt uiMaxValue  ) {;}
+  Void  codeSaoMergeLeft  ( UInt  uiCode, UInt uiCompIdx );
+  Void  codeSaoMergeUp    ( UInt  uiCode);
+  Void  codeSaoTypeIdx    ( UInt  uiCode);
+  Void  codeSaoUflc       ( UInt  uiCode);
+  Void  codeScalingList      ( TComScalingList* scalingList     ){ assert (0);  return;};
+  
+#if RWTH_SDC_DLT_B0036
+  Void codeSDCFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSDCResidualData  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment );
+  Void codeSDCPredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+
+private:
+  Void  xWriteUnarySymbol    ( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset );
+  Void  xWriteUnaryMaxSymbol ( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol );
+  Void  xWriteEpExGolomb     ( UInt uiSymbol, UInt uiCount );
+  Void  xWriteGoRiceExGolomb ( UInt uiSymbol, UInt &ruiGoRiceParam );
+  Void  xWriteTerminatingBit ( UInt uiBit );
+  
+  Void  xCopyFrom            ( TEncSbac* pSrc );
+  Void  xCopyContextsFrom    ( TEncSbac* pSrc );  
+  
+  Void codeAPSInitInfo(TComAPS* pcAPS) {printf("Not supported in codeAPSInitInfo()\n"); assert(0); exit(1);}
+  Void codeFinish     (Bool bEnd)      { m_pcBinIf->encodeFlush(bEnd); }  //<! flush bits when CABAC termination
+  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);};
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void  xWriteExGolombLevel  ( UInt uiSymbol, ContextModel& rcSCModel  );
+#endif
+#if HHI_DMM_WEDGE_INTRA
+  Void  xCodeWedgeFullInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void  xCodeWedgeFullDeltaInfo     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
+  Void  xCodeWedgePredDirInfo       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void  xCodeWedgePredDirDeltaInfo  ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if HHI_DMM_PRED_TEX
+#if LGE_DMM3_SIMP_C0044
+  Void  xCodeWedgePredTexInfo       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void  xCodeWedgePredTexDeltaInfo  ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void  xCodeContourPredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if LGE_EDGE_INTRA_A0070
+  Void  xCodeEdgeIntraInfo( TComDataCU* pcCU, UInt uiPartIdx );
+#endif
+
+protected:
+  TComBitIf*    m_pcBitIf;
+  TComSlice*    m_pcSlice;
+  TEncBinIf*    m_pcBinIf;
+  Bool          m_bAlfCtrl;
+  
+  //SBAC RD
+  UInt          m_uiCoeffCost;
+  
+  // Adaptive loop filter
+  UInt          m_uiMaxAlfCtrlDepth;
+  Int           m_iSliceGranularity; //!< slice granularity
+  //--Adaptive loop filter
+  
+public:
+
+  /// set slice granularity
+  Void setSliceGranularity(Int iSliceGranularity)  {m_iSliceGranularity = iSliceGranularity;}
+
+  /// get slice granularity
+  Int  getSliceGranularity()                       {return m_iSliceGranularity;             }
+  Void codeAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if LGE_ILLUCOMP_B0045
+  Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if H3D_IVRP
+  Void codeResPredFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if H3D_IVMP
+  Void codeMVPIdx        ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Int iNum );
+#else
+  Void codeMVPIdx        ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+#endif
+  
+  Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag);
+  Void codeTransformSubdivFlag ( UInt uiSymbol, UInt uiCtx );
+  Void codeQtCbf               ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeIntraDirLumaAng     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeIntraDirChroma      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeInterDir            ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeRefFrmIdx           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void codeMvd                 ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+  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 );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // for RD-optimizatioon
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+  Void estCBFBit                     ( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  Void estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  Void estSignificantMapBit          ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType );
+  Void estSignificantCoefficientsBit ( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  
+  Void updateContextTables           ( SliceType eSliceType, Int iQp, Bool bExecuteFinish=true  );
+  Void updateContextTables           ( SliceType eSliceType, Int iQp  ) { this->updateContextTables( eSliceType, iQp, true); };
+  Void writeTileMarker               ( UInt uiTileIdx, UInt uiBitsUsed );
+
+  
+  TEncBinIf* getEncBinIf()  { return m_pcBinIf; }
+private:
+  UInt                 m_uiLastQp;
+  
+  ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
+  Int                  m_numContextModels;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+#if LGE_ILLUCOMP_B0045
+  ContextModel3DBuffer m_cCUICFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+#if H3D_IVRP
+  ContextModel3DBuffer m_cResPredFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUAlfCtrlFlagSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+  
+  ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
+  ContextModel3DBuffer m_cCUSigSCModel;
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+  
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+  
+  ContextModel3DBuffer m_cALFFlagSCModel;
+  ContextModel3DBuffer m_cALFUvlcSCModel;
+  ContextModel3DBuffer m_cALFSvlcSCModel;
+  ContextModel3DBuffer m_cCUAMPSCModel;
+  ContextModel3DBuffer m_cSaoFlagSCModel;
+  ContextModel3DBuffer m_cSaoUvlcSCModel;
+  ContextModel3DBuffer m_cSaoSvlcSCModel;
+  ContextModel3DBuffer m_cSaoMergeLeftSCModel;
+  ContextModel3DBuffer m_cSaoMergeUpSCModel;
+  ContextModel3DBuffer m_cSaoTypeIdxSCModel;
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  ContextModel3DBuffer m_cDmmFlagSCModel;
+  ContextModel3DBuffer m_cDmmModeSCModel;
+  ContextModel3DBuffer m_cDmmDataSCModel;
+#endif
+#if LGE_EDGE_INTRA_A0070
+  ContextModel3DBuffer m_cEdgeIntraSCModel;
+#if LGE_EDGE_INTRA_DELTA_DC
+  ContextModel3DBuffer m_cEdgeIntraDeltaDCSCModel;
+#endif
+#endif
+  
+#if RWTH_SDC_DLT_B0036
+  ContextModel3DBuffer m_cSDCFlagSCModel;
+  
+  ContextModel3DBuffer m_cSDCResidualFlagSCModel;
+  ContextModel3DBuffer m_cSDCResidualSignFlagSCModel;
+  ContextModel3DBuffer m_cSDCResidualSCModel;
+  
+  ContextModel3DBuffer m_cSDCPredModeSCModel;
+#endif
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCSBAC_H__DDA7CDC4_EDE3_4015_9D32_2156249C82AA__INCLUDED_)
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 341)
@@ -0,0 +1,8043 @@
+/* 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-2012, 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     TEncSearch.cpp
+ \brief    encoder search class
+ */
+
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/TComMotionInfo.h"
+#include "TEncSearch.h"
+#include <math.h>
+
+#if RWTH_SDC_DLT_B0036
+#define GetDepthValue2Idx(val)     (pcCU->getSlice()->getSPS()->depthValue2idx(val))
+#define GetIdx2DepthValue(val)     (pcCU->getSlice()->getSPS()->idx2DepthValue(val))
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+static TComMv s_acMvRefineH[9] =
+{
+  TComMv(  0,  0 ), // 0
+  TComMv(  0, -1 ), // 1
+  TComMv(  0,  1 ), // 2
+  TComMv( -1,  0 ), // 3
+  TComMv(  1,  0 ), // 4
+  TComMv( -1, -1 ), // 5
+  TComMv(  1, -1 ), // 6
+  TComMv( -1,  1 ), // 7
+  TComMv(  1,  1 )  // 8
+};
+
+static TComMv s_acMvRefineQ[9] =
+{
+  TComMv(  0,  0 ), // 0
+  TComMv(  0, -1 ), // 1
+  TComMv(  0,  1 ), // 2
+  TComMv( -1, -1 ), // 5
+  TComMv(  1, -1 ), // 6
+  TComMv( -1,  0 ), // 3
+  TComMv(  1,  0 ), // 4
+  TComMv( -1,  1 ), // 7
+  TComMv(  1,  1 )  // 8
+};
+
+static UInt s_auiDFilter[9] =
+{
+  0, 1, 0,
+  2, 3, 2,
+  0, 1, 0
+};
+
+TEncSearch::TEncSearch()
+{
+  m_ppcQTTempCoeffY  = NULL;
+  m_ppcQTTempCoeffCb = NULL;
+  m_ppcQTTempCoeffCr = NULL;
+  m_pcQTTempCoeffY   = NULL;
+  m_pcQTTempCoeffCb  = NULL;
+  m_pcQTTempCoeffCr  = 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;
+
+  setWpScalingDistParam( NULL, -1, REF_PIC_LIST_X );
+}
+
+TEncSearch::~TEncSearch()
+{
+  if ( m_pTempPel )
+  {
+    delete [] m_pTempPel;
+    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];
+#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;
+#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_puhQTTempTrIdx;
+  delete[] m_puhQTTempCbf[0];
+  delete[] m_puhQTTempCbf[1];
+  delete[] m_puhQTTempCbf[2];
+  delete[] m_pcQTTempTComYuv;
+  
+  m_tmpYuvPred.destroy();
+}
+
+void TEncSearch::init(TEncCfg*      pcEncCfg,
+                      TComTrQuant*  pcTrQuant,
+                      Int           iSearchRange,
+                      Int           bipredSearchRange,
+#if DV_V_RESTRICTION_B0037
+                      Bool          bUseDisparitySearchRangeRestriction,
+                      Int           iVerticalDisparitySearchRange,
+#endif
+                      Int           iFastSearch,
+                      Int           iMaxDeltaQP,
+                      TEncEntropy*  pcEntropyCoder,
+                      TComRdCost*   pcRdCost,
+                      TEncSbac*** pppcRDSbacCoder,
+                      TEncSbac*   pcRDGoOnSbacCoder
+                      )
+{
+  m_pcEncCfg             = pcEncCfg;
+  m_pcTrQuant            = pcTrQuant;
+  m_iSearchRange         = iSearchRange;
+  m_bipredSearchRange    = bipredSearchRange;
+#if DV_V_RESTRICTION_B0037
+  m_bUseDisparitySearchRangeRestriction = bUseDisparitySearchRangeRestriction;
+  m_iVerticalDisparitySearchRange = iVerticalDisparitySearchRange;
+#endif
+  m_iFastSearch          = iFastSearch;
+  m_iMaxDeltaQP          = iMaxDeltaQP;
+  m_pcEntropyCoder       = pcEntropyCoder;
+  m_pcRdCost             = pcRdCost;
+  
+  m_pppcRDSbacCoder     = pppcRDSbacCoder;
+  m_pcRDGoOnSbacCoder   = pcRDGoOnSbacCoder;
+  
+  m_bUseSBACRD          = pppcRDSbacCoder ? true : false;
+  
+  for (Int iDir = 0; iDir < 2; iDir++)
+  {
+    for (Int iRefIdx = 0; iRefIdx < 33; iRefIdx++)
+    {
+      m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange;
+    }
+  }
+  
+  m_puiDFilter = s_auiDFilter + 4;
+  
+  // initialize motion cost
+#if !FIX203
+  m_pcRdCost->initRateDistortionModel( m_iSearchRange << 2 );
+#endif
+  
+#if H3D_IVMP
+  const Int iNumAMVPCands = AMVP_MAX_NUM_CANDS + 1;
+  for( Int iNum = 0; iNum < iNumAMVPCands+1; iNum++)
+    for( Int iIdx = 0; iIdx < iNumAMVPCands; iIdx++)
+#else
+  for( Int iNum = 0; iNum < AMVP_MAX_NUM_CANDS+1; iNum++)
+    for( Int iIdx = 0; iIdx < AMVP_MAX_NUM_CANDS; iIdx++)
+#endif
+    {
+      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 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];
+#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_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_tmpYuvPred.create(MAX_CU_SIZE, MAX_CU_SIZE);
+}
+
+#if FASTME_SMOOTHER_MV
+#define FIRSTSEARCHSTOP     1
+#else
+#define FIRSTSEARCHSTOP     0
+#endif
+
+#define TZ_SEARCH_CONFIGURATION                                                                                 \
+const Int  iRaster                  = 5;  /* TZ soll von aussen ?ergeben werden */                            \
+const Bool bTestOtherPredictedMV    = 0;                                                                      \
+const Bool bTestZeroVector          = 1;                                                                      \
+const Bool bTestZeroVectorStart     = 0;                                                                      \
+const Bool bTestZeroVectorStop      = 0;                                                                      \
+const Bool bFirstSearchDiamond      = 1;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
+const Bool bFirstSearchStop         = FIRSTSEARCHSTOP;                                                        \
+const UInt uiFirstSearchRounds      = 3;  /* first search stop X rounds after best match (must be >=1) */     \
+const Bool bEnableRasterSearch      = 1;                                                                      \
+const Bool bAlwaysRasterSearch      = 0;  /* ===== 1: BETTER but factor 2 slower ===== */                     \
+const Bool bRasterRefinementEnable  = 0;  /* enable either raster refinement or star refinement */            \
+const Bool bRasterRefinementDiamond = 0;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
+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) */  \
+
+
+__inline Void TEncSearch::xTZSearchHelp( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance )
+{
+  UInt  uiSad;
+  
+  Pel*  piRefSrch;
+  
+  piRefSrch = rcStruct.piRefY + iSearchY * rcStruct.iYStride + iSearchX;
+  
+  //-- 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 )
+    {
+      m_cDistParam.iSubShift = 1;
+    }
+  }
+
+  setDistParamComp(0);  // Y component
+
+  // distortion
+#if LGE_ILLUCOMP_B0045
+  m_cDistParam.bUseIC = pcPatternKey->getICFlag();
+#endif
+  uiSad = m_cDistParam.DistFunc( &m_cDistParam );
+  
+  // motion cost
+  uiSad += m_pcRdCost->getCost( iSearchX, iSearchY );
+
+  // regularization cost
+  if( m_pcRdCost->useMultiviewReg() )
+  {
+    uiSad += m_pcRdCost->getMultiviewRegCost( 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 )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  // 2 point search,                   //   1 2 3
+  // check only the 2 untested points  //   4 0 5
+  // around the start point            //   6 7 8
+  Int iStartX = rcStruct.iBestX;
+  Int iStartY = rcStruct.iBestY;
+  switch( rcStruct.ucPointNr )
+  {
+    case 1:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY, 0, 2 );
+      }
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY - 1, 0, 2 );
+      }
+    }
+      break;
+    case 2:
+    {
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        if ( (iStartX - 1) >= iSrchRngHorLeft )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY - 1, 0, 2 );
+        }
+        if ( (iStartX + 1) <= iSrchRngHorRight )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY - 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 3:
+    {
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY - 1, 0, 2 );
+      }
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY, 0, 2 );
+      }
+    }
+      break;
+    case 4:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        if ( (iStartY + 1) <= iSrchRngVerBottom )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY + 1, 0, 2 );
+        }
+        if ( (iStartY - 1) >= iSrchRngVerTop )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY - 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 5:
+    {
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        if ( (iStartY - 1) >= iSrchRngVerTop )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY - 1, 0, 2 );
+        }
+        if ( (iStartY + 1) <= iSrchRngVerBottom )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY + 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 6:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY , 0, 2 );
+      }
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY + 1, 0, 2 );
+      }
+    }
+      break;
+    case 7:
+    {
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        if ( (iStartX - 1) >= iSrchRngHorLeft )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY + 1, 0, 2 );
+        }
+        if ( (iStartX + 1) <= iSrchRngHorRight )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY + 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 8:
+    {
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY, 0, 2 );
+      }
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY + 1, 0, 2 );
+      }
+    }
+      break;
+    default:
+    {
+      assert( false );
+    }
+      break;
+  } // switch( rcStruct.ucPointNr )
+}
+
+__inline Void TEncSearch::xTZ8PointSquareSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  // 8 point search,                   //   1 2 3
+  // search around the start point     //   4 0 5
+  // with the required  distance       //   6 7 8
+  assert( iDist != 0 );
+  const Int iTop        = iStartY - iDist;
+  const Int iBottom     = iStartY + iDist;
+  const Int iLeft       = iStartX - iDist;
+  const Int iRight      = iStartX + iDist;
+  rcStruct.uiBestRound += 1;
+  
+  if ( iTop >= iSrchRngVerTop ) // check top
+  {
+    if ( iLeft >= iSrchRngHorLeft ) // check top left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iTop, 1, iDist );
+    }
+    // top middle
+    xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+    
+    if ( iRight <= iSrchRngHorRight ) // check top right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iTop, 3, iDist );
+    }
+  } // check top
+  if ( iLeft >= iSrchRngHorLeft ) // check middle left
+  {
+    xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+  }
+  if ( iRight <= iSrchRngHorRight ) // check middle right
+  {
+    xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+  }
+  if ( iBottom <= iSrchRngVerBottom ) // check bottom
+  {
+    if ( iLeft >= iSrchRngHorLeft ) // check bottom left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iBottom, 6, iDist );
+    }
+    // check bottom middle
+    xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+    
+    if ( iRight <= iSrchRngHorRight ) // check bottom right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iBottom, 8, iDist );
+    }
+  } // check bottom
+}
+
+__inline Void TEncSearch::xTZ8PointDiamondSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  // 8 point search,                   //   1 2 3
+  // search around the start point     //   4 0 5
+  // with the required  distance       //   6 7 8
+  assert ( iDist != 0 );
+  const Int iTop        = iStartY - iDist;
+  const Int iBottom     = iStartY + iDist;
+  const Int iLeft       = iStartX - iDist;
+  const Int iRight      = iStartX + iDist;
+  rcStruct.uiBestRound += 1;
+  
+  if ( iDist == 1 ) // iDist == 1
+  {
+    if ( iTop >= iSrchRngVerTop ) // check top
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+    }
+    if ( iLeft >= iSrchRngHorLeft ) // check middle left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+    }
+    if ( iRight <= iSrchRngHorRight ) // check middle right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+    }
+    if ( iBottom <= iSrchRngVerBottom ) // check bottom
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+    }
+  }
+  else // if (iDist != 1)
+  {
+    if ( iDist <= 8 )
+    {
+      const Int iTop_2      = iStartY - (iDist>>1);
+      const Int iBottom_2   = iStartY + (iDist>>1);
+      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
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX,  iTop,      2, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2,  iTop_2,    1, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iTop_2,    3, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft,    iStartY,   4, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight,   iStartY,   5, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2,  iBottom_2, 6, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iBottom_2, 8, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX,  iBottom,   7, iDist    );
+      }
+      else // check border
+      {
+        if ( iTop >= iSrchRngVerTop ) // check top
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+        }
+        if ( iTop_2 >= iSrchRngVerTop ) // check half top
+        {
+          if ( iLeft_2 >= iSrchRngHorLeft ) // check half left
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2, iTop_2, 1, (iDist>>1) );
+          }
+          if ( iRight_2 <= iSrchRngHorRight ) // check half right
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iTop_2, 3, (iDist>>1) );
+          }
+        } // check half top
+        if ( iLeft >= iSrchRngHorLeft ) // check left
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+        }
+        if ( iRight <= iSrchRngHorRight ) // check right
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+        }
+        if ( iBottom_2 <= iSrchRngVerBottom ) // check half bottom
+        {
+          if ( iLeft_2 >= iSrchRngHorLeft ) // check half left
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2, iBottom_2, 6, (iDist>>1) );
+          }
+          if ( iRight_2 <= iSrchRngHorRight ) // check half right
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iBottom_2, 8, (iDist>>1) );
+          }
+        } // check half bottom
+        if ( iBottom <= iSrchRngVerBottom ) // check bottom
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+        }
+      } // check border
+    }
+    else // iDist > 8
+    {
+      if ( iTop >= iSrchRngVerTop && iLeft >= iSrchRngHorLeft &&
+          iRight <= iSrchRngHorRight && iBottom <= iSrchRngVerBottom ) // check border
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop,    0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft,   iStartY, 0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight,  iStartY, 0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 0, iDist );
+        for ( Int index = 1; index < 4; index++ )
+        {
+          Int iPosYT = iTop    + ((iDist>>2) * index);
+          Int iPosYB = iBottom - ((iDist>>2) * index);
+          Int iPosXL = iStartX - ((iDist>>2) * index);
+          Int iPosXR = iStartX + ((iDist>>2) * index);
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYT, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYT, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYB, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYB, 0, iDist );
+        }
+      }
+      else // check border
+      {
+        if ( iTop >= iSrchRngVerTop ) // check top
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 0, iDist );
+        }
+        if ( iLeft >= iSrchRngHorLeft ) // check left
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 0, iDist );
+        }
+        if ( iRight <= iSrchRngHorRight ) // check right
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 0, iDist );
+        }
+        if ( iBottom <= iSrchRngVerBottom ) // check bottom
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 0, iDist );
+        }
+        for ( Int index = 1; index < 4; index++ )
+        {
+          Int iPosYT = iTop    + ((iDist>>2) * index);
+          Int iPosYB = iBottom - ((iDist>>2) * index);
+          Int iPosXL = iStartX - ((iDist>>2) * index);
+          Int iPosXR = iStartX + ((iDist>>2) * index);
+          
+          if ( iPosYT >= iSrchRngVerTop ) // check top
+          {
+            if ( iPosXL >= iSrchRngHorLeft ) // check left
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYT, 0, iDist );
+            }
+            if ( iPosXR <= iSrchRngHorRight ) // check right
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYT, 0, iDist );
+            }
+          } // check top
+          if ( iPosYB <= iSrchRngVerBottom ) // check bottom
+          {
+            if ( iPosXL >= iSrchRngHorLeft ) // check left
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYB, 0, iDist );
+            }
+            if ( iPosXR <= iSrchRngHorRight ) // check right
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYB, 0, iDist );
+            }
+          } // check bottom
+        } // for ...
+      } // check border
+    } // iDist <= 8
+  } // iDist == 1
+}
+
+//<--
+
+UInt TEncSearch::xPatternRefinement( TComPattern* pcPatternKey,
+                                    TComMv baseRefMv,
+                                    Int iFrac, TComMv& rcMvFrac
+                                   )
+{
+  UInt  uiDist;
+  UInt  uiDistBest  = MAX_UINT;
+  UInt  uiDirecBest = 0;
+  
+  Pel*  piRefPos;
+  Int iRefStride = m_filteredBlock[0][0].getStride();
+#if NS_HAD
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
+#endif
+  
+  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();
+    if ( horVal == 2 && ( verVal & 1 ) == 0 )
+      piRefPos += 1;
+    if ( ( horVal & 1 ) == 0 && verVal == 2 )
+      piRefPos += iRefStride;
+    cMvTest = pcMvRefine[i];
+    cMvTest += rcMvFrac;
+
+    setDistParamComp(0);  // Y component
+
+    m_cDistParam.pCur = piRefPos;
+#if LGE_ILLUCOMP_B0045
+    m_cDistParam.bUseIC = pcPatternKey->getICFlag();
+#endif
+    uiDist = m_cDistParam.DistFunc( &m_cDistParam );
+    uiDist += m_pcRdCost->getCost( cMvTest.getHor(), cMvTest.getVer() );
+    
+    if ( uiDist < uiDistBest )
+    {
+      uiDistBest  = uiDist;
+      uiDirecBest = i;
+    }
+  }
+  
+  rcMvFrac = pcMvRefine[uiDirecBest];
+  
+  return uiDistBest;
+}
+
+Void
+TEncSearch::xEncSubdivCbfQT( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            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, uiFullDepth );
+      }
+    }
+  }
+  
+  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 );
+    }
+  }
+
+  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;
+  }
+  
+  {
+    //===== Cbfs =====
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+    }
+  }
+}
+
+
+Void
+TEncSearch::xEncCoeffQT( TComDataCU*  pcCU,
+                        UInt         uiTrDepth,
+                        UInt         uiAbsPartIdx,
+                        TextType     eTextType,
+                        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 );
+  
+  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 );
+}
+
+
+Void
+TEncSearch::xEncIntraHeader( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            Bool         bLuma,
+                            Bool         bChroma )
+{
+  if( bLuma )
+  {
+    // CU header
+    if( uiAbsPartIdx == 0 )
+    {
+      if( !pcCU->getSlice()->isIntra() )
+      {
+        m_pcEntropyCoder->encodeSkipFlag( pcCU, 0, true );
+        m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+      }
+      
+      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))
+        {
+          return;
+        }
+      }
+    }
+    // luma prediction mode
+    if( pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+    {
+      if( uiAbsPartIdx == 0 )
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, 0 );
+      }
+    }
+    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 if( ( uiAbsPartIdx % uiQNumParts ) == 0 )
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
+      }
+    }
+  }
+  if( bChroma )
+  {
+    // chroma prediction mode
+    if( uiAbsPartIdx == 0 )
+    {
+      m_pcEntropyCoder->encodeIntraDirModeChroma( pcCU, 0, true );
+    }
+  }
+}
+
+
+UInt
+TEncSearch::xGetIntraBitsQT( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            Bool         bLuma,
+                            Bool         bChroma,
+                            Bool         bRealCoeff /* just for test */ )
+{
+  m_pcEntropyCoder->resetBits();
+  xEncIntraHeader ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
+  xEncSubdivCbfQT ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
+  
+  if( bLuma )
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_LUMA,      bRealCoeff );
+  }
+  if( bChroma )
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_U,  bRealCoeff );
+    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, 
+                                Dist&       ruiDist 
+#if LG_ZEROINTRADEPTHRESI_A0087
+                                ,Bool        bZeroResi
+#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 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  ();
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern   ( pcCU, uiTrDepth, uiAbsPartIdx );
+  pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+  
+#if LGE_EDGE_INTRA_A0070
+  if( uiLumaPredMode >= EDGE_INTRA_IDX )
+  {
+#if LGE_EDGE_INTRA_DELTA_DC
+    if( uiLumaPredMode == EDGE_INTRA_DELTA_IDX )
+      xAssignEdgeIntraDeltaDCs( pcCU, uiAbsPartIdx, piOrg, uiStride, piPred, uiWidth, uiHeight );
+#endif
+
+    predIntraLumaEdge( pcCU, pcCU->getPattern(), uiAbsPartIdx, uiWidth, uiHeight, piPred, uiStride
+#if LGE_EDGE_INTRA_DELTA_DC
+     , uiLumaPredMode == EDGE_INTRA_DELTA_IDX
+#endif
+    );
+  }
+  else
+#endif
+  
+  //===== get prediction signal =====
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( uiLumaPredMode >= NUM_INTRA_MODE )
+  {
+    predIntraLumaDMM( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail, true );
+  }
+  else
+  {
+#endif
+  predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  }
+#endif
+  
+  //===== 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;
+    }
+  }
+#if LG_ZEROINTRADEPTHRESI_A0087
+  if(bZeroResi)
+  {
+    Pel* pResi = piResi;
+
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      memset( pResi, 0, sizeof( Pel ) * uiWidth );
+      pResi += uiStride;
+    }
+  }
+#endif
+  
+  //===== transform and quantization =====
+  //--- init rate estimation arrays for RDOQ ---
+  if( m_pcEncCfg->getUseRDOQ() )
+  {
+    m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiWidth, TEXT_LUMA );
+  }
+  //--- transform and quantization ---
+  UInt uiAbsSum = 0;
+  pcCU       ->setTrIdxSubParts ( uiTrDepth, uiAbsPartIdx, uiFullDepth );
+
+  m_pcTrQuant->setQPforQuant    ( pcCU->getQP( 0 ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+#if RDOQ_CHROMA_LAMBDA 
+  m_pcTrQuant->selectLambda     (TEXT_LUMA);  
+#endif
+  m_pcTrQuant->transformNxN     ( pcCU, piResi, uiStride, pcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+                                 pcArlCoeff, 
+#endif
+                                 uiWidth, uiHeight, uiAbsSum, TEXT_LUMA, uiAbsPartIdx );
+  
+  //--- set coded block flag ---
+  pcCU->setCbfSubParts          ( ( uiAbsSum ? 1 : 0 ) << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+  //--- inverse transform ---
+  if( uiAbsSum )
+  {
+    Int scalingListType = 0 + g_eTTable[(Int)TEXT_LUMA];
+    assert(scalingListType < 6);
+#if LOSSLESS_CODING
+    m_pcTrQuant->invtransformNxN( pcCU, TEXT_LUMA,pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType );
+#else
+    m_pcTrQuant->invtransformNxN( TEXT_LUMA,pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType );
+#endif
+  }
+  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 ] = Clip( pPred[ uiX ] + pResi[ uiX ] );
+        pRecQt   [ uiX ] = pReco[ uiX ];
+        pRecIPred[ uiX ] = pReco[ uiX ];
+      }
+      pPred     += uiStride;
+      pResi     += uiStride;
+      pReco     += uiStride;
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+  
+  //===== update distortion =====
+#if HHI_VSO
+  if ( m_pcRdCost->getUseVSO() )
+  {
+#if LGE_WVSO_A0119
+    if ( m_pcRdCost->getUseWVSO() )
+    {    
+      Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+      Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+      Dist iD = (Dist) m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+      Dist iVSO = m_pcRdCost->getDistVS  ( pcCU, uiAbsPartIdx, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, false, 0 );
+      ruiDist += (iDWeight * iD + iVSOWeight * iVSO) / ( iDWeight + iVSOWeight);
+    }
+    else
+#endif
+    {
+      ruiDist += m_pcRdCost->getDistVS  ( pcCU, uiAbsPartIdx, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, false, 0 );
+    }
+  }
+  else
+#endif
+  {
+    ruiDist += m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+  }
+}
+
+
+Void
+TEncSearch::xIntraCodingChromaBlk( TComDataCU* pcCU,
+                                  UInt        uiTrDepth,
+                                  UInt        uiAbsPartIdx,
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  Dist&       ruiDist,
+                                  UInt        uiChromaId )
+{
+  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();
+  
+  //===== update chroma mode =====
+  if( uiChromaPredMode == DM_CHROMA_IDX )
+  {
+    uiChromaPredMode          = pcCU->getLumaIntraDir( 0 );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    mapDMMtoIntraMode( uiChromaPredMode );
+#endif
+  }
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
+
+  if( uiChromaPredMode == LM_CHROMA_IDX && uiChromaId == 0 )
+  {
+    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail, true );
+    getLumaRecPixels( pcCU->getPattern(), uiWidth, uiHeight );
+  }
+  
+  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 =====
+  if( uiChromaPredMode == LM_CHROMA_IDX )
+  {
+    predLMIntraChroma( pcCU->getPattern(), pPatChroma, piPred, uiStride, uiWidth, uiHeight, uiChromaId );
+  }
+  else
+  {
+    predIntraChromaAng( pcCU->getPattern(), pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );  
+  }
+  
+  //===== 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( m_pcEncCfg->getUseRDOQ() )
+    {
+      m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiWidth, eText );
+    }
+    //--- transform and quantization ---
+    UInt uiAbsSum = 0;
+
+    if(eText == TEXT_CHROMA_U)
+    {
+      m_pcTrQuant->setQPforQuant     ( pcCU->getQP( 0 ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset() );
+    }
+    else
+    {
+      m_pcTrQuant->setQPforQuant     ( pcCU->getQP( 0 ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset2nd() );
+    }
+
+#if RDOQ_CHROMA_LAMBDA 
+    m_pcTrQuant->selectLambda      (TEXT_CHROMA);  
+#endif
+    m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+                                     pcArlCoeff, 
+#endif
+                                     uiWidth, uiHeight, uiAbsSum, eText, uiAbsPartIdx );
+    //--- 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 < 6);
+#if LOSSLESS_CODING
+      m_pcTrQuant->invtransformNxN( pcCU, TEXT_CHROMA, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType );
+#else
+      m_pcTrQuant->invtransformNxN( TEXT_CHROMA, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType );
+#endif
+    }
+    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 ] = Clip( pPred[ uiX ] + pResi[ uiX ] );
+        pRecQt   [ uiX ] = pReco[ uiX ];
+        pRecIPred[ uiX ] = pReco[ uiX ];
+      }
+      pPred     += uiStride;
+      pResi     += uiStride;
+      pReco     += uiStride;
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+  
+  //===== update distortion =====
+#if WEIGHTED_CHROMA_DISTORTION
+  ruiDist += m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, true );
+#else
+  ruiDist += m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+#endif
+}
+
+
+
+Void 
+TEncSearch::xRecurIntraCodingQT( TComDataCU*  pcCU, 
+                                UInt         uiTrDepth,
+                                UInt         uiAbsPartIdx, 
+                                Bool         bLumaOnly,
+                                TComYuv*     pcOrgYuv, 
+                                TComYuv*     pcPredYuv, 
+                                TComYuv*     pcResiYuv, 
+                                Dist&        ruiDistY,
+                                Dist&        ruiDistC,
+#if HHI_RQT_INTRA_SPEEDUP
+                                Bool         bCheckFirst,
+#endif
+                                Double&      dRDCost 
+#if LG_ZEROINTRADEPTHRESI_A0087
+                               ,Bool         bZeroResi
+#endif
+                              )
+{
+  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) );
+  
+#if HHI_RQT_INTRA_SPEEDUP
+  if( bCheckFirst && bCheckFull )
+  {
+    bCheckSplit = false;
+  }
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( pcCU->getLumaIntraDir( uiAbsPartIdx ) >= NUM_INTRA_MODE )
+  {
+    bCheckSplit = false;
+  }
+#endif
+#if LGE_EDGE_INTRA_A0070
+  if( pcCU->getLumaIntraDir( uiAbsPartIdx ) >= EDGE_INTRA_IDX )
+  {
+    bCheckSplit = false;
+  }
+#endif
+  Double  dSingleCost   = MAX_DOUBLE;
+  Dist    uiSingleDistY = 0;
+  Dist    uiSingleDistC = 0;
+  UInt    uiSingleCbfY  = 0;
+  UInt    uiSingleCbfU  = 0;
+  UInt    uiSingleCbfV  = 0;
+  
+  if( bCheckFull )
+  {
+    //----- store original entropy coding status -----
+    if( m_bUseSBACRD && bCheckSplit )
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    //----- code luma block with given intra prediction mode and store Cbf-----
+    dSingleCost   = 0.0;
+#if LG_ZEROINTRADEPTHRESI_A0087
+    xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistY, bZeroResi ); 
+#else
+    xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistY ); 
+#endif
+    if( bCheckSplit )
+    {
+      uiSingleCbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth );
+    }
+    //----- code chroma blocks with given intra prediction mode and store Cbf-----
+    if( !bLumaOnly )
+    {
+      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 );
+      }
+    }
+    //----- determine rate and r-d cost -----
+    UInt uiSingleBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
+
+#if HHI_VSO
+    if ( m_pcRdCost->getUseLambdaScaleVSO())
+    {
+      dSingleCost = m_pcRdCost->calcRdCostVSO( uiSingleBits, uiSingleDistY + uiSingleDistC );
+    }
+    else
+#endif
+    {
+    dSingleCost       = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDistY + uiSingleDistC );
+  }
+  }
+  
+  if( bCheckSplit )
+  {
+    //----- store full entropy coding status, load original entropy coding status -----
+    if( m_bUseSBACRD )
+    {
+      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;
+    Dist    uiSplitDistY    = 0;
+    Dist    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 )
+    {
+#if HHI_RQT_INTRA_SPEEDUP
+      xRecurIntraCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiSplitDistY, uiSplitDistC, bCheckFirst, dSplitCost );
+#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 );
+      }
+    }
+    //----- restore context states -----
+    if( m_bUseSBACRD )
+    {
+      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 HHI_VSO
+    if( m_pcRdCost->getUseLambdaScaleVSO() )
+    {
+      dSplitCost = m_pcRdCost->calcRdCostVSO( uiSplitBits, uiSplitDistY + uiSplitDistC );
+    }
+    else
+#endif
+    {
+    dSplitCost       = m_pcRdCost->calcRdCost( uiSplitBits, uiSplitDistY + uiSplitDistC );
+    }
+    
+    //===== compare and set best =====
+    if( dSplitCost < dSingleCost )
+    {
+      //--- update cost ---
+      ruiDistY += uiSplitDistY;
+      ruiDistC += uiSplitDistC;
+      dRDCost  += dSplitCost;
+      return;
+    }
+    //----- set entropy coding status -----
+    if( m_bUseSBACRD )
+    {
+      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 );
+    if( !bLumaOnly )
+    {
+      pcCU->setCbfSubParts( uiSingleCbfU << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth );
+      pcCU->setCbfSubParts( uiSingleCbfV << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth );
+    }
+    
+    //--- set reconstruction for next intra prediction blocks ---
+    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 HHI_VSO
+  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  ();
+
+    m_pcRdCost->setRenModelData( pcCU, uiAbsPartIdx, piSrc, (Int) uiSrcStride, (Int) uiWidth, (Int) uiHeight );
+  }
+#endif
+
+  ruiDistY += uiSingleDistY;
+  ruiDistC += uiSingleDistC;
+  dRDCost  += dSingleCost;
+}
+
+#if RWTH_SDC_DLT_B0036
+Void TEncSearch::xIntraCodingSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, Bool bResidual )
+{
+  UInt    uiLumaPredMode    = pcCU     ->getLumaIntraDir( uiAbsPartIdx );
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 );
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 );
+  UInt    uiStride          = pcOrgYuv ->getStride  ();
+  Pel*    piOrg             = pcOrgYuv ->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piReco            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  
+  AOF( uiWidth == uiHeight );
+  AOF( uiAbsPartIdx == 0 );
+  AOF( pcCU->getSDCAvailable(uiAbsPartIdx) );
+  AOF( pcCU->getSDCFlag(uiAbsPartIdx) );
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern   ( pcCU, 0, uiAbsPartIdx );
+  pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, 0, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+  
+  //===== get prediction signal =====
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( uiLumaPredMode >= NUM_INTRA_MODE )
+  {
+    predIntraLumaDMM( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail, true );
+  }
+  else
+  {
+#endif
+    predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  }
+#endif
+  
+  // number of segments depends on prediction mode
+  UInt uiNumSegments = 1;  
+  Bool* pbMask = NULL;
+  UInt uiMaskStride = 0;
+  
+  if( uiLumaPredMode == DMM_WEDGE_FULL_IDX || uiLumaPredMode == DMM_WEDGE_PREDDIR_IDX )
+  {
+    Int uiTabIdx = (uiLumaPredMode == DMM_WEDGE_FULL_IDX)?pcCU->getWedgeFullTabIdx(uiAbsPartIdx):pcCU->getWedgePredDirTabIdx(uiAbsPartIdx);
+    
+    WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+    TComWedgelet* pcWedgelet = &(pacWedgeList->at( uiTabIdx ));
+    
+    uiNumSegments = 2;
+    pbMask = pcWedgelet->getPattern();
+    uiMaskStride = pcWedgelet->getStride();
+  }
+  
+  // get DC prediction for each segment
+  Pel apDCPredValues[2];
+  xAnalyzeSegmentsSDC(piPred, uiStride, uiWidth, apDCPredValues, uiNumSegments, pbMask, uiMaskStride );
+  
+  // get original DC for each segment
+  Pel apDCOrigValues[2];
+  xAnalyzeSegmentsSDC(piOrg, uiStride, uiWidth, apDCOrigValues, uiNumSegments, pbMask, uiMaskStride );
+  
+  for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
+  {
+    // remap reconstructed value to valid depth values
+    Pel pDCRec = bResidual?apDCOrigValues[uiSegment]:apDCPredValues[uiSegment];
+    
+    // get residual (idx)
+    Pel pResidualIdx = GetDepthValue2Idx( pDCRec ) - GetDepthValue2Idx( apDCPredValues[uiSegment] );
+    
+    // save SDC DC offset
+    pcCU->setSDCSegmentDCOffset(pResidualIdx, uiSegment, uiAbsPartIdx);
+  }
+  
+  // reconstruct residual based on mask + DC residuals
+  Pel apDCResiValues[2];
+  //Pel apDCRecoValues[2];
+  for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
+  {
+    Pel   pPredIdx    = GetDepthValue2Idx( apDCPredValues[uiSegment] );
+    Pel   pResiIdx    = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+    Pel   pRecoValue  = GetIdx2DepthValue( pPredIdx + pResiIdx );
+    
+    //apDCRecoValues[uiSegment]  = pRecoValue;
+    apDCResiValues[uiSegment]  = pRecoValue - apDCPredValues[uiSegment];
+  }
+  
+  //===== reconstruction =====
+  Bool* pMask     = pbMask;
+  Pel* pPred      = piPred;
+  Pel* pReco      = piReco;
+  Pel* pRecIPred  = piRecIPred;
+  
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      UChar ucSegment = pMask?(UChar)pMask[uiX]:0;
+      assert( ucSegment < uiNumSegments );
+      
+      Pel pPredVal= apDCPredValues[ucSegment];
+      Pel pResiDC = apDCResiValues[ucSegment];
+      
+      pReco    [ uiX ] = Clip( pPredVal + pResiDC );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+    pMask     += uiMaskStride;
+  }
+  
+  // clear UV
+  UInt  uiStrideC     = pcPredYuv->getCStride();
+  Pel   *pRecCb       = pcPredYuv->getCbAddr();
+  Pel   *pRecCr       = pcPredYuv->getCrAddr();
+  
+  for (Int y=0; y<uiHeight/2; y++)
+  {
+    for (Int x=0; x<uiWidth/2; x++)
+    {
+      pRecCb[x] = (Pel)(128<<g_uiBitIncrement);
+      pRecCr[x] = (Pel)(128<<g_uiBitIncrement);
+    }
+    
+    pRecCb += uiStrideC;
+    pRecCr += uiStrideC;
+  }
+  
+  //===== determine distortion =====
+#if HHI_VSO
+  if ( m_pcRdCost->getUseVSO() )
+  {
+    ruiDist = m_pcRdCost->getDistVS  ( pcCU, uiAbsPartIdx, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, false, 0 );
+  }
+  else
+#endif
+  {
+    ruiDist = m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+  }
+  
+  //----- determine rate and r-d cost -----
+  m_pcEntropyCoder->resetBits();
+
+  // encode reduced intra header
+  m_pcEntropyCoder->encodeSkipFlag( pcCU, 0, true );
+  m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+  
+  // encode pred direction + residual data
+  m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+  
+  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+  
+#if HHI_VSO
+  if ( m_pcRdCost->getUseLambdaScaleVSO())
+  {
+    dRDCost = m_pcRdCost->calcRdCostVSO( uiBits, ruiDist );
+  }
+  else
+#endif
+  {
+    dRDCost = m_pcRdCost->calcRdCost( uiBits, ruiDist );
+  }
+}
+#endif
+
+Void
+TEncSearch::xSetIntraResultQT( TComDataCU* pcCU,
+                              UInt        uiTrDepth,
+                              UInt        uiAbsPartIdx,
+                              Bool        bLumaOnly,
+                              TComYuv*    pcRecoYuv )
+{
+  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 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 );
+#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 );
+#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 );
+    }
+  }
+}
+
+
+
+Void 
+TEncSearch::xRecurIntraChromaCodingQT( TComDataCU*  pcCU, 
+                                      UInt         uiTrDepth,
+                                      UInt         uiAbsPartIdx, 
+                                      TComYuv*     pcOrgYuv, 
+                                      TComYuv*     pcPredYuv, 
+                                      TComYuv*     pcResiYuv, 
+                                      Dist&        ruiDist )
+{
+  UInt uiFullDepth = pcCU->getDepth( 0 ) +  uiTrDepth;
+  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 0 ); 
+    xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 1 ); 
+  }
+  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 );
+    }
+  }
+}
+
+Void
+TEncSearch::xSetIntraResultChromaQT( TComDataCU* pcCU,
+                                    UInt        uiTrDepth,
+                                    UInt        uiAbsPartIdx,
+                                    TComYuv*    pcRecoYuv )
+{
+  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 );
+      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
+    
+    //===== copy reconstruction =====
+    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++ )
+    {
+      xSetIntraResultChromaQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv );
+    }
+  }
+}
+
+
+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( pcCU->getPattern(), pPatChromaU, uiMode, piPredU, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+    predIntraChromaAng( pcCU->getPattern(), pPatChromaV, uiMode, piPredV, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+    
+    //--- get SAD ---
+    UInt  uiSAD  = m_pcRdCost->calcHAD( piOrgU, uiStride, piPredU, uiStride, uiWidth, uiHeight );
+    uiSAD       += m_pcRdCost->calcHAD( 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 ) );
+}
+
+Void 
+TEncSearch::estIntraPredQT( TComDataCU* pcCU, 
+                           TComYuv*    pcOrgYuv, 
+                           TComYuv*    pcPredYuv, 
+                           TComYuv*    pcResiYuv, 
+                           TComYuv*    pcRecoYuv,
+                           Dist&       ruiDistC,
+                           Bool        bLumaOnly )
+{
+  UInt    uiDepth        = pcCU->getDepth(0);
+  UInt    uiNumPU        = pcCU->getNumPartInter();
+  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);
+  Dist    uiOverallDistY = 0;
+  Dist    uiOverallDistC = 0;
+  UInt    CandNum;
+  Double  CandCostList[ FAST_UDI_MAX_RDMODE_NUM ];
+  
+  //===== set QP and clear Cbf =====
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() == true)
+  {
+    pcCU->setQPSubParts( pcCU->getQP(0), 0, uiDepth );
+  }
+  else
+  {
+    pcCU->setQPSubParts( pcCU->getSlice()->getSliceQp(), 0, uiDepth );
+  }
+  
+  //===== loop over partitions =====
+  UInt uiPartOffset = 0;
+  for( UInt uiPU = 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 );
+    
+    //===== 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 ];
+    
+#if LGE_EDGE_INTRA_A0070
+  Bool bTestEdgeIntra = false;
+  if ( m_pcEncCfg->isDepthCoder() && uiWidth >= LGE_EDGE_INTRA_MIN_SIZE && uiWidth <= LGE_EDGE_INTRA_MAX_SIZE && uiWidth == uiHeight )
+  {
+    bTestEdgeIntra = true;
+
+    Bool bEdgeExist;
+
+    bEdgeExist = xEdgePartition( pcCU, uiPartOffset, pcCU->getPartitionSize(0) == SIZE_NxN );
+
+    if( !bEdgeExist )
+      bTestEdgeIntra = false;
+  }
+#endif
+    
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    Bool bTestDmm = ( m_pcEncCfg->getUseDMM() );
+#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, pcCU, bAboveAvail, bLeftAvail );
+
+        // use hadamard transform here
+        Dist uiSad;
+#if HHI_VSO
+        if ( m_pcRdCost->getUseVSO() )
+        {
+#if SAIT_VSO_EST_A0033
+          if ( m_pcRdCost->getUseEstimatedVSD() )
+          {          
+            TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+            TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+
+            uiSad = (Dist) ( m_pcRdCost->getDistPart( piPred, uiStride, piOrg, uiStride, pcVirRec->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiPartOffset), pcVirOrg->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiPartOffset), pcVirRec->getStride(), uiWidth, uiHeight ) );
+#if LGE_WVSO_A0119
+            if ( m_pcRdCost->getUseWVSO() )
+            {    
+              Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+              Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+              Dist iD = (Dist) m_pcRdCost->calcHAD( piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+              uiSad = (Dist) (iDWeight * iD + iVSDWeight * uiSad) / (iDWeight + iVSDWeight);
+            }
+#endif
+          }
+          else
+#endif
+          {          
+            Bool bSad = !m_pcRdCost->getUseRenModel();
+            uiSad = m_pcRdCost->getDistVS(pcCU, uiPartOffset, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, bSad, 0 );
+#if LGE_WVSO_A0119
+            if ( m_pcRdCost->getUseWVSO() )
+            {    
+              Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+              Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getDWeight();
+              Dist iD = (Dist) m_pcRdCost->calcHAD( piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+              uiSad = (Dist) (iDWeight * iD + iVSOWeight * uiSad) / (iDWeight + iVSOWeight);
+            }
+#endif
+          }
+        }
+        else
+#endif
+        {
+          uiSad = (Dist) m_pcRdCost->calcHAD( piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+        }
+
+        UInt   iModeBits = xModeBitsIntra( pcCU, uiMode, uiPU, uiPartOffset, uiDepth, uiInitTrDepth );
+
+        Double dLambda;
+#if HHI_VSO
+        if ( m_pcRdCost->getUseLambdaScaleVSO() )
+        {
+          dLambda = m_pcRdCost->getUseRenModel() ? m_pcRdCost->getLambdaVSO() : m_pcRdCost->getSqrtLambdaVSO();
+          //GT: Sad is SSE for VSO4
+        }
+        else
+        {
+          dLambda = m_pcRdCost->getSqrtLambda();
+        }
+#else
+        dLambda = m_pcRdCost->getSqrtLambda();
+#endif
+
+        Double cost = (Double)uiSad + (Double)iModeBits *  dLambda;
+
+        CandNum += xUpdateCandList( uiMode, cost, numModesForFullRD, uiRdModeList, CandCostList );
+
+#if LGE_EDGE_INTRA_A0070
+        if ( bTestEdgeIntra ) bTestEdgeIntra = uiSad ? true : false;
+#endif
+      }
+    
+#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
+    {
+      for( Int i=0; i < numModesForFullRD; i++)
+      {
+        uiRdModeList[i] = i;
+      }
+    }
+    
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    if( m_pcEncCfg->getUseDMM() && bTestDmm && uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE && uiWidth == uiHeight )
+    {
+#if HHI_DMM_WEDGE_INTRA
+      UInt uiTabIdx  = 0;
+      Int  iDeltaDC1 = 0;
+      Int  iDeltaDC2 = 0;
+      findWedgeFullMinDist( pcCU, uiPartOffset, piOrg, piPred, uiStride, uiWidth, uiHeight, uiTabIdx, iDeltaDC1, iDeltaDC2, bAboveAvail, bLeftAvail );
+      pcCU->setWedgeFullTabIdxSubParts  ( uiTabIdx,  uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setWedgeFullDeltaDC1SubParts( iDeltaDC1, uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setWedgeFullDeltaDC2SubParts( iDeltaDC2, uiPartOffset, uiDepth + uiInitTrDepth );
+
+      uiRdModeList[ numModesForFullRD++ ] = DMM_WEDGE_FULL_IDX;
+      uiRdModeList[ numModesForFullRD++ ] = DMM_WEDGE_FULL_D_IDX;
+
+      if ( uiWidth > 4 )
+      {
+        Int  iWedgeDeltaEnd = 0;
+
+        iDeltaDC1 = 0;
+        iDeltaDC2 = 0;
+
+        findWedgePredDirMinDist( pcCU, uiPartOffset, piOrg, piPred, uiStride, uiWidth, uiHeight, uiTabIdx, iWedgeDeltaEnd, iDeltaDC1, iDeltaDC2, bAboveAvail, bLeftAvail );
+        pcCU->setWedgePredDirTabIdxSubParts  ( uiTabIdx,       uiPartOffset, uiDepth + uiInitTrDepth );
+        pcCU->setWedgePredDirDeltaEndSubParts( iWedgeDeltaEnd, uiPartOffset, uiDepth + uiInitTrDepth );
+        pcCU->setWedgePredDirDeltaDC1SubParts( iDeltaDC1,      uiPartOffset, uiDepth + uiInitTrDepth );
+        pcCU->setWedgePredDirDeltaDC2SubParts( iDeltaDC2,      uiPartOffset, uiDepth + uiInitTrDepth );
+
+        uiRdModeList[ numModesForFullRD++ ] = DMM_WEDGE_PREDDIR_IDX;
+        uiRdModeList[ numModesForFullRD++ ] = DMM_WEDGE_PREDDIR_D_IDX;
+      }
+#endif
+#if HHI_DMM_PRED_TEX
+      
+#if FLEX_CODING_ORDER_M23723
+      if ( pcCU->getSlice()->getSPS()->getUseDMM34() )
+      {
+#endif
+      UInt uiTexTabIdx  = 0;
+      Int  iTexDeltaDC1 = 0;
+      Int  iTexDeltaDC2 = 0;
+#if LGE_DMM3_SIMP_C0044
+      UInt uiTexIntraIdx = 0;
+      findWedgeTexMinDist( pcCU, uiPartOffset, piOrg, piPred, uiStride, uiWidth, uiHeight, uiTexTabIdx, iTexDeltaDC1, iTexDeltaDC2, bAboveAvail, bLeftAvail, uiTexIntraIdx); 
+      pcCU->setWedgePredTexIntraTabIdxSubParts( uiTexIntraIdx, uiPartOffset, uiDepth + uiInitTrDepth );
+#else
+      findWedgeTexMinDist( pcCU, uiPartOffset, piOrg, piPred, uiStride, uiWidth, uiHeight, uiTexTabIdx, iTexDeltaDC1, iTexDeltaDC2, bAboveAvail, bLeftAvail ); 
+#endif
+      pcCU->setWedgePredTexTabIdxSubParts  ( uiTexTabIdx,  uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setWedgePredTexDeltaDC1SubParts( iTexDeltaDC1, uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setWedgePredTexDeltaDC2SubParts( iTexDeltaDC2, uiPartOffset, uiDepth + uiInitTrDepth );
+
+      uiRdModeList[ numModesForFullRD++ ] = DMM_WEDGE_PREDTEX_IDX;
+      uiRdModeList[ numModesForFullRD++ ] = DMM_WEDGE_PREDTEX_D_IDX;
+
+      if ( uiWidth > 4 )
+      {
+        iTexDeltaDC1 = 0;
+        iTexDeltaDC2 = 0;
+
+        findContourPredTex( pcCU, uiPartOffset, piOrg, piPred, uiStride, uiWidth, uiHeight, iTexDeltaDC1, iTexDeltaDC2, bAboveAvail, bLeftAvail );
+        pcCU->setContourPredTexDeltaDC1SubParts( iTexDeltaDC1, uiPartOffset, uiDepth + uiInitTrDepth );
+        pcCU->setContourPredTexDeltaDC2SubParts( iTexDeltaDC2, uiPartOffset, uiDepth + uiInitTrDepth );
+
+        uiRdModeList[ numModesForFullRD++ ] = DMM_CONTOUR_PREDTEX_IDX;
+        uiRdModeList[ numModesForFullRD++ ] = DMM_CONTOUR_PREDTEX_D_IDX;
+      }
+#if FLEX_CODING_ORDER_M23723
+      }
+#endif
+#endif
+    }
+#endif
+#if LGE_EDGE_INTRA_A0070
+  if( bTestEdgeIntra )
+  {
+    uiRdModeList[ numModesForFullRD++ ] = EDGE_INTRA_IDX;
+#if LGE_EDGE_INTRA_DELTA_DC
+    uiRdModeList[ numModesForFullRD++ ] = EDGE_INTRA_DELTA_IDX;
+#endif
+  }
+#endif
+
+    //===== check modes (using r-d costs) =====
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+    UInt   uiSecondBestMode  = MAX_UINT;
+    Double dSecondBestPUCost = MAX_DOUBLE;
+#endif
+    
+    UInt    uiBestPUMode  = 0;
+    Dist    uiBestPUDistY = 0;
+    Dist    uiBestPUDistC = 0;
+    Double  dBestPUCost   = MAX_DOUBLE;
+#if RWTH_SDC_DLT_B0036
+    Bool    bBestUseSDC   = false;
+    Pel     apBestDCOffsets[2] = {0,0};
+#endif
+    for( UInt uiMode = 0; uiMode < numModesForFullRD; uiMode++ )
+    {
+#if LG_ZEROINTRADEPTHRESI_A0087
+    Bool bAllowZeroResi = pcCU->getSlice()->getIsDepth() && (pcCU->getSlice()->getPOC()%pcCU->getPic()->getIntraPeriod());// && (uiMode < NUM_INTRA_MODE);
+    for(UInt uiCnt = 0; uiCnt < (bAllowZeroResi ? 2 : 1); uiCnt++)
+    {
+      Bool bZeroResi = uiCnt ? true : false;
+#endif
+      // set luma prediction mode
+      UInt uiOrgMode = uiRdModeList[uiMode];
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#if HHI_DMM_PRED_TEX && FLEX_CODING_ORDER_M23723
+      if( m_pcEncCfg->getIsDepth() && !predIntraLumaDMMAvailable( uiOrgMode, uiWidth, uiHeight, pcCU->getSlice()->getSPS()->getUseDMM34() ) 
+#if LGE_EDGE_INTRA_A0070
+        && uiOrgMode < EDGE_INTRA_IDX
+#endif
+        )
+
+#else
+
+      if( m_pcEncCfg->getIsDepth() && !predIntraLumaDMMAvailable( uiOrgMode, uiWidth, uiHeight ) 
+#if LGE_EDGE_INTRA_A0070
+        && uiOrgMode < EDGE_INTRA_IDX
+#endif
+        )
+#endif
+      {
+        continue;
+      }
+#endif
+      
+#if RWTH_SDC_DLT_B0036
+      UInt uiUseSDC = ( m_pcEncCfg->getUseSDC() && pcCU->getPartitionSize(uiPartOffset) == SIZE_2Nx2N )?1:0;
+      
+      for( UInt uiSDC=0; uiSDC<=uiUseSDC; uiSDC++ )
+      {
+        for( UInt uiRes = 0; uiRes<=uiSDC; uiRes++ )
+        {
+#endif
+
+      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+      
+      // set context models
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+      }
+      
+      // determine residual for partition
+      Dist   uiPUDistY = 0;
+      Dist   uiPUDistC = 0;
+      Double dPUCost   = 0.0;
+
+
+      // reset Model
+#if HHI_VSO
+      if( m_pcRdCost->getUseRenModel() )
+      {
+        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight );
+      }
+#endif
+#if RWTH_SDC_DLT_B0036
+          // last check: if not available for current intra prediction mode, don't try
+          if( uiSDC == 1 && !pcCU->getSDCAvailable(uiPartOffset) )
+            continue;
+          
+          pcCU->setSDCFlagSubParts( uiSDC == 1, uiPartOffset, 0, uiDepth + uiInitTrDepth );
+          
+          if(uiSDC == 1)
+          {
+            pcCU->setTrIdxSubParts(0, uiPartOffset, uiDepth + uiInitTrDepth);
+            pcCU->setCbfSubParts(1, 1, 1, uiPartOffset, uiDepth + uiInitTrDepth);
+            
+            // start encoding with SDC
+            xIntraCodingSDC(pcCU, uiPartOffset, pcOrgYuv, pcPredYuv, uiPUDistY, dPUCost, (uiRes==1));
+          }
+          else
+          {
+#endif
+#if HHI_RQT_INTRA_SPEEDUP
+#if LG_ZEROINTRADEPTHRESI_A0087
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, true, dPUCost, bZeroResi );
+#else
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, true, dPUCost );
+#endif
+#else
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, dPUCost );
+#endif
+#if RWTH_SDC_DLT_B0036
+          }
+#endif
+      
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+        uiSecondBestMode  = uiBestPUMode;
+        dSecondBestPUCost = dBestPUCost;
+#endif
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        uiBestPUDistC = uiPUDistC;
+        dBestPUCost   = dPUCost;
+        
+#if RWTH_SDC_DLT_B0036
+        if( uiSDC == 1 )
+        {
+          bBestUseSDC = true;
+          
+          // copy reconstruction
+          pcPredYuv->copyPartToPartYuv(pcRecoYuv, uiPartOffset, uiWidth, uiHeight);
+          
+          // copy DC values
+          apBestDCOffsets[0] = pcCU->getSDCSegmentDCOffset(0, uiPartOffset);
+          apBestDCOffsets[1] = pcCU->getSDCSegmentDCOffset(1, uiPartOffset);
+        }
+        else
+        {
+          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 ) );
+#if RWTH_SDC_DLT_B0036
+        }
+#endif
+      }
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+      else if( dPUCost < dSecondBestPUCost )
+      {
+        uiSecondBestMode  = uiOrgMode;
+        dSecondBestPUCost = dPUCost;
+      }
+#endif
+#if LG_ZEROINTRADEPTHRESI_A0087
+    }
+#endif
+#if RWTH_SDC_DLT_B0036
+      } // SDC residual loop
+    } // SDC loop
+#endif
+    } // Mode loop
+    
+#if HHI_RQT_INTRA_SPEEDUP
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+    for( UInt ui =0; ui < 2; ++ui )
+#endif
+    {
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+      UInt uiOrgMode   = ui ? uiSecondBestMode  : uiBestPUMode;
+      if( uiOrgMode == MAX_UINT )
+      {
+        break;
+      }
+#else
+      UInt uiOrgMode = uiBestPUMode;
+#endif
+      
+      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+      
+      // set context models
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+      }
+      
+      // determine residual for partition
+      Dist   uiPUDistY = 0;
+      Dist   uiPUDistC = 0;
+      Double dPUCost   = 0.0;
+
+#if HHI_VSO
+      // 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 );
+      
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        uiBestPUDistC = uiPUDistC;
+        dBestPUCost   = dPUCost;
+#if RWTH_SDC_DLT_B0036
+        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 ) );
+        
+      }
+    } // Mode loop
+#endif
+    
+    //--- update overall distortion ---
+    uiOverallDistY += uiBestPUDistY;
+    uiOverallDistC += uiBestPUDistC;
+    
+#if RWTH_SDC_DLT_B0036
+    if( bBestUseSDC )
+    {
+      pcCU->setTrIdxSubParts(0, uiPartOffset, uiDepth + uiInitTrDepth);
+      pcCU->setCbfSubParts(1, 1, 1, uiPartOffset, uiDepth + uiInitTrDepth);
+      
+      //=== copy best DC segment values back to CU ====
+      pcCU->setSDCSegmentDCOffset(apBestDCOffsets[0], 0, uiPartOffset);
+      pcCU->setSDCSegmentDCOffset(apBestDCOffsets[1], 1, uiPartOffset);
+    }
+    else
+    {
+#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 ) );
+#if RWTH_SDC_DLT_B0036
+    }
+#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();
+      for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+      {
+        for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+        {
+          piDes[ uiX ] = piSrc[ uiX ];
+        }
+      }
+
+#if HHI_VSO
+      // 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 ];
+          }
+        }
+      }
+    }
+    
+    //=== update PU data ====
+    pcCU->setLumaIntraDirSubParts     ( uiBestPUMode, uiPartOffset, uiDepth + uiInitTrDepth );
+#if RWTH_SDC_DLT_B0036
+    pcCU->setSDCFlagSubParts          ( bBestUseSDC, uiPartOffset, 0, uiDepth + uiInitTrDepth );
+#endif
+    pcCU->copyToPic                   ( uiDepth, uiPU, uiInitTrDepth );
+  } // PU loop
+  
+  
+  if( uiNumPU > 1 )
+  { // set Cbf for all blocks
+    UInt uiCombCbfY = 0;
+    UInt uiCombCbfU = 0;
+    UInt uiCombCbfV = 0;
+    UInt uiPartIdx  = 0;
+    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 );
+    }
+    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;
+    }
+  }
+  
+  //===== reset context models =====
+  if(m_bUseSBACRD)
+  {
+    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;
+}
+
+
+
+Void 
+TEncSearch::estIntraPredChromaQT( TComDataCU* pcCU, 
+                                 TComYuv*    pcOrgYuv, 
+                                 TComYuv*    pcPredYuv, 
+                                 TComYuv*    pcResiYuv, 
+                                 TComYuv*    pcRecoYuv,
+                                 Dist        uiPreCalcDistC )
+{
+  UInt    uiDepth     = pcCU->getDepth(0);
+  UInt    uiBestMode  = 0;
+  Dist    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++ )
+  {
+    if ( !pcCU->getSlice()->getSPS()->getUseLMChroma() && uiModeList[uiMode] == LM_CHROMA_IDX )
+    {
+      continue;
+    }
+    //----- restore context models -----
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+    }
+    
+    //----- chroma coding -----
+    Dist    uiDist = 0;
+    pcCU->setChromIntraDirSubParts  ( uiModeList[uiMode], 0, uiDepth );
+    xRecurIntraChromaCodingQT       ( pcCU,   0, 0, pcOrgYuv, pcPredYuv, pcResiYuv, uiDist );
+    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 ) );
+    }
+  }
+  
+  //----- 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 ) );
+  pcCU->setChromIntraDirSubParts( uiBestMode, 0, uiDepth );
+  pcCU->getTotalDistortion      () += uiBestDist - uiPreCalcDistC;
+  
+  //----- restore context models -----
+  if( m_bUseSBACRD )
+  {
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][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 uiStride stride of the original/prediction/residual sample arrays
+ * \param uiWidth block width
+ * \param uiHeight block height
+ * \param ttText texture component type
+ * \returns Void
+ */
+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 )
+{
+  UInt uiX, uiY;
+  UInt uiReconStride;
+  Pel* pOrg  = piOrg;
+  Pel* pPCM  = piPCM;
+  Pel* pPred = piPred;
+  Pel* pResi = piResi;
+  Pel* pReco = piReco;
+  Pel* pRecoPic;
+  UInt uiInternalBitDepth = g_uiBitDepth + g_uiBitIncrement;
+  UInt uiPCMBitDepth;
+
+  if( eText == TEXT_LUMA)
+  {
+    uiReconStride = pcCU->getPic()->getPicYuvRec()->getStride();
+    pRecoPic      = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
+    uiPCMBitDepth = 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);
+    }
+    uiPCMBitDepth = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+  }
+
+  // Reset pred and residual
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pPred[uiX] = 0;
+      pResi[uiX] = 0;
+    }
+    pPred += uiStride;
+    pResi += uiStride;
+  }
+
+  // Encode
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pPCM[uiX] = (pOrg[uiX]>>(uiInternalBitDepth - uiPCMBitDepth));
+    }
+    pPCM += uiWidth;
+    pOrg += uiStride;
+  }
+
+  pPCM  = piPCM;
+
+  // Reconstruction
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pReco   [uiX] = (pPCM[uiX]<<(uiInternalBitDepth - uiPCMBitDepth));
+      pRecoPic[uiX] = pReco[uiX];
+    }
+    pPCM += uiWidth;
+    pReco += uiStride;
+    pRecoPic += uiReconStride;
+  }
+}
+
+/**  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 )
+{
+  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;
+  Dist   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 );
+
+  m_pcEntropyCoder->resetBits();
+  xEncIntraHeader ( pcCU, uiDepth, uiAbsPartIdx, true, false);
+  uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseLambdaScaleVSO() )
+  {
+    dCost =  m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );
+  }
+  else
+#endif
+  {
+  dCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+  }
+
+  if(m_bUseSBACRD)
+  {
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+  }
+
+  pcCU->getTotalBits()       = uiBits;
+  pcCU->getTotalCost()       = dCost;
+  pcCU->getTotalDistortion() = uiDistortion;
+
+  pcCU->copyToPic(uiDepth, 0, 0);
+}
+
+Void TEncSearch::xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, UInt& ruiErr, Bool bHadamard )
+{
+#if !MERL_VSP_C0152
+  motionCompensation( pcCU, &m_tmpYuvPred, REF_PIC_LIST_X, iPartIdx );
+#endif
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0;
+  pcCU->getPartIndexAndSize( iPartIdx, uiAbsPartIdx, iWidth, iHeight );
+#if MERL_VSP_C0152
+  motionCompensation( pcCU, &m_tmpYuvPred,  pcCU->getZorderIdxInCU(), REF_PIC_LIST_X, iPartIdx );
+#endif
+  DistParam cDistParam;
+
+  cDistParam.bApplyWeight = false;
+
+  m_pcRdCost->setDistParam( cDistParam, 
+                            pcYuvOrg->getLumaAddr( uiAbsPartIdx ), pcYuvOrg->getStride(), 
+                            m_tmpYuvPred .getLumaAddr( uiAbsPartIdx ), m_tmpYuvPred .getStride(), 
+#if NS_HAD
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME() );
+#endif
+#if LGE_ILLUCOMP_B0045
+  cDistParam.bUseIC = 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
+#if CU_BASED_MRG_CAND_LIST
+                                 , TComMvField* cMvFieldNeighbours,  
+                                 UChar* uhInterDirNeighbours,
+                                 Int& numValidMergeCand
+#endif
+#if MERL_VSP_C0152
+                                 , Int* iVSPIndexTrue
+#endif
+                                 )
+{
+#if !CU_BASED_MRG_CAND_LIST
+#if H3D_IVMP
+  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+  Int numValidMergeCand = 0;
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS_MEM; ++ui )
+#else
+  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  Int numValidMergeCand = 0;
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+#endif
+  {
+    uhInterDirNeighbours[ui] = 0;
+  }
+#endif
+
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0; 
+
+  pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
+  UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
+#if CU_BASED_MRG_CAND_LIST
+  PartSize partSize = pcCU->getPartitionSize( 0 );
+  if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && partSize != SIZE_2Nx2N && pcCU->getWidth( 0 ) <= 8 )
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+    if ( iPUIdx == 0 )
+    {
+      pcCU->getInterMergeCandidates( 0, 0, uiDepth, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+    }
+    pcCU->setPartSizeSubParts( partSize, 0, uiDepth );
+  }
+  else
+  {
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+  }
+#else
+#if MERL_VSP_C0152
+  pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, uiDepth, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand, iVSPIndexTrue );
+#else
+  pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, uiDepth, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+#endif
+#endif
+
+
+#if H3D_IVMP
+  const int maxNumMergeCand = MRG_MAX_NUM_CANDS_SIGNALED + ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() ? 1 : 0 );
+#endif
+  ruiCost = MAX_UINT;
+  for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+  {
+    {
+      UInt uiCostCand = MAX_UINT;
+      UInt uiBitsCand = 0;
+      
+      PartSize ePartSize = pcCU->getPartitionSize( 0 );
+
+      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 MERL_VSP_C0152
+      {
+        Int iVSPIdx = 0;
+        Int numVSPIdx;
+        numVSPIdx = 3;
+        for (Int i = 0; i < numVSPIdx; i++)
+        {
+          if (iVSPIndexTrue[i] == uiMergeCand)
+            {
+              iVSPIdx = i+1;
+              break;
+            }
+        }
+        pcCU->setVSPIndexSubParts( iVSPIdx, uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx ) );
+      }
+#endif
+      xGetInterPredictionError( pcCU, pcYuvOrg, iPUIdx, uiCostCand, m_pcEncCfg->getUseHADME() );
+      uiBitsCand = uiMergeCand + 1;
+#if H3D_IVMP
+      if (uiMergeCand == maxNumMergeCand - 1 )
+#else
+      if (uiMergeCand == MRG_MAX_NUM_CANDS_SIGNALED -1)
+#endif
+      {
+         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;
+      }
+    }
+  }
+}
+
+/** search of the best candidate for inter prediction
+ * \param pcCU
+ * \param pcOrgYuv
+ * \param rpcPredYuv
+ * \param rpcResiYuv
+ * \param rpcRecoYuv
+ * \param bUseRes
+ * \returns Void
+ */
+#if AMP_MRG
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes, Bool bUseMRG)
+#else
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes )
+#endif
+{
+  m_acYuvPred[0].clear();
+  m_acYuvPred[1].clear();
+  m_cYuvPredTemp.clear();
+  rpcPredYuv->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->getNumPartInter();
+  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
+
+#if CU_BASED_MRG_CAND_LIST
+#if H3D_IVMP
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+  Int numValidMergeCand = 0 ;
+#else
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  Int numValidMergeCand = 0 ;
+#endif 
+#endif 
+
+#if H3D_IVMP
+  Int iNumAMVPCands = AMVP_MAX_NUM_CANDS + ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() ? 1 : 0 );
+#endif
+
+  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];
+    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++) uiCostTempL0[iNumRef] = MAX_UINT;
+    UInt          uiBitsTempL0[MAX_NUM_REF];
+    xGetBlkBits( ePartSize, pcCU->getSlice()->isInterP(), iPartIdx, uiLastMode, uiMbBits);
+    
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+#if MERL_VSP_C0152
+    //reset the VSP flag to be 0
+    pcCU->setVSPIndexSubParts( 0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr) );
+#endif
+#if AMP_MRG
+    Bool bTestNormalMC = true;
+    
+    if ( bUseMRG && pcCU->getWidth( 0 ) > 8 && iNumPart == 2 )
+    {
+      bTestNormalMC = false;
+    }
+    
+    if (bTestNormalMC)
+    {
+#endif
+
+    //  Uni-directional prediction
+    for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+    {
+      RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+      
+      for ( Int iRefIdxTemp = 0; iRefIdxTemp < pcCU->getSlice()->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
+      {
+        uiBitsTemp = uiMbBits[iRefList];
+        if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 )
+        {
+          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
+        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)
+        {
+          bestBiPDist = biPDistTemp;
+          bestBiPMvpL1 = aaiMvpIdx[iRefList][iRefIdxTemp];
+          bestBiPRefIdxL1 = iRefIdxTemp;
+        }
+
+#if H3D_IVMP
+        uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][iNumAMVPCands];
+#else
+        uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
+#endif
+#if ZERO_MVD_EST
+        if ((iRefList != 1 || !pcCU->getSlice()->getNoBackPredFlag()) &&
+            (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0 || pcCU->getSlice()->getRefIdxOfLC(eRefPicList, 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 ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+        {
+          if ( iRefList && ( pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag() && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)>=0 ) ) )
+            {
+              if ( pcCU->getSlice()->getNoBackPredFlag() )
+              {
+                cMvTemp[1][iRefIdxTemp] = cMvTemp[0][iRefIdxTemp];
+                uiCostTemp = uiCostTempL0[iRefIdxTemp];
+                /*first subtract the bit-rate part of the cost of the other list*/
+                uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[iRefIdxTemp] );
+              }
+              else
+              {
+                cMvTemp[1][iRefIdxTemp] = cMvTemp[0][pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)]; 
+                uiCostTemp = uiCostTempL0[pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)];
+                /*first subtract the bit-rate part of the cost of the other list*/
+                uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)] );
+              }
+              /*correct the bit-rate part of the current ref*/
+              m_pcRdCost->setPredictor  ( cMvPred[iRefList][iRefIdxTemp] );
+              uiBitsTemp += m_pcRdCost->getBits( cMvTemp[1][iRefIdxTemp].getHor(), cMvTemp[1][iRefIdxTemp].getVer() );
+              /*calculate the correct cost*/
+              uiCostTemp += m_pcRdCost->getCost( uiBitsTemp );
+            }
+            else
+            {
+              xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+            }
+        }
+        else
+        {
+          if (iRefList && pcCU->getSlice()->getNoBackPredFlag())
+          {
+            uiCostTemp = MAX_UINT;
+            cMvTemp[1][iRefIdxTemp] = cMvTemp[0][iRefIdxTemp];
+          }
+          else
+          { 
+            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 )
+        if ( pcCU->getAMVPMode(uiPartAddr) == AM_EXPL )
+        {          
+          xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
+        }
+
+        if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag())
+        {
+          if(iRefList==REF_PIC_LIST_0)
+          {
+            uiCostTempL0[iRefIdxTemp] = uiCostTemp;
+            uiBitsTempL0[iRefIdxTemp] = uiBitsTemp;
+            if(pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, iRefIdxTemp)<0)
+            {
+              uiCostTemp = MAX_UINT;
+            }
+          }
+          else
+          {
+            if(pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, iRefIdxTemp)<0)
+            {
+              uiCostTemp = MAX_UINT;
+            }           
+          }
+        }
+
+        if ( ( iRefList == 0 && uiCostTemp < uiCost[iRefList] ) ||
+            ( iRefList == 1 &&  pcCU->getSlice()->getNoBackPredFlag() && iRefIdxTemp == iRefIdx[0] ) ||
+            ( iRefList == 1 && (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0) && (iRefIdxTemp==0 || iRefIdxTemp == iRefIdx[0]) && !pcCU->getSlice()->getNoBackPredFlag() && (iRefIdxTemp == pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)) ) ||
+            ( iRefList == 1 && !pcCU->getSlice()->getNoBackPredFlag() && uiCostTemp < uiCost[iRefList] ) )
+          {
+            uiCost[iRefList] = uiCostTemp;
+            uiBits[iRefList] = uiBitsTemp; // storing for bi-prediction
+            
+            // set motion
+            cMv[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
+            iRefIdx[iRefList] = iRefIdxTemp;
+            pcCU->getCUMvField(eRefPicList)->setAllMv( cMv[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField(eRefPicList)->setAllRefIdx( iRefIdx[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+
+            if(!pcCU->getSlice()->getMvdL1ZeroFlag())
+            {
+              // storing list 1 prediction signal for iterative bi-directional prediction
+              if ( eRefPicList == REF_PIC_LIST_1 )
+              {
+                TComYuv*  pcYuvPred = &m_acYuvPred[iRefList];
+#if MERL_VSP_C0152
+                motionCompensation ( pcCU, pcYuvPred, pcCU->getZorderIdxInCU(),  eRefPicList, iPartIdx );
+#else
+                motionCompensation ( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+#endif
+              }
+              if ( (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) && eRefPicList == REF_PIC_LIST_0 )
+              {
+                TComYuv*  pcYuvPred = &m_acYuvPred[iRefList];
+#if MERL_VSP_C0152
+                motionCompensation ( pcCU, pcYuvPred, pcCU->getZorderIdxInCU(),  eRefPicList, iPartIdx );
+#else
+                motionCompensation ( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+#endif
+              }
+            }
+          }
+      }
+    }
+    //  Bi-directional prediction
+    if ( pcCU->getSlice()->isInterB() )
+    {
+      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];
+
+      if(pcCU->getSlice()->getMvdL1ZeroFlag())
+      {
+        xCopyAMVPInfo(&aacAMVPInfo[1][bestBiPRefIdxL1], pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo());
+        pcCU->setMVPIdxSubParts( bestBiPMvpL1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        aaiMvpIdxBi[1][bestBiPRefIdxL1] = bestBiPMvpL1;
+        cMvPredBi[1][bestBiPRefIdxL1]   = pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo()->m_acMvCand[bestBiPMvpL1];
+
+        cMvBi[1] = cMvPredBi[1][bestBiPRefIdxL1];
+        iRefIdxBi[1] = bestBiPRefIdxL1;
+        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];
+#if MERL_VSP_C0152
+        motionCompensation( pcCU, pcYuvPred, pcCU->getZorderIdxInCU(),  REF_PIC_LIST_1, iPartIdx );
+#else
+        motionCompensation( pcCU, pcYuvPred, REF_PIC_LIST_1, iPartIdx );
+#endif
+        uiMotBits[0] = uiBits[0] - uiMbBits[0];
+        uiMotBits[1] = uiMbBits[1];
+
+        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1) > 1 )
+        {
+          uiMotBits[1] += bestBiPRefIdxL1+1;
+          if ( bestBiPRefIdxL1 == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1 ) uiMotBits[1]--;
+        }
+
+#if H3D_IVMP
+        uiMotBits[1] += m_auiMVPIdxCost[aaiMvpIdxBi[1][bestBiPRefIdxL1]][iNumAMVPCands];
+#else
+        uiMotBits[1] += m_auiMVPIdxCost[aaiMvpIdxBi[1][bestBiPRefIdxL1]][AMVP_MAX_NUM_CANDS];
+#endif
+
+        uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
+
+        cMvTemp[1][bestBiPRefIdxL1] = cMvBi[1];
+      }
+      else
+      {
+        uiMotBits[0] = uiBits[0] - uiMbBits[0];
+        uiMotBits[1] = uiBits[1] - uiMbBits[1];
+        uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
+      }
+
+      // 4-times iteration (default)
+      Int iNumIter = 4;
+      
+      // fast encoder setting: only one iteration
+      if ( m_pcEncCfg->getUseFastEnc() || pcCU->getSlice()->getMvdL1ZeroFlag())
+      {
+        iNumIter = 1;
+      }
+      
+      for ( Int iIter = 0; iIter < iNumIter; iIter++ )
+      {
+        
+        Int         iRefList    = iIter % 2;
+        if ( m_pcEncCfg->getUseFastEnc() && (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) )
+        {
+          iRefList = 1;
+        }
+        RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+        if(pcCU->getSlice()->getMvdL1ZeroFlag())
+        {
+          iRefList = 0;
+          eRefPicList = REF_PIC_LIST_0;
+        }
+
+        Bool bChanged = false;
+        
+        iRefStart = 0;
+        iRefEnd   = pcCU->getSlice()->getNumRefIdx(eRefPicList)-1;
+        
+        for ( Int iRefIdxTemp = iRefStart; iRefIdxTemp <= iRefEnd; iRefIdxTemp++ )
+        {
+          uiBitsTemp = uiMbBits[2] + uiMotBits[1-iRefList];
+          if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 )
+          {
+            uiBitsTemp += iRefIdxTemp+1;
+            if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
+          }
+#if H3D_IVMP
+          uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdxBi[iRefList][iRefIdxTemp]][iNumAMVPCands];
+#else
+          uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdxBi[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
+#endif
+          // call ME
+          xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPredBi[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp, true );
+          if ( pcCU->getAMVPMode(uiPartAddr) == AM_EXPL )
+          {
+            xCopyAMVPInfo(&aacAMVPInfo[iRefList][iRefIdxTemp], pcCU->getCUMvField(eRefPicList)->getAMVPInfo());
+            xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPredBi[iRefList][iRefIdxTemp], aaiMvpIdxBi[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
+          }
+
+          if ( uiCostTemp < uiCostBi )
+          {
+            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)
+            {
+              //  Set motion
+              pcCU->getCUMvField( eRefPicList )->setAllMv( cMvBi[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+              pcCU->getCUMvField( eRefPicList )->setAllRefIdx( iRefIdxBi[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+
+              TComYuv* pcYuvPred = &m_acYuvPred[iRefList];
+#if MERL_VSP_C0152
+              motionCompensation( pcCU, pcYuvPred, pcCU->getZorderIdxInCU(),  REF_PIC_LIST_1, iPartIdx );
+#else
+              motionCompensation( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+#endif
+            }
+          }
+        } // for loop-iRefIdxTemp
+        
+        if ( !bChanged )
+        {
+          if ( uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1] && pcCU->getAMVPMode(uiPartAddr) == AM_EXPL )
+          {
+            xCopyAMVPInfo(&aacAMVPInfo[0][iRefIdxBi[0]], pcCU->getCUMvField(REF_PIC_LIST_0)->getAMVPInfo());
+            xCheckBestMVP(pcCU, REF_PIC_LIST_0, cMvBi[0], cMvPredBi[0][iRefIdxBi[0]], aaiMvpIdxBi[0][iRefIdxBi[0]], uiBits[2], uiCostBi);
+            if(!pcCU->getSlice()->getMvdL1ZeroFlag())
+            {
+              xCopyAMVPInfo(&aacAMVPInfo[1][iRefIdxBi[1]], pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo());
+              xCheckBestMVP(pcCU, REF_PIC_LIST_1, cMvBi[1], cMvPredBi[1][iRefIdxBi[1]], aaiMvpIdxBi[1][iRefIdxBi[1]], uiBits[2], uiCostBi);
+            }
+          }
+          break;
+        }
+      } // for loop-iter
+    } // if (B_SLICE)
+#if ZERO_MVD_EST
+    if ( pcCU->getSlice()->isInterB() )
+    {
+      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
+    } //end if bTestNormalMC
+#endif
+    //  Clear Motion Field
+    pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( TComMvField(), ePartSize, uiPartAddr, 0, iPartIdx );
+    pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( TComMvField(), ePartSize, uiPartAddr, 0, iPartIdx );
+    pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,       ePartSize, uiPartAddr, 0, iPartIdx );
+    pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( cMvZero,       ePartSize, uiPartAddr, 0, iPartIdx );
+
+    pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+    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_
+    if ( pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 ) )
+    {
+      uiCost[1] = MAX_UINT;
+    }
+#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->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));
+      pcCU->setMVPIdxSubParts( aaiMvpIdxBi[1][iRefIdxBi[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[1][iRefIdxBi[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+
+      uiMEBits = uiBits[2];
+    }
+    else if ( uiCost[0] <= uiCost[1] )
+    {
+      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->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));
+
+      uiMEBits = uiBits[0];
+    }
+    else
+    {
+      uiLastMode = 1;
+          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) );
+      
+      pcCU->setMVPIdxSubParts( aaiMvpIdx[1][iRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[1][iRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+
+      uiMEBits = uiBits[1];
+    }
+#if AMP_MRG
+    } // end if bTestNormalMC
+#endif
+
+    if ( pcCU->getPartitionSize( uiPartAddr ) != SIZE_2Nx2N )
+    {
+      UInt uiMRGInterDir = 0;     
+      TComMvField cMRGMvField[2];
+      UInt uiMRGIndex = 0;
+#if MERL_VSP_C0152
+      Int iVSPIndexTrue[3] = {-1, -1, -1};
+#endif
+      UInt uiMEInterDir = 0;
+      TComMvField cMEMvField[2];
+
+      m_pcRdCost->getMotionCost( 1, 0 );
+#if AMP_MRG
+      // calculate ME cost
+      UInt uiMEError = MAX_UINT;
+      UInt uiMECost = MAX_UINT;
+
+      if (bTestNormalMC)
+      {
+        xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
+        uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
+      }
+#else
+      // calculate ME cost
+      UInt uiMEError = MAX_UINT;
+      xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
+      UInt uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
+#endif 
+      // save ME result.
+      uiMEInterDir = pcCU->getInterDir( uiPartAddr );
+      pcCU->getMvField( pcCU, uiPartAddr, REF_PIC_LIST_0, cMEMvField[0] );
+      pcCU->getMvField( pcCU, uiPartAddr, REF_PIC_LIST_1, cMEMvField[1] );
+
+      // find Merge result
+      UInt uiMRGCost = MAX_UINT;
+
+
+xMergeEstimation( pcCU, pcOrgYuv, iPartIdx, uiMRGInterDir, cMRGMvField, uiMRGIndex, uiMRGCost
+#if CU_BASED_MRG_CAND_LIST
+                 , cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand,
+#endif
+#if MERL_VSP_C0152
+                 , iVSPIndexTrue
+#endif
+        );
+
+      if ( uiMRGCost < uiMECost )
+      {
+        // set Merge result
+        pcCU->setMergeFlagSubParts ( true,          uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setMergeIndexSubParts( uiMRGIndex,    uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+#if MERL_VSP_C0152
+        {
+          Int iVSPIdx = 0;
+          Int numVSPIdx;
+          numVSPIdx = 3;
+          for (Int i = 0; i < numVSPIdx; i++)
+          {
+            if (iVSPIndexTrue[i] == uiMRGIndex)
+              {
+                iVSPIdx = i+1;
+                break;
+              }
+          }
+          pcCU->setVSPIndexSubParts( iVSPIdx, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        }
+#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->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
+
+        pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      }
+      else
+      {
+        // set ME result
+        pcCU->setMergeFlagSubParts( false,        uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setInterDirSubParts ( uiMEInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+#if MERL_VSP_C0152
+        pcCU->setVSPIndexSubParts ( 0 ,           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 );
+        }
+      }
+    }
+
+    //  MC
+#if MERL_VSP_C0152
+    motionCompensation ( pcCU, rpcPredYuv, pcCU->getZorderIdxInCU(), REF_PIC_LIST_X, iPartIdx);
+#else
+    motionCompensation ( pcCU, rpcPredYuv, REF_PIC_LIST_X, iPartIdx );
+#endif
+  } //  end of for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
+
+  setWpScalingDistParam( pcCU, -1, REF_PIC_LIST_X );
+
+  return;
+}
+
+// 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
+{
+  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;
+  
+  pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+  // Fill the MV Candidates
+  if (!bFilled)
+  {
+    pcCU->fillMvpCand( uiPartIdx, uiPartAddr, eRefPicList, iRefIdx, pcAMVPInfo );
+  }
+  
+  // initialize Mvp index & Mvp
+  iBestIdx = 0;
+  cBestMv  = pcAMVPInfo->m_acMvCand[0];
+#if !ZERO_MVD_EST
+  if( pcCU->getAMVPMode(uiPartAddr) == AM_NONE || (pcAMVPInfo->iN <= 1 && pcCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+  {
+    rcMvPred = cBestMv;
+    
+    pcCU->setMVPIdxSubParts( iBestIdx, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+
+    if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefPicList==REF_PIC_LIST_1)
+    {
+#if H3D_IVMP
+      Int iNumAMVPCands = AMVP_MAX_NUM_CANDS + ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() ? 1 : 0 );
+#if ZERO_MVD_EST
+      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, iNumAMVPCands, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
+#else
+      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, iNumAMVPCands, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+#endif
+#else
+#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
+#endif
+    }
+    return;
+  }
+#endif  
+  if (pcCU->getAMVPMode(uiPartAddr) == AM_EXPL && bFilled)
+  {
+    assert(pcCU->getMVPIdx(eRefPicList,uiPartAddr) >= 0);
+    rcMvPred = pcAMVPInfo->m_acMvCand[pcCU->getMVPIdx(eRefPicList,uiPartAddr)];
+    return;
+  }
+  
+  if (pcCU->getAMVPMode(uiPartAddr) == AM_EXPL)
+  {
+    m_cYuvPredTemp.clear();
+#if ZERO_MVD_EST
+    UInt uiDist;
+#endif
+    //-- Check Minimum Cost.
+    for ( i = 0 ; i < pcAMVPInfo->iN; i++)
+    {
+      UInt uiTmpCost;
+#if H3D_IVMP
+      Int iNumAMVPCands = AMVP_MAX_NUM_CANDS + ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() ? 1 : 0 );
+#if ZERO_MVD_EST
+      uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, iNumAMVPCands, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
+#else
+      uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, iNumAMVPCands, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+#endif
+#else
+#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      
+#endif
+      if ( uiBestCost > uiTmpCost )
+      {
+        uiBestCost = uiTmpCost;
+        cBestMv   = pcAMVPInfo->m_acMvCand[i];
+        iBestIdx  = i;
+        (*puiDistBiP) = uiTmpCost;
+        #if ZERO_MVD_EST
+        (*puiDist) = uiDist;
+        #endif
+      }
+    }
+    
+    m_cYuvPredTemp.clear();
+  }
+  
+  // Setting Best MVP
+  rcMvPred = cBestMv;
+  pcCU->setMVPIdxSubParts( iBestIdx, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+  pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+  return;
+}
+
+UInt TEncSearch::xGetMvpIdxBits(Int iIdx, Int iNum)
+{
+  assert(iIdx >= 0 && iNum >= 0 && iIdx < iNum);
+  
+  if (iNum == 1)
+    return 0;
+  
+  UInt uiLength = 1;
+  Int iTemp = iIdx;
+  if ( iTemp == 0 )
+  {
+    return uiLength;
+  }
+  
+  Bool bCodeLast = ( iNum-1 > iTemp );
+  
+  uiLength += (iTemp-1);
+  
+  if( bCodeLast )
+  {
+    uiLength++;
+  }
+  
+  return uiLength;
+}
+
+Void TEncSearch::xGetBlkBits( PartSize eCUMode, Bool bPSlice, Int iPartIdx, UInt uiLastMode, UInt uiBlkBit[3])
+{
+  if ( eCUMode == SIZE_2Nx2N )
+  {
+    uiBlkBit[0] = (! bPSlice) ? 3 : 1;
+    uiBlkBit[1] = 3;
+    uiBlkBit[2] = 5;
+  }
+  else if ( (eCUMode == SIZE_2NxN || eCUMode == SIZE_2NxnU) || eCUMode == SIZE_2NxnD )
+  {
+    UInt aauiMbBits[2][3][3] = { { {0,0,3}, {0,0,0}, {0,0,0} } , { {5,7,7}, {7,5,7}, {9-3,9-3,9-3} } };
+    if ( bPSlice )
+    {
+      uiBlkBit[0] = 3;
+      uiBlkBit[1] = 0;
+      uiBlkBit[2] = 0;
+    }
+    else
+    {
+      ::memcpy( uiBlkBit, aauiMbBits[iPartIdx][uiLastMode], 3*sizeof(UInt) );
+    }
+  }
+  else if ( (eCUMode == SIZE_Nx2N || eCUMode == SIZE_nLx2N) || eCUMode == SIZE_nRx2N )
+  {
+    UInt aauiMbBits[2][3][3] = { { {0,2,3}, {0,0,0}, {0,0,0} } , { {5,7,7}, {7-2,7-2,9-2}, {9-3,9-3,9-3} } };
+    if ( bPSlice )
+    {
+      uiBlkBit[0] = 3;
+      uiBlkBit[1] = 0;
+      uiBlkBit[2] = 0;
+    }
+    else
+    {
+      ::memcpy( uiBlkBit, aauiMbBits[iPartIdx][uiLastMode], 3*sizeof(UInt) );
+    }
+  }
+  else if ( eCUMode == SIZE_NxN )
+  {
+    uiBlkBit[0] = (! bPSlice) ? 3 : 1;
+    uiBlkBit[1] = 3;
+    uiBlkBit[2] = 5;
+  }
+  else
+  {
+    printf("Wrong!\n");
+    assert( 0 );
+  }
+}
+
+Void TEncSearch::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
+{
+  pDst->iN = pSrc->iN;
+  for (Int i = 0; i < pSrc->iN; i++)
+  {
+    pDst->m_acMvCand[i] = pSrc->m_acMvCand[i];
+  }
+}
+
+Void TEncSearch::xCheckBestMVP ( TComDataCU* pcCU, RefPicList eRefPicList, TComMv cMv, TComMv& rcMvPred, Int& riMVPIdx, UInt& ruiBits, UInt& ruiCost )
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+  
+  assert(pcAMVPInfo->m_acMvCand[riMVPIdx] == rcMvPred);
+  
+  if (pcAMVPInfo->iN < 2) return;
+  
+  m_pcRdCost->getMotionCost( 1, 0 );
+  m_pcRdCost->setCostScale ( 0    );
+  
+  Int iBestMVPIdx = riMVPIdx;
+  
+#if H3D_IVMP
+  Int iNumAMVPCands = AMVP_MAX_NUM_CANDS + ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() ? 1 : 0 );
+#endif
+  
+  m_pcRdCost->setPredictor( rcMvPred );
+  Int iOrgMvBits  = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+#if H3D_IVMP
+  iOrgMvBits += m_auiMVPIdxCost[riMVPIdx][iNumAMVPCands];
+#else
+  iOrgMvBits += m_auiMVPIdxCost[riMVPIdx][AMVP_MAX_NUM_CANDS];
+#endif
+  Int iBestMvBits = iOrgMvBits;
+  
+  for (Int iMVPIdx = 0; iMVPIdx < pcAMVPInfo->iN; iMVPIdx++)
+  {
+    if (iMVPIdx == riMVPIdx) continue;
+    
+    m_pcRdCost->setPredictor( pcAMVPInfo->m_acMvCand[iMVPIdx] );
+    
+    Int iMvBits = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+#if H3D_IVMP
+    iMvBits += m_auiMVPIdxCost[iMVPIdx][iNumAMVPCands];
+#else
+    iMvBits += m_auiMVPIdxCost[iMVPIdx][AMVP_MAX_NUM_CANDS];
+#endif
+    
+    if (iMvBits < iBestMvBits)
+    {
+      iBestMvBits = iMvBits;
+      iBestMVPIdx = iMVPIdx;
+    }
+  }
+  
+  if (iBestMVPIdx != riMVPIdx)  //if changed
+  {
+    rcMvPred = pcAMVPInfo->m_acMvCand[iBestMVPIdx];
+    
+    riMVPIdx = iBestMVPIdx;
+    UInt uiOrgBits = ruiBits;
+    ruiBits = uiOrgBits - iOrgMvBits + iBestMvBits;
+    ruiCost = (ruiCost - m_pcRdCost->getCost( uiOrgBits ))  + m_pcRdCost->getCost( ruiBits );
+  }
+}
+
+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
+                                  )
+{
+  UInt uiCost  = MAX_INT;
+  
+  TComPicYuv* pcPicYuvRef = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec();
+  
+  pcCU->clipMv( cMvCand );
+
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getIsDepth() )
+    cMvCand <<= 2;
+#endif
+
+#if LGE_ILLUCOMP_B0045
+  Bool bICFlag = pcCU->getICFlag(uiPartAddr) && (pcCU->getSlice()->getViewId() != pcCU->getSlice()->getRefViewId(eRefPicList, iRefIdx));
+#endif
+  // prediction pattern
+  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+  {
+    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, true );
+  }
+  else
+  {
+#if LGE_ILLUCOMP_B0045
+    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, false, bICFlag );
+#else
+    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, false );
+#endif
+  }
+
+  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+  {
+    xWeightedPredictionUni( pcCU, pcTemplateCand, uiPartAddr, iSizeX, iSizeY, eRefPicList, pcTemplateCand, uiPartIdx, iRefIdx );
+  }
+
+  // calc distortion
+#if ZERO_MVD_EST
+  m_pcRdCost->getMotionCost( 1, 0 );
+  DistParam cDistParam;
+  m_pcRdCost->setDistParam( cDistParam, 
+                            pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), 
+                            pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), 
+#if NS_HAD
+                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
+#endif
+  ruiDist = cDistParam.DistFunc( &cDistParam );
+  uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
+#else
+// GT: CONSIDER ADDING VSO HERE
+#if WEIGHTED_CHROMA_DISTORTION
+  uiCost = m_pcRdCost->getDistPart( pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, false, DF_SAD );
+#else
+  uiCost = m_pcRdCost->getDistPart( pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, DF_SAD );
+#endif
+  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  )
+{
+  UInt          uiPartAddr;
+  Int           iRoiWidth;
+  Int           iRoiHeight;
+  
+  TComMv        cMvHalf, cMvQter;
+  TComMv        cMvSrchRngLT;
+  TComMv        cMvSrchRngRB;
+  
+  TComYuv*      pcYuv = pcYuvOrg;
+  m_iSearchRange = m_aaiAdaptSR[eRefPicList][iRefIdxPred];
+
+  Int           iSrchRng      = ( bBi ? m_bipredSearchRange : m_iSearchRange );
+#if DV_V_RESTRICTION_B0037
+  Int           iVerDispSrchRng = m_iVerticalDisparitySearchRange;  
+#endif
+  TComPattern*  pcPatternKey  = pcCU->getPattern        ();
+  
+  Double        fWeight       = 1.0;
+  
+  pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+  
+#if LGE_ILLUCOMP_B0045
+  Bool bICFlag = pcCU->getICFlag(uiPartAddr) && (pcCU->getSlice()->getViewId() != pcCU->getSlice()->getRefViewId(eRefPicList, iRefIdxPred));
+  pcPatternKey->setICFlag(bICFlag);
+#endif
+
+  if ( bBi )
+  {
+    TComYuv*  pcYuvOther = &m_acYuvPred[1-(Int)eRefPicList];
+    pcYuv                = &m_cYuvPredTemp;
+    
+    pcYuvOrg->copyPartToPartYuv( pcYuv, uiPartAddr, iRoiWidth, iRoiHeight );
+    
+    pcYuv->removeHighFreq( pcYuvOther, uiPartAddr, iRoiWidth, iRoiHeight );
+    
+    fWeight = 0.5;
+  }
+  
+  //  Search key pattern initialization
+  pcPatternKey->initPattern( pcYuv->getLumaAddr( uiPartAddr ),
+                            pcYuv->getCbAddr  ( uiPartAddr ),
+                            pcYuv->getCrAddr  ( uiPartAddr ),
+                            iRoiWidth,
+                            iRoiHeight,
+                            pcYuv->getStride(),
+                            0, 0, 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 DV_V_RESTRICTION_B0037
+  Bool bMv_VRng_Restricted = false;
+  if( pcCU->getSlice()->getViewId() > 0 
+      &&
+      pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPOC() == pcCU->getSlice()->getPOC()
+      &&
+      m_bUseDisparitySearchRangeRestriction
+     )
+  {
+      bMv_VRng_Restricted = true;
+  }
+#endif
+
+#if DV_V_RESTRICTION_B0037
+  if ( bBi )  xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB, bMv_VRng_Restricted, iVerDispSrchRng );
+  else        xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB, bMv_VRng_Restricted, iVerDispSrchRng );
+#else
+  if ( bBi )  xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  else        xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+#endif
+
+  m_pcRdCost->getMotionCost ( 1, 0 );
+  
+  m_pcRdCost->setPredictor  ( *pcMvPred );
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getIsDepth() )
+    m_pcRdCost->setCostScale  ( 0 );
+  else
+#endif
+  m_pcRdCost->setCostScale  ( 2 );
+
+#if H3D_IVMP
+  { // init inter-view regularization
+    TComMv  cOrgDepthMapMv;
+    Bool    bMultiviewReg = pcCU->getIViewOrgDepthMvPred( iPartIdx, eRefPicList, iRefIdxPred, cOrgDepthMapMv );
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+    if( bMultiviewReg && pcCU->getSlice()->getSPS()->isDepth() )
+    {
+      cOrgDepthMapMv += TComMv( 2, 2 );
+      cOrgDepthMapMv >>= 2;
+    }
+#endif
+    m_pcRdCost->setMultiviewReg( bMultiviewReg ? &cOrgDepthMapMv : 0 );
+    if( bMultiviewReg && !bBi )
+    {
+#if DV_V_RESTRICTION_B0037
+      xSetSearchRange( pcCU, cOrgDepthMapMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB, bMv_VRng_Restricted, iVerDispSrchRng  );
+#else
+      xSetSearchRange( pcCU, cOrgDepthMapMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+#endif
+    }
+  }
+#endif
+#if QC_MVHEVC_B0046
+  m_pcRdCost->setMultiviewReg( 0 );
+#endif
+
+  setWpScalingDistParam( pcCU, iRefIdxPred, eRefPicList );
+  //  Do integer search
+  if ( !m_iFastSearch || bBi )
+  {
+    xPatternSearch      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+  }
+  else
+  {
+    rcMv = ( m_pcRdCost->useMultiviewReg() ? m_pcRdCost->getMultiviewOrgMvPred() : *pcMvPred );
+    xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+  }
+  
+  m_pcRdCost->getMotionCost( 1, 0 );
+
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( ! pcCU->getSlice()->getIsDepth() )
+  {
+#endif
+  m_pcRdCost->setCostScale ( 1 );
+  
+  {
+    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost
+                          ,bBi
+                          );
+  }
+  
+  
+  
+  m_pcRdCost->setCostScale( 0 );
+  rcMv <<= 2;
+  rcMv += (cMvHalf <<= 1);
+  rcMv +=  cMvQter;
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  }
+#endif
+  
+  UInt uiMvBits = m_pcRdCost->getBits( rcMv.getHor(), rcMv.getVer() );
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  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 ) );
+}
+
+#if DV_V_RESTRICTION_B0037
+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 HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getIsDepth() )
+    iMvShift = 0;
+#endif
+  TComMv cTmpMvPred = cMvPred;
+  pcCU->clipMv( cTmpMvPred );
+
+  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 DV_V_RESTRICTION_B0037
+  if ( bMv_VRng_Restricted ) {
+    Int iRestrictMvVrange = ( iVerDispSrchRng ) << iMvShift;    
+    if ( rcMvSrchRngRB.getVer() >= iRestrictMvVrange  ){
+      rcMvSrchRngRB.setVer( iRestrictMvVrange );
+    }
+    //restrict minus vector too
+    if ( rcMvSrchRngLT.getVer() <= -iRestrictMvVrange ){
+      rcMvSrchRngLT.setVer( -iRestrictMvVrange );
+    }
+  }
+#endif
+  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 )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  UInt  uiSad;
+  UInt  uiSadBest         = MAX_UINT;
+  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() )
+  {
+    if ( m_cDistParam.iRows > 8 )
+    {
+      m_cDistParam.iSubShift = 1;
+    }
+  }
+  
+  piRefY += (iSrchRngVerTop * iRefStride);
+  for ( Int y = iSrchRngVerTop; y <= iSrchRngVerBottom; y++ )
+  {
+    for ( Int x = iSrchRngHorLeft; x <= iSrchRngHorRight; x++ )
+    {
+      //  find min. distortion position
+      piRefSrch = piRefY + x;
+      m_cDistParam.pCur = piRefSrch;
+
+      setDistParamComp(0);
+
+#if LGE_ILLUCOMP_B0045
+      m_cDistParam.bUseIC = pcPatternKey->getICFlag();
+#endif
+      uiSad = m_cDistParam.DistFunc( &m_cDistParam );
+      
+      // motion cost
+      uiSad += m_pcRdCost->getCost( x, y );
+      
+      // regularization cost
+      if( m_pcRdCost->useMultiviewReg() )
+      {
+        uiSad += m_pcRdCost->getMultiviewRegCost( x, y );
+      }
+
+      if ( uiSad < uiSadBest )
+      {
+        uiSadBest = uiSad;
+        iBestX    = x;
+        iBestY    = y;
+      }
+    }
+    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 )
+{
+  pcCU->getMvPredLeft       ( m_acMvPredictors[0] );
+  pcCU->getMvPredAbove      ( m_acMvPredictors[1] );
+  pcCU->getMvPredAboveRight ( m_acMvPredictors[2] );
+  
+  switch ( m_iFastSearch )
+  {
+    case 1:
+      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD );
+      break;
+      
+    default:
+      break;
+  }
+}
+
+Void TEncSearch::xTZSearch( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  TZ_SEARCH_CONFIGURATION
+  
+  UInt uiSearchRange = m_iSearchRange;
+  pcCU->clipMv( rcMv );
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( ! pcCU->getSlice()->getIsDepth() )
+#endif
+  rcMv >>= 2;
+  // init TZSearchStruct
+  IntTZSearchStruct cStruct;
+  cStruct.iYStride    = iRefStride;
+  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++ )
+    {
+      TComMv cMv = m_acMvPredictors[index];
+      pcCU->clipMv( cMv );
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+      if( ! pcCU->getSlice()->getIsDepth() )
+#endif
+      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 );
+  }
+  
+  // start search
+  Int  iDist = 0;
+  Int  iStartX = cStruct.iBestX;
+  Int  iStartY = cStruct.iBestY;
+  
+  // first search
+  for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
+  {
+    if ( bFirstSearchDiamond == 1 )
+    {
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+    }
+    else
+    {
+      xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+    }
+    
+    if ( bFirstSearchStop && ( cStruct.uiBestRound >= uiFirstSearchRounds ) ) // stop criterion
+    {
+      break;
+    }
+  }
+  
+  // test whether zero Mv is a better start point than Median predictor
+  if ( bTestZeroVectorStart && ((cStruct.iBestX != 0) || (cStruct.iBestY != 0)) )
+  {
+    xTZSearchHelp( pcPatternKey, cStruct, 0, 0, 0, 0 );
+    if ( (cStruct.iBestX == 0) && (cStruct.iBestY == 0) )
+    {
+      // test its neighborhood
+      for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
+      {
+        xTZ8PointDiamondSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, 0, 0, iDist );
+        if ( bTestZeroVectorStop && (cStruct.uiBestRound > 0) ) // stop criterion
+        {
+          break;
+        }
+      }
+    }
+  }
+  
+  // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
+  if ( cStruct.uiBestDistance == 1 )
+  {
+    cStruct.uiBestDistance = 0;
+    xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+  }
+  
+  // raster search if distance is too big
+  if ( bEnableRasterSearch && ( ((Int)(cStruct.uiBestDistance) > iRaster) || bAlwaysRasterSearch ) )
+  {
+    cStruct.uiBestDistance = iRaster;
+    for ( iStartY = iSrchRngVerTop; iStartY <= iSrchRngVerBottom; iStartY += iRaster )
+    {
+      for ( iStartX = iSrchRngHorLeft; iStartX <= iSrchRngHorRight; iStartX += iRaster )
+      {
+        xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, iRaster );
+      }
+    }
+  }
+  
+  // raster refinement
+  if ( bRasterRefinementEnable && cStruct.uiBestDistance > 0 )
+  {
+    while ( cStruct.uiBestDistance > 0 )
+    {
+      iStartX = cStruct.iBestX;
+      iStartY = cStruct.iBestY;
+      if ( cStruct.uiBestDistance > 1 )
+      {
+        iDist = cStruct.uiBestDistance >>= 1;
+        if ( bRasterRefinementDiamond == 1 )
+        {
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        else
+        {
+          xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+      }
+      
+      // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
+      if ( cStruct.uiBestDistance == 1 )
+      {
+        cStruct.uiBestDistance = 0;
+        if ( cStruct.ucPointNr != 0 )
+        {
+          xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+        }
+      }
+    }
+  }
+  
+  // start refinement
+  if ( bStarRefinementEnable && cStruct.uiBestDistance > 0 )
+  {
+    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(TComDataCU* pcCU,
+                                       TComPattern* pcPatternKey,
+                                       Pel* piRefY,
+                                       Int iRefStride,
+                                       TComMv* pcMvInt,
+                                       TComMv& rcMvHalf,
+                                       TComMv& rcMvQter,
+                                       UInt& ruiCost
+                                       ,Bool biPred
+                                       )
+{
+  //  Reference pattern initialization (integer scale)
+  TComPattern cPatternRoi;
+  Int         iOffset    = pcMvInt->getHor() + pcMvInt->getVer() * iRefStride;
+  cPatternRoi.initPattern( piRefY +  iOffset,
+                          NULL,
+                          NULL,
+                          pcPatternKey->getROIYWidth(),
+                          pcPatternKey->getROIYHeight(),
+                          iRefStride,
+                          0, 0, 0, 0 );
+  
+  //  Half-pel refinement
+  xExtDIFUpSamplingH ( &cPatternRoi, biPred );
+  
+  rcMvHalf = *pcMvInt;   rcMvHalf <<= 1;    // for mv-cost
+  TComMv baseRefMv(0, 0);
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 2, rcMvHalf   );
+  
+  m_pcRdCost->setCostScale( 0 );
+  
+  xExtDIFUpSamplingQ ( &cPatternRoi, rcMvHalf, biPred );
+  baseRefMv = rcMvHalf;
+  baseRefMv <<= 1;
+  
+  rcMvQter = *pcMvInt;   rcMvQter <<= 1;    // for mv-cost
+  rcMvQter += rcMvHalf;  rcMvQter <<= 1;
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 1, rcMvQter);
+}
+
+/** 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
+ */
+#if H3D_IVRP
+Void TEncSearch::encodeResAndCalcRdInterCU( TComDataCU* pcCU, TComYuv* pcYuvOrg, TComYuv* pcYuvPred, TComYuv*& rpcYuvResi, TComYuv*& rpcYuvResiBest, TComYuv*& rpcYuvRec, TComYuv*& rpcYuvResPrd, Bool bSkipRes )
+#else
+Void TEncSearch::encodeResAndCalcRdInterCU( TComDataCU* pcCU, TComYuv* pcYuvOrg, TComYuv* pcYuvPred, TComYuv*& rpcYuvResi, TComYuv*& rpcYuvResiBest, TComYuv*& rpcYuvRec, Bool bSkipRes )
+#endif
+{
+  if ( pcCU->isIntra(0) )
+  {
+    return;
+  }
+  
+  PredMode  ePredMode    = pcCU->getPredictionMode( 0 );
+  Bool      bHighPass    = pcCU->getSlice()->getDepth() ? true : false;
+  UInt      uiBits       = 0, uiBitsBest = 0;
+  Dist      uiDistortion = 0, uiDistortionBest = 0;
+  
+  UInt      uiWidth      = pcCU->getWidth ( 0 );
+  UInt      uiHeight     = pcCU->getHeight( 0 );
+  //  No residual coding : SKIP mode
+  if ( ePredMode == MODE_SKIP && bSkipRes )
+  {
+    rpcYuvResi->clear();
+    
+    pcYuvPred->copyToPartYuv( rpcYuvRec, 0 );
+    
+#if H3D_IVRP
+    if (pcCU->getMergeFlag(0) && pcCU->getMergeIndex(0)==0 && pcCU->getResPredAvail(0))
+    {
+      rpcYuvRec->clip( uiWidth, uiHeight );
+    }
+#endif
+
+#if HHI_VSO    
+    if ( m_pcRdCost->getUseVSO() )
+    {
+      uiDistortion = m_pcRdCost->getDistVS( pcCU, 0, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight     , false, 0 );
+#if LGE_WVSO_A0119
+      if ( m_pcRdCost->getUseWVSO() )
+      {    
+        Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+        Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+        Dist iD   = (Dist) m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      );
+        uiDistortion = (iDWeight * iD + iVSOWeight * (Dist)uiDistortion) / ( iDWeight + iVSOWeight);
+      }
+#endif
+    }
+    else    
+    {
+#endif
+#if WEIGHTED_CHROMA_DISTORTION
+    uiDistortion = m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+    + m_pcRdCost->getDistPart( rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, true )
+    + m_pcRdCost->getDistPart( rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, true );
+#else
+    uiDistortion = m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+    + m_pcRdCost->getDistPart( rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
+    + m_pcRdCost->getDistPart( rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
+#endif
+#if HHI_VSO    
+    }
+#endif
+
+    if( m_bUseSBACRD )
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
+    
+    m_pcEntropyCoder->resetBits();
+#if HHI_MPI
+    if( pcCU->getTextureModeDepth( 0 ) == -1 )
+    {
+#endif
+    m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, 0, 0, true );
+#if LGE_ILLUCOMP_B0045
+    m_pcEntropyCoder->encodeICFlag(pcCU, 0, true
+#if FIX_ILLUCOMP_DEPTH
+      , pcCU->getDepth( 0 )
+#endif
+      );
+#endif
+#if HHI_MPI
+    }
+#endif
+    
+    uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    pcCU->getTotalBits()       = uiBits;
+    pcCU->getTotalDistortion() = uiDistortion;
+
+#if HHI_VSO
+    if ( m_pcRdCost->getUseLambdaScaleVSO() )
+    {
+      pcCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );
+    }
+    else
+#endif
+    {
+    pcCU->getTotalCost()       = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+    }
+    
+    if( m_bUseSBACRD )
+      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 HHI_VSO // necessary? 
+    // set Model
+#if SAIT_VSO_EST_A0033
+    if( !m_pcRdCost->getUseEstimatedVSD()&& m_pcRdCost->getUseRenModel() )
+#else
+    if( m_pcRdCost->getUseRenModel() )
+#endif
+    {
+      Pel*  piSrc       = rpcYuvRec->getLumaAddr();
+      UInt  uiSrcStride = rpcYuvRec->getStride();
+      m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+    }
+#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 = pcCU->getSlice()->getSPS()->getMaxTrDepth() + 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 );
+
+  #if HHI_INTERVIEW_SKIP
+  if( bSkipRes)
+  {
+    rpcYuvResi->clear() ;
+  }
+  else
+  {
+  rpcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, uiWidth );
+  }
+#else
+  rpcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, uiWidth );
+#if H3D_IVRP
+  // add residual prediction
+  if( pcCU->getResPredFlag( 0 ) )
+  {
+    rpcYuvResi->subtract( rpcYuvResi, rpcYuvResPrd, uiWidth, uiHeight );
+  }
+#endif
+#endif
+
+  for ( qp = qpMin; qp <= qpMax; qp++ )
+  {
+    dCost = 0.;
+    uiBits = 0;
+    uiDistortion = 0;
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
+    }
+    
+    Dist uiZeroDistortion = 0;
+#if HHI_VSO
+    if ( m_pcRdCost->getUseVSO() )
+    {
+      m_cYuvRecTemp.create( pcYuvPred->getWidth(), pcYuvPred->getHeight()  );
+    }
+#endif
+#if IBDI_DISTORTION || HHI_VSO
+    xEstimateResidualQT( pcCU, 0, 0, 0, pcYuvOrg, pcYuvPred, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
+#else
+    xEstimateResidualQT( pcCU, 0, 0, 0, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
+#endif
+    
+
+#if HHI_VSO
+    if ( m_pcRdCost->getUseVSO() )
+    {
+      m_cYuvRecTemp.destroy();
+    }
+#endif
+
+    double dZeroCost;
+#if HHI_VSO
+    if( m_pcRdCost->getUseLambdaScaleVSO() )
+    {
+      dZeroCost = m_pcRdCost->calcRdCostVSO( 0, uiZeroDistortion );
+    }
+    else
+#endif
+    {
+      dZeroCost = m_pcRdCost->calcRdCost( 0, uiZeroDistortion );
+    }
+
+#if LOSSLESS_CODING
+    if(pcCU->isLosslessCoded( 0 ))
+    {  
+      dZeroCost = dCost + 1;
+    }
+#endif
+    if ( dZeroCost < dCost )
+    {
+      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 );
+    }
+    else
+    {
+      xSetResidualQTData( pcCU, 0, 0, 0, NULL, pcCU->getDepth(0), false );
+    }
+    
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+    }
+#if 0 // check
+    {
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeCoeff( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0) );
+      const UInt uiBitsForCoeff = m_pcEntropyCoder->getNumberOfWrittenBits();
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+      }
+      if( uiBitsForCoeff != uiBits )
+        assert( 0 );
+    }
+#endif
+    uiBits = 0;
+    {
+      TComYuv *pDummy = NULL;
+      xAddSymbolBitsInter( pcCU, 0, 0, uiBits, pDummy, NULL, pDummy );
+    }
+    
+    Double dExactCost;
+#if HHI_VSO
+    if( m_pcRdCost->getUseLambdaScaleVSO() )
+    {
+      dExactCost = m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );;
+    }
+    else
+#endif
+    {
+      dExactCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+    }
+    
+    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
+      }
+      uiBitsBest       = uiBits;
+      uiDistortionBest = uiDistortion;
+      dCostBest        = dCost;
+      qpBest           = qp;
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+      }
+    }
+
+
+#if HHI_VSO
+#if SAIT_VSO_EST_A0033    
+    if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
+#else
+    if( m_pcRdCost->getUseRenModel() )
+#endif
+    {
+      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 )
+  {
+    if( m_bUseSBACRD )
+    {
+      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
+  }
+  rpcYuvRec->addClip ( pcYuvPred, rpcYuvResiBest, 0, uiWidth );
+  
+  // update with clipped distortion and cost (qp estimation loop uses unclipped values)
+
+#if HHI_VSO // GT: might be removed since VSO already provided clipped distortion
+  if ( m_pcRdCost->getUseVSO() )
+  {
+    uiDistortionBest = m_pcRdCost->getDistVS  ( pcCU, 0, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight, false, 0    );
+#if LGE_WVSO_A0119
+    if ( m_pcRdCost->getUseWVSO() )
+    {    
+      Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+      Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+      Dist iD        = (Dist) m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      );
+      uiDistortionBest = (iDWeight * iD + iVSOWeight * (Dist) uiDistortionBest) / ( iDWeight + iVSOWeight);
+    }
+#endif
+  }
+  else
+#endif
+{
+#if WEIGHTED_CHROMA_DISTORTION
+  uiDistortionBest = m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+  + m_pcRdCost->getDistPart( rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, true )
+  + m_pcRdCost->getDistPart( rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, true );
+#else
+  uiDistortionBest = m_pcRdCost->getDistPart( rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+  + m_pcRdCost->getDistPart( rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 )
+  + m_pcRdCost->getDistPart( rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
+#endif
+}
+#if HHI_VSO
+  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) );
+
+  // set Model
+
+#if HHI_VSO // necessary??
+#if SAIT_VSO_EST_A0033    
+  if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
+#else
+  if( m_pcRdCost->getUseRenModel() )
+#endif
+  {
+    Pel*  piSrc       = rpcYuvRec->getLumaAddr();
+    UInt  uiSrcStride = rpcYuvRec->getStride();
+    m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+}
+#endif
+}
+
+#if IBDI_DISTORTION || HHI_VSO
+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 )
+#else
+Void TEncSearch::xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, Dist &ruiDist, Dist *puiZeroDist )
+#endif
+{
+  const UInt uiTrMode = uiDepth - pcCU->getDepth( 0 );
+  
+  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 ));
+  Bool bCheckFull;
+  if ( SplitFlag && uiDepth == pcCU->getDepth(uiAbsPartIdx) && ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) ) )
+     bCheckFull = false;
+  else
+     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;
+  Dist uiSingleDist = 0;
+  UInt uiAbsSumY = 0, uiAbsSumU = 0, uiAbsSumV = 0;
+  
+  if( m_bUseSBACRD )
+  {
+    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 );
+    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->getNSQTSize ( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+    pcCU->getNSQTSize ( uiTrModeC, uiAbsPartIdx, trWidthC, trHeightC );
+
+    if( bCodeChroma && pcCU->useNonSquareTrans( uiTrMode, uiAbsPartIdx ) && !( uiLog2TrSizeC  == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() && uiTrModeC == 1 ) )
+    {  
+      absTUPartIdxC = pcCU->getNSAddrChroma( uiLog2TrSizeC, uiTrModeC, uiQuadrant, absTUPartIdx );
+    }
+    pcCU->setTrIdxSubParts( uiDepth - pcCU->getDepth( 0 ), uiAbsPartIdx, uiDepth );
+    if (m_pcEncCfg->getUseRDOQ())
+    {
+      m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidth, trHeight, TEXT_LUMA );        
+    }
+
+    m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), 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,    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 );          
+      }
+
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset() );
+
+#if RDOQ_CHROMA_LAMBDA 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA); 
+#endif
+
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCbAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrU, 
+#if ADAPTIVE_QP_SELECTION
+                                 pcArlCoeffCurrU, 
+#endif        
+                                 trWidthC, trHeightC, uiAbsSumU, TEXT_CHROMA_U, uiAbsPartIdx );
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset2nd() );
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
+#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_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+      }
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
+      uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsY;
+      
+      {
+        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() - ( uiSingleBitsY + uiSingleBitsU );
+    }
+    
+    const UInt uiNumSamplesLuma = 1 << (uiLog2TrSize<<1);
+    const UInt uiNumSamplesChro = 1 << (uiLog2TrSizeC<<1);
+    
+    Dist uiDistY;
+
+//GT VSO
+
+    // GT Fix: Not necessary for VSO, however used for chroma later, irrelevant except from valgrind error message
+    ::memset( m_pTempPel, 0, sizeof( Pel ) * uiNumSamplesLuma ); // not necessary needed for inside of recursion (only at the beginning)
+    
+#if HHI_VSO
+    if ( m_pcRdCost->getUseVSO() )
+    {
+#if SAIT_VSO_EST_A0033
+      if( m_pcRdCost->getUseEstimatedVSD() )
+      {
+        TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+        TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+        uiDistY = m_pcRdCost->getDistPart( m_pTempPel, 1<< uiLog2TrSize, pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(), pcVirRec->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiAbsPartIdx), pcVirOrg->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiAbsPartIdx), pcVirRec->getStride(), 1<< uiLog2TrSize, 1<< uiLog2TrSize );
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+          Dist iD   = (Dist) m_pcRdCost->getDistPart( m_pTempPel, trWidth, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight );
+          uiDistY = (iDWeight * iD + iVSDWeight * (Dist)uiDistY) / ( iDWeight + iVSDWeight);
+        }
+#endif
+      }
+      else
+#endif
+      {      
+        uiDistY = m_pcRdCost->getDistVS  ( pcCU, uiAbsPartIdx, pcPred->getLumaAddr( uiAbsPartIdx ), pcPred->getStride(), pcOrg->getLumaAddr( uiAbsPartIdx), pcOrg->getStride(), 1<< uiLog2TrSize, 1<< uiLog2TrSize, false, 0 ); // initialized with zero residual distortion
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+          Dist iD   = (Dist) m_pcRdCost->getDistPart( m_pTempPel, trWidth, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight );
+          uiDistY = (iDWeight * iD + iVSOWeight * (Dist)uiDistY) / ( iDWeight + iVSOWeight);
+        }
+#endif
+      }
+    }
+    else
+#endif
+    {
+#if IBDI_DISTORTION
+     uiDistY = m_pcRdCost->getDistPart( pcPred->getLumaAddr( absTUPartIdx ), pcPred->getStride(), pcOrg->getLumaAddr( absTUPartIdx), pcOrg->getStride(), trWidth, trHeight);
+#else
+     uiDistY = m_pcRdCost->getDistPart( 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 ), false, pcCU->getSlice()->getSliceType(), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+      Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
+      assert(scalingListType < 6);     
+#if LOSSLESS_CODING
+      m_pcTrQuant->invtransformNxN( pcCU, TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
+#else     
+      m_pcTrQuant->invtransformNxN( TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
+#endif
+      
+      Dist uiNonzeroDistY;
+
+#if HHI_VSO      
+      if ( m_pcRdCost->getUseVSO() )
+      {
+#if SAIT_VSO_EST_A0033
+        if ( m_pcRdCost->getUseEstimatedVSD() )
+        {          
+          TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+          TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+          uiNonzeroDistY = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( uiAbsPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(), pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(), pcVirRec->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx ), pcVirOrg->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx ), pcVirRec->getStride(), 1<< uiLog2TrSize,    1<< uiLog2TrSize );
+#if LGE_WVSO_A0119
+          if ( m_pcRdCost->getUseWVSO() )
+          {    
+            Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+            Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+            Dist iD = (Dist) m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
+            uiNonzeroDistY = (iDWeight * iD + iVSDWeight * (Dist) uiNonzeroDistY) / ( iDWeight + iVSDWeight);
+          }
+#endif
+        }
+        else
+#endif
+        {        
+          m_cYuvRecTemp.addClipPartLuma( &m_pcQTTempTComYuv[uiQTTempAccessLayer], pcPred, uiAbsPartIdx, 1<< uiLog2TrSize  );
+          uiNonzeroDistY = m_pcRdCost->getDistVS( pcCU, uiAbsPartIdx, m_cYuvRecTemp.getLumaAddr(uiAbsPartIdx), m_cYuvRecTemp.getStride(),
+                                                  pcOrg->getLumaAddr( uiAbsPartIdx ), pcOrg->getStride(), 1<< uiLog2TrSize,   1<< uiLog2TrSize, false, 0 );
+#if LGE_WVSO_A0119
+          if ( m_pcRdCost->getUseWVSO() )
+          {    
+            Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+            Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+            Dist iD = (Dist) m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
+            uiNonzeroDistY = (iDWeight * iD + iVSOWeight * (Dist) uiNonzeroDistY) / ( iDWeight + iVSOWeight);
+          }
+#endif
+        }
+      }
+      else
+#endif
+      {
+        uiNonzeroDistY = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
+          pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
+      }
+
+#if LOSSLESS_CODING
+      if (pcCU->isLosslessCoded(0)) 
+      {
+        uiDistY = uiNonzeroDistY;
+      }
+      else
+      {
+
+      Double singleCostY;
+      Double nullCostY;
+
+#if HHI_VSO      
+      if ( m_pcRdCost->getUseLambdaScaleVSO())
+      {
+        singleCostY = m_pcRdCost->calcRdCostVSO( uiSingleBitsY, uiNonzeroDistY );
+        nullCostY   = m_pcRdCost->calcRdCostVSO( 0, uiDistY );
+      }
+      else
+#endif
+      {
+        singleCostY = m_pcRdCost->calcRdCost( uiSingleBitsY, uiNonzeroDistY );
+        nullCostY   = m_pcRdCost->calcRdCost( 0, uiDistY );
+      }
+        if( nullCostY < singleCostY )  
+        {    
+          uiAbsSumY = 0;
+          ::memset( pcCoeffCurrY, 0, sizeof( TCoeff ) * uiNumSamplesLuma );
+        }
+        else
+        {
+          uiDistY = uiNonzeroDistY;
+        }
+      }
+#else
+      Double dSingleCostY;
+      Double dNullCostY;
+
+#if HHI_VSO      
+      if ( m_pcRdCost->getUseLambdaScaleVSO())
+      {
+        dSingleCostY = m_pcRdCost->calcRdCostVSO( uiSingleBitsY, uiNonzeroDistY );
+        dNullCostY   = m_pcRdCost->calcRdCostVSO( 0, uiDistY );
+      }
+      else
+#endif
+      {
+        dSingleCostY = m_pcRdCost->calcRdCost( uiSingleBitsY, uiNonzeroDistY );
+        dNullCostY   = m_pcRdCost->calcRdCost( 0, uiDistY );
+      }
+      if( dNullCostY < dSingleCostY )
+      {
+        uiAbsSumY = 0;
+        ::memset( pcCoeffCurrY, 0, sizeof( TCoeff ) * uiNumSamplesLuma );
+      }
+      else
+      {
+        uiDistY = uiNonzeroDistY;
+      }
+#endif
+    }
+    
+    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;
+      } 
+    }
+    
+
+    Dist uiDistU = 0;
+    Dist uiDistV = 0;
+    if( bCodeChroma )
+    {
+#if IBDI_DISTORTION
+      uiDistU = m_pcRdCost->getDistPart( pcPred->getCbAddr( absTUPartIdxC ), pcPred->getCStride(), pcOrg->getCbAddr( absTUPartIdxC ), pcOrg->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                          , true
+#endif
+                                          );
+#else
+      uiDistU = m_pcRdCost->getDistPart( m_pTempPel, trWidthC, pcResi->getCbAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                          , true
+#endif
+                                          ); // initialized with zero residual destortion
+#endif
+      if ( puiZeroDist )
+      {
+        *puiZeroDist += uiDistU;
+      }
+      if( uiAbsSumU )
+      {
+        Pel *pcResiCurrU = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
+
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset() );
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
+        assert(scalingListType < 6);
+#if LOSSLESS_CODING
+        m_pcTrQuant->invtransformNxN( pcCU, TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType  );
+#else
+        m_pcTrQuant->invtransformNxN( TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType );
+#endif       
+        
+
+        const Dist uiNonzeroDistU = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+          pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
+
+#if WEIGHTED_CHROMA_DISTORTION
+          , true
+#endif
+          );
+
+#if LOSSLESS_CODING
+        if(pcCU->isLosslessCoded(0))  
+        {
+          uiDistU = uiNonzeroDistU;
+        }
+        else
+        {
+          const Double dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
+          const Double dNullCostU   = m_pcRdCost->calcRdCost( 0, uiDistU );
+          if( dNullCostU < dSingleCostU )
+          {
+            uiAbsSumU = 0;
+            ::memset( pcCoeffCurrU, 0, sizeof( TCoeff ) * uiNumSamplesChro );
+          }
+          else
+          {
+            uiDistU = uiNonzeroDistU;
+          }
+        }
+#else
+        const Double dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
+        const Double dNullCostU   = m_pcRdCost->calcRdCost( 0, uiDistU );
+        if( dNullCostU < dSingleCostU )
+        {
+          uiAbsSumU = 0;
+          ::memset( pcCoeffCurrU, 0, sizeof( TCoeff ) * uiNumSamplesChro );
+        }
+        else
+        {
+          uiDistU = uiNonzeroDistU;
+        }
+#endif
+      }
+      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;
+        }
+      }
+      
+#if IBDI_DISTORTION
+      uiDistV = m_pcRdCost->getDistPart( pcPred->getCrAddr( absTUPartIdxC ), pcPred->getCStride(), pcOrg->getCrAddr( absTUPartIdxC ), pcOrg->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                          , true
+#endif
+                                          );
+#else
+      uiDistV = m_pcRdCost->getDistPart( m_pTempPel, trWidthC, pcResi->getCrAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                          , true
+#endif
+                                          ); // initialized with zero residual destortion
+#endif
+      if ( puiZeroDist )
+      {
+        *puiZeroDist += uiDistV;
+      }
+      if( uiAbsSumV )
+      {
+        Pel *pcResiCurrV = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
+        if( !uiAbsSumU )
+        {
+          m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), pcCU->getSlice()->getPPS()->getChromaQpOffset2nd() );
+        }
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
+        assert(scalingListType < 6);
+#if LOSSLESS_CODING
+        m_pcTrQuant->invtransformNxN( pcCU, TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType );
+#else
+        m_pcTrQuant->invtransformNxN( TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType );
+#endif
+        const Dist uiNonzeroDistV = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+          pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
+#if WEIGHTED_CHROMA_DISTORTION
+                                                   , true
+#endif
+                                                   );
+#if LOSSLESS_CODING
+        if (pcCU->isLosslessCoded(0)) 
+        {
+          uiDistV = uiNonzeroDistV;
+        }
+        else
+        {
+          const Double dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
+          const Double dNullCostV   = m_pcRdCost->calcRdCost( 0, uiDistV );
+          if( dNullCostV < dSingleCostV )
+          {
+            uiAbsSumV = 0;
+            ::memset( pcCoeffCurrV, 0, sizeof( TCoeff ) * uiNumSamplesChro );
+          }
+          else
+          {
+            uiDistV = uiNonzeroDistV;
+          }
+        }
+#else
+        const Double dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
+        const Double dNullCostV   = m_pcRdCost->calcRdCost( 0, uiDistV );
+        if( dNullCostV < dSingleCostV )
+        {
+          uiAbsSumV = 0;
+          ::memset( pcCoeffCurrV, 0, sizeof( TCoeff ) * uiNumSamplesChro );
+        }
+        else
+        {
+          uiDistV = uiNonzeroDistV;
+        }
+#endif
+      }
+      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( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+
+    m_pcEntropyCoder->resetBits();
+
+    {
+      if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+      {
+        m_pcEntropyCoder->encodeTransformSubdivFlag( 0, uiDepth );
+      }
+    }
+
+    {
+      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 );
+    }
+
+    uiSingleBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+    uiSingleDist = uiDistY + uiDistU + uiDistV;
+#if HHI_VSO
+    if ( m_pcRdCost->getUseLambdaScaleVSO())
+    {
+      dSingleCost = m_pcRdCost->calcRdCostVSO( uiSingleBits, uiSingleDist );
+    }
+    else
+#endif
+    {
+    dSingleCost = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDist );
+  }  
+  } // CHECK FULL
+  
+  // code sub-blocks
+  if( bCheckSplit )
+  {
+    if( m_bUseSBACRD && bCheckFull )
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    Dist uiSubdivDist = 0;
+    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 = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrSize - 1, uiAbsPartIdx + ui * uiQPartNumSubdiv, absTUPartIdx, ui, uiTrMode + 1 );
+#if IBDI_DISTORTION || HHI_VSO
+      xEstimateResidualQT( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcOrg, pcPred, pcResi, uiDepth + 1, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist );
+#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;
+    }
+    
+    if( m_bUseSBACRD )
+    {
+      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 );
+    }
+    
+    uiSubdivBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+#if HHI_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;
+      }
+    }
+    assert( bCheckFull );
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+    }
+  }
+
+
+#if HHI_VSO
+#if SAIT_VSO_EST_A0033
+  if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
+#else
+  if ( m_pcRdCost->getUseRenModel() ) //Only done if not split ( see return above )
+#endif
+  {
+    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  ();
+    }
+    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 );
+  }
+}
+
+Void TEncSearch::xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType )
+{
+  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) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, uiDepth );
+    }
+  }
+
+  {
+    assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
+    if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+    {
+      const Bool bFirstCbfOfCU = uiLog2TrSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() || 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 ) );
+      }
+    }
+  }
+  
+  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 );
+      }
+    }
+    else
+    {
+      if( eType == TEXT_LUMA     && pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA,     uiTrMode ) )
+      {
+        Int trWidth  = 1 << uiLog2TrSize;
+        Int trHeight = 1 << uiLog2TrSize;
+        pcCU->getNSQTSize( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
+      }
+      if( bCodeChroma )
+      {
+        Int trWidth  = 1 << uiLog2TrSizeC;
+        Int trHeight = 1 << uiLog2TrSizeC;
+        pcCU->getNSQTSize( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+        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 );
+        }
+      }
+    }
+  }
+  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 );
+      }
+    }
+  }
+}
+
+Void TEncSearch::xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial )
+{
+  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;
+      pcCU->getNSQTSize( uiTrMode, uiAbsPartIdx, trWidth, trHeight );
+      m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartLuma    ( pcResi, absTUPartIdx, trWidth , trHeight );
+
+      if( bCodeChroma )
+      {
+        Int trWidthC  = 1 << uiLog2TrSizeC;
+        Int trHeightC = 1 << uiLog2TrSizeC;
+        UInt absTUPartIdxC = absTUPartIdx;
+        pcCU->getNSQTSize( uiTrModeC, uiAbsPartIdx, trWidthC, trHeightC );
+
+        if( pcCU->useNonSquareTrans( uiTrModeC, uiAbsPartIdx ) && !( uiLog2TrSizeC  == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() && uiTrModeC == 1 ) )
+        {          
+          absTUPartIdxC = pcCU->getNSAddrChroma( uiLog2TrSizeC, uiTrModeC, uiQuadrant, absTUPartIdx );
+          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, absTUPartIdxC, trWidthC, trHeightC );
+        }
+        else
+          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);
+    const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth] + 2;
+    for( UInt ui = 0; ui < 4; ++ui )
+    {
+      UInt nsAddr = 0;
+      nsAddr = pcCU->getNSAbsPartIdx( uiLog2TrSize-1, uiAbsPartIdx + ui * uiQPartNumSubdiv, absTUPartIdx, ui, uiCurrTrMode + 1);
+      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 )
+{
+  if( m_bUseSBACRD )
+  {
+    // Reload only contexts required for coding intra mode information
+    m_pcRDGoOnSbacCoder->loadIntraDirModeLuma( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+  }
+  
+  pcCU->setLumaIntraDirSubParts ( uiMode, uiPartOffset, uiDepth + uiInitTrDepth );
+  
+  m_pcEntropyCoder->resetBits();
+  m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPartOffset);
+  
+  return m_pcEntropyCoder->getNumberOfWrittenBits();
+}
+
+UInt TEncSearch::xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList )
+{
+  UInt i;
+  UInt shift=0;
+  
+  while ( shift<uiFastCandNum && uiCost<CandCostList[ uiFastCandNum-1-shift ] ) shift++;
+  
+  if( shift!=0 )
+  {
+    for(i=1; i<shift; i++)
+    {
+      CandModeList[ uiFastCandNum-i ] = CandModeList[ uiFastCandNum-1-i ];
+      CandCostList[ uiFastCandNum-i ] = CandCostList[ uiFastCandNum-1-i ];
+    }
+    CandModeList[ uiFastCandNum-shift ] = uiMode;
+    CandCostList[ uiFastCandNum-shift ] = uiCost;
+    return 1;
+  }
+  
+  return 0;
+}
+
+/** add inter-prediction syntax elements for a CU block
+ * \param pcCU
+ * \param uiQp
+ * \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 )
+{
+  if ( pcCU->isSkipped( 0 ) )
+  {
+#if HHI_MPI
+    if( pcCU->getTextureModeDepth( 0 ) != -1 )
+    {
+      return;
+    }
+#endif
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
+    m_pcEntropyCoder->encodeMergeIndex(pcCU, 0, 0, true);
+#if LGE_ILLUCOMP_B0045
+    m_pcEntropyCoder->encodeICFlag(pcCU, 0, true
+#if FIX_ILLUCOMP_DEPTH
+      , pcCU->getDepth( 0 )
+#endif
+      );
+#endif
+    ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+  else
+  {
+    m_pcEntropyCoder->resetBits();
+#if HHI_MPI
+    if( pcCU->getTextureModeDepth( 0 ) == -1 )
+    {
+#endif
+    m_pcEntropyCoder->encodeSkipFlag ( pcCU, 0, true );
+    if (pcCU->getPredictionMode(0) == MODE_SKIP)
+    {
+      pcCU->setPredModeSubParts( MODE_INTER, 0, pcCU->getDepth(0) );
+    }
+    m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+    m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+    m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+#if LGE_ILLUCOMP_B0045
+    m_pcEntropyCoder->encodeICFlag(pcCU, 0, true
+#if FIX_ILLUCOMP_DEPTH
+      , pcCU->getDepth( 0 )
+#endif
+      );
+#endif
+#if HHI_MPI
+    }
+#endif
+    Bool bDummy = false;
+    m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0), bDummy );
+    
+    ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+}
+
+/**
+ * \brief Generate half-sample interpolated block
+ *
+ * \param pattern Reference picture ROI
+ * \param biPred    Flag indicating whether block is for biprediction
+ */
+Void TEncSearch::xExtDIFUpSamplingH( TComPattern* pattern, Bool biPred )
+{
+  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 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);
+}
+
+/**
+ * \brief Generate quarter-sample interpolated blocks
+ *
+ * \param pattern    Reference picture ROI
+ * \param halfPelRef Half-pel mv
+ * \param biPred     Flag indicating whether block is for biprediction
+ */
+Void TEncSearch::xExtDIFUpSamplingQ( TComPattern* pattern, TComMv halfPelRef, Bool biPred )
+{
+  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 filterSize = NTAPS_LUMA;
+  
+  Int halfFilterSize = (filterSize>>1);
+
+  Int extHeight = (halfPelRef.getVer() == 0) ? height + filterSize : height + filterSize-1;
+  
+  // Horizontal filter 1/4
+  srcPtr = pattern->getROIY() - halfFilterSize * srcStride - 1;
+  intPtr = m_filteredBlockTmp[1].getLumaAddr();
+  if (halfPelRef.getVer() > 0)
+  {
+    srcPtr += srcStride;
+  }
+  if (halfPelRef.getHor() >= 0)
+  {
+    srcPtr += 1;
+  }
+  m_if.filterHorLuma(srcPtr, srcStride, intPtr, intStride, width, extHeight, 1, false);
+  
+  // Horizontal filter 3/4
+  srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
+  intPtr = m_filteredBlockTmp[3].getLumaAddr();
+  if (halfPelRef.getVer() > 0)
+  {
+    srcPtr += srcStride;
+  }
+  if (halfPelRef.getHor() > 0)
+  {
+    srcPtr += 1;
+  }
+  m_if.filterHorLuma(srcPtr, srcStride, intPtr, intStride, width, extHeight, 3, false);        
+  
+  // Generate @ 1,1
+  intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][1].getLumaAddr();
+  if (halfPelRef.getVer() == 0)
+  {
+    intPtr += intStride;
+  }
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+  
+  // 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);
+  
+  if (halfPelRef.getVer() != 0)
+  {
+    // Generate @ 2,1
+    intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][1].getLumaAddr();
+    if (halfPelRef.getVer() == 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true);
+    
+    // Generate @ 2,3
+    intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][3].getLumaAddr();
+    if (halfPelRef.getVer() == 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true);
+  }
+  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);
+    
+    // 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);
+  }
+  
+  if (halfPelRef.getHor() != 0)
+  {
+    // Generate @ 1,2
+    intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[1][2].getLumaAddr();
+    if (halfPelRef.getHor() > 0)
+    {
+      intPtr += 1;
+    }
+    if (halfPelRef.getVer() >= 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+    
+    // Generate @ 3,2
+    intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[3][2].getLumaAddr();
+    if (halfPelRef.getHor() > 0)
+    {
+      intPtr += 1;
+    }
+    if (halfPelRef.getVer() > 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);  
+  }
+  else
+  {
+    // Generate @ 1,0
+    intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[1][0].getLumaAddr();
+    if (halfPelRef.getVer() >= 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+    
+    // Generate @ 3,0
+    intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[3][0].getLumaAddr();
+    if (halfPelRef.getVer() > 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
+  }
+  
+  // Generate @ 1,3
+  intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][3].getLumaAddr();
+  if (halfPelRef.getVer() == 0)
+  {
+    intPtr += intStride;
+  }
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+  
+  // 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);
+}
+
+/** set wp tables
+ * \param TComDataCU* pcCU
+ * \param iRefIdx
+ * \param eRefPicListCur
+ * \returns Void
+ */
+Void  TEncSearch::setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur )
+{
+  if ( iRefIdx<0 )
+  {
+    m_cDistParam.bApplyWeight = false;
+    return;
+  }
+
+  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->getWPBiPredIdc() ) ;
+
+  if ( !m_cDistParam.bApplyWeight ) return;
+
+  Int iRefIdx0 = ( eRefPicListCur == REF_PIC_LIST_0 ) ? iRefIdx : (-1);
+  Int iRefIdx1 = ( eRefPicListCur == REF_PIC_LIST_1 ) ? iRefIdx : (-1);
+
+  getWpScaling( pcCU, iRefIdx0, iRefIdx1, wp0 , wp1 );
+
+  if ( iRefIdx0 < 0 ) wp0 = NULL;
+  if ( iRefIdx1 < 0 ) wp1 = NULL;
+
+  m_cDistParam.wpCur  = NULL;
+
+  if ( eRefPicListCur == REF_PIC_LIST_0 )
+  {
+    m_cDistParam.wpCur = wp0;
+  }
+  else
+  {
+    m_cDistParam.wpCur = wp1;
+  }
+}
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#if ((HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX)&&FLEX_CODING_ORDER_M23723)
+Bool TEncSearch::predIntraLumaDMMAvailable( UInt uiMode, UInt uiWidth, UInt uiHeight, Bool bDMMAvailable34 )
+#else
+Bool TEncSearch::predIntraLumaDMMAvailable( UInt uiMode, UInt uiWidth, UInt uiHeight )
+#endif
+{
+  if( uiMode < NUM_INTRA_MODE ) return true;
+
+  Bool bDMMAvailable = m_pcEncCfg->getUseDMM();
+
+#if HHI_DMM_WEDGE_INTRA
+  if( uiMode == DMM_WEDGE_FULL_IDX        ||
+      uiMode == DMM_WEDGE_FULL_D_IDX      ||
+      uiMode == DMM_WEDGE_PREDDIR_IDX     ||
+      uiMode == DMM_WEDGE_PREDDIR_D_IDX )
+  {
+    if( (uiWidth != uiHeight) || (uiWidth < DMM_WEDGEMODEL_MIN_SIZE) || (uiWidth > DMM_WEDGEMODEL_MAX_SIZE) || ( ( uiMode == DMM_WEDGE_PREDDIR_IDX || uiMode == DMM_WEDGE_PREDDIR_D_IDX ) && uiWidth == 4 ) )
+    {
+      bDMMAvailable = false;
+    }
+  }
+#endif
+#if HHI_DMM_PRED_TEX
+  if( uiMode == DMM_WEDGE_PREDTEX_IDX     ||
+      uiMode == DMM_WEDGE_PREDTEX_D_IDX   ||
+      uiMode == DMM_CONTOUR_PREDTEX_IDX   ||
+      uiMode == DMM_CONTOUR_PREDTEX_D_IDX )
+  {
+    if( (uiWidth != uiHeight) || (uiWidth < DMM_WEDGEMODEL_MIN_SIZE) || (uiWidth > DMM_WEDGEMODEL_MAX_SIZE) || ( ( uiMode == DMM_CONTOUR_PREDTEX_IDX || uiMode == DMM_CONTOUR_PREDTEX_D_IDX ) && uiWidth == 4 ) )
+    {
+      bDMMAvailable = false;
+    }
+
+#if FLEX_CODING_ORDER_M23723
+    if ( !bDMMAvailable34 )
+    {
+      bDMMAvailable = false;
+    }
+#endif
+
+  }
+#endif
+
+  return bDMMAvailable;
+}
+
+Void TEncSearch::xGetWedgeDeltaDCsMinDist( TComWedgelet* pcWedgelet,
+                                           TComDataCU*   pcCU,
+                                           UInt          uiAbsPtIdx,
+                                           Pel*          piOrig,
+                                           Pel*          piPredic,
+                                           UInt          uiStride,
+                                           UInt          uiWidth,
+                                           UInt          uiHeight,
+                                           Int&          riDeltaDC1,
+                                           Int&          riDeltaDC2,
+                                           Bool          bAboveAvail,
+                                           Bool          bLeftAvail )
+{
+  Int iDC1 = 0;
+  Int iDC2 = 0;
+  calcWedgeDCs       ( pcWedgelet, piOrig,   uiStride, iDC1, iDC2 );
+  assignWedgeDCs2Pred( pcWedgelet, piPredic, uiStride, iDC1, iDC2 );
+
+  Int iPredDC1 = 0;
+  Int iPredDC2 = 0;
+  Int* piMask = pcCU->getPattern()->getAdiOrgBuf( uiWidth, uiHeight, m_piYuvExt );
+  Int iMaskStride = ( uiWidth<<1 ) + 1;
+  piMask += iMaskStride+1;
+  getWedgePredDCs( pcWedgelet, piMask, iMaskStride, iPredDC1, iPredDC2, bAboveAvail, bLeftAvail );
+
+  riDeltaDC1 = iDC1 - iPredDC1;
+  riDeltaDC2 = iDC2 - iPredDC2;
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseVSO() )
+  {
+    Int iFullDeltaDC1 = riDeltaDC1;
+    Int iFullDeltaDC2 = riDeltaDC2;
+
+    Dist uiBestDist     = RDO_DIST_MAX;
+    UInt  uiBestQStepDC1 = 0;
+    UInt  uiBestQStepDC2 = 0;
+
+    UInt uiDeltaDC1Max = abs(iFullDeltaDC1);
+    UInt uiDeltaDC2Max = abs(iFullDeltaDC2);
+
+    //VSO Level delta DC check range extension
+    uiDeltaDC1Max += (uiDeltaDC1Max>>1);
+    uiDeltaDC2Max += (uiDeltaDC2Max>>1);
+
+    // limit search range to [0, IBDI_MAX]
+    if( iFullDeltaDC1 <  0 && uiDeltaDC1Max >                abs(iPredDC1) ) { uiDeltaDC1Max =                abs(iPredDC1); }
+    if( iFullDeltaDC1 >= 0 && uiDeltaDC1Max > g_uiIBDI_MAX - abs(iPredDC1) ) { uiDeltaDC1Max = g_uiIBDI_MAX - abs(iPredDC1); }
+
+    if( iFullDeltaDC2 <  0 && uiDeltaDC2Max >                abs(iPredDC2) ) { uiDeltaDC2Max =                abs(iPredDC2); }
+    if( iFullDeltaDC2 >= 0 && uiDeltaDC2Max > g_uiIBDI_MAX - abs(iPredDC2) ) { uiDeltaDC2Max = g_uiIBDI_MAX - abs(iPredDC2); }
+
+    // init dist with original DCs
+    assignWedgeDCs2Pred( pcWedgelet, piPredic, uiStride, iDC1, iDC2 );
+
+    Dist uiOrgDist = RDO_DIST_MAX;
+#if SAIT_VSO_EST_A0033
+    if ( m_pcRdCost->getUseEstimatedVSD() )
+    {          
+      TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+      TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+      uiOrgDist = m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, pcVirRec->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirOrg->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirRec->getStride(), uiWidth, uiHeight );
+#if LGE_WVSO_A0119
+      if ( m_pcRdCost->getUseWVSO() )
+      {    
+        Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+        Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+        Dist iD = (Dist) m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false, DF_SAD );
+        uiOrgDist = (iDWeight * iD + iVSDWeight * (Dist) uiOrgDist) / ( iDWeight + iVSDWeight);
+      }
+#endif // LGE_WVSO_A0119
+    }
+    else       
+#endif // SAIT_VSO_EST_A0033
+    {        
+      uiOrgDist = m_pcRdCost->getDistVS( pcCU, 0, piPredic, uiStride,  piOrig, uiStride, uiWidth, uiHeight, false, 0 );
+#if LGE_WVSO_A0119
+      if ( m_pcRdCost->getUseWVSO() )
+      {    
+        Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+        Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+        Dist iD = (Dist) m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false, DF_SAD );
+        uiOrgDist = (iDWeight * iD + iVSOWeight * (Dist) uiOrgDist) / ( iDWeight + iVSOWeight);
+      }
+#endif // LGE_WVSO_A0119
+    }
+    uiBestDist     = uiOrgDist;
+    uiBestQStepDC1 = abs(iFullDeltaDC1);
+    uiBestQStepDC2 = abs(iFullDeltaDC2);
+
+    // coarse search with step size 4
+    for( UInt uiQStepDC1 = 0; uiQStepDC1 < uiDeltaDC1Max; uiQStepDC1 += 4 )
+    {
+      Int iTestDC1 = Clip( iPredDC1 + ((Int)(uiQStepDC1) * (Int)(( iFullDeltaDC1 < 0 ) ? -1 : 1)) );
+      for( UInt uiQStepDC2 = 0; uiQStepDC2 < uiDeltaDC2Max; uiQStepDC2 += 4 )
+      {
+        Int iTestDC2 = Clip( iPredDC2 + ((Int)(uiQStepDC2) * (Int)(( iFullDeltaDC2 < 0 ) ? -1 : 1)) );
+
+        assignWedgeDCs2Pred( pcWedgelet, piPredic, uiStride, iTestDC1, iTestDC2 );
+
+        Dist uiAct4Dist = RDO_DIST_MAX;
+#if SAIT_VSO_EST_A0033
+        if ( m_pcRdCost->getUseEstimatedVSD() )
+        {          
+          TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+          TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+          uiAct4Dist = m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, pcVirRec->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirOrg->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirRec->getStride(), uiWidth, uiHeight );
+#if LGE_WVSO_A0119
+          if ( m_pcRdCost->getUseWVSO() )
+          {    
+            Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+            Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+            Dist iD = (Dist) m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false, DF_SAD );
+            uiAct4Dist = (iDWeight * iD + iVSDWeight * (Dist) uiAct4Dist) / ( iDWeight + iVSDWeight);
+          }
+#endif // LGE_WVSO_A0119
+        }
+        else       
+#endif // SAIT_VSO_EST_A0033
+        {        
+          uiAct4Dist = m_pcRdCost->getDistVS( pcCU, 0, piPredic, uiStride,  piOrig, uiStride, uiWidth, uiHeight, false, 0 );
+#if LGE_WVSO_A0119
+          if ( m_pcRdCost->getUseWVSO() )
+          {    
+            Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+            Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+            Dist iD = (Dist) m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false, DF_SAD );
+            uiAct4Dist = (iDWeight * iD + iVSOWeight * (Dist) uiAct4Dist) / ( iDWeight + iVSOWeight);
+          }
+#endif // LGE_WVSO_A0119
+        }
+
+        if( uiAct4Dist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+        {
+          uiBestDist     = uiAct4Dist;
+          uiBestQStepDC1 = uiQStepDC1;
+          uiBestQStepDC2 = uiQStepDC2;
+        }
+      }
+    }
+
+    // refinement +-3
+    for( UInt uiQStepDC1 = (UInt)max(0, ((Int)uiBestQStepDC1-3)); uiQStepDC1 <= (uiBestQStepDC1+3); uiQStepDC1++ )
+    {
+      Int iTestDC1 = Clip( iPredDC1 + ((Int)(uiQStepDC1) * (Int)(( iFullDeltaDC1 < 0 ) ? -1 : 1)) );
+      for( UInt uiQStepDC2 = (UInt)max(0, ((Int)uiBestQStepDC2-3)); uiQStepDC2 <= (uiBestQStepDC2+3); uiQStepDC2++ )
+      {
+        Int iTestDC2 = Clip( iPredDC2 + ((Int)(uiQStepDC2) * (Int)(( iFullDeltaDC2 < 0 ) ? -1 : 1)) );
+
+        assignWedgeDCs2Pred( pcWedgelet, piPredic, uiStride, iTestDC1, iTestDC2 );
+
+        Dist uiActDist = RDO_DIST_MAX;
+#if SAIT_VSO_EST_A0033
+        if ( m_pcRdCost->getUseEstimatedVSD() )
+        {          
+          TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+          TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+          uiActDist = m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, pcVirRec->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirOrg->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirRec->getStride(), uiWidth, uiHeight );
+#if LGE_WVSO_A0119
+          if ( m_pcRdCost->getUseWVSO() )
+          {    
+            Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+            Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+            Dist iD = (Dist) m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false, DF_SAD );
+            uiActDist = (iDWeight * iD + iVSDWeight * (Dist) uiActDist) / ( iDWeight + iVSDWeight);
+          }
+#endif // LGE_WVSO_A0119
+        }
+        else       
+#endif // SAIT_VSO_EST_A0033
+        {        
+          uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPredic, uiStride,  piOrig, uiStride, uiWidth, uiHeight, false, 0 );
+#if LGE_WVSO_A0119
+          if ( m_pcRdCost->getUseWVSO() )
+          {    
+            Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+            Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+            Dist iD = (Dist) m_pcRdCost->getDistPart( piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false, DF_SAD );
+            uiActDist = (iDWeight * iD + iVSOWeight * (Dist) uiActDist) / ( iDWeight + iVSOWeight);
+          }
+#endif // LGE_WVSO_A0119
+        }
+
+        if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+        {
+          uiBestDist     = uiActDist;
+          uiBestQStepDC1 = uiQStepDC1;
+          uiBestQStepDC2 = uiQStepDC2;
+        }
+      }
+    }
+
+    iFullDeltaDC1 = (Int)(uiBestQStepDC1) * (Int)(( iFullDeltaDC1 < 0 ) ? -1 : 1);
+    iFullDeltaDC2 = (Int)(uiBestQStepDC2) * (Int)(( iFullDeltaDC2 < 0 ) ? -1 : 1);
+
+    riDeltaDC1 = iFullDeltaDC1;
+    riDeltaDC2 = iFullDeltaDC2;
+  }
+#endif
+
+}
+#endif
+#if HHI_DMM_WEDGE_INTRA
+Void TEncSearch::findWedgeFullMinDist( TComDataCU*  pcCU,
+                                       UInt         uiAbsPtIdx,
+                                       Pel*         piOrig,
+                                       Pel*         piPredic,
+                                       UInt         uiStride,
+                                       UInt         uiWidth,
+                                       UInt         uiHeight,
+                                       UInt&        ruiTabIdx,
+                                       Int&         riDeltaDC1,
+                                       Int&         riDeltaDC2,
+                                       Bool         bAboveAvail,
+                                       Bool         bLeftAvail )
+{
+  assert( uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+  Dist iDist = RDO_DIST_MAX;
+  WedgeNodeList* pacWedgeNodeList = &g_aacWedgeNodeLists[(g_aucConvertToBit[uiWidth])];
+  xSearchWedgeFullMinDistFast( pcCU, uiAbsPtIdx, pacWedgeNodeList, pacWedgeList, piOrig, uiStride, uiWidth, uiHeight, ruiTabIdx, iDist );
+
+  TComWedgelet* pcBestWedgelet = &(pacWedgeList->at(ruiTabIdx));
+  xGetWedgeDeltaDCsMinDist( pcBestWedgelet, pcCU, uiAbsPtIdx, piOrig, piPredic, uiStride, uiWidth, uiHeight, riDeltaDC1, riDeltaDC2, bAboveAvail, bLeftAvail );
+}
+
+Void TEncSearch::findWedgePredDirMinDist( TComDataCU*  pcCU,
+                                          UInt         uiAbsPtIdx,
+                                          Pel*         piOrig,
+                                          Pel*         piPredic,
+                                          UInt         uiStride,
+                                          UInt         uiWidth,
+                                          UInt         uiHeight,
+                                          UInt&        ruiTabIdx,
+                                          Int&         riWedgeDeltaEnd,
+                                          Int&         riDeltaDC1,
+                                          Int&         riDeltaDC2,
+                                          Bool         bAboveAvail,
+                                          Bool         bLeftAvail )
+{
+  assert( uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+
+  ruiTabIdx       = 0;
+  riWedgeDeltaEnd = 0;
+
+  xSearchWedgePredDirMinDist( pcCU, uiAbsPtIdx, pacWedgeList, piOrig, uiStride, uiWidth, uiHeight, ruiTabIdx, riWedgeDeltaEnd );
+
+  TComWedgelet* pcBestWedgelet = &(pacWedgeList->at(ruiTabIdx));
+  xGetWedgeDeltaDCsMinDist( pcBestWedgelet, pcCU, uiAbsPtIdx, piOrig, piPredic, uiStride, uiWidth, uiHeight, riDeltaDC1, riDeltaDC2, bAboveAvail, bLeftAvail );
+}
+
+Void TEncSearch::xSearchWedgeFullMinDist( TComDataCU* pcCU, UInt uiAbsPtIdx, WedgeList* pacWedgeList, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, Dist& riDist )
+{
+  ruiTabIdx = 0;
+
+  // local pred buffer
+  TComYuv cPredYuv;
+  cPredYuv.create( uiWidth, uiHeight );
+  cPredYuv.clear();
+
+  UInt uiPredStride = cPredYuv.getStride();
+  Pel* piPred       = cPredYuv.getLumaAddr();
+
+  Int  iDC1 = 0;
+  Int  iDC2 = 0;
+  // regular wedge search
+  Dist uiBestDist   = RDO_DIST_MAX;
+  UInt uiBestTabIdx = 0;
+
+  for( UInt uiIdx = 0; uiIdx < pacWedgeList->size(); uiIdx++ )
+  {
+    calcWedgeDCs       ( &(pacWedgeList->at(uiIdx)), piRef,  uiRefStride,  iDC1, iDC2 );
+    assignWedgeDCs2Pred( &(pacWedgeList->at(uiIdx)), piPred, uiPredStride, iDC1, iDC2 );
+
+    Dist uiActDist = RDO_DIST_MAX;
+#if HHI_VSO
+    if( m_pcRdCost->getUseVSO() )
+    {
+#if SAIT_VSO_EST_A0033
+      if ( m_pcRdCost->getUseEstimatedVSD() )
+      {          
+        TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+        TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+        uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, pcVirRec->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirOrg->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirRec->getStride(), uiWidth, uiHeight );
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+          Dist iD = (Dist) m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+          uiActDist = (iDWeight * iD + iVSDWeight * (Int) uiActDist) / ( iDWeight + iVSDWeight);
+        }
+#endif
+      }
+      else
+#endif
+      {      
+        uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, 0 );
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+          Dist iD = (Dist) m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+          uiActDist = (iDWeight * iD + iVSOWeight * (Int) uiActDist) / ( iDWeight + iVSOWeight);
+        }
+#endif
+      }
+    }
+    else
+    {
+      uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+    }
+#else
+    uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+#endif
+
+    if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+    {
+      uiBestDist   = uiActDist;
+      uiBestTabIdx = uiIdx;
+    }
+  }
+  ruiTabIdx = uiBestTabIdx;
+  riDist    = uiBestDist;
+
+  cPredYuv.destroy();
+  return;
+}
+
+Void TEncSearch::xSearchWedgeFullMinDistFast( TComDataCU* pcCU, UInt uiAbsPtIdx, WedgeNodeList* pacWedgeNodeList, WedgeList* pacWedgeList, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, Dist& riDist )
+{
+  ruiTabIdx = 0;
+
+  // local pred buffer
+  TComYuv cPredYuv;
+  cPredYuv.create( uiWidth, uiHeight );
+  cPredYuv.clear();
+
+  UInt uiPredStride = cPredYuv.getStride();
+  Pel* piPred       = cPredYuv.getLumaAddr();
+
+  Int  iDC1 = 0;
+  Int  iDC2 = 0;
+
+  // coarse wedge search
+  Dist uiBestDist   = RDO_DIST_MAX;
+  UInt uiBestNodeId = 0;
+  for( UInt uiNodeId = 0; uiNodeId < pacWedgeNodeList->size(); uiNodeId++ )
+  {
+    calcWedgeDCs       ( &(pacWedgeList->at(pacWedgeNodeList->at(uiNodeId).getPatternIdx())), piRef,  uiRefStride,  iDC1, iDC2 );
+    assignWedgeDCs2Pred( &(pacWedgeList->at(pacWedgeNodeList->at(uiNodeId).getPatternIdx())), piPred, uiPredStride, iDC1, iDC2 );
+
+    Dist uiActDist = RDO_DIST_MAX;
+#if HHI_VSO
+    if( m_pcRdCost->getUseVSO() )
+    {
+#if SAIT_VSO_EST_A0033
+      if ( m_pcRdCost->getUseEstimatedVSD() )
+      {          
+        TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+        TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+        uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, pcVirRec->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirOrg->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()), pcVirRec->getStride(), uiWidth, uiHeight );
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+          Dist iD = (Dist) m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+          uiActDist = (iDWeight * iD + iVSDWeight * (Int) uiActDist) / ( iDWeight + iVSDWeight);
+        }
+#endif
+      }
+      else
+#endif
+      {
+        uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, 0 );
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+          Dist iD = (Dist) m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+          uiActDist = (iDWeight * iD + iVSOWeight * (Int) uiActDist) / ( iDWeight + iVSOWeight);
+        }
+#endif
+      }
+    }
+    else
+    {
+      uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+    }
+#else
+    uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+#endif
+    if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+    {
+      uiBestDist   = uiActDist;
+      uiBestNodeId = uiNodeId;
+    }
+  }
+
+  // refinement
+  Dist uiBestDistRef = uiBestDist;
+  UInt uiBestTabIdxRef  = pacWedgeNodeList->at(uiBestNodeId).getPatternIdx();
+  for( UInt uiRefId = 0; uiRefId < NUM_WEDGE_REFINES; uiRefId++ )
+  {
+    if( pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId ) != NO_IDX )
+    {
+      calcWedgeDCs       ( &(pacWedgeList->at(pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId ))), piRef,  uiRefStride,  iDC1, iDC2 );
+      assignWedgeDCs2Pred( &(pacWedgeList->at(pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId ))), piPred, uiPredStride, iDC1, iDC2 );
+
+      Dist uiActDist = RDO_DIST_MAX;
+#if HHI_VSO
+      if( m_pcRdCost->getUseVSO() )
+      {
+        uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, 0 );
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+          Dist iD = (Dist) m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+          uiActDist = (iDWeight * iD + iVSOWeight * (Int) uiActDist) / ( iDWeight + iVSOWeight);
+        }
+#endif
+      }
+      else
+      {
+        uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+      }
+#else
+      uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+#endif
+      if( uiActDist < uiBestDistRef || uiBestDistRef == RDO_DIST_MAX )
+      {
+        uiBestDistRef   = uiActDist;
+        uiBestTabIdxRef = pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId );
+      }
+    }
+  }
+
+  riDist    = uiBestDistRef;
+  ruiTabIdx = uiBestTabIdxRef;
+
+  cPredYuv.destroy();
+  return;
+}
+
+Void TEncSearch::xSearchWedgePredDirMinDist( TComDataCU* pcCU, UInt uiAbsPtIdx, WedgeList* pacWedgeList, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, Int& riWedgeDeltaEnd )
+{
+  ruiTabIdx       = 0;
+  riWedgeDeltaEnd = 0;
+
+  // local pred buffer
+  TComYuv cPredYuv;
+  cPredYuv.create( uiWidth, uiHeight );
+  cPredYuv.clear();
+
+  UInt uiPredStride = cPredYuv.getStride();
+  Pel* piPred       = cPredYuv.getLumaAddr();
+
+  Int  iDC1 = 0;
+  Int  iDC2 = 0;
+
+  // regular wedge search
+  Dist uiBestDist    = RDO_DIST_MAX;
+  UInt uiBestTabIdx  = 0;
+  Int  iBestDeltaEnd = 0;
+
+  UInt uiIdx = 0;
+  for( Int iTestDeltaEnd = -DMM_WEDGE_PREDDIR_DELTAEND_MAX; iTestDeltaEnd <= DMM_WEDGE_PREDDIR_DELTAEND_MAX; iTestDeltaEnd++ )
+  {
+    uiIdx = getBestContinueWedge( pcCU, uiAbsPtIdx, uiWidth, uiHeight, iTestDeltaEnd );
+    calcWedgeDCs       ( &(pacWedgeList->at(uiIdx)), piRef,  uiRefStride,  iDC1, iDC2 );
+    assignWedgeDCs2Pred( &(pacWedgeList->at(uiIdx)), piPred, uiPredStride, iDC1, iDC2 );
+
+    Dist uiActDist = RDO_DIST_MAX;
+#if HHI_VSO
+    if( m_pcRdCost->getUseVSO() )
+    {
+#if SAIT_VSO_EST_A0033
+      if ( m_pcRdCost->getUseEstimatedVSD() )
+      {          
+        TComPicYuv* pcVirRec = m_pcRdCost->getVideoRecPicYuv();
+        TComPicYuv* pcVirOrg = m_pcRdCost->getDepthPicYuv();
+        uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, pcVirRec->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiAbsPtIdx), pcVirOrg->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiAbsPtIdx), pcVirRec->getStride(), uiWidth, uiHeight );
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSDWeight = m_pcRdCost->getVSDWeight() * m_pcRdCost->getVSDWeight();
+          Dist iD = (Dist) m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+          uiActDist = (iDWeight * iD + iVSDWeight * (Int) uiActDist) / ( iDWeight + iVSDWeight);
+        }
+#endif
+      }
+      else
+#endif
+      {      
+        uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, 0 );
+#if LGE_WVSO_A0119
+        if ( m_pcRdCost->getUseWVSO() )
+        {    
+          Int iDWeight = m_pcRdCost->getDWeight() * m_pcRdCost->getDWeight();
+          Int iVSOWeight = m_pcRdCost->getVSOWeight() * m_pcRdCost->getVSOWeight();
+          Dist iD = (Dist) m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+          uiActDist = (iDWeight * iD + iVSOWeight * (Int) uiActDist) / ( iDWeight + iVSOWeight);
+        }
+#endif
+      }
+    }
+    else
+    {
+      uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+    }
+#else
+    uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, DF_SAD );
+#endif
+
+    if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+    {
+      uiBestDist    = uiActDist;
+      uiBestTabIdx  = uiIdx;
+      iBestDeltaEnd = iTestDeltaEnd;
+    }
+    else if( uiIdx == uiBestTabIdx && abs(iTestDeltaEnd) < abs(iBestDeltaEnd) )
+    {
+      iBestDeltaEnd = iTestDeltaEnd;
+    }
+  }
+
+  ruiTabIdx       = uiBestTabIdx;
+  riWedgeDeltaEnd = iBestDeltaEnd;
+
+  cPredYuv.destroy();
+  return;
+}
+#endif //  HHI_DMM_WEDGE_INTRA
+
+#if HHI_DMM_PRED_TEX
+Void TEncSearch::findWedgeTexMinDist( TComDataCU*  pcCU, 
+                                      UInt         uiAbsPtIdx, 
+                                      Pel*         piOrig, 
+                                      Pel*         piPredic, 
+                                      UInt         uiStride, 
+                                      UInt         uiWidth, 
+                                      UInt         uiHeight, 
+                                      UInt&        ruiTabIdx, 
+                                      Int&         riDeltaDC1, 
+                                      Int&         riDeltaDC2, 
+                                      Bool         bAboveAvail, 
+                                      Bool         bLeftAvail
+#if LGE_DMM3_SIMP_C0044
+                                      ,UInt&        ruiIntraTabIdx
+#endif
+                                      )
+{
+  assert( uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+
+#if LGE_DMM3_SIMP_C0044
+  ruiTabIdx = getBestWedgeFromTex( pcCU, uiAbsPtIdx, uiWidth, uiHeight, piOrig, uiStride, ruiIntraTabIdx );
+#else
+  ruiTabIdx = getBestWedgeFromTex( pcCU, uiAbsPtIdx, uiWidth, uiHeight );
+#endif
+
+  TComWedgelet* pcBestWedgelet = &(pacWedgeList->at(ruiTabIdx));
+  xGetWedgeDeltaDCsMinDist( pcBestWedgelet, pcCU, uiAbsPtIdx, piOrig, piPredic, uiStride, uiWidth, uiHeight, riDeltaDC1, riDeltaDC2, bAboveAvail, bLeftAvail );
+}
+
+Void TEncSearch::findContourPredTex( TComDataCU*  pcCU,
+                                     UInt         uiAbsPtIdx,
+                                     Pel*         piOrig,
+                                     Pel*         piPredic,
+                                     UInt         uiStride,
+                                     UInt         uiWidth,
+                                     UInt         uiHeight,
+                                     Int&         riDeltaDC1,
+                                     Int&         riDeltaDC2,
+                                     Bool         bAboveAvail,
+                                     Bool         bLeftAvail )
+{
+  // get contour pattern
+  TComWedgelet* pcContourWedge = new TComWedgelet( uiWidth, uiHeight );
+  getBestContourFromTex( pcCU, uiAbsPtIdx, uiWidth, uiHeight, pcContourWedge );
+
+  xGetWedgeDeltaDCsMinDist( pcContourWedge, pcCU, uiAbsPtIdx, piOrig, piPredic, uiStride, uiWidth, uiHeight, riDeltaDC1, riDeltaDC2, bAboveAvail, bLeftAvail );
+
+  pcContourWedge->destroy();
+  delete pcContourWedge;
+}
+#endif // HHI_DMM_PRED_TEX
+
+#if LGE_EDGE_INTRA_A0070
+Bool TEncSearch::xCheckTerminatedEdge( Bool* pbEdge, Int iX, Int iY, Int iWidth, Int iHeight )
+{
+  if( (iY % 2) == 0 ) // vertical edge
+  {
+    Bool bTopConnected = false;
+    Bool bBottomConnected = false;
+
+    if( iY != 0 )
+    {
+      if( pbEdge[ iX + (iY - 2) * 2 * iWidth ] )
+        bTopConnected = true;
+      if( pbEdge[ (iX - 1) + (iY - 1) * 2 * iWidth ] )
+        bTopConnected = true;
+      if( pbEdge[ (iX + 1) + (iY - 1) * 2 * iWidth ] )
+        bTopConnected = true;
+    }
+    else
+    {
+      bTopConnected = true;
+    }
+
+
+    if( iY != 2 * iHeight - 2 )
+    {
+      if( pbEdge[ iX + (iY + 2) * 2 * iWidth ] )
+        bBottomConnected = true;
+      if( pbEdge[ (iX - 1) + (iY + 1) * 2 * iWidth ] )
+        bBottomConnected = true;
+      if( pbEdge[ (iX + 1) + (iY + 1) * 2 * iWidth ] )
+        bBottomConnected = true;
+    }
+    else
+    {
+      bBottomConnected = true;
+    }
+
+
+    if( bTopConnected && bBottomConnected )
+    {
+      return true;
+    }
+    else
+    {
+      return false;
+    }
+  }
+  else
+  {
+    Bool bLeftConnected = false;
+    Bool bRightConnected = false;
+
+    if( iX != 0 )
+    {
+      if( pbEdge[ (iX - 2) + iY * 2 * iWidth ] )
+        bLeftConnected = true;
+      if( pbEdge[ (iX - 1) + (iY - 1) * 2 * iWidth ] )
+        bLeftConnected = true;
+      if( pbEdge[ (iX - 1) + (iY + 1) * 2 * iWidth ] )
+        bLeftConnected = true;
+    }
+    else
+    {
+      bLeftConnected = true;
+    }
+
+    if( iX != 2 * iWidth - 2 )
+    {
+      if( pbEdge[ (iX + 2) + iY * 2 * iWidth ] )
+        bRightConnected = true;
+      if( pbEdge[ (iX + 1) + (iY - 1) * 2 * iWidth ] )
+        bRightConnected = true;
+      if( pbEdge[ (iX + 1) + (iY + 1) * 2 * iWidth ] )
+        bRightConnected = true;
+    }
+    else
+    {
+      bRightConnected = true;
+    }
+
+
+    if( bLeftConnected && bRightConnected )
+    {
+      return true;
+    }
+    else
+    {
+      return false;
+    }
+  }
+}
+
+#if LGE_EDGE_INTRA_PIXEL_DIFFERENCE
+Bool TEncSearch::xEdgePartition( TComDataCU* pcCU, UInt uiPartIdx, Bool bPU4x4 )
+{
+  Pel* pcOrgY   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr());
+  UInt uiStride = pcCU->getPic()->getPicYuvOrg()->getStride();
+  Int iWidth    = pcCU->getWidth(uiPartIdx) >> (bPU4x4 ? 1 : 0);
+  Int iHeight   = pcCU->getHeight(uiPartIdx) >> (bPU4x4 ? 1 : 0);
+  Bool* pbEdge  = (Bool*) xMalloc( Bool, iWidth * iHeight * 4 );
+
+  {
+    UInt uiOffsetX = 0;
+    UInt uiOffsetY = 0;
+    UInt uiAbsPartIdx = pcCU->getZorderIdxInCU() + uiPartIdx;
+
+    uiOffsetX =  (uiAbsPartIdx & 0x1) |
+      ((uiAbsPartIdx & 0x4)  >> 1) |
+      ((uiAbsPartIdx & 0x10) >> 2) |
+      ((uiAbsPartIdx & 0x40) >> 3);
+    uiOffsetY = ((uiAbsPartIdx & 0x2)  >> 1) |
+      ((uiAbsPartIdx & 0x8)  >> 2) |
+      ((uiAbsPartIdx & 0x20) >> 3) |
+      ((uiAbsPartIdx & 0x80) >> 4);
+    uiOffsetX *= 4;
+    uiOffsetY *= 4;
+    pcOrgY += (uiOffsetX + uiOffsetY * uiStride);
+
+  }
+
+  Short* psDiffX = new Short[ iWidth * iHeight ];
+  Short* psDiffY = new Short[ iWidth * iHeight ];
+  Bool*  pbEdgeX = new Bool [ iWidth * iHeight ];
+  Bool*  pbEdgeY = new Bool [ iWidth * iHeight ];
+
+  // Find Horizontal Gradient & Edge Detection ((x+1, y) - (x,y))
+  for( Int y=0; y<iHeight; y++ )
+  {
+    Short* psDiffXPtr = &psDiffX[ y * iHeight ];
+    Bool*  pbEdgeXPtr = &pbEdgeX[ y * iHeight ];
+    for(Int x=0; x<iWidth-1; x++ )
+    {
+      *psDiffXPtr = pcOrgY[ x+1 + y*uiStride ] - pcOrgY[ x + y*uiStride ];
+      if(*psDiffXPtr >= LGE_EDGE_INTRA_THRESHOLD || *psDiffXPtr <= (-1)*LGE_EDGE_INTRA_THRESHOLD)
+      {
+        *pbEdgeXPtr = true;
+      }
+      else
+      {
+        *pbEdgeXPtr = false;
+      }
+
+      psDiffXPtr++;
+      pbEdgeXPtr++;
+    }
+  }
+
+  // Find Vertical Gradient & Edge Detection((x,y+1) - (x,y))
+  for( Int y=0; y<iHeight-1; y++ )
+  {
+    Short* psDiffYPtr = &psDiffY[ y * iHeight ];
+    Bool*  pbEdgeYPtr = &pbEdgeY[ y * iHeight ];
+    for(Int x=0; x<iWidth; x++ )
+    {
+      *psDiffYPtr = pcOrgY[ x + (y+1)*uiStride ] - pcOrgY [ x + y*uiStride ];
+      if(*psDiffYPtr >= LGE_EDGE_INTRA_THRESHOLD || *psDiffYPtr <= (-1)*LGE_EDGE_INTRA_THRESHOLD)
+      {
+        *pbEdgeYPtr = true;
+      }
+      else
+      {
+        *pbEdgeYPtr = false;
+      }
+
+      psDiffYPtr++;
+      pbEdgeYPtr++;
+    }
+  }
+
+  // Eliminate local maximum
+  for( Int y=0; y<iHeight; y++ )
+  {
+    Short* psDiffXPtr = &psDiffX[ y * iHeight ];
+    Bool*  pbEdgeXPtr = &pbEdgeX[ y * iHeight ];
+    for( Int x=0; x<iWidth-1; x++ )
+    {
+      UShort usAbs0=0, usAbs1=0, usAbs2=0;  // 0 : left, 1 : current, 2 : right
+
+      if( x > 0 && *(pbEdgeXPtr-1) == true )
+      {
+        if( *(psDiffXPtr-1) >= 0)
+        {
+          usAbs0 = *(psDiffXPtr-1);
+
+        }
+        else
+        {
+          usAbs0 = (-1) * *(psDiffXPtr-1);
+        }
+      }
+      if( *pbEdgeXPtr == true )
+      {
+        if( *(psDiffXPtr) >= 0)
+        {
+          usAbs1 = *(psDiffXPtr);
+        }
+        else
+        {
+          usAbs1 = (-1) * *(psDiffXPtr);
+        }
+      }
+      if( x < iWidth-2 && *(pbEdgeXPtr+1) == true )
+      {
+        if( *(psDiffXPtr+1) >= 0)
+        {
+          usAbs2 = *(psDiffXPtr+1);
+          //bSign2 = true;
+        }
+        else
+        {
+          usAbs2 = (-1) * *(psDiffXPtr+1);
+        }
+      }
+
+      if( x == 0 )
+      {
+        if( usAbs1 < usAbs2 )
+        {
+          *pbEdgeXPtr = false;
+        }
+      }
+      else if( x == iWidth-2 )
+      {
+        if( usAbs1 <= usAbs0 )
+          *pbEdgeXPtr = false;
+      }
+      else
+      {
+        if( usAbs2 > usAbs0 )
+        {
+          if( usAbs1 < usAbs2 )
+            *pbEdgeXPtr = false;
+        }
+        else
+        {
+          if( usAbs1 <= usAbs0 )
+            *pbEdgeXPtr = false;
+        }
+      }
+
+      psDiffXPtr++;
+      pbEdgeXPtr++;
+    }
+  }
+
+  for( Int y=0; y<iHeight-1; y++ )
+  {
+    Short* psDiffYPtr = &psDiffY[ y * iWidth ];
+    Bool*  pbEdgeYPtr = &pbEdgeY[ y * iWidth ];
+    for( Int x=0; x<iWidth; x++ )
+    {
+      UShort usAbs0=0, usAbs1=0, usAbs2=0;  // 0 : upper, 1 : current, 2 : bottom
+      if( y > 0 && *(pbEdgeYPtr-iWidth) == true )
+      {
+        if( *(psDiffYPtr-iWidth) >= 0)
+        {
+          usAbs0 = *(psDiffYPtr-iWidth);
+        }
+        else
+        {
+          usAbs0 = (-1) * *(psDiffYPtr-iWidth);          
+        }
+      }
+      if( *pbEdgeYPtr == true )
+      {
+        if( *(psDiffYPtr) >= 0)
+        {
+          usAbs1 = *(psDiffYPtr);
+        }
+        else
+        {
+          usAbs1 = (-1) * *(psDiffYPtr);
+        }
+      }
+      if( y < iHeight-2 && *(pbEdgeYPtr+iWidth) == true )
+      {
+        if( *(psDiffYPtr+iWidth) >= 0)
+        {
+          usAbs2 = *(psDiffYPtr+iWidth);          
+        }
+        else
+        {
+          usAbs2 = (-1) * *(psDiffYPtr+iWidth);
+        }
+      }
+
+      if( y == 0 )
+      {
+        if( usAbs1 < usAbs2 )
+          *pbEdgeYPtr = false;
+      }
+      else if( y == iHeight-2 )
+      {
+        if( usAbs1 <= usAbs0 )
+          *pbEdgeYPtr = false;
+      }
+      else
+      {
+        if( usAbs2 > usAbs0 )
+        {
+          if( usAbs1 < usAbs2 )
+            *pbEdgeYPtr = false;
+        }
+        else
+        {
+          if( usAbs1 <= usAbs0 )
+            *pbEdgeYPtr = false;
+        }
+      }
+
+      psDiffYPtr++;
+      pbEdgeYPtr++;
+    }
+  }
+
+  // Edge Merging
+  for( Int i=0; i< 4 * iWidth * iHeight; i++ )
+    pbEdge[ i ] = false;
+  /// Even Line (0,2,4,6,...) => Vertical Edge
+  for( Int i=0; i<iHeight; i++)
+  {
+    for( Int j=0; j<iWidth-1; j++)
+    {
+      pbEdge[ (2 * j + 1) + (2 * i) * 2 * iWidth ] = pbEdgeX[ j + i * iHeight ];
+    }
+  }
+  /// Odd Line (1,3,5,7,...) => Horizontal Edge
+  for( Int i=0; i<iHeight-1; i++)
+  {
+    for( Int j=0; j<iWidth; j++)
+    {
+      pbEdge[ (2 * j) + (2 * i + 1) * 2 * iWidth ] = pbEdgeY[ j + i * iHeight ]; 
+    }
+  }
+
+  // Intersection Filling
+  /// Vertical Edge between Horizontal Edges
+  for( Int i = 1; i < 2 * iHeight - 3; i += 2)
+  {
+    for( Int j = 0; j < 2 * iWidth - 1; j += 2)
+    {
+      if( pbEdge[ j + i * 2 * iWidth ] )
+      {
+        if( j != 0 && pbEdge[ (j - 2) + ((i + 2) * 2 * iWidth) ] )
+        {
+          if( !pbEdge[ (j - 1) + ((i - 1) * 2 * iWidth) ] && !pbEdge[ (j - 1) + ((i + 3) * 2 * iWidth) ] )
+            pbEdge[ (j - 1) + ((i + 1) * 2 * iWidth) ] = true;
+        }
+        if( j != 2 * iWidth - 2 && pbEdge[ (j + 2) + ((i + 2) * 2 * iWidth) ] )
+        {
+          if( !pbEdge[ (j + 1) + ((i - 1) * 2 * iWidth) ] && !pbEdge[ (j + 1) + ((i + 3) * 2 * iWidth) ] )
+            pbEdge[ (j + 1) + ((i + 1) * 2 * iWidth) ] = true;
+        }
+      }
+    }
+  }
+  /// Horizontal Edge between Vertical Edges
+  for( Int j = 1; j < 2 * iWidth - 3; j += 2)
+  {
+    for( Int i = 0; i < 2 * iHeight - 1; i += 2)
+    {
+      if( pbEdge[ j + i * 2 * iWidth ] )
+      {
+        if( i != 0 && pbEdge[ (j + 2) + ((i - 2) * 2 * iWidth) ] )
+        {
+          if( !pbEdge[ (j - 1) + ((i - 1) * 2 * iWidth) ] && !pbEdge[ (j + 3) + ((i - 1) * 2 * iWidth) ] )
+            pbEdge[ (j + 1) + ((i - 1) * 2 * iWidth) ] = true;
+        }
+        if( i != 2 * iHeight - 2 && pbEdge[ (j + 2) + ((i + 2) * 2 * iWidth) ] )
+        {
+          if( !pbEdge[ (j - 1) + ((i + 1) * 2 * iWidth) ] && !pbEdge[ (j + 3) + ((i + 1) * 2 * iWidth) ] )
+            pbEdge[ (j + 1) + ((i + 1) * 2 * iWidth) ] = true;
+        }
+      }
+    }
+  }
+
+  // Static Pruning Unnecessary Edges
+  /// Step1. Stack push the unconnected edges
+  UShort* pusUnconnectedEdgeStack = new UShort[ 4 * iWidth * iHeight ]; // approximate size calculation
+  Int iUnconnectedEdgeStackPtr = 0;
+  //// Vertical Edges
+  for( Int i = 0; i < 2 * iHeight - 1; i += 2 )
+  {
+    for( Int j = 1; j < 2 * iWidth - 2; j += 2 )
+    {
+      if( pbEdge[ j + i * 2 * iWidth ] )
+      {
+        if( !xCheckTerminatedEdge( pbEdge, j, i, iWidth, iHeight ) )
+        {
+          pusUnconnectedEdgeStack[iUnconnectedEdgeStackPtr] = (i << 8) | (j);
+          iUnconnectedEdgeStackPtr++;
+        }
+      }
+    }
+  }
+
+  //// Horizontal Edges
+  for( Int i = 1; i < 2 * iHeight - 2; i += 2 )
+  {
+    for( Int j = 0; j < 2 * iWidth - 1; j += 2 )
+    {
+      if( pbEdge[ j + i * 2 * iWidth ] )
+      {
+        if( !xCheckTerminatedEdge( pbEdge, j, i, iWidth, iHeight ) )
+        {
+          pusUnconnectedEdgeStack[iUnconnectedEdgeStackPtr] = (i << 8) | (j);
+          iUnconnectedEdgeStackPtr++;
+        }
+      }
+    }
+  }
+
+  /// Step2. Remove the edges from the stack and push the new unconnected edges
+  //// (This step may contain duplicated edges already in the stack)
+  //// (But it doesn't cause any functional problems)
+  while( iUnconnectedEdgeStackPtr != 0 )
+  {
+    iUnconnectedEdgeStackPtr--;
+    Int iX = pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] & 0xff;
+    Int iY = pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] >> 8;
+
+    pbEdge[ iX + iY * 2 * iWidth ] = false;
+
+    if( iY % 2 == 1 && iX > 0 && pbEdge[ iX - 2 + iY * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX - 2, iY, iWidth, iHeight ) ) // left
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 0) << 8) | (iX - 2);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iY % 2 == 1 && iX < 2 * iWidth - 2 && pbEdge[ iX + 2 + iY * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX + 2, iY, iWidth, iHeight ) ) // right
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 0) << 8) | (iX + 2);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iY % 2 == 0 && iY > 0 && pbEdge[ iX + (iY - 2) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX, iY - 2, iWidth, iHeight ) ) // top
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY - 2) << 8) | (iX + 0);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iY % 2 == 0 && iY < 2 * iHeight - 2 && pbEdge[ iX + (iY + 2) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX, iY + 2, iWidth, iHeight ) ) // bottom
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 2) << 8) | (iX + 0);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iX > 0 && iY > 0 && pbEdge[ iX - 1 + (iY - 1) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX - 1, iY - 1, iWidth, iHeight ) ) // left-top
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY - 1) << 8) | (iX - 1);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iX < 2 * iWidth - 1 && iY > 0 && pbEdge[ iX + 1 + (iY - 1) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX + 1, iY - 1, iWidth, iHeight ) ) // right-top
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY - 1) << 8) | (iX + 1);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iX > 0 && iY < 2 * iHeight - 1 && pbEdge[ iX - 1 + (iY + 1) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX - 1, iY + 1, iWidth, iHeight ) ) // left-bottom
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 1) << 8) | (iX - 1);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iX < 2 * iWidth - 1 && iY < 2 * iHeight - 1 && pbEdge[ iX + 1 + (iY + 1) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX + 1, iY + 1, iWidth, iHeight ) ) // right-bottom
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 1) << 8) | (iX + 1);
+      iUnconnectedEdgeStackPtr++;
+    }
+  }
+
+
+  // Region Generation ( edge -> region )
+  Bool* pbRegion = pcCU->getEdgePartition( uiPartIdx );
+  Bool* pbVisit  = new Bool[ iWidth * iHeight ];
+
+  for( UInt ui = 0; ui < iWidth * iHeight; ui++ )
+  {
+    pbRegion[ ui ] = true; // fill it as region 1 (we'll discover region 0 next)
+    pbVisit [ ui ] = false;
+  }
+
+  Int* piStack = new Int[ iWidth * iHeight ];
+
+  Int iPtr = 0;
+
+  piStack[iPtr++] = (0 << 8) | (0);
+  pbRegion[ 0 ] = false;
+
+  while(iPtr > 0)
+  {
+    Int iTmp = piStack[--iPtr];
+    Int iX1, iY1;
+    iX1 = iTmp & 0xff;
+    iY1 = (iTmp >> 8) & 0xff;
+
+    pbVisit[ iX1 + iY1 * iWidth ] = true;
+
+    assert( iX1 >= 0 && iX1 < iWidth );
+    assert( iY1 >= 0 && iY1 < iHeight );
+
+    if( iX1 > 0 && !pbEdge[ 2 * iX1 - 1 + 4 * iY1 * iWidth ] && !pbVisit[ iX1 - 1 + iY1 * iWidth ] )
+    {
+      piStack[iPtr++] = (iY1 << 8) | (iX1 - 1);
+      pbRegion[ iX1 - 1 + iY1 * iWidth ] = false;
+    }
+    if( iX1 < iWidth - 1 && !pbEdge[ 2 * iX1 + 1 + 4 * iY1 * iWidth ] && !pbVisit[ iX1 + 1 + iY1 * iWidth ] )
+    {
+      piStack[iPtr++] = (iY1 << 8) | (iX1 + 1);
+      pbRegion[ iX1 + 1 + iY1 * iWidth ] = false;
+    }
+    if( iY1 > 0 && !pbEdge[ 2 * iX1 + 2 * (2 * iY1 - 1) * iWidth ] && !pbVisit[ iX1 + (iY1 - 1) * iWidth ] )
+    {
+      piStack[iPtr++] = ((iY1 - 1) << 8) | iX1;
+      pbRegion[ iX1 + (iY1 - 1) * iWidth ] = false;
+    }
+    if( iY1 < iHeight - 1 && !pbEdge[ 2 * iX1 + 2 * (2 * iY1 + 1) * iWidth ] && !pbVisit[ iX1 + (iY1 + 1) * iWidth ] )
+    {
+      piStack[iPtr++] = ((iY1 + 1) << 8) | iX1;
+      pbRegion[ iX1 + (iY1 + 1) * iWidth ] = false;
+    }
+  }
+
+  ///////////
+  iPtr = 0;
+  for( Int i = 0; i < iWidth * iHeight; i++ )
+    pbVisit[ i ] = false;
+  piStack[ iPtr++ ] = (0 << 8) | (0); // initial seed
+  while( iPtr > 0 && iPtr < iWidth * iHeight )
+  {
+    Int iX;
+    Int iY;
+    iPtr--;
+    iX = piStack[ iPtr ] & 0xff;
+    iY = piStack[ iPtr ] >> 8;
+    pbVisit[ iY * iWidth + iX ] = true;
+
+    if( iY > 0 && !pbVisit[ (iY - 1) * iWidth + iX ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ (iY - 1) * iWidth + iX ] )
+    {
+      piStack[ iPtr++ ] = ((iY - 1) << 8) | iX;
+    }
+    if( iY < iHeight - 1 && !pbVisit[ (iY + 1) * iWidth + iX ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ (iY + 1) * iWidth + iX ] )
+    {
+      piStack[ iPtr++ ] = ((iY + 1) << 8) | iX;
+    }
+    if( iX > 0 && !pbVisit[ iY * iWidth + (iX - 1) ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ iY * iWidth + (iX - 1) ] )
+    {
+      piStack[ iPtr++ ] = (iY << 8) | (iX - 1);
+    }
+    if( iX < iWidth - 1 && !pbVisit[ iY * iWidth + (iX + 1) ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ iY * iWidth + (iX + 1) ] )
+    {
+      piStack[ iPtr++ ] = (iY << 8) | (iX + 1);
+    }
+  }
+  assert( iPtr == 0 || iPtr == iWidth * iHeight );
+
+  Bool bBipartition;
+  if( iPtr == iWidth * iHeight )
+  {
+    bBipartition = false; // single partition
+  }
+  else
+  {
+    for( Int i = 0; i < iWidth * iHeight; i++ )
+    {
+      if( !pbVisit[ i ] )
+      {
+        piStack[ iPtr++ ] = (( i / iWidth ) << 8) | ( i % iWidth );
+        pbVisit[ i ] = true;
+        break;
+      }
+    }
+    while( iPtr > 0 )
+    {
+      Int iX;
+      Int iY;
+      iPtr--;
+      iX = piStack[ iPtr ] & 0xff;
+      iY = piStack[ iPtr ] >> 8;
+      pbVisit[ iY * iWidth + iX ] = true;
+
+      if( iY > 0 && !pbVisit[ (iY - 1) * iWidth + iX ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ (iY - 1) * iWidth + iX ] )
+      {
+        piStack[ iPtr++ ] = ((iY - 1) << 8) | iX;
+      }
+      if( iY < iHeight - 1 && !pbVisit[ (iY + 1) * iWidth + iX ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ (iY + 1) * iWidth + iX ] )
+      {
+        piStack[ iPtr++ ] = ((iY + 1) << 8) | iX;
+      }
+      if( iX > 0 && !pbVisit[ iY * iWidth + (iX - 1) ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ iY * iWidth + (iX - 1) ] )
+      {
+        piStack[ iPtr++ ] = (iY << 8) | (iX - 1);
+      }
+      if( iX < iWidth - 1 && !pbVisit[ iY * iWidth + (iX + 1) ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ iY * iWidth + (iX + 1) ] )
+      {
+        piStack[ iPtr++ ] = (iY << 8) | (iX + 1);
+      }
+    }
+    bBipartition = true;
+    for( Int i = 0; i < iWidth * iHeight; i++ )
+    {
+      if( !pbVisit[ i ] )
+      {
+        bBipartition = false;
+        break;
+      }
+    }
+  }
+
+  xFree( pbEdge );
+  delete[] pbEdgeX; pbEdgeX = NULL;
+  delete[] pbEdgeY; pbEdgeY = NULL;
+  delete[] psDiffX; psDiffX = NULL;
+  delete[] psDiffY; psDiffY = NULL;
+  delete[] pusUnconnectedEdgeStack; pusUnconnectedEdgeStack = NULL;
+  delete[] pbVisit; pbVisit = NULL;
+  delete[] piStack; piStack = NULL;
+
+  Bool bCheckPossibleChain;
+
+  if( bBipartition )
+    bCheckPossibleChain = xConstructChainCode( pcCU, uiPartIdx, bPU4x4 );
+  else
+    bCheckPossibleChain = false;
+
+  return bCheckPossibleChain;
+}
+
+#endif
+
+Bool TEncSearch::xConstructChainCode( TComDataCU* pcCU, UInt uiPartIdx, Bool bPU4x4 )
+{
+  UInt   uiWidth    = pcCU->getWidth( uiPartIdx ) >> (bPU4x4 ? 1 : 0);
+  UInt   uiHeight   = pcCU->getHeight( uiPartIdx ) >> (bPU4x4 ? 1 : 0);
+  Bool*  pbEdge     = (Bool*) xMalloc( Bool, uiWidth * uiHeight * 4 );
+  Bool*  pbVisit    = (Bool*) xMalloc( Bool, uiWidth * uiHeight * 4 );
+  UInt   uiMaxEdge  = uiWidth * (LGE_EDGE_INTRA_MAX_EDGE_NUM_PER_4x4 / 4);
+  Bool*  pbRegion   = pcCU->getEdgePartition( uiPartIdx );
+  UChar* piEdgeCode = pcCU->getEdgeCode( uiPartIdx );
+  Bool   bStartLeft = false;
+  Bool   bPossible  = false;
+  Bool   bFinish    = false;
+  Int    iStartPosition = -1;
+  Int    iPtr = 0;
+  Int    iDir = -1, iNextDir = -1;
+  Int    iArrow = -1, iNextArrow = -1;
+  Int    iX = -1, iY = -1;
+  Int    iDiffX = 0, iDiffY = 0;
+  UChar  iCode = 255;
+  UInt   uiWidth2 = uiWidth * 2;
+
+  for( Int i = 0; i < uiWidth * uiHeight * 4; i++ )
+    pbEdge[ i ] = false;
+
+  for( Int i = 0; i < uiHeight; i++ )
+  {
+    for( Int j = 0; j < uiWidth - 1; j++ )
+    {
+      if( pbRegion[ i * uiWidth + j ] != pbRegion[ i * uiWidth + j + 1 ] )
+        pbEdge[ i * uiWidth * 4 + j * 2 + 1 ] = true;
+    }
+  }
+
+  for( Int i = 0; i < uiHeight - 1; i++ )
+  {
+    for( Int j = 0; j < uiWidth; j++ )
+    {
+      if( pbRegion[ (i + 0) * uiWidth + j ] != pbRegion[ (i + 1) * uiWidth + j ] )
+        pbEdge[ (2 * i + 1) * 2 * uiWidth + j * 2 ] = true;
+    }
+  }
+
+  for( Int i = 1; i < uiWidth2 - 2; i+=2 )
+  {
+    if(pbEdge[ i ])
+    {
+      bPossible  = true;
+      bStartLeft = false;
+      iStartPosition = iX = i;
+      iY = 0;
+      iDir = 3;
+      iArrow = 3;
+      break;
+    }
+  }
+
+  if( !bPossible )
+  {
+    for( Int i = 1; i < uiWidth2 - 2; i+=2 )
+    {
+      if(pbEdge[ i * uiWidth2 ])
+      {
+        bPossible  = true;
+        bStartLeft = true;
+        iX = 0;
+        iStartPosition = iY = i;
+        iDir = 1;
+        iArrow = 1;
+        break;
+      }
+    }
+  }
+
+  if( bPossible )
+  {
+    for( Int i = 0; i < 4 * uiWidth * uiHeight; i++ )
+      pbVisit[ i ] = false;
+
+    while( !bFinish )
+    {
+      Bool bArrowSkip = false;
+      pbVisit[ iX + iY * uiWidth2 ] = true;
+
+      switch( iDir )
+      {
+      case 0: // left
+        if( iX > 0 && !pbVisit[ (iX - 2) + iY * uiWidth2 ] && pbEdge[ (iX - 2) + iY * uiWidth2 ] ) // left
+        {
+          iDiffX = -2;
+          iDiffY =  0;
+          iNextDir = 0;
+          iNextArrow = 0;
+        }
+        else if( iX > 0 && !pbVisit[ (iX - 1) + (iY - 1) * uiWidth2 ] && pbEdge[ (iX - 1) + (iY - 1) * uiWidth2 ] ) // top
+        {
+          iDiffX = -1;
+          iDiffY = -1;
+          iNextDir = 2;
+          iNextArrow = 4;
+        }
+        else if( iX > 0 && !pbVisit[ (iX - 1) + (iY + 1) * uiWidth2 ] && pbEdge[ (iX - 1) + (iY + 1) * uiWidth2 ] ) // bottom
+        {
+          iDiffX = -1;
+          iDiffY = +1;
+          iNextDir = 3;
+          iNextArrow = iArrow;
+          if( !(iPtr == 0 && iX == uiWidth2 - 2 && iY == uiHeight * 2 - 3) )
+            bArrowSkip = true;
+          else
+            iNextArrow = 3;
+        }
+        else if( iX == 0 )
+        {
+          iDiffX = 0;
+          iDiffY = 0;
+          iNextDir = iDir;
+          iNextArrow = iArrow;
+          bFinish = true;
+          continue;
+        }
+        else
+        {
+          iPtr = 0; // edge loop or unwanted case
+          bFinish = true;
+          //continue;
+          assert(false);
+        }
+        break;
+      case 1: // right
+        if( iX < uiWidth2 - 2 && !pbVisit[ (iX + 2) + iY * uiWidth2 ] && pbEdge[ (iX + 2) + iY * uiWidth2 ] ) // right
+        {
+          iDiffX = +2;
+          iDiffY =  0;
+          iNextDir = 1;
+          iNextArrow = 1;
+        }
+        else if( iX < uiWidth2 - 2 && !pbVisit[ (iX + 1) + (iY - 1) * uiWidth2 ] && pbEdge[ (iX + 1) + (iY - 1) * uiWidth2 ] ) // top
+        {
+          iDiffX = +1;
+          iDiffY = -1;
+          iNextDir = 2;
+          iNextArrow = iArrow;
+          if( !(iPtr == 0 && iX == 0 && iY == 1) )
+            bArrowSkip = true;
+          else
+            iNextArrow = 2;
+        }
+        else if( iX < uiWidth2 - 2 && !pbVisit[ (iX + 1) + (iY + 1) * uiWidth2 ] && pbEdge[ (iX + 1) + (iY + 1) * uiWidth2 ] ) // bottom
+        {
+          iDiffX = +1;
+          iDiffY = +1;
+          iNextDir = 3;
+          iNextArrow = 7;
+        }
+        else if( iX == uiWidth2 - 2 )
+        {
+          iDiffX = 0;
+          iDiffY = 0;
+          iNextDir = iDir;
+          iNextArrow = iArrow;
+          bFinish = true;
+          continue;
+        }
+        else
+        {
+          iPtr = 0; // edge loop or unwanted case
+          bFinish = true;
+          //continue;
+          assert(false);
+        }
+        break;
+      case 2: // top
+        if( iY > 0 && !pbVisit[ (iX - 1) + (iY - 1) * uiWidth2 ] && pbEdge[ (iX - 1) + (iY - 1) * uiWidth2 ] ) // left
+        {
+          iDiffX = -1;
+          iDiffY = -1;
+          iNextDir = 0;
+          iNextArrow = iArrow;
+          if( !(iPtr == 0 && iX == 1 && iY == uiHeight * 2 - 2) )
+            bArrowSkip = true;
+          else
+            iNextArrow = 0;
+        }
+        else if( iY > 0 && !pbVisit[ (iX + 1) + (iY - 1) * uiWidth2 ] && pbEdge[ (iX + 1) + (iY - 1) * uiWidth2 ] ) // right
+        {
+          iDiffX = +1;
+          iDiffY = -1;
+          iNextDir = 1;
+          iNextArrow = 5;
+        }
+        else if( iY > 0 && !pbVisit[ iX + (iY - 2) * uiWidth2 ] && pbEdge[ iX + (iY - 2) * uiWidth2 ] ) // top
+        {
+          iDiffX =  0;
+          iDiffY = -2;
+          iNextDir = 2;
+          iNextArrow = 2;
+        }
+        else if( iY == 0 )
+        {
+          iDiffX = 0;
+          iDiffY = 0;
+          iNextDir = iDir;
+          iNextArrow = iArrow;
+          bFinish = true;
+          continue;
+        }
+        else
+        {
+          iPtr = 0; // edge loop or unwanted case
+          bFinish = true;
+          //continue;
+          assert(false);
+        }
+        break;
+      case 3: // bottom
+        if( iY < uiWidth2 - 2 && !pbVisit[ (iX - 1) + (iY + 1) * uiWidth2 ] && pbEdge[ (iX - 1) + (iY + 1) * uiWidth2 ] ) // left
+        {
+          iDiffX = -1;
+          iDiffY = +1;
+          iNextDir = 0;
+          iNextArrow = 6;
+        }
+        else if( iY < uiWidth2 - 2 && !pbVisit[ (iX + 1) + (iY + 1) * uiWidth2 ] && pbEdge[ (iX + 1) + (iY + 1) * uiWidth2 ] ) // right
+        {
+          iDiffX = +1;
+          iDiffY = +1;
+          iNextDir = 1;
+          iNextArrow = iArrow;
+          if( !(iPtr == 0 && iX == uiWidth * 2 - 3 && iY == 0) )
+            bArrowSkip = true;
+          else
+            iNextArrow = 1;
+        }
+        else if( iY < uiWidth2 - 2 && !pbVisit[ iX + (iY + 2) * uiWidth2 ] && pbEdge[ iX + (iY + 2) * uiWidth2 ] ) // bottom
+        {
+          iDiffX =  0;
+          iDiffY = +2;
+          iNextDir = 3;
+          iNextArrow = 3;
+        }
+        else if( iY == uiWidth2 - 2 )
+        {
+          iDiffX = 0;
+          iDiffY = 0;
+          iNextDir = iDir;
+          iNextArrow = iArrow;
+          bFinish = true;
+          continue;
+        }
+        else
+        {
+          iPtr = 0; // edge loop or unwanted case
+          bFinish = true;
+          //continue;
+          assert(false);
+        }
+        break;
+      }
+
+      const UChar tableCode[8][8] = { { 0, -1, 4, 3, 2, 6, 1, 5 }, // iArrow(current direction), iNextArrow(next direction)
+      { -1, 0, 3, 4, 5, 1, 6, 2 },
+      { 3, 4, 0, -1, 1, 2, 5, 6 },
+      { 4, 3, -1, 0, 6, 5, 2, 1 },
+      { 1, 6, 2, 5, 0, 4, 3, -1 },
+      { 5, 2, 1, 6, 3, 0, -1, 4 },
+      { 2, 5, 6, 1, 4, -1, 0, 3 },
+      { 6, 1, 5, 2, -1, 3, 4, 0 } };
+
+      iCode = tableCode[iArrow][iNextArrow];
+
+      if(iPtr >= uiMaxEdge)
+      {
+        iPtr = 0; // over the maximum number of edge
+        bPossible = false;
+        break;
+      }
+
+      if( !bArrowSkip )
+      {
+        piEdgeCode[iPtr++] = iCode; // first edge coding
+        //printf("xEdgeCoding: (%d,%d)->(%d,%d) code %d\n",iX,iY, iX+iDiffX, iY+iDiffY, iCode);
+      }
+
+      iX += iDiffX;
+      iY += iDiffY;
+      iDir = iNextDir;
+      iArrow = iNextArrow;
+    }
+  }
+
+  pcCU->setEdgeLeftFirst( uiPartIdx, bStartLeft );
+  pcCU->setEdgeStartPos ( uiPartIdx, bStartLeft ? (iStartPosition - 1) >> 1 : (iStartPosition + 1) >> 1);
+  pcCU->setEdgeNumber   ( uiPartIdx, iPtr );
+
+  xFree( pbEdge );
+  xFree( pbVisit );
+
+  return (iPtr != 0);
+}
+
+#if LGE_EDGE_INTRA_DELTA_DC
+Void TEncSearch::xAssignEdgeIntraDeltaDCs( TComDataCU*   pcCU,
+                                          UInt          uiAbsPartIdx,
+                                          Pel*          piOrig,
+                                          UInt          uiStride,
+                                          Pel*          piPredic,
+                                          UInt          uiWidth,
+                                          UInt          uiHeight )
+{
+  Int iDC0 = 0;
+  Int iDC1 = 0;
+  Int iPredDC0 = 0;
+  Int iPredDC1 = 0;
+  Int iDeltaDC0 = 0;
+  Int iDeltaDC1 = 0;
+
+  Bool* pbRegion = pcCU->getEdgePartition( uiAbsPartIdx );
+
+  Int* piMask = pcCU->getPattern()->getAdiOrgBuf( uiWidth, uiHeight, m_piYuvExt );
+  Int iMaskStride = ( uiWidth<<1 ) + 1;
+
+  // DC Calculation
+  {
+    UInt uiSum0 = 0;
+    UInt uiSum1 = 0;
+    UInt uiCount0 = 0;
+    UInt uiCount1 = 0;
+
+    Pel* piTemp = piOrig;
+    for( UInt ui = 0; ui < uiHeight; ui++ )
+    {
+      for( UInt uii = 0; uii < uiWidth; uii++ )
+      {
+        if( pbRegion[ ui * uiWidth + uii ] == false )
+        {
+          uiSum0 += (piTemp[ uii ]);
+          uiCount0++;
+        }
+        else
+        {
+          uiSum1 += (piTemp[ uii ]);
+          uiCount1++;
+        }
+      }
+      piTemp += uiStride;
+    }
+    if( uiCount0 == 0 )
+      assert(false);
+    if( uiCount1 == 0 )
+      assert(false);
+    iDC0 = uiSum0 / uiCount0; // TODO : integer op.
+    iDC1 = uiSum1 / uiCount1;
+  }
+
+  // PredDC Calculation
+  {
+    UInt uiSum0 = 0;
+    UInt uiSum1 = 0;
+    UInt uiCount0 = 0;
+    UInt uiCount1 = 0;
+
+    for( UInt ui = 0; ui < uiWidth; ui++ )
+    {
+      if( pbRegion[ ui ] == false )
+      {
+        uiSum0 += (piMask[ ui + 1 ]);
+        uiCount0++;
+      }
+      else
+      {
+        uiSum1 += (piMask[ ui + 1 ]);
+        uiCount1++;
+      }
+    }
+    for( UInt ui = 0; ui < uiHeight; ui++ ) // (0,0) recount (to avoid division)
+    {
+      if( pbRegion[ ui * uiWidth ] == false )
+      {
+        uiSum0 += (piMask[ (ui + 1) * iMaskStride ]);
+        uiCount0++;
+      }
+      else
+      {
+        uiSum1 += (piMask[ (ui + 1) * iMaskStride ]);
+        uiCount1++;
+      }
+    }
+    if( uiCount0 == 0 )
+      assert(false);
+    if( uiCount1 == 0 )
+      assert(false);
+    iPredDC0 = uiSum0 / uiCount0; // TODO : integer op.
+    iPredDC1 = uiSum1 / uiCount1;
+  }
+
+  iDeltaDC0 = iDC0 - iPredDC0;
+  iDeltaDC1 = iDC1 - iPredDC1;
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseVSO() )
+  {
+    Int iFullDeltaDC0 = iDeltaDC0;
+    Int iFullDeltaDC1 = iDeltaDC1;
+
+    xDeltaDCQuantScaleDown( pcCU, iFullDeltaDC0 );
+    xDeltaDCQuantScaleDown( pcCU, iFullDeltaDC1 );
+
+    Dist  uiBestDist     = RDO_DIST_MAX;
+    UInt  uiBestQStepDC0 = 0;
+    UInt  uiBestQStepDC1 = 0;
+
+    UInt uiDeltaDC0Max = abs(iFullDeltaDC0);
+    UInt uiDeltaDC1Max = abs(iFullDeltaDC1);
+
+    //VSO Level delta DC check range extension
+    uiDeltaDC0Max += (uiDeltaDC0Max>>1);
+    uiDeltaDC1Max += (uiDeltaDC1Max>>1);
+
+    for( UInt uiQStepDC0 = 1; uiQStepDC0 <= uiDeltaDC0Max; uiQStepDC0++  )
+    {
+      Int iLevelDeltaDC0 = (Int)(uiQStepDC0) * (Int)(( iFullDeltaDC0 < 0 ) ? -1 : 1);
+      xDeltaDCQuantScaleUp( pcCU, iLevelDeltaDC0 );
+
+      Int iTestDC0 = Clip( iPredDC0 + iLevelDeltaDC0 );
+      for( UInt uiQStepDC1 = 1; uiQStepDC1 <= uiDeltaDC1Max; uiQStepDC1++  )
+      {
+        Int iLevelDeltaDC1 = (Int)(uiQStepDC1) * (Int)(( iFullDeltaDC1 < 0 ) ? -1 : 1);
+        xDeltaDCQuantScaleUp( pcCU, iLevelDeltaDC1 );
+
+        Int iTestDC1 = Clip( iPredDC1 + iLevelDeltaDC1 );
+
+        Pel* piTemp = piPredic;
+        for( UInt ui = 0; ui < uiHeight; ui++ )
+        {
+          for( UInt uii = 0; uii < uiWidth; uii++ )
+          {
+            if( pbRegion[ ui * uiWidth + uii ] == false )
+            {
+              piTemp[ uii ] = iTestDC0;
+            }
+            else
+            {
+              piTemp[ uii ] = iTestDC1;
+            }
+          }
+          piTemp += uiStride;
+        }
+
+        Dist uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPredic, uiStride,  piOrig, uiStride, uiWidth, uiHeight, false, 0 );
+        if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+        {
+          uiBestDist     = uiActDist;
+          uiBestQStepDC0 = uiQStepDC0;
+          uiBestQStepDC1 = uiQStepDC1;
+        }
+      }
+    }
+
+    iFullDeltaDC0 = (Int)(uiBestQStepDC0) * (Int)(( iFullDeltaDC0 < 0 ) ? -1 : 1);
+    iFullDeltaDC1 = (Int)(uiBestQStepDC1) * (Int)(( iFullDeltaDC1 < 0 ) ? -1 : 1);
+    xDeltaDCQuantScaleUp( pcCU, iFullDeltaDC0 );
+    xDeltaDCQuantScaleUp( pcCU, iFullDeltaDC1 );
+    iDeltaDC0 = iFullDeltaDC0;
+    iDeltaDC1 = iFullDeltaDC1;
+  }
+#endif // HHI_VSO
+
+  xDeltaDCQuantScaleDown( pcCU, iDeltaDC0 );
+  xDeltaDCQuantScaleDown( pcCU, iDeltaDC1 );
+
+  pcCU->setEdgeDeltaDC0( uiAbsPartIdx, iDeltaDC0 );
+  pcCU->setEdgeDeltaDC1( uiAbsPartIdx, iDeltaDC1 );
+}
+#endif // LGE_EDGE_INTRA_DELTA_DC
+#endif // LGE_EDGE_INTRA_A0070
+  
+#if RWTH_SDC_DLT_B0036
+Void TEncSearch::xAnalyzeSegmentsSDC( Pel* pOrig, UInt uiStride, UInt uiSize, Pel* rpSegMeans, UInt uiNumSegments, Bool* pMask, UInt uiMaskStride )
+{
+  Int iSumDepth[2];
+  memset(iSumDepth, 0, sizeof(Int)*2);
+  Int iSumPix[2];
+  memset(iSumPix, 0, sizeof(Int)*2);
+#if HS_REFERENCE_SUBSAMPLE_C0154
+  Int subSamplePix;
+  if ( uiSize == 64 || uiSize == 32 )
+  {
+    subSamplePix = 2;
+  }
+  else
+  {
+    subSamplePix = 1;
+  }
+  for (Int y=0; y<uiSize; y+=subSamplePix)
+  {
+    for (Int x=0; x<uiSize; x+=subSamplePix)
+    {
+      UChar ucSegment = pMask?(UChar)pMask[x]:0;
+      assert( ucSegment < uiNumSegments );
+  
+      iSumDepth[ucSegment] += pOrig[x];
+      iSumPix[ucSegment]   += 1;
+    }
+
+    pOrig  += uiStride*subSamplePix;
+    pMask  += uiMaskStride*subSamplePix;
+  }
+#else //HS_REFERENCE_SUBSAMPLE_C0154
+  for (Int y=0; y<uiSize; y++)
+  {
+    for (Int x=0; x<uiSize; x++)
+    {
+      UChar ucSegment = pMask?(UChar)pMask[x]:0;
+      assert( ucSegment < uiNumSegments );
+      
+      iSumDepth[ucSegment] += pOrig[x];
+      iSumPix[ucSegment]   += 1;
+    }
+    
+    pOrig  += uiStride;
+    pMask  += uiMaskStride;
+  }
+#endif // HS_REFERENCE_SUBSAMPLE_C0154
+  // compute mean for each segment
+  for( UChar ucSeg = 0; ucSeg < uiNumSegments; ucSeg++ )
+  {
+    if( iSumPix[ucSeg] > 0 )
+      rpSegMeans[ucSeg] = iSumDepth[ucSeg] / iSumPix[ucSeg];
+    else
+      rpSegMeans[ucSeg] = 0;  // this happens for zero-segments
+  }
+}
+#endif // RWTH_SDC_DLT_B0036
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSearch.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSearch.h	(revision 341)
@@ -0,0 +1,618 @@
+/* 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-2012, 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     TEncSearch.h
+    \brief    encoder search class (header)
+*/
+
+#ifndef __TENCSEARCH__
+#define __TENCSEARCH__
+
+// Include files
+#include "TLibCommon/TComYuv.h"
+#include "TLibCommon/TComMotionInfo.h"
+#include "TLibCommon/TComPattern.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComPic.h"
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TEncCfg.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncCu;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder search class
+class TEncSearch : public TComPrediction
+{
+private:
+  TCoeff**        m_ppcQTTempCoeffY;
+  TCoeff**        m_ppcQTTempCoeffCb;
+  TCoeff**        m_ppcQTTempCoeffCr;
+  TCoeff*         m_pcQTTempCoeffY;
+  TCoeff*         m_pcQTTempCoeffCb;
+  TCoeff*         m_pcQTTempCoeffCr;
+#if ADAPTIVE_QP_SELECTION
+  Int**           m_ppcQTTempArlCoeffY;
+  Int**           m_ppcQTTempArlCoeffCb;
+  Int**           m_ppcQTTempArlCoeffCr;
+  Int*            m_pcQTTempArlCoeffY;
+  Int*            m_pcQTTempArlCoeffCb;
+  Int*            m_pcQTTempArlCoeffCr;
+#endif
+  UChar*          m_puhQTTempTrIdx;
+  UChar*          m_puhQTTempCbf[3];
+  
+  TComYuv*        m_pcQTTempTComYuv;
+  TComYuv         m_tmpYuvPred; // To be used in xGetInterPredictionError() to avoid constant memory allocation/deallocation
+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
+#if DV_V_RESTRICTION_B0037
+  Bool            m_bUseDisparitySearchRangeRestriction;
+  Int             m_iVerticalDisparitySearchRange;
+#endif
+  Int             m_iFastSearch;
+  Int             m_aaiAdaptSR[2][33];
+  TComMv          m_cSrchRngLT;
+  TComMv          m_cSrchRngRB;
+  TComMv          m_acMvPredictors[3];
+  
+  // RD computation
+  TEncSbac***     m_pppcRDSbacCoder;
+  TEncSbac*       m_pcRDGoOnSbacCoder;
+  Bool            m_bUseSBACRD;
+  DistParam       m_cDistParam;
+  
+  // Misc.
+  Pel*            m_pTempPel;
+  UInt*           m_puiDFilter;
+  Int             m_iMaxDeltaQP;
+  
+
+#if HHI_VSO
+  TComYuv         m_cYuvRecTemp; 
+#endif
+  
+  // AMVP cost computation
+#if H3D_IVMP
+  UInt            m_auiMVPIdxCost[AMVP_MAX_NUM_CANDS+2][AMVP_MAX_NUM_CANDS+2]; //th array bounds
+#else
+  // 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
+#endif
+  
+public:
+  TEncSearch();
+  virtual ~TEncSearch();
+  
+  Void init(  TEncCfg*      pcEncCfg,
+            TComTrQuant*  pcTrQuant,
+            Int           iSearchRange,
+            Int           bipredSearchRange,
+#if DV_V_RESTRICTION_B0037
+            Bool          bUseDisparitySearchRangeRestriction,
+            Int           iVerticalDisparitySearchRange,
+#endif
+            Int           iFastSearch,
+            Int           iMaxDeltaQP,
+            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);
+  
+  typedef struct
+  {
+    Pel*  piRefY;
+    Int   iYStride;
+    Int   iBestX;
+    Int   iBestY;
+    UInt  uiBestRound;
+    UInt  uiBestDistance;
+    UInt  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 );
+  __inline Void xTZ2PointSearch       ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB );
+  __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 );
+
+public:
+  Void  preestChromaPredMode    ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv );
+  Void  estIntraPredQT          ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv,
+                                  Dist&       ruiDistC,
+                                  Bool        bLumaOnly );
+  Void  estIntraPredChromaQT    ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv,
+                                  Dist        uiPreCalcDistC );
+  
+  
+  /// encoder estimation - inter prediction (non-skip)
+  Void predInterSearch          ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*&   rpcPredYuv,
+                                  TComYuv*&   rpcResiYuv,
+                                  TComYuv*&   rpcRecoYuv,
+                                  Bool        bUseRes = false
+#if AMP_MRG
+                                 ,Bool        bUseMRG = false
+#endif
+                                );
+  
+#if H3D_IVRP
+  /// encode residual and compute rd-cost for inter mode
+  Void encodeResAndCalcRdInterCU( TComDataCU* pcCU,
+                                  TComYuv*    pcYuvOrg,
+                                  TComYuv*    pcYuvPred,
+                                  TComYuv*&   rpcYuvResi,
+                                  TComYuv*&   rpcYuvResiBest,
+                                  TComYuv*&   rpcYuvRec,
+                                  TComYuv*&   rpcYuvResPrd,
+                                  Bool        bSkipRes );
+#else
+  /// 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 );
+#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 );
+protected:
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // Intra search
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void  xEncSubdivCbfQT           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma );
+  Void  xEncCoeffQT               ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TextType     eTextType,
+                                    Bool         bRealCoeff );
+  Void  xEncIntraHeader           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma );
+  UInt  xGetIntraBitsQT           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma,
+                                    Bool         bRealCoeff );
+  
+  Void  xIntraCodingLumaBlk       ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    Dist&        ruiDist 
+#if LG_ZEROINTRADEPTHRESI_A0087
+                                   ,Bool        bZeroResi = false
+#endif
+                                   );
+  Void  xIntraCodingChromaBlk     ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    Dist&        ruiDist,
+                                    UInt         uiChromaId );
+  Void  xRecurIntraCodingQT       ( TComDataCU*  pcCU, 
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx, 
+                                    Bool         bLumaOnly,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    Dist&        ruiDistY,
+                                    Dist&        ruiDistC,
+#if HHI_RQT_INTRA_SPEEDUP
+                                    Bool         bCheckFirst,
+#endif
+                                    Double&      dRDCost 
+#if LG_ZEROINTRADEPTHRESI_A0087
+                                   ,Bool         bZeroResi = 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, 
+                                    Dist&        ruiDist );
+  Void  xSetIntraResultChromaQT   ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcRecoYuv );
+  
+#if RWTH_SDC_DLT_B0036
+  Void  xAnalyzeSegmentsSDC       ( Pel* pOrig,
+                                   UInt uiStride,
+                                   UInt uiSize,
+                                   Pel* rpSegMeans,
+                                   UInt uiNumSegments,
+                                   Bool* pMask,
+                                   UInt uiMaskStride );
+  
+  Void  xIntraCodingSDC           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, Bool bResidual );
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // DMM intra search
+  // -------------------------------------------------------------------------------------------------------------------
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+
+  Bool predIntraLumaDMMAvailable  ( UInt           uiMode, 
+                                    UInt           uiWidth, 
+#if HHI_DMM_PRED_TEX && FLEX_CODING_ORDER_M23723
+                                    UInt         uiHeight, 
+                                    Bool         bDMMAvailable34 );
+#else
+                                    UInt         uiHeight );
+#endif
+
+  Void xGetWedgeDeltaDCsMinDist   ( TComWedgelet*  pcWedgelet, 
+                                    TComDataCU*    pcCU, 
+                                    UInt           uiAbsPtIdx, 
+                                    Pel*           piOrig, 
+                                    Pel*           piPredic, 
+                                    UInt           uiStride, 
+                                    UInt           uiWidth, 
+                                    UInt           uiHeight, 
+                                    Int&           riDeltaDC1, 
+                                    Int&           riDeltaDC2, 
+                                    Bool           bAboveAvail, 
+                                    Bool           bLeftAvail );
+#endif
+
+#if LGE_EDGE_INTRA_A0070
+  Bool  xEdgePartition       ( TComDataCU* pcCU, UInt uiPartIdx, Bool bPU4x4 );
+  Bool  xCheckTerminatedEdge ( Bool* pbEdge, Int iX, Int iY, Int iWidth, Int iHeight );
+  Bool  xConstructChainCode  ( TComDataCU* pcCU, UInt uiPartIdx, Bool bPU4x4 );
+#if LGE_EDGE_INTRA_DELTA_DC
+  Void  xAssignEdgeIntraDeltaDCs( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piOrig, UInt uiStride, Pel* piPredic, UInt uiWidth, UInt uiHeight );
+#endif
+#endif
+
+#if HHI_DMM_WEDGE_INTRA
+  Void findWedgeFullMinDist       ( TComDataCU*    pcCU, 
+                                    UInt           uiAbsPtIdx,
+                                    Pel*           piOrig,
+                                    Pel*           piPredic,
+                                    UInt           uiStride,
+                                    UInt           uiWidth,
+                                    UInt           uiHeight,
+                                    UInt&          ruiTabIdx,
+                                    Int&           riDeltaDC1,
+                                    Int&           riDeltaDC2,
+                                    Bool           bAboveAvail,
+                                    Bool           bLeftAvail );
+  Void findWedgePredDirMinDist    ( TComDataCU*    pcCU, 
+                                    UInt           uiAbsPtIdx,
+                                    Pel*           piOrig,
+                                    Pel*           piPredic,
+                                    UInt           uiStride,
+                                    UInt           uiWidth,
+                                    UInt           uiHeight,
+                                    UInt&          ruiTabIdx,
+                                    Int&           riWedgeDeltaEnd,
+                                    Int&           riDeltaDC1,
+                                    Int&           riDeltaDC2,
+                                    Bool           bAboveAvail,
+                                    Bool           bLeftAvail );
+  Void xSearchWedgeFullMinDist    ( TComDataCU*    pcCU, 
+                                    UInt           uiAbsPtIdx, 
+                                    WedgeList*     pacWedgeList, 
+                                    Pel*           piRef, 
+                                    UInt           uiRefStride, 
+                                    UInt           uiWidth, 
+                                    UInt           uiHeight, 
+                                    UInt&          ruiTabIdx, 
+                                    Dist&          riDist );
+
+  Void xSearchWedgeFullMinDistFast( TComDataCU*    pcCU, 
+                                    UInt           uiAbsPtIdx, 
+                                    WedgeNodeList* pacWedgeNodeList, 
+                                    WedgeList*     pacWedgeList, 
+                                    Pel*           piRef, 
+                                    UInt           uiRefStride, 
+                                    UInt           uiWidth, 
+                                    UInt           uiHeight, 
+                                    UInt&          ruiTabIdx, 
+                                    Dist&          riDist );
+  Void xSearchWedgePredDirMinDist ( TComDataCU*    pcCU, 
+                                    UInt           uiAbsPtIdx, 
+                                    WedgeList*     pacWedgeList, 
+                                    Pel*           piRef, 
+                                    UInt           uiRefStride, 
+                                    UInt           uiWidth, 
+                                    UInt           uiHeight, 
+                                    UInt&          ruiTabIdx, 
+                                    Int&           riWedgeDeltaEnd );
+#endif // HHI_DMM_WEDGE_INTRA
+#if HHI_DMM_PRED_TEX
+  Void findWedgeTexMinDist        ( TComDataCU*    pcCU, 
+                                    UInt           uiAbsPtIdx,
+                                    Pel*           piOrig,
+                                    Pel*           piPredic,
+                                    UInt           uiStride,
+                                    UInt           uiWidth,
+                                    UInt           uiHeight,
+                                    UInt&          ruiTabIdx,
+                                    Int&           riDeltaDC1,
+                                    Int&           riDeltaDC2,
+                                    Bool           bAboveAvail,
+                                    Bool           bLeftAvail
+#if LGE_DMM3_SIMP_C0044
+                                    ,UInt&         ruiIntraTabIdx
+#endif
+                                    );
+  Void findContourPredTex         ( TComDataCU*    pcCU, 
+                                    UInt           uiAbsPtIdx,
+                                    Pel*           piOrig,
+                                    Pel*           piPredic,
+                                    UInt           uiStride,
+                                    UInt           uiWidth,
+                                    UInt           uiHeight,
+                                    Int&           riDeltaDC1,
+                                    Int&           riDeltaDC2,
+                                    Bool           bAboveAvail,
+                                    Bool           bLeftAvail );
+#endif // HHI_DMM_PRED_TEX
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // Inter search (AMP)
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xEstimateMvPredAMVP        ( TComDataCU* pcCU,
+                                    TComYuv*    pcOrgYuv,
+                                    UInt        uiPartIdx,
+                                    RefPicList  eRefPicList,
+                                    Int         iRefIdx,
+                                    TComMv&     rcMvPred,
+                                    Bool        bFilled = false
+                                  , UInt*       puiDistBiP = NULL
+                                  #if ZERO_MVD_EST
+                                  , UInt*       puiDist = NULL
+                                  #endif
+                                     );
+  
+  Void xCheckBestMVP              ( TComDataCU* pcCU,
+                                    RefPicList  eRefPicList,
+                                    TComMv      cMv,
+                                    TComMv&     rcMvPred,
+                                    Int&        riMVPIdx,
+                                    UInt&       ruiBits,
+                                    UInt&       ruiCost );
+  
+  UInt 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
+                                   );
+  
+  
+  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
+#if CU_BASED_MRG_CAND_LIST
+                                  , TComMvField* cMvFieldNeighbours,  
+                                    UChar* uhInterDirNeighbours,
+                                    Int& numValidMergeCand
+#endif
+#if MERL_VSP_C0152
+                                  , Int* iVSPIndexTrue
+#endif
+                                   );
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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 DV_V_RESTRICTION_B0037
+  Void xSetSearchRange            ( TComDataCU*   pcCU,
+                                    TComMv&       cMvPred,
+                                    Int           iSrchRng,
+                                    TComMv&       rcMvSrchRngLT,
+                                    TComMv&       rcMvSrchRngRB,
+                                    Bool          bDispSrchRngRst,
+                                    Int           iDispVerSrchRng );
+#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 IBDI_DISTORTION || HHI_VSO
+  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, Dist &ruiDist, Dist *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 );
+  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  setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur );
+  inline  Void  setDistParamComp( UInt uiComp )  { m_cDistParam.uiComp = uiComp; }
+  
+};// END CLASS DEFINITION TEncSearch
+
+//! \}
+
+#endif // __TENCSEARCH__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 341)
@@ -0,0 +1,1503 @@
+/* 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-2012, 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     TEncSlice.cpp
+    \brief    slice encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSlice.h"
+#include "../../App/TAppEncoder/TAppEncTop.h"
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSlice::TEncSlice()
+{
+  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;
+#if FCO_DVP_REFINE_C0132_C0170
+  m_pPicBaseTxt = NULL;
+  m_pPicBaseDepth = NULL;
+#endif
+}
+
+TEncSlice::~TEncSlice()
+{
+}
+
+Void TEncSlice::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth )
+{
+  // create prediction picture
+  if ( m_apcPicYuvPred == NULL )
+  {
+    m_apcPicYuvPred  = new TComPicYuv;
+    m_apcPicYuvPred->create( iWidth, iHeight, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
+  }
+  
+  // create residual picture
+  if( m_apcPicYuvResi == NULL )
+  {
+    m_apcPicYuvResi  = new TComPicYuv;
+    m_apcPicYuvResi->create( iWidth, iHeight, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
+  }
+}
+
+Void TEncSlice::destroy()
+{
+  // destroy prediction picture
+  if ( m_apcPicYuvPred )
+  {
+    m_apcPicYuvPred->destroy();
+    delete m_apcPicYuvPred;
+    m_apcPicYuvPred  = NULL;
+  }
+  
+  // destroy residual picture
+  if ( m_apcPicYuvResi )
+  {
+    m_apcPicYuvResi->destroy();
+    delete m_apcPicYuvResi;
+    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;
+}
+
+Void TEncSlice::init( TEncTop* pcEncTop )
+{
+  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 );
+  m_pdRdPicQp         = (Double*)xMalloc( Double, m_pcCfg->getDeltaQpRD() * 2 + 1 );
+  m_piRdPicQp         = (Int*   )xMalloc( Int,    m_pcCfg->getDeltaQpRD() * 2 + 1 );
+}
+
+/**
+ - non-referenced frame marking
+ - QP computation based on temporal structure
+ - lambda computation based on QP
+ - set temporal layer ID and the parameter sets
+ .
+ \param pcPic         picture class
+ \param iPOCLast      POC of last picture
+ \param uiPOCCurr     current POC
+ \param iNumPicRcvd   number of received pictures
+ \param iTimeOffset   POC offset for hierarchical structure
+ \param iDepth        temporal layer depth
+ \param rpcSlice      slice header class
+ \param pSPS          SPS associated with the slice
+ \param pPPS          PPS associated with the slice
+ */
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int iPOCLast, UInt uiPOCCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS * pVPS, TComSPS* pSPS, TComPPS *pPPS, bool isDepth )
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int iPOCLast, UInt uiPOCCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS * pVPS, TComSPS* pSPS, TComPPS *pPPS )
+#endif
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int iPOCLast, UInt uiPOCCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS )
+#endif
+{
+  Double dQP;
+  Double dLambda;
+  
+  rpcSlice = pcPic->getSlice(0);
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  rpcSlice->setVPS( pVPS );
+#endif
+  rpcSlice->setSPS( pSPS );
+  rpcSlice->setPPS( pPPS );
+  rpcSlice->setSliceBits(0);
+  rpcSlice->setPic( pcPic );
+  rpcSlice->initSlice();
+  rpcSlice->initTiles();
+  rpcSlice->setPicOutputFlag( true );
+  rpcSlice->setPOC( uiPOCCurr );
+  
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  rpcSlice->setViewOrderIdx(m_pcCfg->getViewOrderIdx());    // will be changed to view_id
+#endif 
+#if LGE_ILLUCOMP_B0045
+  rpcSlice->setApplyIC(false);
+#endif
+  // set mutliview parameters
+  rpcSlice->initMultiviewSlice( pcPic->getCodedScale(), pcPic->getCodedOffset() );
+
+  // depth computation based on GOP size
+  int iDepth;
+  {
+    Int i, j;
+    Int iPOC = rpcSlice->getPOC()%m_pcCfg->getGOPSize();
+    if ( iPOC == 0 )
+    {
+      iDepth = 0;
+    }
+    else
+    {
+      Int iStep = m_pcCfg->getGOPSize();
+      iDepth    = 0;
+      for( i=iStep>>1; i>=1; i>>=1 )
+      {
+        for ( j=i; j<m_pcCfg->getGOPSize(); j+=iStep )
+        {
+          if ( j == iPOC )
+          {
+            i=0;
+            break;
+          }
+        }
+        iStep>>=1;
+        iDepth++;
+      }
+    }
+  }
+  
+  // slice type
+  SliceType eSliceTypeBaseView;
+  if( iPOCLast == 0 || uiPOCCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0 )
+  {
+    eSliceTypeBaseView = I_SLICE;
+  }
+  else
+  {
+    eSliceTypeBaseView = B_SLICE;
+  }
+  SliceType eSliceType = eSliceTypeBaseView;
+  if( eSliceTypeBaseView == I_SLICE && m_pcCfg->getGOPEntry(MAX_GOP).m_POC == 0 && m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType != 'I' )
+  {
+    eSliceType = B_SLICE; 
+  }
+  rpcSlice->setSliceType( eSliceType );
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // Non-referenced frame marking
+  // ------------------------------------------------------------------------------------------------------------------
+  rpcSlice->setReferenced( m_pcCfg->getGOPEntry(iGOPid).m_refPic );
+  if( eSliceTypeBaseView == I_SLICE )
+  {
+    rpcSlice->setReferenced(true);
+  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // QP setting
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  dQP = m_pcCfg->getQP();
+  if( eSliceType != I_SLICE )
+  {
+#if LOSSLESS_CODING
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffsetY() ) && (rpcSlice->getSPS()->getUseLossless()))) 
+#endif
+    {
+    dQP += m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_QPOffset;
+    }
+  }
+  
+  // modify QP
+  Int* pdQPs = m_pcCfg->getdQPs();
+  if ( pdQPs )
+  {
+    dQP += pdQPs[ rpcSlice->getPOC() ];
+  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // Lambda computation
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Int iQP;
+  Double dOrigQP = dQP;
+
+  // pre-compute lambda and QP values for all possible QP candidates
+  for ( Int iDQpIdx = 0; iDQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; iDQpIdx++ )
+  {
+    // 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)NumberBFrames );
+#if FULL_NBIT
+    Int    bitdepth_luma_qp_scale = 6 * (g_uiBitDepth - 8);
+#else
+    Int    bitdepth_luma_qp_scale = 0;
+#endif
+    Double qp_temp = (Double) dQP + bitdepth_luma_qp_scale - SHIFT_QP;
+#if FULL_NBIT
+    Double qp_temp_orig = (Double) dQP - SHIFT_QP;
+#endif
+    // Case #1: I or P-slices (key-frame)
+    Double dQPFactor;
+    if( eSliceType != I_SLICE ) 
+    {
+      dQPFactor = m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_QPFactor;
+    }
+    else
+    {
+      dQPFactor = 0.57 * dLambda_scale;
+    }
+
+    dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
+
+    if ( iDepth>0 )
+    {
+#if FULL_NBIT
+        dLambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#else
+        dLambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#endif
+    }
+    
+    // if hadamard is used in ME process
+    if ( !m_pcCfg->getUseHADME() )
+    {
+      dLambda *= 0.95;
+    }
+    
+    iQP = max( -pSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+
+    m_pdRdPicLambda[iDQpIdx] = dLambda;
+    m_pdRdPicQp    [iDQpIdx] = dQP;
+    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 )
+  {
+    dLambda *= m_pcCfg->getLambdaModifier( iDepth );
+  }
+
+  // store lambda
+  m_pcRdCost ->setLambda( dLambda );
+#if WEIGHTED_CHROMA_DISTORTION
+// 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 = 1.0;
+  if(iQP >= 0)
+  {
+    weight = pow( 2.0, (iQP-g_aucChromaScale[iQP])/3.0 );  // takes into account of the chroma qp mapping without chroma qp Offset
+  }
+  m_pcRdCost ->setChromaDistortionWeight( weight );     
+#endif
+
+#if HHI_VSO
+  m_pcRdCost->setUseLambdaScaleVSO  ( (m_pcCfg->getUseVSO() ||  m_pcCfg->getForceLambdaScaleVSO()) && m_pcCfg->isDepthCoder()  );
+  m_pcRdCost->setLambdaVSO( dLambda * m_pcCfg->getLambdaScaleVSO() );
+#endif
+
+#if SAIT_VSO_EST_A0033
+  m_pcRdCost->setDisparityCoeff( m_pcCfg->getDispCoeff() );
+#endif
+#if LGE_WVSO_A0119
+  if( m_pcCfg->getUseWVSO() && m_pcCfg->isDepthCoder() )
+  {
+
+    Int iDWeight, iVSOWeight, iVSDWeight;
+    iDWeight = m_pcCfg->getDWeight();
+    iVSOWeight = m_pcCfg->getVSOWeight();
+    iVSDWeight = m_pcCfg->getVSDWeight();
+
+    m_pcRdCost->setDWeight( iDWeight );
+    m_pcRdCost->setVSOWeight( iVSOWeight );
+    m_pcRdCost->setVSDWeight( iVSDWeight );
+
+  }
+#endif
+#if RDOQ_CHROMA_LAMBDA 
+// for RDOQ
+  m_pcTrQuant->setLambda( dLambda, dLambda / weight );    
+#else
+  m_pcTrQuant->setLambda( dLambda );
+#endif
+
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+// For ALF or SAO
+  rpcSlice   ->setLambda( dLambda, dLambda / weight );  
+#else
+  rpcSlice   ->setLambda( dLambda );
+#endif
+  
+#if H3D_IVMP
+  m_pcRdCost ->setLambdaMVReg ( dLambda * m_pcCfg->getMultiviewMvRegLambdaScale() );
+#endif
+  
+#if HB_LAMBDA_FOR_LDC
+  // restore original slice type
+  eSliceType = eSliceTypeBaseView;
+  if( eSliceTypeBaseView == I_SLICE && m_pcCfg->getGOPEntry(MAX_GOP).m_POC == 0 && m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType != 'I' )
+  {
+    eSliceType = B_SLICE;
+  }
+  rpcSlice->setSliceType( eSliceType );
+#endif
+  
+  rpcSlice->setSliceQp          ( iQP );
+#if ADAPTIVE_QP_SELECTION
+  rpcSlice->setSliceQpBase      ( iQP );
+#endif
+  rpcSlice->setSliceQpDelta     ( 0 );
+  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);
+  
+  rpcSlice->setLoopFilterOffsetInAPS( m_pcCfg->getLoopFilterOffsetInAPS() );
+  if (rpcSlice->getPPS()->getDeblockingFilterControlPresent())
+  {
+    rpcSlice->setInheritDblParamFromAPS( m_pcCfg->getLoopFilterOffsetInAPS() ? 1 : 0 );
+    rpcSlice->setLoopFilterDisable( m_pcCfg->getLoopFilterDisable() );
+    if ( !rpcSlice->getLoopFilterDisable())
+    {
+      rpcSlice->setLoopFilterBetaOffset( m_pcCfg->getLoopFilterBetaOffset() );
+      rpcSlice->setLoopFilterTcOffset( m_pcCfg->getLoopFilterTcOffset() );
+    }
+  }
+
+  rpcSlice->setDepth            ( iDepth );
+  
+  pcPic->setTLayer( m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_temporalId );
+  if( eSliceType == I_SLICE )
+  {
+    pcPic->setTLayer(0);
+  }
+  rpcSlice->setTLayer( pcPic->getTLayer() );
+
+  assert( m_apcPicYuvPred );
+  assert( m_apcPicYuvResi );
+  
+  pcPic->setPicYuvPred( m_apcPicYuvPred );
+  pcPic->setPicYuvResi( m_apcPicYuvResi );
+  rpcSlice->setSliceMode            ( m_pcCfg->getSliceMode()            );
+  rpcSlice->setSliceArgument        ( m_pcCfg->getSliceArgument()        );
+  rpcSlice->setEntropySliceMode     ( m_pcCfg->getEntropySliceMode()     );
+  rpcSlice->setEntropySliceArgument ( m_pcCfg->getEntropySliceArgument() );
+
+#if ( HHI_MPI || H3D_IVMP )
+  #if ( HHI_MPI && H3D_IVMP )
+  const int iExtraMergeCandidates = ( pSPS->getUseMVI() || pSPS->getMultiviewMvPredMode() ) ? 1 : 0;
+  #elif HHI_MPI
+  const int iExtraMergeCandidates = pSPS->getUseMVI() ? 1 : 0;
+  #elif MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  const int iExtraMergeCandidates = ( isDepth || pSPS->getMultiviewMvPredMode() ) ? 1 : 0;
+  #else
+  const int iExtraMergeCandidates = pSPS->getMultiviewMvPredMode() ? 1 : 0;
+  #endif
+  rpcSlice->setMaxNumMergeCand      (MRG_MAX_NUM_CANDS_SIGNALED+iExtraMergeCandidates);
+#else
+  rpcSlice->setMaxNumMergeCand      (MRG_MAX_NUM_CANDS_SIGNALED);
+#endif
+  xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPredIdc() );
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncSlice::setSearchRange( TComSlice* pcSlice )
+{
+  Int iCurrPOC = pcSlice->getPOC();
+  Int iRefPOC;
+  Int iGOPSize = m_pcCfg->getGOPSize();
+  Int iOffset = (iGOPSize >> 1);
+  Int iMaxSR = m_pcCfg->getSearchRange();
+  Int iNumPredDir = pcSlice->isInterP() ? 1 : 2;
+  
+  for (Int iDir = 0; iDir <= iNumPredDir; iDir++)
+  {
+    RefPicList e = (RefPicList)iDir;
+    for (Int iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(e); iRefIdx++)
+    {
+      iRefPOC = pcSlice->getRefPic(e, iRefIdx)->getPOC();
+      Int iNewSR = Clip3(8, iMaxSR, (iMaxSR*ADAPT_SR_SCALE*abs(iCurrPOC - iRefPOC)+iOffset)/iGOPSize);
+      m_pcPredSearch->setAdaptiveSearchRange(iDir, iRefIdx, iNewSR);
+    }
+  }
+}
+
+/**
+ - multi-loop slice encoding for different slice QP
+ .
+ \param rpcPic    picture class
+ */
+Void TEncSlice::precompressSlice( TComPic*& rpcPic )
+{
+  // if deltaQP RD is not used, simply return
+  if ( m_pcCfg->getDeltaQpRD() == 0 )
+  {
+    return;
+  }
+  
+  TComSlice* pcSlice        = rpcPic->getSlice(getSliceIdx());
+  Double     dPicRdCostBest = MAX_DOUBLE;
+  UInt       uiQpIdxBest = 0;
+  
+  Double dFrameLambda;
+#if FULL_NBIT
+  Int    SHIFT_QP = 12 + 6 * (g_uiBitDepth - 8);
+#else
+  Int    SHIFT_QP = 12;
+#endif
+  
+  // set frame lambda
+  if (m_pcCfg->getGOPSize() > 1)
+  {
+    dFrameLambda = 0.68 * pow (2, (m_piRdPicQp[0]  - SHIFT_QP) / 3.0) * (pcSlice->isInterB()? 2 : 1);
+  }
+  else
+  {
+    dFrameLambda = 0.68 * pow (2, (m_piRdPicQp[0] - SHIFT_QP) / 3.0);
+  }
+  m_pcRdCost      ->setFrameLambda(dFrameLambda);
+  
+  // for each QP candidate
+  for ( UInt uiQpIdx = 0; uiQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; uiQpIdx++ )
+  {
+    pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdx] );
+#if ADAPTIVE_QP_SELECTION
+    pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdx] );
+#endif
+    m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#if WEIGHTED_CHROMA_DISTORTION
+    // 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 = 1.0;
+    if(iQP >= 0)
+    {
+      weight = pow( 2.0, (iQP-g_aucChromaScale[iQP])/3.0 );  // takes into account of the chroma qp mapping without chroma qp Offset
+    }
+    m_pcRdCost    ->setChromaDistortionWeight( weight );     
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+    // for RDOQ
+    m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight );
+#else
+    m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#endif
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+    // For ALF or SAO
+    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight ); 
+#else
+    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#endif
+#if H3D_IVMP
+    m_pcRdCost    ->setLambdaMVReg         ( m_pdRdPicLambda[uiQpIdx] * m_pcCfg->getMultiviewMvRegLambdaScale() );
+#endif
+    
+    // try compress
+    compressSlice   ( rpcPic );
+    
+    Double dPicRdCost;
+    UInt64 uiPicDist        = m_uiPicDist;
+    UInt64 uiALFBits        = 0;
+    
+    m_pcGOPEncoder->preLoopFilterPicAll( rpcPic, uiPicDist, uiALFBits );
+    
+    // compute RD cost and choose the best
+    dPicRdCost = m_pcRdCost->calcRdCost64( m_uiPicTotalBits + uiALFBits, uiPicDist, true, DF_SSE_FRAME);
+    
+    if ( dPicRdCost < dPicRdCostBest )
+    {
+      uiQpIdxBest    = uiQpIdx;
+      dPicRdCostBest = dPicRdCost;
+    }
+  }
+  
+  // set best values
+  pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdxBest] );
+#if ADAPTIVE_QP_SELECTION
+  pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdxBest] );
+#endif
+  m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#if WEIGHTED_CHROMA_DISTORTION
+  // 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 = 1.0;
+  if(iQP >= 0)
+  {
+    weight = pow( 2.0, (iQP-g_aucChromaScale[iQP])/3.0 );  // takes into account of the chroma qp mapping without chroma qp Offset
+  }
+  m_pcRdCost ->setChromaDistortionWeight( weight );     
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+  // for RDOQ 
+  m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight ); 
+#else
+  m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#endif
+#if ALF_CHROMA_LAMBDA || SAO_CHROMA_LAMBDA
+  // For ALF or SAO
+  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight ); 
+#else
+  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#endif
+#if H3D_IVMP
+  m_pcRdCost    ->setLambdaMVReg         ( m_pdRdPicLambda[uiQpIdxBest] * m_pcCfg->getMultiviewMvRegLambdaScale() );
+#endif
+}
+
+/** \param rpcPic   picture class
+ */
+Void TEncSlice::compressSlice( TComPic*& rpcPic )
+{
+  UInt  uiCUAddr;
+  UInt   uiStartCUAddr;
+  UInt   uiBoundingCUAddr;
+  rpcPic->getSlice(getSliceIdx())->setEntropySliceCounter(0);
+  TEncBinCABAC* pppcRDSbacCoder = NULL;
+  TComSlice* pcSlice            = rpcPic->getSlice(getSliceIdx());
+  xDetermineStartAndBoundingCUAddr ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, false );
+#if LG_ZEROINTRADEPTHRESI_A0087
+  rpcPic->setIntraPeriod(this->m_pcCfg->getIntraPeriod());
+#endif
+  
+  // initialize cost values
+  m_uiPicTotalBits  = 0;
+  m_dPicRdCost      = 0;
+  m_uiPicDist       = 0;
+  
+#if CABAC_INIT_FLAG && FIX_POZNAN_CABAC_INIT_FLAG
+  Bool bReset =(pcSlice->getPOC() == 0) || 
+    (pcSlice->getPOC() % m_pcCfg->getIntraPeriod() == 0) ||
+    (pcSlice->getPPS()->getEncPrevPOC() % m_pcCfg->getIntraPeriod() == 0) ||
+    (pcSlice->getPOC()/m_pcCfg->getIntraPeriod() > pcSlice->getPPS()->getEncPrevPOC()/m_pcCfg->getIntraPeriod()) ||
+    (m_pcGOPEncoder->getGOPSize() == 0);
+
+  if ( bReset && pcSlice->getPPS()->getCabacInitPresentFlag())
+  {
+    pcSlice->getPPS()->setEncCABACTableIdx(pcSlice->getSliceType()); // reset cabac initialization table index
+  };
+#endif
+
+  // set entropy coder
+  if( m_pcCfg->getUseSBACRD() )
+  {
+    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 );
+  }
+  else
+  {
+    m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+    m_pcEntropyCoder->resetEntropy      ();
+    m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+  }
+  
+  //------------------------------------------------------------------------------
+  //  Weighted Prediction parameters estimation.
+  //------------------------------------------------------------------------------
+  // calculate AC/DC values for current picture
+  if( pcSlice->getPPS()->getUseWP() || pcSlice->getPPS()->getWPBiPredIdc() )
+  {
+    xCalcACDCParamSlice(pcSlice);
+  }
+#if FIX_LGE_WP_FOR_3D_C0223
+  Bool bWp_explicit = (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPredIdc());
+
+  if ( bWp_explicit )
+  {
+    //------------------------------------------------------------------------------
+    //  Weighted Prediction implemented at Slice level. SliceMode=2 is not supported yet.
+    //------------------------------------------------------------------------------
+    if ( pcSlice->getSliceMode()==2 || pcSlice->getEntropySliceMode()==2 )
+    {
+      printf("Weighted Prediction is not supported with slice mode determined by max number of bins.\n"); exit(0);
+    }
+    xEstimateWPParamSlice( pcSlice );
+    pcSlice->initWpScaling();
+#if !FIX_LGE_WP_FOR_3D_C0223 // Interim fix for encoder/decoder mismatch of non-fade sequence
+    // check WP on/off
+    xCheckWPEnable( pcSlice );
+#endif
+  }
+#else
+
+  Bool bWp_explicit = (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPredIdc()==1);
+  Bool bWp_implicit = (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPredIdc()==2);
+
+  if ( bWp_explicit || bWp_implicit )
+  {
+    //------------------------------------------------------------------------------
+    //  Weighted Prediction implemented at Slice level. SliceMode=2 is not supported yet.
+    //------------------------------------------------------------------------------
+    if ( pcSlice->getSliceMode()==2 || pcSlice->getEntropySliceMode()==2 )
+    {
+      printf("Weighted Prediction is not supported with slice mode determined by max number of bins.\n"); exit(0);
+    }
+
+    if( bWp_explicit )
+    {
+      xEstimateWPParamSlice( pcSlice );
+    }
+    
+    pcSlice->initWpScaling();
+
+    // check WP on/off
+    if( bWp_explicit )
+    {
+      xCheckWPEnable( pcSlice );
+    }
+  }
+#endif
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcCfg->getUseAdaptQpSelect() )
+  {
+    m_pcTrQuant->clearSliceARLCnt();
+    if(pcSlice->getSliceType()!=I_SLICE)
+    {
+      Int qpBase = pcSlice->getSliceQpBase();
+      pcSlice->setSliceQp(qpBase + m_pcTrQuant->getQpDelta(qpBase));
+    }
+  }
+#endif
+  // initialize ALF parameters
+  m_pcEntropyCoder->setAlfCtrl(false);
+  m_pcEntropyCoder->setMaxAlfCtrlDepth(0); //unnecessary
+  
+#if SAIT_VSO_EST_A0033
+ if( m_pcCfg->getUseVSO() )
+ {
+
+   Int frameWidth = m_pcCfg->getSourceWidth();
+   Pel* pVideoRec = m_pcRdCost->getVideoRecPicYuv()->getLumaAddr();
+   Int iVideoRecStride = m_pcRdCost->getVideoRecPicYuv()->getStride();
+
+   Pel* pDepthOrg = m_pcRdCost->getDepthPicYuv()->getLumaAddr();
+   Int iDepthOrgStride = m_pcRdCost->getDepthPicYuv()->getStride();
+
+   for( Int y = 0 ; y < m_pcCfg->getSourceHeight() ; y++ )
+   {
+     pVideoRec[-1] = pVideoRec[0];
+     pVideoRec[frameWidth] = pVideoRec[frameWidth-1];
+     pDepthOrg[-1] = pDepthOrg[0];
+     pDepthOrg[frameWidth] = pDepthOrg[frameWidth-1];
+
+     pVideoRec += iVideoRecStride;
+     pDepthOrg += iDepthOrgStride;
+   }
+ }
+#endif
+
+  TEncTop* pcEncTop = (TEncTop*) m_pcCfg;
+  TEncSbac**** ppppcRDSbacCoders    = pcEncTop->getRDSbacCoders();
+  TComBitCounter* pcBitCounters     = pcEncTop->getBitCounters();
+  Int  iNumSubstreams = 1;
+  UInt uiTilesAcross  = 0;
+
+#if LGE_ILLUCOMP_B0045
+  if (pcEncTop->getViewId() != 0 
+#if !LGE_ILLUCOMP_DEPTH_C0046
+      && !pcEncTop->isDepthCoder() 
+#endif
+      && pcEncTop->getUseIC())   // DCP of ViewID 0 is not available
+  {
+    pcSlice ->xSetApplyIC();
+  }
+#endif
+
+  if( m_pcCfg->getUseSBACRD() )
+  {
+    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]);
+    }
+  }
+  //if( m_pcCfg->getUseSBACRD() )
+  {
+    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
+  }
+
+#if MERL_VSP_C0152
+  // Send Depth/Texture pointers to slice level
+  pcSlice->setBWVSPLUTParam(m_aiShiftLUT, m_iShiftPrec);
+  pcSlice->setRefPicBaseTxt(m_pPicBaseTxt);
+  pcSlice->setRefPicBaseDepth(m_pPicBaseDepth);
+#endif
+
+  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;
+#if !QC_MVHEVC_B0046
+  Int iLastPosY = -1;
+#endif
+  // for every CU in slice
+  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 );
+#if !QC_MVHEVC_B0046
+    if ( m_pcRdCost->getUseRenModel() )
+    {
+      // updated renderer model if necessary
+      Int iCurPosX;
+      Int iCurPosY; 
+      pcCU->getPosInPic(0, iCurPosX, iCurPosY );
+      if ( iCurPosY != iLastPosY )
+      {
+        iLastPosY = iCurPosY; 
+        
+        m_pcGOPEncoder->getEncTop()->getEncTop()->setupRenModel( rpcPic->getCurrSlice()->getPOC() , rpcPic->getCurrSlice()->getSPS()->getViewId(), rpcPic->getCurrSlice()->getSPS()->isDepth() ? 1 : 0, iCurPosY );
+      }
+    }    
+#endif
+    // inherit from TR if necessary, select substream to use.
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      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;
+      }
+      if ( pcSlice->getPPS()->getNumSubstreams() > 1 && (uiCol == uiTileLCUX) )
+      {
+        // 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)))
+             )||
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getEntropySliceCurStartCUAddr()) ||
+             ((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())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())     // cannot be first CU of slice
+    {
+#if CABAC_INIT_FLAG
+      SliceType sliceType = pcSlice->getSliceType();
+      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag() && pcSlice->getPPS()->getEncCABACTableIdx()!=0)
+      {
+        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 );
+#else
+      m_pcEntropyCoder->updateContextTables ( pcSlice->getSliceType(), pcSlice->getSliceQp(), false );
+      m_pcEntropyCoder->setEntropyCoder     ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+      m_pcEntropyCoder->updateContextTables ( pcSlice->getSliceType(), pcSlice->getSliceQp() );
+      m_pcEntropyCoder->setEntropyCoder     ( m_pcSbacCoder, pcSlice );
+#endif
+    }
+    // if RD based on SBAC is used
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      // set go-on entropy coder
+      m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
+      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+      
+      ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
+      // 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()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE && ( ( pcSlice->getSliceBits() + m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
+      {
+        pcSlice->setNextSlice( true );
+        break;
+      }
+      if (m_pcCfg->getEntropySliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE && pcSlice->getEntropySliceCounter()+pppcRDSbacCoder->getBinsCoded() > m_pcCfg->getEntropySliceArgument()&&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getEntropySliceCurEndCUAddr())
+      {
+        pcSlice->setNextEntropySlice( true );
+        break;
+      }
+      if( m_pcCfg->getUseSBACRD() )
+      {
+         ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
+       
+         //Store probabilties of second LCU in line into buffer
+        if (pcSlice->getPPS()->getNumSubstreams() > 1 && uiCol == uiTileLCUX+1)
+        {
+          m_pcBufferSbacCoders[uiTileCol].loadContexts(ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]);
+        }
+      }
+    }
+    // other case: encodeCU is not called
+    else
+    {
+      m_pcCuEncoder->compressCU( pcCU );
+      m_pcCuEncoder->encodeCU( pcCU );
+      if (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE && ( ( pcSlice->getSliceBits()+ m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
+      {
+        pcSlice->setNextSlice( true );
+        break;
+      }
+      if (m_pcCfg->getEntropySliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE && pcSlice->getEntropySliceCounter()+ m_pcEntropyCoder->getNumberOfWrittenBits()> m_pcCfg->getEntropySliceArgument()&&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getEntropySliceCurEndCUAddr())
+      {
+        pcSlice->setNextEntropySlice( true );
+        break;
+      }
+    }
+    
+    m_uiPicTotalBits += pcCU->getTotalBits();
+    m_dPicRdCost     += pcCU->getTotalCost();
+    m_uiPicDist      += pcCU->getTotalDistortion();
+  }
+  xRestoreWPparam( pcSlice );
+}
+
+/**
+ \param  rpcPic        picture class
+ \retval rpcBitstream  bitstream class
+ */
+Void TEncSlice::encodeSlice   ( TComPic*& rpcPic, TComOutputBitstream* pcBitstream, TComOutputBitstream* pcSubstreams )
+{
+  UInt       uiCUAddr;
+  UInt       uiStartCUAddr;
+  UInt       uiBoundingCUAddr;
+  TComSlice* pcSlice = rpcPic->getSlice(getSliceIdx());
+
+  uiStartCUAddr=pcSlice->getEntropySliceCurStartCUAddr();
+  uiBoundingCUAddr=pcSlice->getEntropySliceCurEndCUAddr();
+  // 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 ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( rpcPic->getPOC() );
+  DTRACE_CABAC_T( "\n" );
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#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;
+
+  UInt uiEncCUOrder;
+
+  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*/
+  for( uiEncCUOrder = uiStartCUAddr /rpcPic->getNumPartInCU();
+       uiEncCUOrder < (uiBoundingCUAddr+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
+       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
+  {
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      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 && (uiCol == uiTileLCUX))
+      {
+        // 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)))
+             ))||
+             (true/*bEnforceEntropySliceRestriction*/ &&
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getEntropySliceCurStartCUAddr()) ||
+             ((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())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())     // cannot be first CU of slice
+    {
+      Int iTileIdx            = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr);
+      Bool bWriteTileMarker   = false;
+      // check if current iTileIdx should have a marker
+      for (Int iEntryIdx=0; iEntryIdx<m_pcCfg->getMaxTileMarkerEntryPoints()-1; iEntryIdx++)
+      {
+        bWriteTileMarker = ( (((Int)((iEntryIdx+1)*m_pcCfg->getMaxTileMarkerOffset()+0.5)) == iTileIdx ) && iEntryIdx < (m_pcCfg->getMaxTileMarkerEntryPoints()-1)) ? true : false;
+        if (bWriteTileMarker)
+        {
+          break;
+        }
+      }
+      {
+        // 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
+        {
+#if CABAC_INIT_FLAG
+          SliceType sliceType  = pcSlice->getSliceType();
+          if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag() && pcSlice->getPPS()->getEncCABACTableIdx()!=0)
+          {
+            sliceType = (SliceType) pcSlice->getPPS()->getEncCABACTableIdx();
+          }
+          m_pcEntropyCoder->updateContextTables( sliceType, pcSlice->getSliceQp() );
+#else
+          m_pcEntropyCoder->updateContextTables( pcSlice->getSliceType(), pcSlice->getSliceQp() );
+#endif
+          pcSubstreams[uiSubStrm].write( 1, 1 );
+          pcSubstreams[uiSubStrm].writeAlignZero();
+        }
+      }
+      {
+        // Write TileMarker into the appropriate substream (nothing has been written to it yet).
+        if (m_pcCfg->getTileMarkerFlag() && bWriteTileMarker)
+        {
+          // Log locations where tile markers are to be inserted during emulation prevention
+          UInt uiMarkerCount = pcSubstreams[uiSubStrm].getTileMarkerLocationCount();
+          pcSubstreams[uiSubStrm].setTileMarkerLocation     ( uiMarkerCount, pcSubstreams[uiSubStrm].getNumberOfWrittenBits() >> 3 );
+          pcSubstreams[uiSubStrm].setTileMarkerLocationCount( uiMarkerCount + 1 );
+          // Write tile index
+          m_pcEntropyCoder->writeTileMarker(iTileIdx, rpcPic->getPicSym()->getBitsUsedByTileIdx()); // Tile index
+        }
+
+        
+        UInt uiAccumulatedSubstreamLength = 0;
+        for (Int iSubstrmIdx=0; iSubstrmIdx < iNumSubstreams; iSubstrmIdx++)
+        {
+          uiAccumulatedSubstreamLength += pcSubstreams[iSubstrmIdx].getNumberOfWrittenBits();
+        }
+        UInt uiLocationCount = pcSlice->getTileLocationCount();
+        // add bits coded in previous entropy slices + bits coded so far
+        pcSlice->setTileLocation( uiLocationCount, (pcSlice->getTileOffstForMultES() + uiAccumulatedSubstreamLength - uiBitsOriginallyInSubstreams) >> 3 ); 
+        pcSlice->setTileLocationCount( uiLocationCount + 1 );
+      }
+    }
+
+#if H3D_QTL
+    rpcPic->setReduceBitsFlag(true);
+#endif
+
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );    
+
+    if ( pcSlice->getSPS()->getUseSAO() && pcSlice->getAPS()->getSaoInterleavingFlag() && pcSlice->getSaoEnabledFlag() )
+    {
+      Int iNumCuInWidth     = pcSlice->getAPS()->getSaoParam()->numCuInWidth;
+      Int iCUAddrInSlice    = uiCUAddr - (pcSlice->getSliceCurStartCUAddr() /rpcPic->getNumPartInCU());
+      Int iCUAddrUpInSlice  = iCUAddrInSlice - iNumCuInWidth;
+      Int rx = uiCUAddr % iNumCuInWidth;
+      Int ry = uiCUAddr / iNumCuInWidth;
+      m_pcEntropyCoder->encodeSaoUnitInterleaving( rx, ry, pcSlice->getAPS()->getSaoParam(),pcCU, iCUAddrInSlice, iCUAddrUpInSlice, pcSlice->getSPS()->getLFCrossSliceBoundaryFlag());
+    }
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+    if ( (m_pcCfg->getSliceMode()!=0 || m_pcCfg->getEntropySliceMode()!=0) && 
+      uiCUAddr == rpcPic->getPicSym()->getCUOrderMap((uiBoundingCUAddr+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU()-1) )
+    {
+      m_pcCuEncoder->encodeCU( pcCU, true );
+    }
+    else
+    {
+      m_pcCuEncoder->encodeCU( pcCU );
+    }
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif    
+    if( m_pcCfg->getUseSBACRD() )
+    {
+       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 (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiCol == uiTileLCUX+1))
+      {
+        m_pcBufferSbacCoders[uiTileCol].loadContexts( &pcSbacCoders[uiSubStrm] );
+      }
+    }
+
+#if H3D_QTL
+    rpcPic->setReduceBitsFlag(false);
+#endif
+
+  }
+
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcCfg->getUseAdaptQpSelect() )
+  {
+    m_pcTrQuant->storeSliceQpNext(pcSlice);
+  }
+#endif
+#if CABAC_INIT_FLAG
+  if (pcSlice->getPPS()->getCabacInitPresentFlag())
+  {
+    m_pcEntropyCoder->determineCabacInitIdx();
+  }
+#endif
+}
+
+/** Determines the starting and bounding LCU address of current slice / entropy 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& uiStartCUAddr, UInt& uiBoundingCUAddr, 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 AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE:
+      uiCUAddrIncrement        = m_pcCfg->getSliceArgument();
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = pcSlice->getSliceCurEndCUAddr();
+      break;
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE:
+      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()) >> (m_pcCfg->getSliceGranularity() << 1);
+        }
+      }
+
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+  }
+  else
+  {
+    UInt uiCUAddrIncrement     ;
+    switch (m_pcCfg->getSliceMode())
+    {
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE:
+      uiCUAddrIncrement        = m_pcCfg->getSliceArgument();
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE:
+      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()) >> (m_pcCfg->getSliceGranularity() << 1);
+        }
+      }
+
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+  }
+
+  Bool tileBoundary = false;
+  if ((m_pcCfg->getSliceMode() == AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE || m_pcCfg->getSliceMode() == AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE) && 
+      (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;
+    }
+  }
+
+  // Entropy slice
+  UInt uiStartCUAddrEntropySlice, uiBoundingCUAddrEntropySlice;
+  uiStartCUAddrEntropySlice    = pcSlice->getEntropySliceCurStartCUAddr();
+  uiBoundingCUAddrEntropySlice = uiNumberOfCUsInFrame;
+  if (bEncodeSlice) 
+  {
+    UInt uiCUAddrIncrement;
+    switch (m_pcCfg->getEntropySliceMode())
+    {
+    case SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE:
+      uiCUAddrIncrement               = m_pcCfg->getEntropySliceArgument();
+      uiBoundingCUAddrEntropySlice    = ((uiStartCUAddrEntropySlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (uiStartCUAddrEntropySlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrEntropySlice    = pcSlice->getEntropySliceCurEndCUAddr();
+      break;
+    default:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrEntropySlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    pcSlice->setEntropySliceCurEndCUAddr( uiBoundingCUAddrEntropySlice );
+  }
+  else
+  {
+    UInt uiCUAddrIncrement;
+    switch (m_pcCfg->getEntropySliceMode())
+    {
+    case SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE:
+      uiCUAddrIncrement               = m_pcCfg->getEntropySliceArgument();
+      uiBoundingCUAddrEntropySlice    = ((uiStartCUAddrEntropySlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (uiStartCUAddrEntropySlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrEntropySlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    pcSlice->setEntropySliceCurEndCUAddr( uiBoundingCUAddrEntropySlice );
+  }
+  if(uiBoundingCUAddrEntropySlice>uiBoundingCUAddrSlice)
+  {
+    uiBoundingCUAddrEntropySlice = uiBoundingCUAddrSlice;
+    pcSlice->setEntropySliceCurEndCUAddr(uiBoundingCUAddrSlice);
+  }
+  //calculate real entropy slice start address
+  UInt uiInternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getEntropySliceCurStartCUAddr()) % rpcPic->getNumPartInCU();
+  UInt uiExternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getEntropySliceCurStartCUAddr()) / 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->setEntropySliceCurStartCUAddr(uiRealStartAddress);
+  uiStartCUAddrEntropySlice=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;
+  
+  // Make a joint decision based on reconstruction and entropy slice bounds
+  uiStartCUAddr    = max(uiStartCUAddrSlice   , uiStartCUAddrEntropySlice   );
+  uiBoundingCUAddr = min(uiBoundingCUAddrSlice, uiBoundingCUAddrEntropySlice);
+
+
+  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()==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE && m_pcCfg->getEntropySliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE)
+      || (m_pcCfg->getSliceMode()==0 && m_pcCfg->getEntropySliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE)
+      || (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE && m_pcCfg->getEntropySliceMode()==0) 
+      || (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE && m_pcCfg->getEntropySliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE)
+      || (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_TILES_IN_SLICE && m_pcCfg->getEntropySliceMode()==0) 
+      || tileBoundary
+)
+    {
+      if (uiBoundingCUAddrSlice < uiBoundingCUAddrEntropySlice)
+      {
+        pcSlice->setNextSlice       ( true );
+        pcSlice->setNextEntropySlice( false );
+      }
+      else if (uiBoundingCUAddrSlice > uiBoundingCUAddrEntropySlice)
+      {
+        pcSlice->setNextSlice       ( false );
+        pcSlice->setNextEntropySlice( true );
+      }
+      else
+      {
+        pcSlice->setNextSlice       ( true );
+        pcSlice->setNextEntropySlice( true );
+      }
+    }
+    else
+    {
+      pcSlice->setNextSlice       ( false );
+      pcSlice->setNextEntropySlice( false );
+    }
+  }
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSlice.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncSlice.h	(revision 341)
@@ -0,0 +1,156 @@
+/* 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-2012, 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     TEncSlice.h
+    \brief    slice encoder class (header)
+*/
+
+#ifndef __TENCSLICE__
+#define __TENCSLICE__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TEncCu.h"
+#include "WeightPredAnalysis.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+class TEncGOP;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice encoder class
+class TEncSlice
+  : public WeightPredAnalysis
+{
+private:
+  // 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
+  UInt64                  m_uiPicDist;                          ///< total distortion for the picture
+  Double                  m_dPicRdCost;                         ///< picture-level RD cost
+  Double*                 m_pdRdPicLambda;                      ///< array of lambda candidates
+  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
+  
+  UInt                    m_uiSliceIdx;
+
+#if MERL_VSP_C0152
+  // Data temporarily stored, will be sent to TComSlice level where the data will be actually used
+  TComPic* m_pPicBaseTxt;
+  TComPic* m_pPicBaseDepth;
+  Int*     m_aiShiftLUT;
+  Int      m_iShiftPrec;
+#endif
+
+public:
+  TEncSlice();
+  virtual ~TEncSlice();
+  
+  Void    create              ( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth );
+  Void    destroy             ();
+  Void    init                ( TEncTop* pcEncTop );
+  
+  /// preparation of slice encoding (reference marking, QP and lambda)
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+#if MTK_DEPTH_MERGE_TEXTURE_CANDIDATE_C0137
+  Void    initEncSlice        ( TComPic*  pcPic, Int iPOCLast, UInt uiPOCCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, bool isDepth );
+#else
+  Void    initEncSlice        ( TComPic*  pcPic, Int iPOCLast, UInt uiPOCCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS );
+#endif
+#else
+  Void    initEncSlice        ( TComPic*  pcPic, Int iPOCLast, UInt uiPOCCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS );
+#endif
+  // compress and encode slice
+  Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
+  Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
+  Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* rpcBitstream, TComOutputBitstream* pcSubstreams  );
+  
+  // 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 );
+  UInt    getSliceIdx()         { return m_uiSliceIdx;                    }
+  Void    setSliceIdx(UInt i)   { m_uiSliceIdx = i;                       }
+
+#if MERL_VSP_C0152
+   Void     setBWVSPLUTParam    ( Int *pShiftLUT, Int iLoG2LUTPrec ) { m_aiShiftLUT = pShiftLUT; m_iShiftPrec = 2-iLoG2LUTPrec; }
+   Void     setRefPicBaseTxt    ( TComPic*pPicTxt   ) { m_pPicBaseTxt = pPicTxt;    }
+   Void     setRefPicBaseDepth  ( TComPic*pPicDepth ) { m_pPicBaseDepth = pPicDepth;}
+   Void     getBWVSPLUTParam    ( Int*& pShiftLUT, Int& iShiftPrec ) { pShiftLUT = m_aiShiftLUT; iShiftPrec = m_iShiftPrec; }
+   TComPic* getRefPicBaseTxt    () { return m_pPicBaseTxt;   }
+   TComPic* getRefPicBaseDepth  () { return m_pPicBaseDepth; }
+#endif
+};
+
+//! \}
+
+#endif // __TENCSLICE__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncTop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncTop.cpp	(revision 341)
@@ -0,0 +1,1127 @@
+/* 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-2012, 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     TEncTop.cpp
+    \brief    encoder class
+*/
+
+#include "TLibCommon/CommonDef.h"
+#include "TEncTop.h"
+#include "TEncPic.h"
+#include "../../App/TAppEncoder/TAppEncTop.h"
+#if FAST_BIT_EST
+#include "TLibCommon/ContextModel.h"
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncTop::TEncTop()
+{
+  m_iPOCLast          = -1;
+  m_iNumPicRcvd       =  0;
+  m_uiNumAllPicCoded  =  0;
+  m_pppcRDSbacCoder   =  NULL;
+  m_pppcBinCoderCABAC =  NULL;
+  m_cRDGoOnSbacCoder.init( &m_cRDGoOnBinCoderCABAC );
+#if ENC_DEC_TRACE
+  g_hTrace = fopen( "TraceEnc.txt", "wb" );
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#endif
+
+  m_iMaxRefPicNum     = 0;
+
+#if FAST_BIT_EST
+  ContextModel::buildNextStateTable();
+#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;
+}
+
+TEncTop::~TEncTop()
+{
+#if ENC_DEC_TRACE
+  fclose( g_hTrace );
+#endif
+}
+
+Void TEncTop::create ()
+{
+  // initialize global variables
+  if( m_viewId == 0 && m_isDepth == false )
+  {
+    initROM();
+  }
+
+
+  // create processing unit classes
+  m_cGOPEncoder.        create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight );
+  m_cSliceEncoder.      create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  m_cCuEncoder.         create( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight );
+  if (m_bUseSAO)
+  {
+    m_cEncSAO.setSaoInterleavingFlag(getSaoInterleavingFlag());
+    m_cEncSAO.setMaxNumOffsetsPerPic(getMaxNumOffsetsPerPic());
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+    m_cEncSAO.createEncBuffer();
+  }
+#if ADAPTIVE_QP_SELECTION
+  if (m_bUseAdaptQpSelect)
+  {
+    m_cTrQuant.initSliceQpDelta();
+  }
+#endif
+  m_cAdaptiveLoopFilter.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  m_cLoopFilter.        create( g_uiMaxCUDepth );
+  
+#if DEPTH_MAP_GENERATION
+  m_cDepthMapGenerator. create( false, getSourceWidth(), getSourceHeight(), g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiBitDepth + g_uiBitIncrement, PDM_SUB_SAMP_EXP_X(m_uiPredDepthMapGeneration), PDM_SUB_SAMP_EXP_Y(m_uiPredDepthMapGeneration) );
+#endif
+#if H3D_IVRP
+  m_cResidualGenerator. create( false, getSourceWidth(), getSourceHeight(), g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiBitDepth + g_uiBitIncrement );
+#endif
+
+  if(m_bUseALF)
+  {
+    m_cAdaptiveLoopFilter.setAlfCoefInSlice(m_bALFParamInSlice);
+    m_cAdaptiveLoopFilter.createAlfGlobalBuffers();
+  }
+
+  if(m_bUseSAO || m_bUseALF)
+  {
+    m_vAPS.reserve(MAX_NUM_SUPPORTED_APS);
+  }
+
+  // if SBAC-based RD optimization is used
+  if( m_bUseSBACRD )
+  {
+    m_pppcRDSbacCoder = new TEncSbac** [g_uiMaxCUDepth+1];
+#if FAST_BIT_EST
+    m_pppcBinCoderCABAC = new TEncBinCABACCounter** [g_uiMaxCUDepth+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];
+#if FAST_BIT_EST
+      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;
+#if FAST_BIT_EST
+        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
+#else
+        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+#endif
+        m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
+      }
+    }
+  }
+  m_pcTAppEncTop = NULL;
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( g_aacWedgeLists.empty() && m_bUseDMM )
+  {
+    initWedgeLists();
+  }
+#endif
+}
+
+/**
+ - 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] );
+  }
+  if( m_bUseSBACRD )
+  {
+    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] );
+        }
+      }
+    }
+  }
+}
+
+Void TEncTop::destroy ()
+{
+  if(m_bUseALF)
+  {
+    m_cAdaptiveLoopFilter.destroyAlfGlobalBuffers();
+  }
+
+  for(Int i=0; i< m_vAPS.size(); i++)
+  {
+    TComAPS& cAPS = m_vAPS[i];
+    m_cGOPEncoder.freeAPS(&cAPS, &m_cSPS);
+  }
+
+  // destroy processing unit classes
+  m_cGOPEncoder.        destroy();
+  m_cSliceEncoder.      destroy();
+  m_cCuEncoder.         destroy();
+  if (m_cSPS.getUseSAO())
+  {
+    m_cEncSAO.destroy();
+    m_cEncSAO.destroyEncBuffer();
+  }
+  m_cAdaptiveLoopFilter.destroy();
+  m_cLoopFilter.        destroy();
+
+#if DEPTH_MAP_GENERATION
+  m_cDepthMapGenerator. destroy();
+#endif
+#if H3D_IVRP
+  m_cResidualGenerator. destroy();
+#endif
+
+  m_RPSList.            destroy();
+  
+  // SBAC RD
+  if( m_bUseSBACRD )
+  {
+    Int iDepth;
+    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+      {
+        delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+        delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+      }
+    }
+    
+    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      delete [] m_pppcRDSbacCoder[iDepth];
+      delete [] m_pppcBinCoderCABAC[iDepth];
+    }
+    
+    delete [] m_pppcRDSbacCoder;
+    delete [] m_pppcBinCoderCABAC;
+
+    for ( UInt ui = 0; ui < m_iNumSubstreams; ui++ )
+    {
+      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+        {
+          delete m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx];
+          delete m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx];
+        }
+      }
+
+      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        delete [] m_ppppcRDSbacCoders  [ui][iDepth];
+        delete [] m_ppppcBinCodersCABAC[ui][iDepth];
+      }
+      delete[] m_ppppcRDSbacCoders  [ui];
+      delete[] m_ppppcBinCodersCABAC[ui];
+    }
+    delete[] m_ppppcRDSbacCoders;
+    delete[] m_ppppcBinCodersCABAC;
+  }
+  delete[] m_pcSbacCoders;
+  delete[] m_pcBinCoderCABACs;
+  delete[] m_pcRDGoOnSbacCoders;  
+  delete[] m_pcRDGoOnBinCodersCABAC;
+  delete[] m_pcBitCounters;
+  delete[] m_pcRdCosts;
+  
+  // destroy ROM
+  if(m_viewId == 0 && m_isDepth == false)
+  {
+  destroyROM();
+  }
+  
+  return;
+}
+
+Void TEncTop::init( TAppEncTop* pcTAppEncTop )
+{
+  UInt *aTable4=NULL, *aTable8=NULL;
+  UInt* aTableLastPosVlcIndex=NULL; 
+  // initialize SPS
+  xInitSPS();
+  
+  // initialize PPS
+  m_cPPS.setSPS(&m_cSPS);
+  m_cSPS.setRPSList(&m_RPSList);
+  xInitPPS();
+  xInitRPS();
+
+  xInitSPSforInterViewRefs();
+  xInitPPSforTiles();
+
+  // initialize processing unit classes
+  m_cGOPEncoder.  init( this );
+  m_cSliceEncoder.init( this );
+  m_cCuEncoder.   init( this );
+  
+  m_pcTAppEncTop = pcTAppEncTop;
+
+#if DEPTH_MAP_GENERATION
+#if VIDYO_VPS_INTEGRATION
+  m_cDepthMapGenerator.init( (TComPrediction*)this->getPredSearch(), m_pcTAppEncTop->getVPSAccess(), m_pcTAppEncTop->getSPSAccess(), m_pcTAppEncTop->getAUPicAccess() );
+#else
+  m_cDepthMapGenerator.init( (TComPrediction*)this->getPredSearch(), m_pcTAppEncTop->getSPSAccess(), m_pcTAppEncTop->getAUPicAccess() );
+#endif
+#endif
+#if H3D_IVRP
+  m_cResidualGenerator.init( &m_cTrQuant, &m_cDepthMapGenerator );
+#endif
+
+  // initialize transform & quantization class
+  m_pcCavlcCoder = getCavlcCoder();
+  
+  m_cTrQuant.init( g_uiMaxCUWidth, g_uiMaxCUHeight, 1 << m_uiQuadtreeTULog2MaxSize,
+                  0,
+                  aTable4, aTable8, 
+                  aTableLastPosVlcIndex, m_bUseRDOQ, true 
+#if ADAPTIVE_QP_SELECTION                  
+                  , m_bUseAdaptQpSelect
+#endif
+                  );
+  
+  // initialize encoder search class
+#if DV_V_RESTRICTION_B0037
+  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_bUseDisparitySearchRangeRestriction, m_iVerticalDisparitySearchRange, m_iFastSearch, 0, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
+#else
+  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_iFastSearch, 0, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
+#endif
+  if(m_bUseALF)
+  {
+    m_cAdaptiveLoopFilter.setALFEncodePassReduction( m_iALFEncodePassReduction );
+    m_cAdaptiveLoopFilter.setALFMaxNumberFilters( m_iALFMaxNumberFilters );
+    m_cAdaptiveLoopFilter.initPicQuadTreePartition(m_bALFPicBasedEncode );   
+  }
+
+  m_iMaxRefPicNum = 0;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncTop::initNewPic( TComPicYuv* pcPicYuvOrg, TComPicYuv* pcOrgPdmDepth )
+{
+  TComPic* pcPicCurr = NULL;
+
+  // get original YUV
+  xGetNewPicBuffer( pcPicCurr );
+  pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+
+#if INTER_VIEW_VECTOR_SCALING_C0115
+  pcPicCurr->setViewOrderIdx(m_iViewOrderIdx);    // will be changed to view_id
+#endif
+  pcPicCurr->setScaleOffset( m_aaiCodedScale, m_aaiCodedOffset );
+
+#if H3D_IVMP
+  if( m_uiMultiviewMvRegMode )
+  {
+    AOF( pcOrgPdmDepth );
+    AOF( pcPicCurr->getOrgDepthMap() );
+    pcOrgPdmDepth->copyToPic( pcPicCurr->getOrgDepthMap() );
+  }
+  else
+  {
+    AOT( pcOrgPdmDepth );
+    AOT( pcPicCurr->getOrgDepthMap() );
+  }
+#endif
+
+#if DEPTH_MAP_GENERATION
+  // add extra pic buffers
+  Bool  bNeedPrdDepthMapBuf = ( m_uiPredDepthMapGeneration > 0 );
+  if( bNeedPrdDepthMapBuf && !pcPicCurr->getPredDepthMap() )
+  {
+    pcPicCurr->addPrdDepthMapBuffer( PDM_SUB_SAMP_EXP_X(m_uiPredDepthMapGeneration), PDM_SUB_SAMP_EXP_Y(m_uiPredDepthMapGeneration) );
+  }
+#endif
+
+  // compute image characteristics
+  if ( getUseAdaptiveQP() )
+  {
+    m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
+  }
+}
+
+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;
+    pcPic = NULL;
+  }
+}
+
+/**
+ - Application has picture buffer list with size of GOP + 1
+ - Picture buffer list acts like as ring buffer
+ - End of the list has the latest picture
+ .
+ \param   bEos                true if end-of-sequence is reached
+ \param   pcPicYuvOrg         original YUV picture
+ \retval  rcListPicYuvRecOut  list of reconstruction YUV pictures
+ \retval  rcListBitstreamOut  list of output bitstreams
+ \retval  iNumEncoded         number of encoded pictures
+ */
+Void TEncTop::encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Int gopId )
+{  
+
+  if( gopId == 0)
+  {
+    m_cGOPEncoder.initGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);  
+  }
+
+  {
+    m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, gopId );
+  }
+  
+  if( gopId + 1 == m_cGOPEncoder.getGOPSize() )
+  {
+    iNumEncoded         = m_iNumPicRcvd;
+    m_iNumPicRcvd       = 0;
+    m_uiNumAllPicCoded += iNumEncoded;
+  }
+}
+
+
+#if HHI_INTERVIEW_SKIP || H3D_IVMP || H3D_IVRP
+Void
+TEncTop::deleteExtraPicBuffers( Int iPoc )
+{
+  TComPic*                      pcPic = 0;
+  TComList<TComPic*>::iterator  cIter = m_cListPic.begin();
+  TComList<TComPic*>::iterator  cEnd  = m_cListPic.end  ();
+  for( ; cIter != cEnd; cIter++ )
+  {
+    if( (*cIter)->getPOC() == iPoc )
+    {
+      pcPic = *cIter;
+      break;
+    }
+  }
+  AOF( pcPic );
+  if ( pcPic )
+  {
+#if H3D_IVMP
+    pcPic->removeOrgDepthMapBuffer();
+#endif
+#if H3D_IVRP
+    pcPic->removeResidualBuffer   ();
+#endif
+#if HHI_INTERVIEW_SKIP
+    pcPic->removeUsedPelsMapBuffer();
+#endif
+  }
+}
+#endif
+
+Void
+TEncTop::compressMotion( Int iPoc )
+{
+  TComPic*                      pcPic = 0;
+  TComList<TComPic*>::iterator  cIter = m_cListPic.begin();
+  TComList<TComPic*>::iterator  cEnd  = m_cListPic.end  ();
+  for( ; cIter != cEnd; cIter++ )
+  {
+    if( (*cIter)->getPOC() == iPoc )
+    {
+      pcPic = *cIter;
+      break;
+    }
+  }
+  AOF( pcPic );
+  if ( pcPic )
+  {
+    pcPic->compressMotion();
+  }
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - Application has picture buffer list with size of GOP + 1
+ - Picture buffer list acts like as ring buffer
+ - End of the list has the latest picture
+ .
+ \retval rpcPic obtained picture buffer
+ */
+Void TEncTop::xGetNewPicBuffer ( TComPic*& rpcPic )
+{
+  TComSlice::sortPicList(m_cListPic);
+  
+  if (m_cListPic.size() >= (UInt)(m_iGOPSize + getMaxDecPicBuffering(MAX_TLAYER-1) + 2) )
+  {
+    TComList<TComPic*>::iterator iterPic  = m_cListPic.begin();
+    Int iSize = Int( m_cListPic.size() );
+    for ( Int i = 0; i < iSize; i++ )
+    {
+      rpcPic = *(++iterPic);
+      if(rpcPic->getSlice(0)->isReferenced() == false)
+         break;
+    }
+  }
+  else
+  {
+        if ( getUseAdaptiveQP() )
+        {
+          TEncPic* pcEPic = new TEncPic;
+          pcEPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_cPPS.getMaxCuDQPDepth()+1 );
+          rpcPic = pcEPic;
+        }
+        else
+        {
+          rpcPic = new TComPic;
+          rpcPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+        }
+    m_cListPic.pushBack( rpcPic );
+  }
+#if HHI_INTERVIEW_SKIP
+  if( m_bInterViewSkip )
+  {
+    rpcPic->addUsedPelsMapBuffer();
+  }
+#endif
+  rpcPic->setReconMark (false);
+  
+  m_iPOCLast++;
+  m_iNumPicRcvd++;
+  
+#if H3D_IVMP
+  if( m_uiMultiviewMvRegMode )
+  {
+    rpcPic->addOrgDepthMapBuffer();
+  }
+#endif
+  
+  rpcPic->getSlice(0)->setPOC( m_iPOCLast );
+  // mark it should be extended
+  rpcPic->getPicYuvRec()->setBorderExtension(false);
+  rpcPic->getPicYuvOrg()->setBorderExtension(false); 
+}
+
+Void TEncTop::xInitSPS()
+{
+  m_cSPS.setPicWidthInLumaSamples         ( m_iSourceWidth      );
+  m_cSPS.setPicHeightInLumaSamples        ( m_iSourceHeight     );
+  m_cSPS.setPicCroppingFlag( m_croppingMode!= 0 );
+  if (m_croppingMode != 0)
+  {
+    m_cSPS.setPicCropLeftOffset( m_cropLeft );
+    m_cSPS.setPicCropRightOffset( m_cropRight );
+    m_cSPS.setPicCropTopOffset( m_cropTop );
+    m_cSPS.setPicCropBottomOffset( m_cropBottom );
+  }
+  m_cSPS.setMaxCUWidth    ( g_uiMaxCUWidth      );
+  m_cSPS.setMaxCUHeight   ( g_uiMaxCUHeight     );
+  m_cSPS.setMaxCUDepth    ( g_uiMaxCUDepth      );
+  m_cSPS.setMinTrDepth    ( 0                   );
+  m_cSPS.setMaxTrDepth    ( 1                   );
+  
+  m_cSPS.setPCMLog2MinSize (m_uiPCMLog2MinSize);
+  m_cSPS.setUsePCM        ( m_usePCM           );
+  m_cSPS.setPCMLog2MaxSize( m_pcmLog2MaxSize  );
+
+  m_cSPS.setUseALF        ( m_bUseALF           );
+  if(m_bUseALF)
+  {
+    m_cSPS.setUseALFCoefInSlice(m_bALFParamInSlice);
+  }
+  
+#if RWTH_SDC_DLT_B0036
+  m_cSPS.setUseDLT        ( m_bUseDLT );
+#endif
+  
+  m_cSPS.setQuadtreeTULog2MaxSize( m_uiQuadtreeTULog2MaxSize );
+  m_cSPS.setQuadtreeTULog2MinSize( m_uiQuadtreeTULog2MinSize );
+  m_cSPS.setQuadtreeTUMaxDepthInter( m_uiQuadtreeTUMaxDepthInter    );
+  m_cSPS.setQuadtreeTUMaxDepthIntra( m_uiQuadtreeTUMaxDepthIntra    );
+  
+#if LOSSLESS_CODING
+  m_cSPS.setUseLossless   ( m_useLossless  );
+#endif
+  m_cSPS.setUseLMChroma   ( m_bUseLMChroma           );  
+  
+  m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
+  
+  m_cSPS.setUseLComb    ( m_bUseLComb           );
+  m_cSPS.setLCMod       ( m_bLCMod   );
+  m_cSPS.setUseNSQT( m_useNSQT );
+  
+  Int i;
+#if HHI_AMVP_OFF
+  for ( i = 0; i < g_uiMaxCUDepth; i++ )
+  {
+    m_cSPS.setAMVPMode( i, AM_NONE );
+  }
+#else
+  for ( i = 0; i < g_uiMaxCUDepth; i++ )
+  {
+    m_cSPS.setAMVPMode( i, AM_EXPL );
+  }
+#endif
+  
+  for (i = 0; i < g_uiMaxCUDepth-1; i++ )
+  {
+    m_cSPS.setAMPAcc( i, m_useAMP );
+    //m_cSPS.setAMPAcc( i, 1 );
+  }
+
+  m_cSPS.setUseAMP ( m_useAMP );
+
+  for (i = g_uiMaxCUDepth-1; i < g_uiMaxCUDepth; i++ )
+  {
+    m_cSPS.setAMPAcc(i, 0);
+  }
+
+  m_cSPS.setBitDepth    ( g_uiBitDepth        );
+  m_cSPS.setBitIncrement( g_uiBitIncrement    );
+  m_cSPS.setQpBDOffsetY ( (Int)(6*(g_uiBitDepth + g_uiBitIncrement - 8)) );
+  m_cSPS.setQpBDOffsetC ( (Int)(6*(g_uiBitDepth + g_uiBitIncrement - 8)) );
+
+  m_cSPS.setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+  m_cSPS.setUseSAO( m_bUseSAO );
+
+  m_cSPS.setMaxTLayers( m_maxTempLayer );
+  m_cSPS.setTemporalIdNestingFlag( false );
+  for ( i = 0; i < m_cSPS.getMaxTLayers(); i++ )
+  {
+    m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
+    m_cSPS.setNumReorderPics(m_numReorderPics[i], i);
+  }
+  m_cSPS.setPCMBitDepthLuma (g_uiPCMBitDepthLuma);
+  m_cSPS.setPCMBitDepthChroma (g_uiPCMBitDepthChroma);
+  m_cSPS.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag );
+
+  m_cSPS.setLFCrossTileBoundaryFlag( m_bLFCrossTileBoundaryFlag );
+  m_cSPS.setUniformSpacingIdr( m_iUniformSpacingIdr );
+  m_cSPS.setNumColumnsMinus1( m_iNumColumnsMinus1 );
+  m_cSPS.setNumRowsMinus1( m_iNumRowsMinus1 );
+  if( m_iUniformSpacingIdr == 0 )
+  {
+    m_cSPS.setColumnWidth( m_puiColumnWidth );
+    m_cSPS.setRowHeight( m_puiRowHeight );
+  }
+  m_cSPS.setScalingListFlag ( (m_useScalingListId == 0) ? 0 : 1 );
+  m_cSPS.setUseDF( m_loopFilterOffsetInAPS );
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  m_cSPS.setUseDMM( m_bUseDMM );
+#endif
+
+#if HHI_DMM_PRED_TEX && FLEX_CODING_ORDER_M23723
+  m_cSPS.setUseDMM34( m_bUseDMM34 );
+#endif
+
+#if H3D_QTL
+  m_cSPS.setUseQTLPC( m_bUseQTLPC );
+#endif
+#if HHI_MPI
+  m_cSPS.setUseMVI( m_bUseMVI );
+#endif
+
+  if( m_isDepth )
+  {
+#if FCO_FIX_SPS_CHANGE
+    m_cSPS.initMultiviewSPSDepth    ( m_viewId, m_iViewOrderIdx, m_uiCamParPrecision, m_bCamParInSliceHeader, m_aaiCodedScale, m_aaiCodedOffset );
+#else
+    m_cSPS.initMultiviewSPSDepth    ( m_viewId, m_iViewOrderIdx );
+#endif
+
+#if DEPTH_MAP_GENERATION
+    m_cSPS.setPredDepthMapGeneration( m_viewId, true );
+#endif
+#if H3D_IVRP
+    m_cSPS.setMultiviewResPredMode  ( 0 );
+#endif
+  }
+  else
+  {
+#if QC_MVHEVC_B0046
+    m_cSPS.initMultiviewSPS   ( m_viewId);
+#else
+    m_cSPS.initMultiviewSPS           ( m_viewId, m_iViewOrderIdx, m_uiCamParPrecision, m_bCamParInSliceHeader, m_aaiCodedScale, m_aaiCodedOffset );
+#endif
+    if( m_viewId )
+    {
+#if DEPTH_MAP_GENERATION
+#if H3D_IVMP
+      m_cSPS.setPredDepthMapGeneration( m_viewId, false, m_uiPredDepthMapGeneration, m_uiMultiviewMvPredMode, m_uiPdmPrecision, m_aaiPdmScaleNomDelta, m_aaiPdmOffset );
+#else
+      m_cSPS.setPredDepthMapGeneration( m_viewId, false, m_uiPredDepthMapGeneration, 0, m_uiPdmPrecision, m_aaiPdmScaleNomDelta, m_aaiPdmOffset );
+#endif
+#endif
+#if H3D_IVRP
+      m_cSPS.setMultiviewResPredMode  ( m_uiMultiviewResPredMode );
+#endif
+    }
+    else
+    {
+#if DEPTH_MAP_GENERATION
+      m_cSPS.setPredDepthMapGeneration( m_viewId, false );
+#endif
+#if H3D_IVRP
+      m_cSPS.setMultiviewResPredMode  ( 0 );
+#endif
+    }
+  }
+}
+
+Void TEncTop::xInitPPS()
+{
+  m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
+  m_cPPS.setSliceGranularity(m_iSliceGranularity);
+  Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
+
+#if LOSSLESS_CODING
+  Int lowestQP = - m_cSPS.getQpBDOffsetY();
+
+  if(getUseLossless())
+  {
+    if ((getMaxCuDQPDepth() == 0) && (getMaxDeltaQP() == 0 ) && (getQP() == lowestQP) )
+    {
+      bUseDQP = false;
+    }
+    else
+    {
+      bUseDQP = true;
+    }
+  }
+  else
+  {
+    if(bUseDQP == false)
+    {
+      if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
+      {
+        bUseDQP = true;
+      }
+    }
+  }
+
+#else
+  if(bUseDQP == false)
+  {
+    if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
+    {
+      bUseDQP = true;
+    }
+  }
+#endif
+
+  if(bUseDQP)
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( m_iMaxCuDQPDepth );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+  else
+  {
+    m_cPPS.setUseDQP(false);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+
+  m_cPPS.setChromaQpOffset   ( m_iChromaQpOffset    );
+  m_cPPS.setChromaQpOffset2nd( m_iChromaQpOffset2nd );
+
+  m_cPPS.setEntropyCodingMode( 1 ); // In the PPS now, but also remains in slice header!
+  m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams);
+  m_cPPS.setUseWP( m_bUseWeightPred );
+  m_cPPS.setWPBiPredIdc( m_uiBiPredIdc );
+  m_cPPS.setEnableTMVPFlag( m_bEnableTMVP );
+  m_cPPS.setOutputFlagPresentFlag( false );
+  m_cPPS.setSignHideFlag(getSignHideFlag());
+  m_cPPS.setTSIG(getTSIG());
+  m_cPPS.setDeblockingFilterControlPresent (m_DeblockingFilterControlPresent );
+  m_cPPS.setLog2ParallelMergeLevelMinus2      (LOG2_PARALLEL_MERGE_LEVEL_MINUS2);
+#if CABAC_INIT_FLAG
+  m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
+#endif
+}
+
+//Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
+Void TEncTop::xInitRPS()
+{
+  TComReferencePictureSet*      rps;
+  
+  m_RPSList.create(getGOPSize()+m_extraRPSs);
+  for( Int i = 0; i < getGOPSize()+m_extraRPSs; i++) 
+  {
+    GOPEntryMvc ge = getGOPEntry(i);
+    rps = m_RPSList.getReferencePictureSet(i);
+    rps->setNumberOfPictures(ge.m_numRefPics);
+    rps->setNumRefIdc(ge.m_numRefIdc);
+    Int numNeg = 0;
+    Int numPos = 0;
+    for( Int j = 0; j < ge.m_numRefPics; j++)
+    {
+      rps->setDeltaPOC(j,ge.m_referencePics[j]);
+      rps->setUsed(j,ge.m_usedByCurrPic[j]);
+      if(ge.m_referencePics[j]>0)
+      {
+        numPos++;
+      }
+      else
+      {
+        numNeg++;
+      }
+    }
+    rps->setNumberOfNegativePictures(numNeg);
+    rps->setNumberOfPositivePictures(numPos);
+    rps->setInterRPSPrediction(ge.m_interRPSPrediction);
+    if (ge.m_interRPSPrediction)
+    {
+      rps->setDeltaRIdxMinus1(ge.m_deltaRIdxMinus1);
+      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-(ge.m_deltaRIdxMinus1+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
+    }
+  }
+  
+}
+
+   // 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,TComList<TComPic*>& listPic )
+{
+#if QC_REM_IDV_B0046
+  if( (slice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR ||slice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA) && slice->getSPS()->getViewId() && POCCurr == 0 )
+#else
+  if( slice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDV && POCCurr == 0 )
+#endif
+  {
+    TComReferencePictureSet* rps = slice->getLocalRPS();
+    rps->setNumberOfNegativePictures(0);
+    rps->setNumberOfPositivePictures(0);
+    rps->setNumberOfLongtermPictures(0);
+    rps->setNumberOfPictures(0);
+    slice->setRPS(rps);
+  }
+  else
+  {
+    slice->setRPSidx(GOPid);
+
+    for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
+    {    
+      if(m_uiIntraPeriod > 0)
+      {
+        if(POCCurr%m_uiIntraPeriod==m_GOPList[extraNum].m_POC)
+        {
+          slice->setRPSidx(extraNum);
+        }
+      }
+      else
+      {
+        if(POCCurr==m_GOPList[extraNum].m_POC)
+        {
+          slice->setRPSidx(extraNum);
+        }
+      }
+    }
+
+    slice->setRPS(getRPSList()->getReferencePictureSet(slice->getRPSidx()));
+    slice->getRPS()->setNumberOfPictures(slice->getRPS()->getNumberOfNegativePictures()+slice->getRPS()->getNumberOfPositivePictures());
+  }
+}
+
+Void TEncTop::xInitSPSforInterViewRefs()
+{
+  // base view
+  if( getGOPEntry( MAX_GOP ).m_POC == -1 )
+  { 
+    m_cSPS.setNumberOfUsableInterViewRefs( 0 );
+    m_cSPS.setListsModificationPresentFlag( false );
+    return;
+  }
+
+  Int numberUsableInterViewRefs = 0;
+  for( Int i = 0; i < getGOPSize()+1 && numberUsableInterViewRefs < MAX_VIEW_NUM; i++ ) 
+  {
+    GOPEntryMvc ge = ( i < getGOPSize() ) ? getGOPEntry( i ) : getGOPEntry( MAX_GOP );
+    for( Int j = 0; j < ge.m_numInterViewRefPics; j++ )
+    {
+      // add ref view to list
+      Bool onList = false;
+      for( Int k = 0; k < numberUsableInterViewRefs; k++ )
+      {
+        if( ge.m_interViewRefs[j] == m_cSPS.getUsableInterViewRef( k ) )
+        {
+          onList = true;
+          break;
+        }
+      }
+      if( !onList )
+      {
+        m_cSPS.setUsableInterViewRef( (UInt)numberUsableInterViewRefs, ge.m_interViewRefs[j] );
+        numberUsableInterViewRefs++;
+      }
+    }
+  }
+  m_cSPS.setNumberOfUsableInterViewRefs( numberUsableInterViewRefs );
+
+  // sort inter view refs
+  for( Int j = 1; j < m_cSPS.getNumberOfUsableInterViewRefs(); j++ )
+  { 
+    Int deltaViewId = m_cSPS.getUsableInterViewRef( j );
+    for( Int k = j-1; k >= 0; k-- )
+    {
+      Int temp = m_cSPS.getUsableInterViewRef( k );
+      if( deltaViewId > temp )
+      {
+        m_cSPS.setUsableInterViewRef( k+1, temp );
+        m_cSPS.setUsableInterViewRef( k, deltaViewId );
+      }
+    }
+  }
+
+  m_cSPS.setListsModificationPresentFlag( true );
+}
+
+Void  TEncTop::xInitPPSforTiles()
+{
+    m_cPPS.setColumnRowInfoPresent( m_iColumnRowInfoPresent );
+    m_cPPS.setUniformSpacingIdr( m_iUniformSpacingIdr );
+    m_cPPS.setNumColumnsMinus1( m_iNumColumnsMinus1 );
+    m_cPPS.setNumRowsMinus1( m_iNumRowsMinus1 );
+    if( m_iUniformSpacingIdr == 0 )
+    {
+      m_cPPS.setColumnWidth( m_puiColumnWidth );
+      m_cPPS.setRowHeight( m_puiRowHeight );
+    }
+    m_cPPS.setTileBehaviorControlPresentFlag( m_iTileBehaviorControlPresentFlag );
+    m_cPPS.setLFCrossTileBoundaryFlag( m_bLFCrossTileBoundaryFlag );
+
+    // # substreams is "per tile" when tiles are independent.
+    if ( m_iWaveFrontSynchro )
+    {
+      m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams * (m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+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;
+  UInt  uiCummulativeColumnWidth = 0;
+  UInt  uiCummulativeRowHeight = 0;
+
+  //check the column relative parameters
+  if( m_iNumColumnsMinus1 >= (1<<(LOG2_MAX_NUM_COLUMNS_MINUS1+1)) )
+  {
+    printf( "The number of columns is larger than the maximum allowed number of columns.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumColumnsMinus1 >= iWidthInCU )
+  {
+    printf( "The current picture can not have so many columns.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumColumnsMinus1 && m_iUniformSpacingIdr==0 )
+  {
+    for(Int i=0; i<m_iNumColumnsMinus1; i++)
+      uiCummulativeColumnWidth += m_puiColumnWidth[i];
+
+    if( uiCummulativeColumnWidth >= iWidthInCU )
+    {
+      printf( "The width of the column is too large.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+
+  //check the row relative parameters
+  if( m_iNumRowsMinus1 >= (1<<(LOG2_MAX_NUM_ROWS_MINUS1+1)) )
+  {
+    printf( "The number of rows is larger than the maximum allowed number of rows.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumRowsMinus1 >= iHeightInCU )
+  {
+    printf( "The current picture can not have so many rows.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumRowsMinus1 && m_iUniformSpacingIdr==0 )
+  {
+    for(Int i=0; i<m_iNumRowsMinus1; i++)
+      uiCummulativeRowHeight += m_puiRowHeight[i];
+
+    if( uiCummulativeRowHeight >= iHeightInCU )
+    {
+      printf( "The height of the row is too large.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+}
+
+Void TEncTop::setTEncTopList(std::vector<TEncTop*>* pacTEncTopList )
+{
+  assert(m_viewId!=-1); // not to be set for single view coding
+
+  m_pacTEncTopList=pacTEncTopList;
+
+}
+
+Void TEncTop::printOutSummary(UInt uiNumAllPicCoded)
+{
+  assert (uiNumAllPicCoded == m_cAnalyzeAll.getNumPic());
+
+  //--CFG_KDY
+  m_cAnalyzeAll.setFrmRate( getFrameRate() );
+  m_cAnalyzeI.setFrmRate( getFrameRate() );
+  m_cAnalyzeP.setFrmRate( getFrameRate() );
+  m_cAnalyzeB.setFrmRate( getFrameRate() );
+
+  //-- all
+  if(m_viewId==-1)
+    printf( "\n\nSUMMARY --------------------------------------------------------\n" );
+  else {
+    if ( m_isDepth )
+    {
+      printf( "\n\nSUMMARY ---------------------------------------------- DEPTH %2d\n", m_viewId );
+    }
+    else
+    {
+      printf( "\n\nSUMMARY ---------------------------------------------- VIDEO %2d\n", m_viewId );
+    }
+  };
+  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');
+
+//  m_cAnalyzeAll.printSummaryOut();
+//  m_cAnalyzeI.printSummary('I');
+//  m_cAnalyzeP.printSummary('P');
+//  m_cAnalyzeB.printSummary('B');
+}
+
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncTop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/TEncTop.h	(revision 341)
@@ -0,0 +1,251 @@
+/* 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-2012, 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     TEncTop.h
+    \brief    encoder class (header)
+*/
+
+#ifndef __TENCTOP__
+#define __TENCTOP__
+
+// Include files
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/AccessUnit.h"
+#include "TLibCommon/TComDepthMapGenerator.h"
+#include "../TLibCommon/TComResidualGenerator.h"
+
+#include "TLibVideoIO/TVideoIOYuv.h"
+
+#include "TEncCfg.h"
+#include "TEncGOP.h"
+#include "TEncSlice.h"
+#include "TEncEntropy.h"
+#include "TEncCavlc.h"
+#include "TEncSbac.h"
+#include "TEncSearch.h"
+#include "TEncAdaptiveLoopFilter.h"
+#include "TEncSampleAdaptiveOffset.h"
+#include "TEncPreanalyzer.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TAppEncTop;
+
+/// encoder class
+class TEncTop : public TEncCfg
+{
+private:
+  // picture
+  Int                     m_iPOCLast;                     ///< time index (POC)
+  Int                     m_iNumPicRcvd;                  ///< number of received pictures
+  UInt                    m_uiNumAllPicCoded;             ///< number of coded pictures
+  TComList<TComPic*>      m_cListPic;                     ///< dynamic list of pictures
+  
+  // encoder search
+  TEncSearch              m_cSearch;                      ///< encoder search class
+  TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder 
+  TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder  
+  // coding tool
+  TComTrQuant             m_cTrQuant;                     ///< transform & quantization class
+  TComLoopFilter          m_cLoopFilter;                  ///< deblocking filter class
+  TEncSampleAdaptiveOffset m_cEncSAO;                     ///< sample adaptive offset class
+  TEncAdaptiveLoopFilter  m_cAdaptiveLoopFilter;          ///< adaptive loop filter class
+  TEncEntropy             m_cEntropyCoder;                ///< entropy encoder
+  TEncCavlc               m_cCavlcCoder;                  ///< CAVLC encoder
+  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
+  TEncSlice               m_cSliceEncoder;                ///< slice encoder
+  TEncCu                  m_cCuEncoder;                   ///< CU encoder
+ 
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator   m_cDepthMapGenerator;           ///< depth map generator
+#endif
+#if H3D_IVRP
+  TComResidualGenerator   m_cResidualGenerator;           ///< generator for residual pictures
+#endif
+  // SPS
+  TComSPS                 m_cSPS;                         ///< SPS
+  TComPPS                 m_cPPS;                         ///< PPS
+  std::vector<TComAPS>    m_vAPS;  //!< APS container
+  TComRPSList             m_RPSList;                         ///< RPS
+  
+  // 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
+  TEncSbac                m_cRDGoOnSbacCoder;             ///< going on SBAC model for RD stage
+#if FAST_BIT_EST
+  TEncBinCABACCounter***  m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+  TEncBinCABACCounter     m_cRDGoOnBinCoderCABAC;         ///< going on bin coder CABAC for RD stage
+#else
+  TEncBinCABAC***         m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+  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
+
+  std::vector<TEncTop*>*  m_pacTEncTopList;
+  TAppEncTop*             m_pcTAppEncTop;
+
+  TEncAnalyze             m_cAnalyzeAll;
+  TEncAnalyze             m_cAnalyzeI;
+  TEncAnalyze             m_cAnalyzeP;
+  TEncAnalyze             m_cAnalyzeB;
+
+protected:
+  Void  xGetNewPicBuffer  ( TComPic*& rpcPic );           ///< get picture buffer which will be processed
+  Void  xInitSPS          ();                             ///< initialize SPS from encoder options
+  Void  xInitPPS          ();                             ///< initialize PPS from encoder options
+  
+  Void  xInitPPSforTiles  ();
+  Void  xInitRPS          ();                             ///< initialize PPS from encoder options
+  Void  xInitSPSforInterViewRefs();
+
+public:
+  TEncTop();
+  virtual ~TEncTop();
+  
+  Void      create          ();
+  Void      destroy         ();
+  Void      init            ( TAppEncTop* pcTAppEncTop );
+  Void      deletePicBuffer ();
+
+  UInt      getFrameId          (Int iGOPid)  {
+    if(m_iPOCLast == 0)
+    {
+      return(0 );
+    }
+    else
+    {
+      return m_iPOCLast -m_iNumPicRcvd+ getGOPEntry(iGOPid).m_POC ;
+    }
+  }
+#if HHI_INTERVIEW_SKIP || H3D_IVMP || H3D_IVRP
+  Void      deleteExtraPicBuffers   ( Int iPoc );
+#endif
+
+  Void      compressMotion          ( Int iPoc );
+
+  Void      initNewPic(TComPicYuv* pcPicYuvOrg, TComPicYuv* pcOrgPdmDepth = 0);
+
+  Void      createWPPCoders(Int iNumSubstreams);
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member access functions
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComList<TComPic*>*     getListPic            () { return  &m_cListPic;             }
+  TEncSearch*             getPredSearch         () { return  &m_cSearch;              }
+  
+  TComTrQuant*            getTrQuant            () { return  &m_cTrQuant;             }
+  TComLoopFilter*         getLoopFilter         () { return  &m_cLoopFilter;          }
+  TEncAdaptiveLoopFilter* getAdaptiveLoopFilter () { return  &m_cAdaptiveLoopFilter;  }
+  TEncSampleAdaptiveOffset* getSAO              () { return  &m_cEncSAO;              }
+  TEncGOP*                getGOPEncoder         () { return  &m_cGOPEncoder;          }
+  TEncSlice*              getSliceEncoder       () { return  &m_cSliceEncoder;        }
+  TEncCu*                 getCuEncoder          () { return  &m_cCuEncoder;           }
+  TEncEntropy*            getEntropyCoder       () { return  &m_cEntropyCoder;        }
+  TEncCavlc*              getCavlcCoder         () { return  &m_cCavlcCoder;          }
+  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;   }
+  
+  Void                    setTEncTopList        ( std::vector<TEncTop*>* pacTEncTopList );
+  TAppEncTop*             getEncTop             () { return m_pcTAppEncTop; }
+  Int                     getNumAllPicCoded     () { return m_uiNumAllPicCoded; }
+  Void                    printOutSummary       ( UInt uiNumAllPicCoded );
+
+  TComSPS*                getSPS                () { return  &m_cSPS;                 }
+  TComPPS*                getPPS                () { return  &m_cPPS;                 }
+  std::vector<TComAPS>&   getAPS                () { return m_vAPS; }
+  TComRPSList*            getRPSList            () { return  &m_RPSList;                 }
+  
+  Void selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid,TComList<TComPic*>& listPic );
+  TComScalingList*        getScalingList        () { return  &m_scalingList;         }
+  
+  TEncAnalyze*            getAnalyzeAll         () { return &m_cAnalyzeAll; }
+  TEncAnalyze*            getAnalyzeI           () { return &m_cAnalyzeI;   }
+  TEncAnalyze*            getAnalyzeP           () { return &m_cAnalyzeP;   }
+  TEncAnalyze*            getAnalyzeB           () { return &m_cAnalyzeB;   }
+
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator*  getDepthMapGenerator  () { return  &m_cDepthMapGenerator;   }
+#endif
+#if H3D_IVRP
+  TComResidualGenerator*  getResidualGenerator  () { return  &m_cResidualGenerator;   }
+#endif
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // encoder function
+  // -------------------------------------------------------------------------------------------------------------------
+
+  /// encode several number of pictures until end-of-sequence
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Int gopId );
+};
+
+//! \}
+
+#endif // __TENCTOP__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 341)
@@ -0,0 +1,442 @@
+/* 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-2012, 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     WeightedPredAnalysis.cpp
+    \brief    encoder class
+*/
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "WeightPredAnalysis.h"
+
+#define ABS(a)    ((a) < 0 ? - (a) : (a))
+#define DTHRESH (0.99)
+
+WeightPredAnalysis::WeightPredAnalysis()
+{
+  m_weighted_pred_flag = 0;
+  m_weighted_bipred_idc = 0;
+
+  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]);
+        pwp->bPresentFlag      = false;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->iWeight           = 1;
+        pwp->iOffset           = 0;
+      }
+    }
+  }
+}
+
+/** calculate AC and DC values for current original image
+ * \param TComSlice *slice
+ * \returns Void
+ */
+Bool  WeightPredAnalysis::xCalcACDCParamSlice(TComSlice *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;
+
+  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, Int weighted_bipred_idc)
+{
+  m_weighted_pred_flag = weighted_pred_flag;
+  m_weighted_bipred_idc = weighted_bipred_idc;
+}
+
+/** 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()->setWPBiPredIdc(m_weighted_bipred_idc);
+}
+
+/** check weighted pred or non-weighted pred
+ * \param TComSlice *slice
+ * \returns Void
+ */
+Void  WeightPredAnalysis::xCheckWPEnable(TComSlice *slice)
+{
+  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]);
+        iPresentCnt += (Int)pwp->bPresentFlag;
+      }
+    }
+  }
+
+  if(iPresentCnt==0)
+  {
+    slice->getPPS()->setUseWP(false);
+    slice->getPPS()->setWPBiPredIdc(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]);
+          pwp->bPresentFlag      = false;
+          pwp->uiLog2WeightDenom = 0;
+          pwp->iWeight           = 1;
+          pwp->iOffset           = 0;
+        }
+      }
+    }
+    slice->setWpScaling( m_wp );
+  }
+}
+
+/** estimate wp tables for explicit wp
+ * \param TComSlice *slice
+ * \returns Bool
+ */
+Bool  WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *slice)
+{
+  Int iDenom  = 6;
+  Int iRealDenom = iDenom + (g_uiBitDepth+g_uiBitIncrement-8);
+  Int iRealOffset = ((Int)1<<(iRealDenom-1));
+
+  if(slice->getNumRefIdx(REF_PIC_LIST_0)>3)
+  {
+    iDenom  = 7;
+    iRealDenom = iDenom + (g_uiBitDepth+g_uiBitIncrement-8);
+    iRealOffset = ((Int)1<<(iRealDenom-1));
+  }
+  
+  Int iNumPredDir = slice->isInterP() ? 1 : 2;
+  for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+  {
+    RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for ( Int iRefIdxTemp = 0; iRefIdxTemp < slice->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
+    {
+      wpACDCParam *CurrWeightACDCParam, *RefWeightACDCParam;
+      slice->getWpAcDcParam(CurrWeightACDCParam);
+      slice->getRefPic(eRefPicList, iRefIdxTemp)->getSlice(0)->getWpAcDcParam(RefWeightACDCParam);
+
+      for ( Int iComp = 0; iComp < 3; iComp++ )
+      {
+        // current frame
+        Int64 iCurrDC = CurrWeightACDCParam[iComp].iDC;
+        Int64 iCurrAC = CurrWeightACDCParam[iComp].iAC;
+        // reference frame
+        Int64 iRefDC = RefWeightACDCParam[iComp].iDC;
+        Int64 iRefAC = RefWeightACDCParam[iComp].iAC;
+
+        // calculating iWeight and iOffset params
+        Double dWeight = (iRefAC==0) ? (Double)1.0 : ( (Double)(iCurrAC) / (Double)iRefAC);
+        Int iWeight = (Int)( 0.5 + dWeight * (Double)(1<<iDenom) );
+        Int iOffset = (Int)( ((iCurrDC<<iDenom) - ((Int64)iWeight * iRefDC) + (Int64)iRealOffset) >> iRealDenom );
+
+        m_wp[iRefList][iRefIdxTemp][iComp].bPresentFlag = true;
+        m_wp[iRefList][iRefIdxTemp][iComp].iWeight = (Int)iWeight;
+        m_wp[iRefList][iRefIdxTemp][iComp].iOffset = (Int)iOffset;
+        m_wp[iRefList][iRefIdxTemp][iComp].uiLog2WeightDenom = (Int)iDenom;
+      }
+    }
+  }
+
+  // selecting whether WP is used, or not
+  xSelectWP(slice, m_wp, iDenom);
+  
+  slice->setWpScaling( m_wp );
+
+  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;
+
+  for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+  {
+    Int64 iSADWP = 0, iSADnoWP = 0;
+    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(pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][0].iWeight, weightPredTable[iRefList][iRefIdxTemp][0].iOffset);
+      iSADnoWP = this->xCalcSADvalueWP(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(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][1].iWeight, weightPredTable[iRefList][iRefIdxTemp][1].iOffset);
+      iSADnoWP += this->xCalcSADvalueWP(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(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][2].iWeight, weightPredTable[iRefList][iRefIdxTemp][2].iOffset);
+      iSADnoWP += this->xCalcSADvalueWP(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
+
+      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(Pel *pOrgPel, Pel *pRefPel, Int iWidth, Int iHeight, Int iOrgStride, Int iRefStride, Int iDenom, Int iWeight, Int iOffset)
+{
+  Int x, y;
+  Int64 iSAD = 0;
+  Int64 iSize   = iWidth*iHeight;
+  Int64 iRealDenom = iDenom + (g_uiBitDepth+g_uiBitIncrement-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) ) ) );
+    }
+    pOrgPel += iOrgStride;
+    pRefPel += iRefStride;
+  }
+  return (iSAD/iSize);
+}
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 341)
@@ -0,0 +1,76 @@
+/* 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-2012, 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     WeightedPredAnalysis.h
+    \brief    encoder class
+*/
+#ifndef __WEIGHTPREDANALYSIS__
+#define __WEIGHTPREDANALYSIS__
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "TEncCavlc.h"
+
+class  WeightPredAnalysis
+{
+  Bool m_weighted_pred_flag;
+  Int  m_weighted_bipred_idc;
+  wpScalingParam  m_wp[2][MAX_NUM_REF][3];
+
+  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);
+
+  Int64   xCalcDCValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride);
+  Int64   xCalcACValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride, Int64 iDC);
+  Int64   xCalcSADvalueWP(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);
+
+public:
+
+  WeightPredAnalysis();
+
+  // WP analysis :
+  Bool  xCalcACDCParamSlice(TComSlice *slice);
+  Bool  xEstimateWPParamSlice(TComSlice *slice);
+
+  Void  xStoreWPparam(Bool weighted_pred_flag, Int weighted_bipred_idc);
+  Void  xRestoreWPparam(TComSlice *slice);
+  Void  xCheckWPEnable(TComSlice *slice);
+};
+
+#endif // __WEIGHTPREDANALYSIS__
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibExtractor/TExtrTop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 341)
@@ -0,0 +1,111 @@
+/* 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-2011, 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 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     TExtrTop.cpp
+    \brief    extractor class
+*/
+
+#include "TExtrTop.h"
+
+TExtrTop::TExtrTop()
+{
+}
+
+TExtrTop::~TExtrTop()
+{
+}
+
+Void TExtrTop::init()
+{
+  m_cEntropyDecoder.init(&m_cPrediction);
+
+  m_acSPSBuffer.clear();
+}
+
+Bool TExtrTop::extract( InputNALUnit& nalu, std::set<UInt>& rsuiExtractLayerIds )
+{
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  //extraction now has to be done using layer_id
+  UInt uiLayerId = nalu.m_layerId;
+#else
+  UInt uiLayerId = xGetLayerId( nalu.m_viewId, nalu.m_isDepth );
+#endif
+  // Initialize entropy decoder
+  m_cEntropyDecoder.setEntropyDecoder( &m_cCavlcDecoder );
+  m_cEntropyDecoder.setBitstream     ( nalu.m_Bitstream );
+  
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  if ( nalu.m_nalUnitType == NAL_UNIT_VPS )
+  {
+    // a hack for now assuming there's only one VPS in the bitstream
+    m_cEntropyDecoder.decodeVPS( &m_cVPS );
+      
+  }
+#endif
+
+  if ( nalu.m_nalUnitType == NAL_UNIT_SPS )
+  {
+     TComSPS cSPS;
+     TComRPSList cRPS;
+     cSPS.setRPSList( &cRPS );
+#if HHI_MPI || H3D_QTL
+#if VIDYO_VPS_INTEGRATION
+     m_cEntropyDecoder.decodeSPS( &cSPS, m_cVPS.getDepthFlag(uiLayerId) );
+#else
+     m_cEntropyDecoder.decodeSPS( &cSPS, nalu.m_isDepth );
+#endif
+#else
+     m_cEntropyDecoder.decodeSPS( &cSPS );
+#endif
+
+     m_acSPSBuffer.push_back( cSPS );
+  }
+
+  return ( rsuiExtractLayerIds.find( uiLayerId ) != rsuiExtractLayerIds.end() );
+}
+
+
+Void TExtrTop::dumpSpsInfo( std::ostream& rcSpsInfoHandle )
+{
+  rcSpsInfoHandle << "NumSPS = " << m_acSPSBuffer.size() << std::endl;
+
+  for( std::list<TComSPS>::iterator iterSPS = m_acSPSBuffer.begin(); iterSPS != m_acSPSBuffer.end(); iterSPS++ )
+  {
+     rcSpsInfoHandle << std::endl;
+     rcSpsInfoHandle << "layer_id = "              << xGetLayerId( iterSPS->getViewId(), iterSPS->isDepth() ) << std::endl;
+     rcSpsInfoHandle << "seq_parameter_set_id = "  << iterSPS->getSPSId() << std::endl;
+     rcSpsInfoHandle << "view_id = "               << iterSPS->getViewId() << std::endl;
+     rcSpsInfoHandle << "view_order_idx = "        << iterSPS->getViewOrderIdx() << std::endl;
+     rcSpsInfoHandle << "is_depth = "              << iterSPS->isDepth() << std::endl;
+  }
+}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibExtractor/TExtrTop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibExtractor/TExtrTop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibExtractor/TExtrTop.h	(revision 341)
@@ -0,0 +1,83 @@
+/* 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-2011, 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 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     TDecTop.h
+    \brief    decoder class (header)
+*/
+
+#ifndef __TEXTRTOP__
+#define __TEXTRTOP__
+
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPrediction.h"
+#include "../TLibDecoder/TDecCAVLC.h"
+#include "../TLibDecoder/NALread.h"
+#include <list>
+#include <set>
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// decoder class
+class TExtrTop
+{
+private:
+#if VIDYO_VPS_INTEGRATION|QC_MVHEVC_B0046
+  TComVPS                 m_cVPS;
+#endif
+   std::list<TComSPS>      m_acSPSBuffer;
+
+  // functional classes
+  TComPrediction           m_cPrediction;
+  TDecEntropy              m_cEntropyDecoder;
+  TDecCavlc                m_cCavlcDecoder;
+
+public:
+  TExtrTop();
+  virtual ~TExtrTop();
+  
+  Void     init();
+
+  Bool     extract( InputNALUnit& nalu, std::set<UInt>& rsuiExtractLayerIds );
+  Void     dumpSpsInfo( std::ostream& rcSpsInfoHandle );
+  
+  TComSPS *getFirstSPS() { return m_acSPSBuffer.empty() ? 0 : &(m_acSPSBuffer.front()); }
+
+protected:
+   UInt     xGetLayerId( UInt uiViewId, Bool bIsDepth ) { return ( ( uiViewId << 1 ) + ( bIsDepth ? 1 : 0 ) ); }
+};// END CLASS DEFINITION TExtrTop
+
+
+#endif // __TEXTRTOP__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenFilter.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 341)
@@ -0,0 +1,1434 @@
+/* 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-2011, 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 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 "TRenImage.h"
+#include "TRenFilter.h"
+#include "TRenInterpFilter.h"
+
+
+///// COMMON /////
+Void TRenFilter::setSubPelShiftLUT( Int iLutPrec, Int** piSubPelShiftLUT, Int iShift )
+{
+  //ToDo: use same rounding for left and right
+  AOT( iLutPrec < 0 || iLutPrec > 2 );
+  Int iStep = 1 << iLutPrec;
+  for (Int iDelta = 0; iDelta < (iStep << 1)+1; iDelta++ )
+  {
+    for (Int iCurDelta = 0; iCurDelta < (iStep << 1)+1; iCurDelta++ )
+    {
+      if (iCurDelta <= iDelta)
+      {
+        piSubPelShiftLUT[iDelta][iCurDelta] =  (iDelta != 0) ?( ( iStep * iCurDelta + ( iDelta >> 1) )/ iDelta) + iShift * iStep :  iShift * iStep;
+      }
+      else
+      {
+        piSubPelShiftLUT[iDelta][iCurDelta] = 0xdeaddead;
+      }
+    }
+  }
+}
+
+Void TRenFilter::setupZLUT( Bool bBlendUseDistWeight, Int iBlendZThresPerc, Int iRelDistToLeft, Int** ppiBaseShiftLUTLeft, Int** ppiBaseShiftLUTRight, Int& riBlendZThres, Int& riBlendDistWeight, Int* piInvZLUTLeft, Int* piInvZLUTRight )
+{
+  AOT( iRelDistToLeft == -1 );
+  riBlendDistWeight = bBlendUseDistWeight ? iRelDistToLeft :  1 << (REN_VDWEIGHT_PREC - 1);
+
+  for (UInt uiDepthValue = 0; uiDepthValue <= 256; uiDepthValue++)
+  {
+    //GT: retrieve depth approx from shift
+    piInvZLUTLeft [uiDepthValue] = abs( ppiBaseShiftLUTLeft [0][uiDepthValue] );
+    piInvZLUTRight[uiDepthValue] = abs( ppiBaseShiftLUTRight[0][uiDepthValue] );
+  }
+  // Set Threshold
+  riBlendZThres  = ( Max( abs(piInvZLUTLeft[0]- piInvZLUTLeft[255]), abs(piInvZLUTRight[0]- piInvZLUTRight[255]) ) * iBlendZThresPerc + 50)  / 100;
+}
+
+Void TRenFilter::filledToUsedPelMap( PelImage* pcFilledImage, PelImage* pcUsedPelsImage, Int iUsedPelMapMarExt )
+{
+  // Convert to binary map
+  Int iWidth  = pcFilledImage      ->getPlane(0)->getWidth ();
+  Int iHeight = pcFilledImage      ->getPlane(0)->getHeight();
+
+  AOT( iWidth  != pcUsedPelsImage  ->getPlane(0)->getWidth () );
+  AOT( iHeight != pcUsedPelsImage  ->getPlane(0)->getHeight() );
+  AOF( pcUsedPelsImage->is420() );
+
+  Int iSrcStride  = pcFilledImage  ->getPlane(0)->getStride();
+  Int iDstStrideY = pcUsedPelsImage->getPlane(0)->getStride();
+  Int iDstStrideU = pcUsedPelsImage->getPlane(1)->getStride();
+  Int iDstStrideV = pcUsedPelsImage->getPlane(2)->getStride();
+
+  Pel* pcSrcData  = pcFilledImage  ->getPlane(0)->getPlaneData();
+  Pel* pcDstDataY = pcUsedPelsImage->getPlane(0)->getPlaneData();
+  Pel* pcDstDataU = pcUsedPelsImage->getPlane(1)->getPlaneData();
+  Pel* pcDstDataV = pcUsedPelsImage->getPlane(2)->getPlaneData(); // Only used as buffer
+
+  for (Int iPosY = 0; iPosY < iHeight; iPosY++ )
+  {
+    for (Int iPosX = 0; iPosX < iWidth; iPosX++ )
+    {
+      pcDstDataY[iPosX] = ( pcSrcData[iPosX] != REN_IS_FILLED ) ? REN_USED_PEL : REN_UNUSED_PEL;
+
+      if ((iPosX & 1) && (iPosY & 1))
+      {
+        pcDstDataU[iPosX >> 1] = (   ( pcSrcData[iPosX                 ] != REN_IS_FILLED )
+          || ( pcSrcData[iPosX - 1             ] != REN_IS_FILLED )
+          || ( pcSrcData[iPosX     - iSrcStride] != REN_IS_FILLED )
+          || ( pcSrcData[iPosX - 1 - iSrcStride] != REN_IS_FILLED )
+          ) ? REN_USED_PEL : REN_UNUSED_PEL;
+      }
+    }
+
+    if ( iPosY & 1 )
+    {
+      pcDstDataU += iDstStrideU;
+    }
+
+    pcDstDataY += iDstStrideY;
+    pcSrcData  += iSrcStride;
+  }
+
+  //// Dilatation for Interpolation Filters ////
+  //GT: should better be defined somewhere else ...
+  const Int iLumaIntFiltHalfSize   = 4;
+  const Int iChromaIntFiltHalfSize = 2;
+
+  Int iDilateSizeLuma   = iLumaIntFiltHalfSize   +   iUsedPelMapMarExt      ;
+  Int iDilateSizeChroma = iChromaIntFiltHalfSize + ( iUsedPelMapMarExt >> 1);
+
+  pcDstDataY = pcUsedPelsImage->getPlane(0)->getPlaneData();
+  pcDstDataU = pcUsedPelsImage->getPlane(1)->getPlaneData();
+  pcDstDataV = pcUsedPelsImage->getPlane(2)->getPlaneData();
+
+  // Dilate Luma horizontally
+  xDilate( pcDstDataY, iDstStrideY, iWidth, iHeight, pcDstDataY, iDstStrideY, iDilateSizeLuma, false, true  );
+  xDilate( pcDstDataY, iDstStrideY, iWidth, iHeight, pcDstDataY, iDstStrideY, iDilateSizeLuma, false, false );
+
+  // Dilate Chorma vertically and horizontally (for UV-up)
+  xDilate( pcDstDataU, iDstStrideU, iWidth>>1, iHeight>>1, pcDstDataU, iDstStrideU, iDilateSizeChroma, false, true  );
+  xDilate( pcDstDataU, iDstStrideU, iWidth>>1, iHeight>>1, pcDstDataU, iDstStrideU, iDilateSizeChroma, false, false );
+
+  xDilate( pcDstDataU, iDstStrideU, iWidth>>1, iHeight>>1, pcDstDataU, iDstStrideU, iChromaIntFiltHalfSize, true, true  );
+  xDilate( pcDstDataU, iDstStrideU, iWidth>>1, iHeight>>1, pcDstDataU, iDstStrideU, iChromaIntFiltHalfSize, true, false );
+
+  for (Int iPosY = 0; iPosY < (iHeight >> 1); iPosY++ )
+  {
+    for (Int iPosX = 0; iPosX < (iWidth >> 1); iPosX++ )
+    {
+      pcDstDataV[iPosX] = pcDstDataU[iPosX];
+    }
+
+    pcDstDataU += iDstStrideU;
+    pcDstDataV += iDstStrideV;
+  }
+}
+
+/////////// Copy /////////////
+Void TRenFilter::copy(Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  xDistributeArray(pcInputPlaneData, iInputStride, 1, 1, iWidth, iHeight ,pcOutputPlaneData, iOutputStride, 1 , 1 );
+
+}
+
+/////////// Horizontal Mirror ///////////
+template <typename T>
+Void TRenFilter::mirrorHor( TRenImage<T> *pcImage )
+{
+  for (UInt uCurPlane = 0 ; uCurPlane < pcImage->getNumberOfPlanes(); uCurPlane++ )
+  {
+    mirrorHor( pcImage->getPlane(uCurPlane) );
+  }
+}
+
+template <typename T>
+Void TRenFilter::mirrorHor( TRenImagePlane<T> *pcImagePlane )
+{
+  T* pcPlaneData = pcImagePlane->getPlaneDataOrg();
+  T cTemp;
+  UInt uiStride = pcImagePlane->getStride();
+  UInt uiHeight = pcImagePlane->getHeightOrg();
+  UInt uiWidth  = pcImagePlane->getWidthOrg();
+
+  for (UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+  {
+    for (UInt uiPosX = 0; uiPosX < ( (uiWidth+1) >> 1); uiPosX++ )
+    {
+      cTemp = pcPlaneData[uiPosX];
+      pcPlaneData[uiPosX] = pcPlaneData[uiWidth - uiPosX-1];
+      pcPlaneData[uiWidth-uiPosX-1] = cTemp;
+    }
+    pcPlaneData += uiStride;
+  }
+}
+
+/////////// Comparison ///////////
+Int64 TRenFilter::SSE   (PelImagePlane* pcInputPlane1, PelImagePlane* pcInputPlane2   )
+{
+  UInt uiWidth     = pcInputPlane1->getWidth();
+  UInt uiHeight    = pcInputPlane1->getHeight();
+
+  UInt uiStride1   = pcInputPlane1->getStride();
+  UInt uiStride2   = pcInputPlane2->getStride();
+
+  Pel* pucImData1  = pcInputPlane1->getPlaneData();
+  Pel* pucImData2  = pcInputPlane2->getPlaneData();
+
+  return SSE( pucImData1, (Int) uiStride1, (Int) uiWidth, (Int) uiHeight, pucImData2, (Int) uiStride2 );
+}
+
+Int64 TRenFilter::SSE( Pel* piSrc1, Int iSrcStride1, Int iWidth, Int iHeight,  Pel* piSrc2, Int iSrcStride2 )
+{
+  Int64 iSSE = 0;
+
+  Int iShift = g_uiBitIncrement << 1;
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    for(Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      Int iDiff = ( piSrc1[iPosX] - piSrc2[iPosX] );
+      iSSE += (( iDiff * iDiff ) >> iShift);
+    }
+    piSrc1 += iSrcStride1;
+    piSrc2 += iSrcStride2;
+  }
+  return iSSE;
+}
+
+template <typename T>
+Bool TRenFilter::compare( TRenImage<T> *pInputImage1, TRenImage<T> *pInputImage2 )
+{
+  Bool bIsEqual = true;
+  for (UInt uiCurPlane = 0 ; uiCurPlane < pInputImage1->getNumberOfPlanes(); uiCurPlane++ )
+  {
+    bIsEqual = bIsEqual && compare(pInputImage1->getPlane(uiCurPlane), pInputImage2->getPlane(uiCurPlane));
+  }
+  return bIsEqual;
+}
+
+template <typename T>
+Bool TRenFilter::compare   (TRenImagePlane<T>* pcInputPlane1  , TRenImagePlane<T>* pcInputPlane2   )
+{
+  UInt uiWidth  = pcInputPlane1->getWidth();
+  UInt uiHeight = pcInputPlane1->getHeight();
+
+  UInt uiStride1 = pcInputPlane1->getStride();
+  UInt uiStride2 = pcInputPlane2->getStride();
+
+  T* pucImData1  = pcInputPlane1->getPlaneData();
+  T* pucImData2  = pcInputPlane2->getPlaneData();
+
+  Bool bEqual = true;
+  for(UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+  {
+
+    for(UInt uiPosX = 0; uiPosX < uiWidth; uiPosX++)
+    {
+      bEqual = bEqual && ( pucImData1[uiPosX] == pucImData2[uiPosX]);
+    }
+    pucImData1 += uiStride1;
+    pucImData2 += uiStride2;
+  }
+  return bEqual;
+}
+
+/////////// Sampling ///////////
+
+inline Void TRenFilter::sampleUp2Tap13(PelImage* pcInputImage, PelImage* pcOutputImage)
+{// UpSampling from JSVM Software (DownConvertStatic) ???
+  UInt uiNumPlanes = pcInputImage->getNumberOfPlanes();
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumPlanes; uiCurPlane++)
+  {
+    PelImagePlane* pcInputPlane  = pcInputImage ->getPlane(uiCurPlane);
+    PelImagePlane* pcOutputPlane = pcOutputImage->getPlane(uiCurPlane);
+
+    Int iWidth  = pcInputPlane->getWidth();
+    Int iHeight = pcInputPlane->getHeight();
+
+    Int iInputStride  = pcInputPlane->getStride();
+    Int iOutputStride = pcOutputPlane->getStride();
+
+    assert( iWidth  == 2 * pcOutputPlane->getWidth ());
+    assert( iHeight == 2 * pcOutputPlane->getHeight());
+
+    Int iOffset;
+
+    Pel *pcInputPlaneData   = pcInputPlane->getPlaneData();
+    Int *piDataVerUp        = new Int[iWidth * iHeight * 2];
+    Pel *pcOutputPlaneData  = pcOutputPlane->getPlaneData();
+
+    // Up sampling filter.
+    Int aiFilterCoeff[16] = { 0, 0, 1, 0, -5, 0, 20, 32, 20, 0, -5,  0, 1, 0, 0, 32 };
+
+    // Normalization factors for filtered values.
+    Int iDivH = 1, iDivV = 1, iAddH = 0, iAddV = 0;
+
+    // Factors after horizontal and vertical filtering.
+    iDivH = (aiFilterCoeff[15]*aiFilterCoeff[15]); iAddH = iDivH / 2;
+
+    Int* piDst = new Int[2*iWidth];
+    //1) VERTICAL UPSAMPLING.
+
+    // Process all cols.
+    for(Int i=0; i<iWidth; i++ )
+    {
+      // Set source (col) poInter.
+      Pel* pcSrc = &pcInputPlaneData[i];
+
+      // Process all rows.
+      for( Int j=0; j<iHeight; j++ )
+      {
+        // Adjust indices of border samples.
+        Int i00 = ((j <   3) ? 0   : j-3) * iInputStride;
+        Int i01 = ((j <   2) ? 0   : j-2) * iInputStride;
+        Int i02 = ((j <   1) ? 0   : j-1) * iInputStride;
+        Int i03 = ((j < iHeight  ) ? j   : j-1) * iInputStride;
+        Int i04 = ((j < iHeight-1) ? j+1 : j-1) * iInputStride;
+        Int i05 = ((j < iHeight-2) ? j+2 : j-1) * iInputStride;
+        Int i06 = ((j < iHeight-3) ? j+3 : j-1) * iInputStride;
+        Int i07 = ((j < iHeight-4) ? j+4 : j-1) * iInputStride;
+
+        // Calculate filtered (even) sample.
+        piDst[2*j+0] = aiFilterCoeff[13] * pcSrc[i00]
+        + aiFilterCoeff[11] * pcSrc[i01]
+        + aiFilterCoeff[ 9] * pcSrc[i02]
+        + aiFilterCoeff[ 7] * pcSrc[i03]
+        + aiFilterCoeff[ 5] * pcSrc[i04]
+        + aiFilterCoeff[ 3] * pcSrc[i05]
+        + aiFilterCoeff[ 1] * pcSrc[i06];
+
+        // Calculate filtered (odd) sample.
+        piDst[2*j+1] = aiFilterCoeff[14] * pcSrc[i00]
+        + aiFilterCoeff[12] * pcSrc[i01]
+        + aiFilterCoeff[10] * pcSrc[i02]
+        + aiFilterCoeff[ 8] * pcSrc[i03]
+        + aiFilterCoeff[ 6] * pcSrc[i04]
+        + aiFilterCoeff[ 4] * pcSrc[i05]
+        + aiFilterCoeff[ 2] * pcSrc[i06]
+        + aiFilterCoeff[ 0] * pcSrc[i07];
+      }
+
+      // Process all filtered samples.
+      for(Int j=0; j<(2*iHeight); j++ )
+      {
+        // Scale and copy to image buffer.
+        piDataVerUp[iWidth*j+i] = (piDst[j] + iAddV) / iDivV;
+      }
+    }
+
+    // Update h
+    iHeight *= 2;
+
+    // 2) HORIZONTAL UPSAMPLING.
+
+    // Process all rows.
+    for( Int j=0; j<iHeight; j++ )
+    {
+      // Set source (row) poInter.
+      Int* piSrc = &piDataVerUp[iWidth*j];
+
+      // Process all cols.
+      for( Int i=0; i<iWidth; i++ )
+      {
+        // Adjust indices of border samples.
+        Int i00 = (i <   3) ? 0   : i-3;
+        Int i01 = (i <   2) ? 0   : i-2;
+        Int i02 = (i <   1) ? 0   : i-1;
+        Int i03 = (i < iWidth  ) ? i   : iWidth-1;
+        Int i04 = (i < iWidth-1) ? i+1 : iWidth-1;
+        Int i05 = (i < iWidth-2) ? i+2 : iWidth-1;
+        Int i06 = (i < iWidth-3) ? i+3 : iWidth-1;
+        Int i07 = (i < iWidth-4) ? i+4 : iWidth-1;
+
+        // Calculate filtered (even) sample.
+        piDst[2*i+0] =   aiFilterCoeff[13] * piSrc[i00]
+        + aiFilterCoeff[11] * piSrc[i01]
+        + aiFilterCoeff[ 9] * piSrc[i02]
+        + aiFilterCoeff[ 7] * piSrc[i03]
+        + aiFilterCoeff[ 5] * piSrc[i04]
+        + aiFilterCoeff[ 3] * piSrc[i05]
+        + aiFilterCoeff[ 1] * piSrc[i06];
+
+        // Calculate filtered (odd) sample.
+        piDst[2*i+1] = aiFilterCoeff[14] * piSrc[i00]
+        + aiFilterCoeff[12] * piSrc[i01]
+        + aiFilterCoeff[10] * piSrc[i02]
+        + aiFilterCoeff[ 8] * piSrc[i03]
+        + aiFilterCoeff[ 6] * piSrc[i04]
+        + aiFilterCoeff[ 4] * piSrc[i05]
+        + aiFilterCoeff[ 2] * piSrc[i06]
+        + aiFilterCoeff[ 0] * piSrc[i07];
+      }
+
+      iOffset = 2* iOutputStride * j;
+      // Process all filtered samples.
+      for(Int i=0; i<iWidth*2; i++ )
+      {
+        // Scale and copy to image buffer.
+        pcOutputPlaneData[iOffset+i] = Max(Min((Pel) ((piDst[i] + iAddH) / iDivH), g_uiBASE_MAX ),0);
+      }
+    }
+
+    delete [] piDataVerUp;
+    delete [] piDst;
+
+  }
+}
+
+
+Void TRenFilter::sampleDown2Tap13(PelImage* pcInputImage, PelImage* pcOutputImage)
+{ // DownSampling from JSVM Software (DownConvertStatic) ??
+
+  UInt uiNumPlanes = pcInputImage->getNumberOfPlanes();
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumPlanes; uiCurPlane++)
+  {
+    sampleDown2Tap13( pcInputImage ->getPlane(uiCurPlane),  pcOutputImage->getPlane(uiCurPlane) );
+  }
+};
+
+Void TRenFilter::sampleDown2Tap13( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{ // DownSampling from JSVM Software (DownConvertStatic) ??
+  Int iOffset, iPosX, iPosY, k;
+  Int* piDataHorDown = new Int[(Int)(iWidth * iHeight / 2)];
+
+  // Downsampling filter.
+  Int aiFilterCoeff[16] = { 0, 2, 0, -4, -3, 5, 19, 26, 19, 5, -3, -4, 0, 2, 0, 64 };
+
+  // Normalization factors for filtered values.
+  Int iDivH = 1, iDivV = 1, iAddH = 0, iAddV = 0;
+
+  iDivV = (aiFilterCoeff[15]*aiFilterCoeff[15]); iAddV = iDivV / 2;
+
+  // Allocate and init single row of filtered samples.
+  Int* piDst = new Int[iWidth];
+
+  // 1) HORIZONTAL DOWNSAMPLING.
+
+  // Process all rows.
+  for( iPosY=0; iPosY<iHeight; iPosY++ )
+  {
+    // Set source (row) poInter.
+    Pel* pcSrc = &pcInputPlaneData[iInputStride*iPosY];
+
+    // Process all cols.
+    for( iPosX=0, k=0; iPosX<(iWidth/2); iPosX++, k+=2 )
+    {
+      // Adjust indices of border samples.
+      Int i00 = (k <       7) ? 0   : k    -7;
+      Int i01 = (k <       6) ? 0   : k    -6;
+      Int i02 = (k <       5) ? 0   : k    -5;
+      Int i03 = (k <       4) ? 0   : k    -4;
+      Int i04 = (k <       3) ? 0   : k    -3;
+      Int i05 = (k <       2) ? 0   : k    -2;
+      Int i06 = (k <       1) ? 0   : k    -1;
+      Int i07 = (k < iWidth  ) ? k   : iWidth-1;
+      Int i08 = (k < iWidth-1) ? k+1 : iWidth-1;
+      Int i09 = (k < iWidth-2) ? k+2 : iWidth-1;
+      Int i10 = (k < iWidth-3) ? k+3 : iWidth-1;
+      Int i11 = (k < iWidth-4) ? k+4 : iWidth-1;
+      Int i12 = (k < iWidth-5) ? k+5 : iWidth-1;
+      Int i13 = (k < iWidth-6) ? k+6 : iWidth-1;
+      Int i14 = (k < iWidth-7) ? k+7 : iWidth-1;
+
+      // Calculate filtered sample.
+      piDst[iPosX] =     aiFilterCoeff[ 0] * pcSrc[i00]
+      + aiFilterCoeff[ 1] * pcSrc[i01]
+      + aiFilterCoeff[ 2] * pcSrc[i02]
+      + aiFilterCoeff[ 3] * pcSrc[i03]
+      + aiFilterCoeff[ 4] * pcSrc[i04]
+      + aiFilterCoeff[ 5] * pcSrc[i05]
+      + aiFilterCoeff[ 6] * pcSrc[i06]
+      + aiFilterCoeff[ 7] * pcSrc[i07]
+      + aiFilterCoeff[ 8] * pcSrc[i08]
+      + aiFilterCoeff[ 9] * pcSrc[i09]
+      + aiFilterCoeff[10] * pcSrc[i10]
+      + aiFilterCoeff[11] * pcSrc[i11]
+      + aiFilterCoeff[12] * pcSrc[i12]
+      + aiFilterCoeff[13] * pcSrc[i13]
+      + aiFilterCoeff[14] * pcSrc[i14];
+    }
+
+    iOffset = iPosY * iWidth/2;
+    // Process all filtered samples.
+    for( iPosX=0; iPosX<(iWidth/2); iPosX++ )
+    {
+      // Scale and copy back to image buffer.
+      piDataHorDown[iOffset+iPosX] = (piDst[iPosX] + iAddH) / iDivH;
+    }
+  }
+
+  // Update w.
+  iWidth >>= 1;
+
+  // 2) VERTICAL DOWNSAMPLING.
+
+  // Process all cols.
+  for(  iPosX=0; iPosX<iWidth; iPosX++ )
+  {
+    // Set source (col) poInter.
+    Int* piSrc = &piDataHorDown[iPosX];
+
+    // Process all rows.
+    for(  iPosY=0, k=0; iPosY<(iHeight/2); iPosY++, k+=2 )
+    {
+      // Adjust indices of border samples.
+      Int i00 = ((k <       7) ? 0   : k    -7) * iWidth;
+      Int i01 = ((k <       6) ? 0   : k    -6) * iWidth;
+      Int i02 = ((k <       5) ? 0   : k    -5) * iWidth;
+      Int i03 = ((k <       4) ? 0   : k    -4) * iWidth;
+      Int i04 = ((k <       3) ? 0   : k    -3) * iWidth;
+      Int i05 = ((k <       2) ? 0   : k    -2) * iWidth;
+      Int i06 = ((k <       1) ? 0   : k    -1) * iWidth;
+      Int i07 = ((k < iHeight  ) ? k   : iHeight-1) * iWidth;
+      Int i08 = ((k < iHeight-1) ? k+1 : iHeight-1) * iWidth;
+      Int i09 = ((k < iHeight-2) ? k+2 : iHeight-1) * iWidth;
+      Int i10 = ((k < iHeight-3) ? k+3 : iHeight-1) * iWidth;
+      Int i11 = ((k < iHeight-4) ? k+4 : iHeight-1) * iWidth;
+      Int i12 = ((k < iHeight-5) ? k+5 : iHeight-1) * iWidth;
+      Int i13 = ((k < iHeight-6) ? k+6 : iHeight-1) * iWidth;
+      Int i14 = ((k < iHeight-7) ? k+7 : iHeight-1) * iWidth;
+
+      // Calculate filtered sample.
+      piDst[iPosY] =     aiFilterCoeff[ 0] * piSrc[i00]
+      + aiFilterCoeff[ 1] * piSrc[i01]
+      + aiFilterCoeff[ 2] * piSrc[i02]
+      + aiFilterCoeff[ 3] * piSrc[i03]
+      + aiFilterCoeff[ 4] * piSrc[i04]
+      + aiFilterCoeff[ 5] * piSrc[i05]
+      + aiFilterCoeff[ 6] * piSrc[i06]
+      + aiFilterCoeff[ 7] * piSrc[i07]
+      + aiFilterCoeff[ 8] * piSrc[i08]
+      + aiFilterCoeff[ 9] * piSrc[i09]
+      + aiFilterCoeff[10] * piSrc[i10]
+      + aiFilterCoeff[11] * piSrc[i11]
+      + aiFilterCoeff[12] * piSrc[i12]
+      + aiFilterCoeff[13] * piSrc[i13]
+      + aiFilterCoeff[14] * piSrc[i14];
+    }
+
+    // Process all filtered samples.
+    for( iPosY=0; iPosY<(iHeight/2); iPosY++ )
+    {
+      // Scale and copy back to image buffer.
+      pcOutputPlaneData[iOutputStride*iPosY+iPosX] = Max(Min( ( Pel) ( (piDst[iPosY] + iAddV) / iDivV), g_uiBASE_MAX ),0);
+    }
+  }
+
+  delete [] piDataHorDown;
+  delete [] piDst;
+}
+
+Void TRenFilter::sampleDown2Tap13(PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane)
+{ // DownSampling from JSVM Software (DownConvertStatic) ??
+  Int iWidth       = pcInputPlane->getWidth();
+  Int iHeight      = pcInputPlane->getHeight();
+
+  assert( pcOutputPlane->getWidth () == (iWidth  >> 1 ));
+  assert( pcOutputPlane->getHeight() == (iHeight >> 1 ));
+
+  Int iInputStride  = pcInputPlane->getStride();
+  Int iOutputStride = pcOutputPlane->getStride();
+
+  Pel* pcInputPlaneData = pcInputPlane ->getPlaneData();
+  Pel* pcOutputPlaneData = pcOutputPlane->getPlaneData();
+
+  sampleDown2Tap13( pcInputPlaneData, iInputStride, iWidth, iHeight, pcOutputPlaneData, iOutputStride );
+};
+
+Void TRenFilter::sampleVerDown2Tap13( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad)
+{ // DownSampling from JSVM Software (DownConvertStatic) ??
+  Int iWidth       = pcInputPlane->getWidth();
+  Int iHeight      = pcInputPlane->getHeight();
+
+  assert( pcOutputPlane->getWidth () ==  iWidth       );
+  assert( pcOutputPlane->getHeight() == (iHeight >> 1));
+  assert (pcInputPlane ->getPad()    >=            12 );
+  assert (pcOutputPlane->getPad()    >=         uiPad );
+
+  Int iInputStride  = pcInputPlane->getStride();
+  Int iOutputStride = pcOutputPlane->getStride();
+
+  Pel* pcInputPlaneData  = pcInputPlane ->getPlaneData();
+  Pel* pcOutputPlaneData = pcOutputPlane->getPlaneData();
+
+  Int iStr0  = 0;
+  Int iStr1  = iInputStride;
+  Int iStr2  = iStr1  + iInputStride;
+  Int iStr3  = iStr2  + iInputStride;
+  Int iStr4  = iStr3  + iInputStride;
+  Int iStr5  = iStr4  + iInputStride;
+  Int iStr6  = iStr5  + iInputStride;
+  Int iStr7  = iStr6  + iInputStride;
+  Int iStr8  = iStr7  + iInputStride;
+  Int iStr9  = iStr8  + iInputStride;
+  Int iStr10 = iStr9  + iInputStride;
+  Int iStr11 = iStr10 + iInputStride;
+  Int iStr12 = iStr11 + iInputStride;;
+
+
+  // Downsampling filter { 0, 2, 0, -4, -3, 5, 19, 26, 19, 5, -3, -4, 0, 2, 0, 64 };
+  for ( Int iYPos = 0; iYPos < (iHeight >> 1); iYPos++)
+  {
+    Pel* pcTmpIn = pcInputPlaneData - 12 * iInputStride - uiPad;
+    for ( Int iXPos = -uiPad; iXPos < iWidth + uiPad; iXPos++)
+    {
+      Int iTmp0, iTmp1, iTmp2, iTmp3, iTmp4, iTmp5;
+      iTmp0 = pcTmpIn[iStr0] + pcTmpIn[iStr12];
+      iTmp1 = pcTmpIn[iStr2] + pcTmpIn[iStr10];
+      iTmp2 = pcTmpIn[iStr3] + pcTmpIn[iStr9 ];
+      iTmp3 = pcTmpIn[iStr4] + pcTmpIn[iStr8 ];
+      iTmp4 = pcTmpIn[iStr5] + pcTmpIn[iStr7 ];
+      iTmp5 = pcTmpIn[iStr6];
+
+      Int iSum = iTmp4 + iTmp3 - iTmp2 + ((iTmp0 + iTmp4 + iTmp5 - iTmp2) << 1) + ( ( iTmp3 - iTmp1)  << 2) + (  iTmp5 << 3 ) + (( iTmp4 + iTmp5 ) << 4);
+      pcOutputPlaneData[ iXPos ] = (Pel) Clip((iSum + 32) >> 6);
+      pcTmpIn++;
+    }
+    pcOutputPlaneData += iOutputStride;
+    pcInputPlaneData  += (iInputStride << 1);
+  }
+};
+
+Void TRenFilter::sampleHorDown2Tap13( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad )
+{ // DownSampling from JSVM Software (DownConvertStatic) ??
+  Int iWidth       = pcInputPlane->getWidth();
+  Int iHeight      = pcInputPlane->getHeight();
+
+  assert( pcOutputPlane->getWidth () == (iWidth  >> 1));
+  assert( pcOutputPlane->getHeight() ==  iHeight      );
+  assert (pcInputPlane ->getPad()    >=            12 );
+  assert (pcOutputPlane->getPad()    >=         uiPad );
+
+  Int iInputStride  = pcInputPlane ->getStride();
+  Int iOutputStride = pcOutputPlane->getStride();
+
+  Pel* pcInputPlaneData  = pcInputPlane ->getPlaneData()- uiPad * iInputStride ;
+  Pel* pcOutputPlaneData = pcOutputPlane->getPlaneData()- uiPad * iOutputStride;
+
+  // Downsampling filter { 0, 2, 0, -4, -3, 5, 19, 26, 19, 5, -3, -4, 0, 2, 0, 64 };
+  for ( Int iYPos = 0; iYPos < iHeight + 2*uiPad; iYPos++)
+  {
+    Pel* pcTmpIn = pcInputPlaneData - 12;
+    for ( Int iXPos = 0; iXPos < ( iWidth >> 1); iXPos++)
+    {
+      Int iTmp0, iTmp1, iTmp2, iTmp3, iTmp4, iTmp5;
+      iTmp0 = pcTmpIn[0]+ pcTmpIn[12];
+      iTmp1 = pcTmpIn[2]+ pcTmpIn[10];
+      iTmp2 = pcTmpIn[3]+ pcTmpIn[9 ];
+      iTmp3 = pcTmpIn[4]+ pcTmpIn[8 ];
+      iTmp4 = pcTmpIn[5]+ pcTmpIn[7 ];
+      iTmp5 = pcTmpIn[6];
+
+      Int iSum = iTmp4 + iTmp3 - iTmp2 + ((iTmp0 + iTmp4 + iTmp5 - iTmp2) << 1) + ( ( iTmp3 - iTmp1)  << 2) + (  iTmp5 << 3 ) + (( iTmp4 + iTmp5 ) << 4);
+      pcOutputPlaneData[ iXPos ] = (Pel) Clip((iSum + 32) >> 6);
+      pcTmpIn += 2;
+    }
+    pcOutputPlaneData += iOutputStride;
+    pcInputPlaneData  += iInputStride ;
+  }
+};
+
+inline Pel TRenFilter::xMedian3(Pel* pcData)
+{
+  Bool bGT01 = pcData[0] >  pcData[1];
+  Bool bGT12 = pcData[1] >  pcData[2];
+  Bool bGT20 = pcData[2] >  pcData[0];
+
+  return ( (bGT01 && bGT20) || (!bGT01 && !bGT20) ) ?  pcData[0] : ( ( (bGT12 && bGT01) || (!bGT12 && !bGT01) ) ?  pcData[1] : pcData[2]) ;
+}
+
+
+Void TRenFilter::lineMedian3( PelImage* pcImage )
+{
+
+  PelImage* pcTemp = pcImage->create();
+
+  for (UInt uiCurPlane = 0; uiCurPlane < pcImage->getNumberOfPlanes(); uiCurPlane++)
+  {
+    PelImagePlane* pcImPlane   = pcImage->getPlane(uiCurPlane);
+    PelImagePlane* pcTempPlane = pcTemp ->getPlane(uiCurPlane);
+
+    UInt uiWidth  = pcImPlane->getWidth();
+    UInt uiHeight = pcImPlane->getHeight();
+
+    Pel* pcImData   = pcImPlane  ->getPlaneData();
+    Pel* pcTempData = pcTempPlane->getPlaneData();
+
+    UInt uiImDataStride   = pcImPlane  ->getStride();
+    UInt uiTempDataStride = pcTempPlane->getStride();
+
+    for(UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+    {
+      for(UInt uiPosX = 0; uiPosX < uiWidth; uiPosX++)
+      {
+        if ( (uiPosX >= 1) && (uiPosX < (uiWidth - 2)) )
+        {
+          pcTempData[uiPosX] = xMedian3(pcImData + uiPosX - 1);
+        }
+        else
+        {
+          pcTempData[uiPosX] = pcImData[uiPosX];
+        }
+      }
+      pcTempData += uiTempDataStride;
+      pcImData   += uiImDataStride;
+    }
+  }
+
+  pcImage->assign(pcTemp);
+  delete pcTemp;
+}
+
+
+Void TRenFilter::convRect( PelImage* pcImage, UInt uiSize )
+{
+  DoubleImage cKernel(uiSize, uiSize,1,0);
+  cKernel.getPlane(0)->assign( 1 / ( Double( uiSize )  * Double( uiSize) ));
+  conv(pcImage, &cKernel);
+}
+
+Void TRenFilter::binominal( PelImage* pcInputImage, PelImage* pcOutputImage, UInt uiSize )
+{
+  assert( pcInputImage->getNumberOfFullPlanes()   == pcOutputImage->getNumberOfFullPlanes  () );
+  assert( pcInputImage->getNumberOfQuaterPlanes() == pcOutputImage->getNumberOfQuaterPlanes() );
+
+  UInt uiPlane;
+  for (uiPlane = 0; uiPlane < pcInputImage->getNumberOfPlanes(); uiPlane ++)
+  {
+    binominal( pcInputImage->getPlane(uiPlane), pcOutputImage->getPlane(uiPlane), uiSize );
+  }
+
+  for (  ; uiPlane < pcInputImage->getNumberOfPlanes(); uiPlane ++)
+  {
+    binominal( pcInputImage->getPlane(uiPlane), pcOutputImage->getPlane(uiPlane), uiSize >> 1 );
+ }
+}
+
+Void TRenFilter::binominal( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, UInt uiSize )
+{
+  Int iWidth  = pcInputPlane ->getWidth ();
+  Int iHeight = pcInputPlane ->getHeight();
+
+  assert( pcOutputPlane->getWidth () == iWidth  );
+  assert( pcOutputPlane->getHeight() == iHeight );
+  assert( pcInputPlane ->getPad   () >= uiSize );
+  assert( pcOutputPlane->getPad   () >= uiSize );
+
+  if (uiSize == 0)
+  {
+    pcOutputPlane->assign( pcInputPlane );
+    return;
+  };
+
+  Int iInputStride  = pcInputPlane ->getStride();
+  Int iOutputStride = pcOutputPlane->getStride();
+  Int iTempStride   = iWidth + (uiSize << 1);
+
+
+  Pel* pcCurInputData  = pcInputPlane ->getPlaneData() - uiSize;
+  Pel* pcTempData      = new Pel[iTempStride * iHeight];
+  Pel* pcCurTempData   = pcTempData;
+
+  Pel (*fpFilter) ( Pel*, Int ) = NULL;
+
+  switch( uiSize )
+  {
+  case 1:
+    fpFilter = &TRenFilter::xFiltBinom3;
+    break;
+  case 2:
+    fpFilter = &TRenFilter::xFiltBinom5;
+    break;
+  case 3:
+    fpFilter = &TRenFilter::xFiltBinom7;
+    break;
+  case 4:
+    fpFilter = &TRenFilter::xFiltBinom9;
+    break;
+  default:
+      AOT(true);
+  }
+
+  for (Int iPosY = 0; iPosY < iHeight; iPosY++ )
+  {
+    for (Int iPosX = 0; iPosX < iWidth + (uiSize << 1); iPosX++)
+    {
+      pcCurTempData[iPosX] = (*fpFilter)(pcCurInputData + iPosX, iInputStride );
+    }
+    pcCurTempData   += iTempStride;
+    pcCurInputData  += iInputStride;
+  }
+
+  pcCurTempData   = pcTempData + uiSize;
+  Pel* pcCurOutputData = pcOutputPlane->getPlaneData();
+
+  for (Int iPosY = 0; iPosY < iHeight; iPosY++ )
+  {
+    for (Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      pcCurOutputData[iPosX] = (*fpFilter)(pcCurTempData + iPosX, 1);
+    }
+    pcCurTempData    += iTempStride;
+    pcCurOutputData  += iOutputStride;
+  }
+
+  delete[] pcTempData;
+}
+
+Pel TRenFilter::xFiltBinom3( Pel* pcInputData, Int iStride )
+{
+  Int iSum = pcInputData[-1 * iStride ] + pcInputData[ 0 ] +  (pcInputData[iStride ] << 1 );
+  return Clip( (iSum +  2) >>  2 );
+}
+
+Pel TRenFilter::xFiltBinom5( Pel* pcInputData, Int iStride )
+{
+  // { 1,4,6,4,1 }
+  Int iStride0  = 0;
+  Int iStrideM1 = iStride0  - iStride;
+  Int iStrideM2 = iStrideM1 - iStride;
+  Int iStrideP1 = iStride0  + iStride;
+  Int iStrideP2 = iStrideP1 + iStride;
+
+  Int iTmp0 = pcInputData[iStrideM2] + pcInputData[iStrideP2];
+  Int iTmp1 = pcInputData[iStrideM1] + pcInputData[iStrideP1];
+  Int iTmp2 = pcInputData[iStride0 ];
+
+  Int iSum = iTmp0 +  (iTmp2 << 1) + ((iTmp1 + iTmp2) << 2);
+  return Clip( (iSum +  8) >>  4 );
+}
+
+Pel TRenFilter::xFiltBinom7( Pel* pcInputData, Int iStride )
+{
+  // { 1,6,15,20,15,6,1 }
+  Int iStride0  = 0;
+  Int iStrideM1 = iStride0  - iStride;
+  Int iStrideM2 = iStrideM1 - iStride;
+  Int iStrideM3 = iStrideM1 - iStride;
+  Int iStrideP1 = iStride0  + iStride;
+  Int iStrideP2 = iStrideP1 + iStride;
+  Int iStrideP3 = iStrideP1 + iStride;
+
+  Int iTmp0 = pcInputData[iStrideM3] + pcInputData[iStrideP3];
+  Int iTmp1 = pcInputData[iStrideM2] + pcInputData[iStrideP2];
+  Int iTmp2 = pcInputData[iStrideM1] + pcInputData[iStrideP1];
+  Int iTmp3 = pcInputData[iStride0];
+
+  Int iSum = iTmp0 - iTmp2 + ( iTmp1  << 1) + ( (iTmp1 + iTmp3) << 2) + ((iTmp2 + iTmp3) << 4);
+
+  return Clip( (iSum +  32) >>  6 );
+}
+
+Pel TRenFilter::xFiltBinom9( Pel* pcInputData, Int iStride )
+{
+  // {  1     8    28    56    70    56    28     8     1 }
+  Int iStride0  = 0;
+  Int iStrideM1 = iStride0  - iStride;
+  Int iStrideM2 = iStrideM1 - iStride;
+  Int iStrideM3 = iStrideM1 - iStride;
+  Int iStrideM4 = iStrideM1 - iStride;
+  Int iStrideP1 = iStride0  + iStride;
+  Int iStrideP2 = iStrideP1 + iStride;
+  Int iStrideP3 = iStrideP1 + iStride;
+  Int iStrideP4 = iStrideP1 + iStride;
+
+  Int iTmp0 = pcInputData[iStrideM4] + pcInputData[iStrideP4];
+  Int iTmp1 = pcInputData[iStrideM3] + pcInputData[iStrideP3];
+  Int iTmp2 = pcInputData[iStrideM2] + pcInputData[iStrideP2];
+  Int iTmp3 = pcInputData[iStrideM1] + pcInputData[iStrideP1];
+  Int iTmp4 = pcInputData[iStride0];
+
+  Int iSum = iTmp0 + ((iTmp4 ) << 1) + ( ( iTmp4 - iTmp2 ) << 2) +  ( (iTmp1 - iTmp3) << 3 ) +  ((iTmp2 ) << 5) + ((iTmp3+ iTmp4 ) << 6);
+
+  return Clip( (iSum +  128) >>  8 );
+}
+
+
+Pel TRenFilter::interpCHSpline(Double dX, Double dS0, Double dS1, Int iQ0, Int iQ1, Int iQ2, Int iQ3)
+{
+  Double dSq = (dX - dS0) / (dS1 - dS0);
+
+  Double adP[4];
+  Double dSqP2 = dSq * dSq;
+  Double dSqP3 = dSqP2 * dSq;
+
+  adP[0] = 1 - 3 * dSqP2 + 2 * dSqP3;
+  adP[1] = dSq - 2 * dSqP2 + dSqP3;
+  adP[2] = 3 * dSqP2 - 2 * dSqP3;
+  adP[3] = -dSqP2 + dSqP3;
+
+  Double dQ  = adP[0] * iQ0 + adP[1] * iQ1 + adP[2] * iQ2 + adP[3] * iQ3 ;
+
+  Pel cQ = (Pel) ( dQ + 0.5);
+
+  cQ = ( cQ < 0   ? 0   : cQ );
+  cQ = ( cQ > 255 ? 255 : cQ );
+
+  return cQ;
+
+}
+
+Void TRenFilter::diffHorSym(PelImage* pcInputImage, IntImage* pcOutputImage)
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < pcInputImage->getNumberOfPlanes(); uiCurPlane++)
+  {
+    diffHorSym( pcInputImage->getPlane(uiCurPlane), pcOutputImage->getPlane(uiCurPlane));
+  };
+}
+
+Void TRenFilter::diffHorSym(PelImagePlane* pcInputPlane, IntImagePlane* pcOutputPlane)
+{
+  UInt uiInputStride = pcInputPlane ->getStride();
+  UInt uiOutputStride = pcOutputPlane->getStride();
+  UInt uiWidth        = pcInputPlane ->getWidth();
+  UInt uiHeight       = pcInputPlane ->getHeight();
+
+  Pel*   pcInputData   = pcInputPlane ->getPlaneData();
+  Int*   piOutputData  = pcOutputPlane->getPlaneData();
+
+  for (UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+  {
+    for (UInt uiPosX = 1; uiPosX < uiWidth-1; uiPosX++)
+    {
+      piOutputData[uiPosX] = ((Int) pcInputData[uiPosX+1] - (Int) pcInputData[uiPosX-1]);
+      piOutputData[uiPosX] /= 2;
+    };
+
+    piOutputData[0] = piOutputData[1];
+    piOutputData[uiWidth-1] = piOutputData[uiWidth-2];
+    pcInputData += uiInputStride;
+    piOutputData  += uiOutputStride;
+
+  };
+}
+
+Void TRenFilter::laplace( DoubleImage* pcInputImage, DoubleImage* pcOutputImage )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < pcInputImage->getNumberOfPlanes(); uiCurPlane++)
+  {
+    DoubleImagePlane* pcInputPlane  = pcInputImage  ->getPlane(uiCurPlane);
+    DoubleImagePlane* pcOutputPlane = pcOutputImage ->getPlane(uiCurPlane);
+
+    UInt uiWidth  = pcInputPlane->getWidth();
+    UInt uiHeight = pcInputPlane->getHeight();
+
+    Double* pdInputData  = pcInputPlane  ->getPlaneData();
+    Double* pdOutputData = pcOutputPlane ->getPlaneData();
+
+    for (UInt uiPosY = 1; uiPosY < uiHeight-1; uiPosY++)
+    {
+      UInt uOff = uiPosY * uiWidth;
+      for(UInt uiPosX = 1; uiPosX < uiWidth-1; uiPosX++)
+      {
+        UInt uOff2 = uOff + uiPosX;
+        pdOutputData[uOff2] =     4 * pdInputData[uOff2]
+        -   pdInputData[uOff2 - 1]
+        -   pdInputData[uOff2 + 1]
+        -   pdInputData[uOff2 - uiWidth]
+        -   pdInputData[uOff2 + uiWidth];
+      }
+    };
+
+    // left and right margin
+    for (UInt uiPosY = 1; uiPosY < uiHeight-1; uiPosY++)
+    {
+      UInt uOff  = uiPosY * uiWidth;
+      pdOutputData[uOff] = 3 * pdInputData[uOff]
+      -   pdInputData[uOff + 1]
+      -   pdInputData[uOff - uiWidth]
+      -   pdInputData[uOff + uiWidth];
+
+
+      uOff = (uiPosY + 1) * uiWidth - 1;
+      pdOutputData[uOff] = 3 * pdInputData[uOff]
+      -   pdInputData[uOff - 1]
+      -   pdInputData[uOff - uiWidth]
+      -   pdInputData[uOff + uiWidth];
+    }
+
+    for (UInt uiPosX = 1; uiPosX < uiWidth-1; uiPosX++)
+    {
+      UInt uOff  = uiPosX;
+      pdOutputData[uOff] = 3 * pdInputData[uOff]
+      -   pdInputData[uOff + 1]
+      -   pdInputData[uOff - 1]
+      -   pdInputData[uOff + uiWidth];
+
+
+      uOff = (uiHeight - 1) * uiWidth + uiPosX;
+      pdOutputData[uOff] = 3 * pdInputData[uOff]
+      -   pdInputData[uOff + 1]
+      -   pdInputData[uOff - 1]
+      -   pdInputData[uOff - uiWidth];
+    }
+
+    UInt uOff = 0;
+    pdOutputData[uOff] = 2 * pdInputData[uOff] - pdInputData[uOff+1] - pdInputData[ uOff + uiWidth];
+    uOff = uiWidth - 1;
+    pdOutputData[uOff] = 2 * pdInputData[uOff] - pdInputData[uOff-1] - pdInputData[ uOff + uiWidth ];
+    uOff = (uiHeight - 1) * uiWidth;
+    pdOutputData[uOff] = 2 * pdInputData[uOff] - pdInputData[uOff+1] - pdInputData[ uOff - uiWidth];
+    uOff = uiHeight * uiWidth - 1;
+    pdOutputData[uOff] = 2 * pdInputData[uOff] - pdInputData[uOff-1] - pdInputData[ uOff - uiWidth];
+
+  }
+}
+
+
+Void TRenFilter::conv( PelImage* pcImage, DoubleImage* pcKernel )
+{
+  PelImage* pcTemp = pcImage->create();
+
+  DoubleImagePlane* pcKernelPlane = 0;
+  for (UInt uiCurPlane = 0; uiCurPlane < pcImage->getNumberOfPlanes(); uiCurPlane++) {
+
+    PelImagePlane* pcPlane     = pcImage->getPlane(uiCurPlane);
+    PelImagePlane* pcTempPlane = pcTemp ->getPlane(uiCurPlane);
+
+    if ( uiCurPlane <= pcKernel->getNumberOfPlanes() )
+    {
+      pcKernelPlane = pcKernel->getPlane(uiCurPlane);
+    };
+
+    UInt uiWidth  = pcPlane->getWidth();
+    UInt uiHeight = pcPlane->getHeight();
+
+    UInt uiKernelWidth  = pcKernelPlane->getWidth();
+    UInt uiKernelHeight = pcKernelPlane->getHeight();
+
+    Pel*    pcData         = pcPlane      ->getPlaneData();
+    Pel*    pcTempData     = pcTempPlane  ->getPlaneData();
+    Double* pdKernelData   = pcKernelPlane->getPlaneData();
+
+    UInt uiDataStride       = pcPlane      ->getStride();
+    UInt uiTempDataStride   = pcTempPlane  ->getStride();
+    UInt uiKernelDataStride = pcKernelPlane->getStride();
+
+    for(UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+    {
+      UInt uOff = uiPosY * uiTempDataStride;
+      for(UInt uiPosX = 0; uiPosX < uiWidth; uiPosX++)
+      {
+        Double dSum = 0;
+        for(UInt uKY = 0; uKY < uiKernelHeight; uKY++)
+        {
+          UInt uKOff = uKY * uiKernelDataStride;
+
+          Int iYSrc = uiPosY - (uiKernelHeight/2) + uKY;
+
+          if (iYSrc < 0)
+            iYSrc = -iYSrc;
+
+          if (iYSrc >= (Int)uiHeight)
+            iYSrc = 2*uiHeight - iYSrc - 1;
+
+          UInt uSrcOff = iYSrc * uiDataStride;
+
+          for(UInt uKX = 0; uKX < uiKernelWidth; uKX++)
+          {
+            Int iXSrc = uiPosX - (uiKernelWidth/2) + uKX;
+
+            if (iXSrc < 0)
+              iXSrc = -iXSrc;
+
+            if (iXSrc >= (Int)uiWidth)
+              iXSrc = 2*uiWidth - iXSrc - 1;
+
+            dSum += pcData[uSrcOff + iXSrc] * pdKernelData[uKOff + uKX];
+          }
+        }
+        pcTempData[uOff + uiPosX] = (Pel) (dSum + ( ( dSum < 0 ) ? -0.5 : 0.5)  );
+      }
+    }
+  }
+
+  pcImage->assign(pcTemp);
+  delete pcTemp;
+}
+
+
+// Horizontal Up sampling luma
+Void TRenFilter::sampleHorUp( Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  TRenInterpFilter cFilter;
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xDistributeArray              ( pcInputPlaneData, iInputStride, 1 , 1, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride, 1, 1 );
+    break;
+  case 1:
+    xDistributeArray              ( pcInputPlaneData, iInputStride, 1 , 1, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride, 2, 1 );
+    cFilter.xCTI_FilterHalfHor    ( pcInputPlaneData, iInputStride,     1, iInputWidth, iHeight, iOutputStride, 2, ++pcOutputPlaneData );
+    break;
+  case 2:
+    xDistributeArray              ( pcInputPlaneData, iInputStride, 1 , 1, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride, 4, 1 );
+    cFilter.xCTI_FilterQuarter0Hor( pcInputPlaneData, iInputStride, 1, iInputWidth, iHeight, iOutputStride, 4, ++pcOutputPlaneData );
+    cFilter.xCTI_FilterHalfHor    ( pcInputPlaneData, iInputStride, 1, iInputWidth, iHeight, iOutputStride, 4, ++pcOutputPlaneData );
+    cFilter.xCTI_FilterQuarter1Hor( pcInputPlaneData, iInputStride, 1, iInputWidth, iHeight, iOutputStride, 4, ++pcOutputPlaneData );
+    break;
+  }
+}
+
+// horizontal up sampling chroma
+Void TRenFilter::sampleCHorUp(Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xDistributeArray( pcInputPlaneData,   iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                  , iOutputStride, 1 , 1 );
+    break;
+  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 );
+    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  )
+{
+
+  switch ( iLog2HorSampFac )
+  {
+  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 );
+    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 );
+    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 );
+    break;
+  }
+}
+
+// Down Sampling
+// Down sample luma
+Void TRenFilter::sampleHorDown(Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xDistributeArray( pcInputPlaneData, iInputStride, 1, 1, iInputWidth,iHeight, pcOutputPlaneData, iOutputStride, 1 , 1 );
+    break;
+  case 1:
+    xSampleDownHor2(pcInputPlaneData, iInputStride, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride);
+    break;
+  case 2:
+    xSampleDownHor4(pcInputPlaneData, iInputStride, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride);
+    break;
+  }
+}
+
+
+Void TRenFilter::sampleCHorDown(Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  //GT: currently the same as for luma
+  sampleHorDown( iLog2HorSampFac, pcInputPlaneData, iInputStride, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride);
+}
+
+
+
+// Up sampling chroma
+Void TRenFilter::sampleCDownHorDown( Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iInputHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  // create buffer
+  Int iBufferStride   = iInputWidth >> (iLog2HorSampFac + 1);
+  Pel* piBuffer       = new Pel[ iBufferStride * (iInputHeight+2) ];
+
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xSampleDownHor2( pcInputPlaneData - iInputStride,  iInputStride, iInputWidth  , iInputHeight+1, piBuffer,  iBufferStride);
+    break;
+  case 1:
+    xSampleDownHor4( pcInputPlaneData - iInputStride , iInputStride,  iInputWidth , iInputHeight+1, piBuffer, iBufferStride);
+    break;
+  case 2:
+    xSampleDownHor8( pcInputPlaneData - iInputStride , iInputStride,  iInputWidth  , iInputHeight+1, piBuffer, iBufferStride);
+    break;
+  }
+  xSampleDownVer2( piBuffer + iBufferStride       , iBufferStride, iBufferStride, iInputHeight,   pcOutputPlaneData, iOutputStride);
+  delete[] piBuffer;
+}
+
+Void TRenFilter::xDistributeArray(Pel* pcSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* pcDst, Int iDstStride, Int iDstStepX, Int iDstStepY)
+{
+  iDstStride *= iDstStepY;
+  iSrcStride *= iSrcStepY;
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++ )
+  {
+    Pel* pcCurDst = pcDst;
+    Pel* pcCurSrc  = pcSrc;
+    for (Int iXPos = 0; iXPos < iWidth; iXPos ++)
+    {
+      *pcCurDst = *pcCurSrc;
+
+      pcCurDst += iDstStepX;
+      pcCurSrc += iSrcStepX;
+    }
+    pcDst  += iDstStride;
+    pcSrc  += iSrcStride;
+  }
+}
+
+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 )
+{
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  TRenInterpFilter cFilter;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc - iSrcStepX;
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      iSum      = (cFilter.*fpFilter)( piSrcTmp,  iSrcStepX );
+      piDst[x * iDstStepX ] =  Clip ((iSum +  32) >>  6 );
+      piSrcTmp+= iSrcStepX;
+    }
+    piSrc += iSrcStride * iSrcStepY;
+    piDst += iDstStride * iDstStepY;
+  }
+}
+
+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 )
+{
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  TRenInterpFilter cFilter;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc - iSrcStepY * iSrcStride;
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      iSum      = (cFilter.*fpFilter)( piSrcTmp,  iSrcStepY * iSrcStride );
+      piDst[x * iDstStepX ]  =  Clip ((iSum +  32) >>  6 );
+      piSrcTmp += iSrcStepX;
+    }
+    piSrc += iSrcStride * iSrcStepY;
+    piDst += iDstStride * iDstStepY;
+  }
+}
+
+
+Void TRenFilter::xSampleDownHor2( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc - 1 ;
+    for ( Int x = 0; x < (iSrcWidth >> 1); x++ )
+    {
+      // { 1,2,1 }
+      iSum = piSrcTmp[0] + piSrcTmp[2] +  (piSrcTmp[1] << 1);
+      piDst[x] = Clip( (iSum +  2) >>  2 );
+      piSrcTmp += 2;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+};
+
+Void TRenFilter::xSampleDownVer2( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iSrcHeight, Pel* piDst, Int iDstStride  )
+{
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  for ( Int y = (iSrcHeight >> 1); y != 0; y-- )
+  {
+    piSrcTmp = piSrc -1 * iSrcStride;
+    for ( Int x = 0; x < iSrcWidth; x++ )
+    {
+      // { 1,2,1 }
+      iSum = piSrcTmp[0] + piSrcTmp[ iSrcStride << 1] +  (piSrcTmp[ iSrcStride ] << 1);
+      piDst[x] = Clip( (iSum +  2) >>  2 );
+      piSrcTmp += 1;
+    }
+    piSrc += (iSrcStride << 1);
+    piDst += iDstStride;
+  }
+};
+
+Void TRenFilter::xSampleDownHor4( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  Int iTmp0, iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc -2 ;
+    for ( Int x = 0; x < (iSrcWidth >> 2); x++ )
+    {
+      // { 1,4,6,4,1 }
+      iTmp0 = piSrcTmp[0] + piSrcTmp[4];
+      iTmp1 = piSrcTmp[1] + piSrcTmp[3];
+      iTmp2 = piSrcTmp[2];
+
+      iSum = iTmp0 +  (iTmp2 << 1) + ((iTmp1 + iTmp2) << 2);
+      piDst[x] = Clip( (iSum +  8) >>  4 );
+      piSrcTmp += 4;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+};
+
+Void TRenFilter::xSampleDownHor8( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  Int iTmp0, iTmp1, iTmp2, iTmp3;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc -3;
+    for ( Int x = 0; x < (iSrcWidth >> 3); x++ )
+    {
+      // { 1,6,15,20,15,6,1 }
+      iTmp0 = piSrcTmp[0] + piSrcTmp[6];
+      iTmp1 = piSrcTmp[1] + piSrcTmp[5];
+      iTmp2 = piSrcTmp[2] + piSrcTmp[4];
+      iTmp3 = piSrcTmp[3];
+
+      iSum = iTmp0 - iTmp2 + ( iTmp1  << 1) + ( (iTmp1 + iTmp3) << 2) + ((iTmp2 + iTmp3) << 4);
+      piDst[x] = Clip( (iSum +  32) >>  6 );
+      piSrcTmp += 8;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+};
+
+Void TRenFilter::xDilate( Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iSize, Bool bVerticalDir, Bool bToTopOrLeft )
+{
+  Int iFDimStart   = 0;
+  Int iInc         = 1;
+  Int iSDimStart   = 0;
+
+  Int iFDimSrcStrd = bVerticalDir ? 1          : iSrcStride;
+  Int iFDimDstStrd = bVerticalDir ? 1          : iDstStride;
+
+  Int iSDimSrcStrd = bVerticalDir ? iSrcStride : 1;
+  Int iSDimDstStrd = bVerticalDir ? iDstStride : 1;
+
+  Int iFDimEnd     = bVerticalDir ? iWidth -1  : iHeight - 1;
+  Int iSDimEnd     = bVerticalDir ? iHeight-1  : iWidth  - 1;
+
+  if ( bToTopOrLeft )
+  {
+    iSDimStart    = iSDimEnd;
+    iSDimEnd      = 0;
+    iInc         *= -1;
+  }
+
+  for (Int iPosFDim = iFDimStart; iPosFDim <= iFDimEnd; iPosFDim++ )
+  {
+    Int  iCount      = 0;
+    Bool bLastWasOne = false;
+    Bool bDilate     = false;
+    Int  iPosSDim    = iSDimStart;
+    Bool bContinue   = true;
+
+    while ( bContinue )
+    {
+      if ( iCount == iSize )
+      {
+        iCount  = 0;
+        bDilate = false;
+      }
+
+      Pel iVal = piSrc[iPosSDim*iSDimSrcStrd];
+      if( iVal == 0 && bLastWasOne )
+      {
+        iCount  = 0;
+        bDilate = true;
+      }
+
+      if( bDilate )
+      {
+        piDst[iPosSDim*iSDimDstStrd] = REN_USED_PEL;
+        iCount++;
+      }
+      else
+      {
+        piDst[iPosSDim*iSDimDstStrd] = iVal;
+      }
+
+
+      bLastWasOne = (iVal == REN_USED_PEL);
+      bContinue   = (iPosSDim != iSDimEnd);
+      iPosSDim    += iInc;
+    }
+
+    piSrc += iFDimSrcStrd;
+    piDst += iFDimDstStrd;
+  }
+};
+
+
+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 );
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenFilter.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenFilter.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenFilter.h	(revision 341)
@@ -0,0 +1,141 @@
+/* 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-2011, 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 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 __TRENFILTER__
+#define __TRENFILTER__
+
+#include "TLibCommon/CommonDef.h"
+#include "TRenImage.h"
+#include "TRenInterpFilter.h"
+
+typedef Int (TRenInterpFilter::*FpChromaIntFilt) ( Pel*, Int );
+
+class TRenFilter
+{
+public:
+
+  /////////// Helpers ////////
+  static Void setSubPelShiftLUT ( Int iLutPrec, Int** piSubPelShiftLUT, Int iShift );
+  static Void setupZLUT         ( Bool bBlendUseDistWeight, Int iBlendZThresPerc, Int iRelDistToLeft, Int** ppiBaseShiftLUTLeft, Int** ppiBaseShiftLUTRight, Int& riBlendZThres, Int& riBlendDistWeight, Int* piInvZLUTLeft, Int* piInvZLUTRight );
+  static Void filledToUsedPelMap( PelImage* pcFilledImage, PelImage* pcUsedPelsImage, Int iUsedPelMapMarExt  );
+
+  /////////// Copy ///////////
+  static Void copy( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride);
+
+  /////////// Horizontal Mirroring ///////////
+  template <typename T> static Void mirrorHor(        TRenImage<T> *pcInputImage );
+  //Plane
+  template <typename T> static Void mirrorHor(   TRenImagePlane<T> *pcImagePlane );
+
+  /////////// Comparison ///////////
+
+  static Int64                          SSE  ( PelImagePlane*     pcInputPlane1, PelImagePlane*      pcInputPlane2 );
+  static Int64                          SSE  ( Pel* piSrc1,       Int iSrcStride1, Int iWidth, Int iHeight,  Pel* piSrc2, Int iSrcStride2 );
+
+  template <typename T> static Bool compare  (TRenImage<T> *pcInputImage1     , TRenImage<T> *pcInputImage2);
+  //Plane
+  template <typename T> static Bool compare  (TRenImagePlane<T>* pcInputPlane1, TRenImagePlane<T>* pcInputPlane2 );
+
+  /////////// other Filters ///////////
+  static Void binominal  ( PelImage*      pcInputImage,  PelImage*      pcOutputPlane, UInt uiSize);
+  static Void binominal  ( PelImagePlane* pcInputPlane,  PelImagePlane* pcOutputPlane, UInt uiSize );
+
+  static Void lineMedian3( PelImage*      pcImage );
+  static Void convRect   ( PelImage*      pcImage,       UInt uiSize);
+  static Void laplace    ( DoubleImage*   pcInputImage,  DoubleImage* pcOutputImage);
+  static Void diffHorSym ( PelImage*      pcInputImage,  IntImage* pcOutputImage);
+
+  //Plane
+  static Void diffHorSym (PelImagePlane* pcInputPlane, IntImagePlane* pcOutputPlane);
+
+  ///////////  Convolution ///////////
+  static Void conv (PelImage* pcImage, DoubleImage* pcKernel);
+
+  /////////// InterPolation ///////////
+  static Pel interpCHSpline(Double dX, Double dS0, Double dS1, Int iQ0, Int iQ1, Int iQ2, Int iQ3);
+
+
+  /////////// HEVC/ binomial Up and Down sampling ///////////
+  //// Down sampling (binomial)
+  // Horizontally
+  static Void sampleHorDown     (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight     , Pel* pcOutputPlaneData, Int iOutputStride );
+  static Void sampleCHorDown    (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iInputHeight, Pel* pcOutputPlaneData, Int iOutputStride );
+  // 444->420 and horizontally
+  static Void sampleCDownHorDown(Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iInputHeight, Pel* pcOutputPlaneData, Int iOutputStride );
+
+  //// Up sampling (HEVC 8/4 tap)
+  // Horizontally
+  static Void sampleHorUp       (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight,      Pel* pcOutputPlaneData, Int iOutputStride );
+  static Void sampleCHorUp      (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight,      Pel* pcOutputPlaneData, Int iOutputStride );
+  // 420->444 and horizontally
+  static Void sampleCUpHorUp    (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight,      Pel* pcOutputPlaneData, Int iOutputStride );
+
+  //// Down sampling (13 tap)
+
+  static Void sampleDown2Tap13   ( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride );
+  // Plane
+  static Void sampleHorDown2Tap13(PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad);
+  static Void sampleVerDown2Tap13(PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad);
+  static Void sampleDown2Tap13   (PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane);
+  // Image
+  static Void sampleDown2Tap13   (PelImage*      pcInputImage, PelImage*      pcOutputImage);
+  static Void sampleUp2Tap13     (PelImage*      pcInputImage, PelImage*      pcOutImage   );
+private:
+
+  // Helper Functions
+  static inline Pel   xMedian3 (Pel* pcData);
+  static Void         xDilate (Pel* piSrc, Int iSrcStride, Int    iWidth, Int iHeight,    Pel* piDst, Int iDstStride, Int iSize, Bool bVerticalDir, Bool bToTopOrLeft );
+
+  // Down sampling (binomial)
+  static Void xSampleDownHor2 (Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight,    Pel* piDst, Int iDstStride );
+  static Void xSampleDownHor4 (Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight,    Pel* piDst, Int iDstStride );
+  static Void xSampleDownHor8 (Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight,    Pel* piDst, Int iDstStride );
+
+  static Void xSampleDownVer2 (Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iSrcHeight, Pel* piDst, Int iDstStride );
+
+  // Up sampling (8/4-Tap HEVC)
+  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 );
+
+  // Binominal Filtering
+  static Pel  xFiltBinom3     (Pel* pcInputData, Int iStride );
+  static Pel  xFiltBinom5     (Pel* pcInputData, Int iStride );
+  static Pel  xFiltBinom7     (Pel* pcInputData, Int iStride );
+  static Pel  xFiltBinom9     (Pel* pcInputData, Int iStride );
+};
+
+
+#endif //__TRENFILTER__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImage.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImage.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImage.cpp	(revision 341)
@@ -0,0 +1,271 @@
+/* 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-2011, 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 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 "TRenImage.h"
+#include "TRenImagePlane.h"
+#include "TRenFilter.h"
+#include "assert.h"
+
+template<typename T>
+TRenImage<T>::TRenImage( TRenImage& rcIn )
+{
+  allocatePlanes( rcIn.getPlane(0)->getWidth(), rcIn.getPlane(0)->getHeight(), rcIn.getNumberOfFullPlanes(), rcIn.getNumberOfQuaterPlanes() ) ; assign(&rcIn);
+}
+
+template<typename T>
+TRenImage<T>::TRenImage( UInt uiWidth, UInt uiHeight, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes )
+{
+  allocatePlanes( uiWidth, uiHeight, uiNumberOfFullPlanes, uiNumberOfQuaterPlanes );
+}
+
+template<typename T>
+TRenImage<T>::TRenImage() : m_uiNumberOfFullPlanes(0), m_uiNumberOfQuaterPlanes(0), m_uiNumberOfPlanes(0), m_apcPlanes(0)
+{
+
+}
+
+
+template<>
+TRenImage<Pel>::TRenImage( TComPicYuv* pcPicYuv, Bool bFirstPlaneOnly )
+{
+  if (bFirstPlaneOnly) //400
+  {
+    m_uiNumberOfPlanes       = 1;
+    m_uiNumberOfFullPlanes   = 1;
+    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 );
+  }
+  else //420
+  {
+    m_uiNumberOfPlanes       = 3;
+    m_uiNumberOfFullPlanes   = 1;
+    m_uiNumberOfQuaterPlanes = 2;
+
+    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 );
+  }
+}
+
+template<typename T>
+TRenImage<T>* TRenImage<T>::create()
+{
+  return new TRenImage( m_apcPlanes[0]->getWidth(), m_apcPlanes[0]->getHeight(), m_uiNumberOfFullPlanes, m_uiNumberOfQuaterPlanes );
+}
+
+
+template<typename T>
+TRenImage<T>::TRenImage( TComPicYuv* pcPicYuv, Bool bFirstPlaneOnly )
+{
+  assert(0);
+}
+
+template<class T>
+TRenImagePlane<T>* TRenImage<T>::getPlane(UInt uiPlaneNumber) const
+{
+  return m_apcPlanes[uiPlaneNumber];
+}
+
+template<class T>
+TRenImagePlane<T>** TRenImage<T>::getPlanes() const
+{
+  return m_apcPlanes;
+}
+
+template<typename T>
+Void TRenImage<T>::getDataAndStrides( T** pptData, Int* piStrides )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++ )
+  {
+    piStrides[uiCurPlane] = m_apcPlanes[uiCurPlane]->getStride   ();
+    pptData  [uiCurPlane] = m_apcPlanes[uiCurPlane]->getPlaneData();
+  }
+}
+
+
+template<typename T>
+Void TRenImage<T>::getWidthAndHeight( Int* ppiWidths, Int* ppiHeights )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++ )
+  {
+    ppiWidths [uiCurPlane] = m_apcPlanes[uiCurPlane]->getWidth ();
+    ppiHeights[uiCurPlane] = m_apcPlanes[uiCurPlane]->getHeight();
+  }
+}
+
+template<typename T>
+Void TRenImage<T>::allocatePlanes( UInt uiWidth, UInt uiHeight, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes )
+{
+  assert( uiNumberOfFullPlanes + uiNumberOfQuaterPlanes);
+
+  UInt uiHalfWidth  = uiWidth  / 2;
+  UInt uiHalfHeight = uiHeight / 2;
+
+  uiHalfWidth  = (uiHalfWidth  == 0) ? 1 : uiHalfWidth ;
+  uiHalfHeight = (uiHalfHeight == 0) ? 1 : uiHalfHeight;
+
+  m_uiNumberOfPlanes       = uiNumberOfFullPlanes + uiNumberOfQuaterPlanes; ;
+  m_uiNumberOfFullPlanes   = uiNumberOfFullPlanes;
+  m_uiNumberOfQuaterPlanes = uiNumberOfQuaterPlanes;
+
+  this->m_apcPlanes    = new TRenImagePlane<T>*[m_uiNumberOfPlanes];
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfFullPlanes; uiCurPlane++)
+  {
+    this->m_apcPlanes[uiCurPlane] = new TRenImagePlane<T>(uiWidth, uiHeight, REN_LUMA_MARGIN);
+  };
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfQuaterPlanes; uiCurPlane++)
+  {
+    this->m_apcPlanes[uiCurPlane+uiNumberOfFullPlanes] = new TRenImagePlane<T>(uiHalfWidth, uiHalfHeight, REN_LUMA_MARGIN >> 1);
+  };
+}
+
+
+template<class T>
+Void TRenImage<T>::assign(Int iVal)
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    m_apcPlanes[uiCurPlane]->assign( iVal);
+  }
+}
+
+
+template<class T>
+Void TRenImage<T>::devide( Double dDevisor )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    m_apcPlanes[uiCurPlane]->devide(dDevisor);
+  }
+}
+
+
+template<class T> template<class S>
+Void TRenImage<T>::assign( TRenImage<S>* pcSrcImage )
+{
+  if (pcSrcImage->getNumberOfPlanes() != m_uiNumberOfPlanes )
+  {
+    assert(0);
+  }
+
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    m_apcPlanes[uiCurPlane]->assign(pcSrcImage->getPlane(uiCurPlane)->getPlaneDataOrg(),pcSrcImage->getPlane(uiCurPlane)->getStride());
+  }
+}
+
+
+template<typename T>
+Void TRenImage<T>::setData( TRenImage* pcInputImage, Bool bClean )
+{
+  for (UInt uiPlane = 0; uiPlane < m_uiNumberOfPlanes; uiPlane++)
+  {
+    m_apcPlanes[uiPlane]->setData( pcInputImage->getPlane( uiPlane ), bClean );
+  }
+}
+
+template<typename T>
+Void TRenImage<T>::extendMargin()
+{
+  for (UInt uiPlane = 0; uiPlane < m_uiNumberOfPlanes; uiPlane++)
+  {
+    m_apcPlanes[uiPlane]->extendMargin();
+  }
+}
+
+template<class T>
+Void TRenImage<T>::xDeletePlanes()
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    if ( m_apcPlanes[uiCurPlane])
+    {
+      delete m_apcPlanes[uiCurPlane];
+    }
+    m_apcPlanes[uiCurPlane] = 0;
+  }
+}
+
+
+template<class T>
+Void TRenImage<T>::init()
+{
+  // YUV-init
+  m_apcPlanes[0]->assign((Pel) 0 );
+
+  for (UInt uiCurPlane = 1; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    m_apcPlanes[uiCurPlane]->assign( (Pel) ((g_uiIBDI_MAX+1) >> 1) );
+  }
+}
+
+
+template<class T>
+TRenImage<T>::~TRenImage() {
+  xDeletePlanes();
+  delete[] m_apcPlanes;
+}
+
+
+
+template<class T>
+UInt TRenImage<T>::getNumberOfPlanes() const
+{
+  return m_uiNumberOfPlanes;
+}
+
+template<class T>
+UInt TRenImage<T>::getNumberOfQuaterPlanes() const
+{
+  return m_uiNumberOfQuaterPlanes;
+}
+
+template<class T>
+UInt TRenImage<T>::getNumberOfFullPlanes() const
+{
+  return m_uiNumberOfFullPlanes;
+}
+
+template class TRenImage<Pel>;
+template class TRenImage<Int>;
+template class TRenImage<Double>;
+template class TRenImage<Bool>;
+
+
+template Void TRenImage<Pel>::assign<Pel>    (TRenImage<Pel>*   );
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImage.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImage.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImage.h	(revision 341)
@@ -0,0 +1,103 @@
+/* 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-2011, 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 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 __TRENIMAGE__
+#define __TRENIMAGE__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "TRenImagePlane.h"
+
+
+#define PelImage    TRenImage<Pel>
+#define DoubleImage TRenImage<Double>
+#define IntImage    TRenImage<Int>
+
+
+template<typename T>
+class TRenImage
+{
+public:
+
+  // Construction
+  TRenImage( TRenImage& rcInputImage );
+  TRenImage();
+//  TRenImage( TRenImagePlane<T>** ppcYPlanes, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes );
+
+  TRenImage( UInt uiWidth, UInt uiHeight, UInt uiNumPlanes, UInt uiNumQPlanes );
+  TRenImage( TComPicYuv* pcPicYuvIn, Bool bFirstPlaneOnly = false );
+
+  Void allocatePlanes(UInt uiWidth, UInt uiHeight, UInt uiNumFullPlanes, UInt uiNumQuaterPlanes);
+  ~TRenImage();
+
+  TRenImage* create();
+  Void       init();
+
+  // Get Planes and data
+  TRenImagePlane<T>*  getPlane(UInt uiPlaneNumber) const;
+  TRenImagePlane<T>** getPlanes() const;
+
+  Void getDataAndStrides( T**    pptData, Int*  piStrides );
+  Void getWidthAndHeight( Int*  piWidths, Int*  piHeights );
+
+  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; };
+
+  // Assign
+  Void assign(Int iVal);
+  template<typename S> Void assign(TRenImage<S>* pcSrcImage);
+  Void setData( TRenImage* pcInputImage, Bool bClean );
+
+  Void extendMargin();
+  // Operators
+  Void devide( Double dDevisor );
+
+
+private:
+
+  UInt m_uiNumberOfFullPlanes;
+  UInt m_uiNumberOfQuaterPlanes;
+  UInt m_uiNumberOfPlanes;
+  TRenImagePlane<T> ** m_apcPlanes;   // First Full Planes, then Quater Planes
+
+  Void xDeletePlanes();
+};
+
+#endif // __TRENIMAGE__
+
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImagePlane.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 341)
@@ -0,0 +1,527 @@
+/* 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-2011, 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 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 "TRenImagePlane.h"
+#include "TRenFilter.h"
+#include <string.h>
+/////// TRenImagePlane ///////
+
+template<class T>
+TRenImagePlane<T>::TRenImagePlane() { m_bClean = true; }
+
+template<class T>
+TRenImagePlane<T>::TRenImagePlane(UInt uiWidth, UInt uiHeight, UInt uiPad)
+: m_uiWidth(uiWidth), m_uiHeight(uiHeight), m_uiStride(uiWidth+2*uiPad), m_uiWidthOrg(uiWidth+2*uiPad), m_uiHeightOrg(uiHeight+2*uiPad), m_uiPad(uiPad)
+{
+  m_pcDataOrg = new T[ m_uiWidthOrg * m_uiHeightOrg ];
+  m_pcData    = m_pcDataOrg + m_uiPad * m_uiStride + m_uiPad;
+  m_bClean    = true;
+}
+
+template<class T>
+TRenImagePlane<T>::TRenImagePlane(TRenImagePlane* pcPlane)
+: m_uiWidth   (pcPlane->getWidth   ())
+, m_uiHeight  (pcPlane->getHeight  ())
+, m_uiStride  (pcPlane->getStride  ())
+, m_uiWidthOrg(pcPlane->getWidthOrg())
+, m_uiHeightOrg(pcPlane->getHeightOrg())
+, m_uiPad     (pcPlane->getPad     ())
+{
+  m_pcData = new T[m_uiWidthOrg*m_uiHeightOrg];
+  m_bClean = true;
+  assign( pcPlane );
+}
+
+template<typename T>
+TRenImagePlane<T>::TRenImagePlane( T* pcDataOrg, UInt uiWidthOrg, UInt uiHeightOrg, UInt uiStride, UInt uiPad )
+: m_pcData     (pcDataOrg + uiStride * uiPad + uiPad )
+, m_uiWidth    (uiWidthOrg  - 2* uiPad )
+, m_uiHeight   (uiHeightOrg - 2* uiPad )
+, m_uiStride   (uiStride   )
+, m_pcDataOrg  (pcDataOrg  )
+, m_uiWidthOrg (uiWidthOrg )
+, m_uiHeightOrg(uiHeightOrg)
+, m_uiPad      (uiPad      )
+, m_bClean     (false      )
+{
+
+}
+
+template<typename T>
+Void TRenImagePlane<T>::setData( T* pDataOrg, UInt uiWidthOrg, UInt uiHeightOrg, UInt uiStride, UInt uiPad, Bool bClean /*= false*/ ) 
+{
+  deleteData();
+  m_uiPad       = uiPad;
+  m_pcDataOrg   = pDataOrg;
+  m_uiWidthOrg  = uiWidthOrg;
+  m_uiHeightOrg = uiHeightOrg;
+  m_uiWidth     = uiWidthOrg  - 2* uiPad;
+  m_uiHeight    = uiHeightOrg - 2* uiPad;
+  m_uiStride    = uiStride;
+  m_pcData      = m_pcDataOrg + uiPad * m_uiStride + uiPad;
+  m_bClean      = bClean;
+}
+
+template<typename T>
+Void TRenImagePlane<T>::setData( TRenImagePlane<T>* pcInPlane, Bool bClean )
+{
+  deleteData();
+  m_uiPad       = pcInPlane->getPad();
+  m_pcDataOrg   = pcInPlane->getPlaneDataOrg();
+  m_uiWidthOrg  = pcInPlane->getWidthOrg();
+  m_uiHeightOrg = pcInPlane->getHeightOrg();
+  m_uiWidth     = pcInPlane->getWidth();
+  m_uiHeight    = pcInPlane->getHeight();
+  m_uiStride    = pcInPlane->getStride();
+  m_pcData      = pcInPlane->getPlaneData();
+  m_bClean      = bClean;
+  pcInPlane->setClean( !m_bClean );
+}
+
+template<typename T>
+Void TRenImagePlane<T>::setClean( Bool bClean )
+{
+  m_bClean = bClean;
+}
+
+template<class T>
+T* TRenImagePlane<T>::getPlaneData()
+{
+  return m_pcData;
+}
+
+
+template<class T>
+T* TRenImagePlane<T>::getPlaneDataOrg()
+{
+  return m_pcDataOrg;
+}
+
+
+template<class T>
+Void TRenImagePlane<T>::assign(Pel* pcSourceData, UInt uiSourceStride )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) pcSourceData[uiXPos];
+    }
+    pcTargetData += m_uiStride;
+    pcSourceData += uiSourceStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Pel cData)
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) cData;
+    }
+    pcTargetData  += m_uiStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Double* pdData, UInt uiSourceStride )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) pdData[uiXPos];
+    }
+    pcTargetData += m_uiStride;
+    pdData       +=  uiSourceStride;
+
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Double dData)
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) dData;
+    }
+    pcTargetData  += m_uiStride;
+  }
+}
+
+
+template<class T>
+Void TRenImagePlane<T>::assign(Bool* pbData, UInt uiSourceStride )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) pbData[uiXPos];
+    }
+    pcTargetData += m_uiStride;
+    pbData       += uiSourceStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Int iData)
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) iData;
+    }
+    pcTargetData += m_uiStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Int* piData, UInt uiSourceStride )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) piData[uiXPos];
+    }
+    pcTargetData += m_uiStride;
+    piData       += uiSourceStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Bool data)
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) data;
+    }
+    pcTargetData += m_uiStride;
+  }
+}
+
+// Assignments to Bool
+
+template<>
+Void TRenImagePlane<Bool>::assign(Int* piData, UInt uiSourceStride )
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (piData[uiXPos] == 0);
+    }
+    pcTargetData  += m_uiStride;
+    piData        += uiSourceStride;
+
+  }
+}
+
+template<>
+Void TRenImagePlane<Bool>::assign(Int iData)
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (iData == 0);
+    }
+    pcTargetData += m_uiStride;
+  }
+}
+
+template<>
+Void TRenImagePlane<Bool>::assign(Pel* pcData, UInt uiSourceStride )
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (pcData[uiXPos] == 0);
+    }
+    pcTargetData += m_uiStride;
+    pcData       +=  uiSourceStride;
+
+  }
+}
+
+template<>
+Void TRenImagePlane<Bool>::assign(Pel cData)
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (cData == 0);
+    }
+    pcTargetData += m_uiStride;
+  }
+}
+
+template<>
+Void TRenImagePlane<Bool>::assign(Double* pdData, UInt uiSourceStride )
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = ( pdData[uiXPos] == 0);
+    }
+    pcTargetData += m_uiStride;
+    pdData       += uiSourceStride;
+
+  }
+}
+
+
+
+template<>
+Void TRenImagePlane<Bool>::assign(Double dData)
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData [uiXPos] = (dData == 0);
+    }
+    pcTargetData  += m_uiStride;
+  }
+}
+
+
+// Assignments to Pel
+template<>
+Void TRenImagePlane<Pel>::assign(Double* pdData, UInt uiSourceStride )
+{
+  Pel* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (Pel) ( pdData[uiXPos] + pdData[uiXPos] < 0 ? -0.5 : 0.5 ) ;
+    }
+    pcTargetData += m_uiStride;
+    pdData       += uiSourceStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(TRenImagePlane<T>* pcPlane)
+{
+  assign(pcPlane->getPlaneDataOrg(), pcPlane->getStride());
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(TRenImagePlane<T>* pcPlane, UInt uiRow, UInt uiStartOffset, UInt uiEndOffset)
+{
+  T* pcTargetData = m_pcData                + uiRow * m_uiStride;
+  T* pcSourceData = pcPlane->getPlaneData() + uiRow * pcPlane->getStride();
+
+  for (UInt uiPosX = uiStartOffset; uiPosX <= uiEndOffset; uiPosX++)
+  {
+    pcTargetData[uiPosX] = pcSourceData[uiPosX];
+  }
+
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(TRenImagePlane<T>* pcSourcePlane, UInt uiSourceRowStart, UInt uiSourceColStart, UInt uiWidth, UInt uiHeight)
+{
+  T* acSourceData;
+  T* acDestData;
+
+  acSourceData = pcSourcePlane->getPlaneData();
+  acSourceData += uiSourceRowStart * pcSourcePlane->getStride() + uiSourceColStart;
+  acDestData    = m_pcData;
+
+  for (UInt uiPosY = 0; uiPosY < uiHeight ; uiPosY++)
+  {
+    for (UInt uiPosX = 0; uiPosX < uiWidth ; uiPosX++)
+    {
+      acDestData[uiPosX] = acSourceData[uiPosX];
+    }
+    acSourceData += pcSourcePlane->getStride();
+    acDestData   += this        ->getStride();
+  };
+}
+
+
+
+template<class T>
+Void TRenImagePlane<T>::assign( T data , UInt uiRow, UInt uiStartOffset, UInt uiEndOffset)
+{
+  T* pcTargetData = m_pcData + uiRow * m_uiStride;
+  for (UInt uiPosX = uiStartOffset; uiPosX <= uiEndOffset; uiPosX++)
+  {
+    pcTargetData[uiPosX] = data;
+  }
+}
+
+
+template<class T>
+Void TRenImagePlane<T>::devide( Double dDevisor )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiPosY = 0; uiPosY < (m_uiHeightOrg); uiPosY++)
+  {
+    for (UInt uiPosX = 0; uiPosX < m_uiWidthOrg; uiPosX++)
+    {
+      pcTargetData[uiPosX] = (T)  ( ( Double )pcTargetData[uiPosX] / dDevisor );
+    }
+    pcTargetData += m_uiStride;
+  }
+};
+
+template<class T>
+Void TRenImagePlane<T>::multiply( Double dMultiplier ) {
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiPosY = 0; uiPosY < (m_uiHeightOrg); uiPosY++)
+  {
+    for (UInt uiPosX = 0; uiPosX < m_uiWidthOrg; uiPosX++)
+    {
+      pcTargetData[uiPosX] = (T)  ( ( Double )pcTargetData[uiPosX] * dMultiplier );
+    }
+    pcTargetData += m_uiStride;
+  }
+};
+
+
+template<>
+Void TRenImagePlane<Bool>::devide( Double dDevisor )
+{
+  assert(0);
+};
+
+template<>
+Void TRenImagePlane<Bool>::multiply( Double dMultiplier )
+{
+  assert(0);
+};
+
+
+template<class T>
+Void TRenImagePlane<T>::deleteData()
+{
+  if (m_bClean)
+  {
+    if (m_pcDataOrg)
+    {
+      delete[] m_pcDataOrg;
+    };
+  }
+}
+
+template<class T>
+TRenImagePlane<T>::~TRenImagePlane()
+{
+  deleteData();
+}
+
+
+template<typename T>
+Void TRenImagePlane<T>::extendMargin()
+{
+  Int iPad = (Int) m_uiPad;
+  T* pcData = m_pcData;
+
+  for ( Int iPosY = 0; iPosY < (Int) m_uiHeight; iPosY++)
+  {
+    for ( Int iPosX = 0; iPosX < (Int) iPad; iPosX++ )
+    {
+      pcData[ -iPad + iPosX ]  = pcData[0];
+      pcData[m_uiWidth + iPosX ]  = pcData[m_uiWidth -1 ];
+    }
+    pcData += m_uiStride;
+  }
+
+
+  pcData -= (m_uiStride + iPad);
+  for ( Int iPosY = 0; iPosY < iPad; iPosY++ )
+  {
+    memcpy( pcData + (iPosY+1)*m_uiStride, pcData, sizeof(T)*(m_uiWidth + (iPad<<1)) );
+  }
+
+  pcData -= ((m_uiHeight-1) * m_uiStride);
+  for ( Int iPosY = 0; iPosY < iPad; iPosY++ )
+  {
+    memcpy( pcData - (iPosY+1)*m_uiStride, pcData, sizeof(T)*(m_uiWidth + (iPad<<1)) );
+  }
+}
+
+template class TRenImagePlane<Pel>;
+template class TRenImagePlane<Double>;
+template class TRenImagePlane<Bool>;
+template class TRenImagePlane<Int>;
+
+/////// TRenImagePlanePart ///////
+
+template<typename T>
+TRenImagePlanePart<T>::TRenImagePlanePart( TRenImagePlane<T>* pPlane, UInt uHorOff, UInt uVerOff, UInt uWidth, UInt uHeight )
+: TRenImagePlane<T>( pPlane->getPlaneData() + uHorOff + uVerOff * pPlane->getStride(), uWidth, uHeight, pPlane->getStride(),0)
+{
+
+}
+
+template<typename T>
+TRenImagePlanePart<T>::~TRenImagePlanePart()
+{
+  this->m_pcData = NULL;
+}
+
+template class TRenImagePlanePart<Pel>;
+template class TRenImagePlanePart<Double>;
+template class TRenImagePlanePart<Bool>;
+template class TRenImagePlanePart<Int>;
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImagePlane.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 341)
@@ -0,0 +1,123 @@
+/* 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-2011, 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 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 __TRENIMAGEPLANE__
+#define __TRENIMAGEPLANE__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+
+#define PelImagePlane     TRenImagePlane<Pel>
+#define DoubleImagePlane  TRenImagePlane<Double>
+#define IntImagePlane     TRenImagePlane<Int>
+
+template<typename T>
+class TRenImagePlane
+{
+public:
+  // Construction
+  TRenImagePlane();
+  TRenImagePlane( UInt uiWidth, UInt uiHeight, UInt uiPad);
+  TRenImagePlane( TRenImagePlane* pcInputPlane );
+  TRenImagePlane( T* pcDataOrg, UInt uiWidthOrg, UInt uiHeightOrg, UInt uiStride, UInt uiPad );
+
+  ~TRenImagePlane();
+
+  // Get Data
+  T*   getPlaneData();
+  UInt getWidth    () { return m_uiWidth; };
+  UInt getHeight   () { return m_uiHeight; };
+
+  T*   getPlaneDataOrg();
+  UInt getWidthOrg () { return m_uiWidthOrg;  };
+  UInt getHeightOrg() { return m_uiHeightOrg; };
+  UInt getPad      () { return m_uiPad;       };
+  UInt getStride   () { return m_uiStride; };
+
+  Void setData ( T* pDataOrg, UInt uiWidthOrg, UInt uiHeightOrg, UInt uiStride, UInt uiPad, Bool bClean /*= false*/ ); 
+  
+  Void setData ( TRenImagePlane<T>* pcInPlane, Bool bClean );
+  Void setClean( Bool bClean );
+  Void extendMargin();
+
+  // Assignment
+  Void assign( Pel*    data, UInt uiSourceStride );
+  Void assign( Pel     data );
+
+  Void assign( Double* data, UInt uiSourceStride );
+  Void assign( Double  data );
+
+  Void assign( Bool*  data, UInt uiSourceStride );
+  Void assign( Bool   data );
+
+  Void assign( Int*   data, UInt uiSourceStride );
+  Void assign( Int    data );
+
+  Void assign( TRenImagePlane<T>* pcPlane);
+
+  Void assign( T data , UInt uRow, UInt uStartOffset, UInt uEndOffset);
+  Void assign( TRenImagePlane<T>* pcPlane, UInt uRow, UInt uStartOffset, UInt uEndOffset);
+  Void assign( TRenImagePlane<T>* pcSourcePlane, UInt uSourceRowStart, UInt uSourceColStart, UInt uWidth, UInt uHeight);
+
+  // Operators
+  Void devide(   Double dDevisor );
+  Void multiply( Double dMultiplier );
+
+protected:
+  T     *m_pcData;
+  UInt   m_uiWidth;
+  UInt   m_uiHeight;
+  UInt   m_uiStride;
+
+  T     *m_pcDataOrg;
+  UInt   m_uiWidthOrg;
+  UInt   m_uiHeightOrg;
+  UInt   m_uiPad;
+
+  Double m_dRatio;
+  Bool   m_bClean;
+
+private:
+  Void deleteData();
+};
+
+template<typename T>
+class TRenImagePlanePart : public TRenImagePlane< T >
+{
+public:
+  TRenImagePlanePart( TRenImagePlane<T>* pcPlane, UInt uHorOff, UInt uVerOff, UInt uWidth, UInt uHeight);;
+  ~TRenImagePlanePart();;
+};
+
+#endif // __TRENIMAGEPLANE__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenInterpFilter.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 341)
@@ -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-2011, 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 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     TRenInterpFilter.cpp
+    \brief    interpolation filter class (From HM 3.0 TComPredFilter)
+*/
+
+#include "TRenInterpFilter.h"
+
+// ====================================================================================================================
+// Constructor
+// ====================================================================================================================
+
+TRenInterpFilter::TRenInterpFilter()
+{
+  // initial number of taps for Luma
+}
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenInterpFilter.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 341)
@@ -0,0 +1,2234 @@
+/* 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-2011, 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 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     TRenInterpFilter.h
+    \brief    interpolation filter class (header), (From HM 3.0 TComPredFilter))
+*/
+
+#ifndef __TRENINTERPFILTER__
+#define __TRENINTERPFILTER__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "assert.h"
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+// Local type definitions
+#define HAL_IDX   1
+#define QU0_IDX   0
+#define QU1_IDX   2
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// interpolation filter class
+class TRenInterpFilter
+{
+public:
+  TRenInterpFilter();
+  
+  // DIF filter interface (for half & quarter)
+  __inline Void xCTI_FilterHalfHor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  __inline Void xCTI_FilterHalfHor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  
+  __inline Void xCTI_FilterQuarter0Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  __inline Void xCTI_FilterQuarter0Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  
+  __inline Void xCTI_FilterQuarter1Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  __inline Void xCTI_FilterQuarter1Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  
+  __inline Void xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst, Int iDstStridePel, Pel*& rpiDstPel );
+  __inline Void xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst );
+  __inline Void xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst );
+  
+  __inline Void xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst );
+  __inline Void xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst );
+  
+  __inline Void xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst );
+  __inline Void xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst );
+  
+  __inline Void xCTI_Filter2DVerC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Int*& rpiDst, Int iMv);
+  __inline Void xCTI_Filter2DHorC (Int* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+  __inline Void xCTI_Filter1DHorC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+  __inline Void xCTI_Filter1DVerC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+
+   __inline Int xCTI_Filter_VPS04_C_HAL( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VIS04_C_HAL( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_OCT0( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_OCT0( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_QUA0( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_QUA0( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_OCT1( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_OCT1( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_OCT2( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_OCT2( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_QUA1( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_QUA1( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_OCT3( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_OCT3( Int* pSrc, Int iStride );
+
+#if HIGH_ACCURACY_BI
+  __inline Void xCTI_FilterHalfHor_ha(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst); //
+  __inline Void xCTI_FilterHalfHor_ha(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);//
+  
+    
+  __inline Void xCTI_FilterQuarter0Hor_ha(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst); //
+  __inline Void xCTI_FilterQuarter0Hor_ha(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst); //
+  
+  __inline Void xCTI_FilterQuarter1Hor_ha(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst); //
+  __inline Void xCTI_FilterQuarter1Hor_ha(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst); //
+  
+  __inline Void xCTI_FilterHalfVer_ha (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst ); //
+  
+  __inline Void xCTI_FilterQuarter0Ver_ha (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst );
+  __inline Void xCTI_FilterQuarter1Ver_ha (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst );
+  
+  __inline Void xCTI_Filter1DHorC_ha (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+  __inline Void xCTI_Filter1DVerC_ha (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+  __inline Void xCTI_Filter2DHorC_ha (Int* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+
+#endif
+};
+
+#if HIGH_ACCURACY_BI
+__inline Void TRenInterpFilter::xCTI_FilterHalfHor_ha(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  Int shiftNum = g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[        0]+piSrcTmp[iSrcStep7];
+      iTmp1 = piSrcTmp[iSrcStep]+piSrcTmp[iSrcStep6];
+      iTmp2 = piSrcTmp[iSrcStep2]+piSrcTmp[iSrcStep5];
+      iTmp3 = piSrcTmp[iSrcStep3]+piSrcTmp[iSrcStep4];
+
+      iTmpA = (iTmp3 << 2) - iTmp2;
+
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+      
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfHor_ha(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+ 
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  Int shiftNum = 6 + g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[        0]+piSrcTmp[iSrcStep7];
+      iTmp1 = piSrcTmp[iSrcStep ]+piSrcTmp[iSrcStep6];
+      iTmp2 = piSrcTmp[iSrcStep2]+piSrcTmp[iSrcStep5];
+      iTmp3 = piSrcTmp[iSrcStep3]+piSrcTmp[iSrcStep4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;
+      
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+
+}
+
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Hor_ha(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+  Int shiftNum = g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep3] + piSrcTmp[iSrcStep5];
+      iTmp2 = piSrcTmp[iSrcStep6] + piSrcTmp[iSrcStep4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStep]             << 2 )
+            - ( ( piSrcTmp[iSrcStep2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep4]           << 4 )
+            + ( piSrcTmp[iSrcStep3]             << 6);
+      
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum + shiftOffset) >> shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0,16383, (iSum + shiftOffset) >> shiftNum );
+#endif
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Hor_ha(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+  
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+  Int shiftNum = 6 + g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+    
+      iTmp1 = piSrcTmp[iSrcStep3] + piSrcTmp[iSrcStep5];
+      iTmp2 = piSrcTmp[iSrcStep6] + piSrcTmp[iSrcStep4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStep]             << 2 )
+            - ( ( piSrcTmp[iSrcStep2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep4]           << 4 )
+            + (   piSrcTmp[iSrcStep3]           << 6 );
+      
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0, 16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+
+}
+
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Hor_ha(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+  Int shiftNum = g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep4] + piSrcTmp[iSrcStep2];
+      iTmp2 = piSrcTmp[iSrcStep ] + piSrcTmp[iSrcStep3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStep6]           << 2 )
+            - ( ( piSrcTmp[iSrcStep5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep3]           << 4 )
+            + (   piSrcTmp[iSrcStep4]           << 6 );
+
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0, 16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+
+
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Hor_ha(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+  Int shiftNum = 6+g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep4] + piSrcTmp[iSrcStep2];
+      iTmp2 = piSrcTmp[iSrcStep ] + piSrcTmp[iSrcStep3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStep6]           << 2 )
+            - ( ( piSrcTmp[iSrcStep5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep3]           << 4 )
+            + (   piSrcTmp[iSrcStep4]           << 6 );
+      
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0, 16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+
+}
+
+
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Ver_ha (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+  Int shiftNum = g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStride3] + piSrcTmp[iSrcStride5];
+      iTmp2 = piSrcTmp[iSrcStride6] + piSrcTmp[iSrcStride4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStride]             << 2 )
+            - ( ( piSrcTmp[iSrcStride2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride4]           << 4 )
+            + (   piSrcTmp[iSrcStride3]           << 6);
+      
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0, 16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+
+}
+
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Ver_ha (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+  Int shiftNum = g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      /// {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      iTmp1 = piSrcTmp[iSrcStride4] + piSrcTmp[iSrcStride2];
+      iTmp2 = piSrcTmp[iSrcStride ] + piSrcTmp[iSrcStride3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStride6]           << 2 )
+            - ( ( piSrcTmp[iSrcStride5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride3]           << 4 )
+            + (   piSrcTmp[iSrcStride4]           << 6 );
+            
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0, 16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfVer_ha  (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+  Int shiftNum = g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+  Int  iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[          0]+piSrcTmp[iSrcStride7];
+      iTmp1 = piSrcTmp[iSrcStride ]+piSrcTmp[iSrcStride6];
+      iTmp2 = piSrcTmp[iSrcStride2]+piSrcTmp[iSrcStride5];
+      iTmp3 = piSrcTmp[iSrcStride3]+piSrcTmp[iSrcStride4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;        
+      
+#if REMOVE_INTERMEDIATE_CLIPPING
+      piDst   [x * iDstStep] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+      piDst   [x * iDstStep] = Clip3(0, 16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+
+}
+
+
+#endif
+
+// ------------------------------------------------------------------------------------------------
+// DCTIF filters
+// ------------------------------------------------------------------------------------------------
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfHor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[        0]+piSrcTmp[iSrcStep7];
+      iTmp1 = piSrcTmp[iSrcStep]+piSrcTmp[iSrcStep6];
+      iTmp2 = piSrcTmp[iSrcStep2]+piSrcTmp[iSrcStep5];
+      iTmp3 = piSrcTmp[iSrcStep3]+piSrcTmp[iSrcStep4];
+
+      iTmpA = (iTmp3 << 2) - iTmp2;
+
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;
+
+      piDst   [x * iDstStep] = Clip( (iSum +  32) >>  6 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfHor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[        0]+piSrcTmp[iSrcStep7];
+      iTmp1 = piSrcTmp[iSrcStep ]+piSrcTmp[iSrcStep6];
+      iTmp2 = piSrcTmp[iSrcStep2]+piSrcTmp[iSrcStep5];
+      iTmp3 = piSrcTmp[iSrcStep3]+piSrcTmp[iSrcStep4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;
+      
+      piDst   [x * iDstStep] = Clip( (iSum +  2048) >>  12 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep3] + piSrcTmp[iSrcStep5];
+      iTmp2 = piSrcTmp[iSrcStep6] + piSrcTmp[iSrcStep4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+             - ( ( piSrcTmp[iSrcStep2] - iTmp2 ) << 1 )
+             + (  piSrcTmp[iSrcStep]             << 2 )
+             - ( ( piSrcTmp[iSrcStep2] + iTmp1 ) << 3 )
+             + (   piSrcTmp[iSrcStep4]           << 4 );
+      
+      piDst   [x * iDstStep] = Clip(( (iSum +  32) >>  6 )+ piSrcTmp[iSrcStep3]);
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+    
+      iTmp1 = piSrcTmp[iSrcStep3] + piSrcTmp[iSrcStep5];
+      iTmp2 = piSrcTmp[iSrcStep6] + piSrcTmp[iSrcStep4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStep]             << 2 )
+            - ( ( piSrcTmp[iSrcStep2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep4]           << 4 )
+            + (   piSrcTmp[iSrcStep3]           << 6 );
+      
+      piDst   [x * iDstStep] = Clip( (iSum +  2048) >>  12 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep4] + piSrcTmp[iSrcStep2];
+      iTmp2 = piSrcTmp[iSrcStep ] + piSrcTmp[iSrcStep3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStep6]           << 2 )
+            - ( ( piSrcTmp[iSrcStep5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep3]           << 4 );
+      
+      piDst   [x * iDstStep] = Clip( ((iSum +  32) >>  6) + piSrcTmp[iSrcStep4] );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep4] + piSrcTmp[iSrcStep2];
+      iTmp2 = piSrcTmp[iSrcStep ] + piSrcTmp[iSrcStep3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStep6]           << 2 )
+            - ( ( piSrcTmp[iSrcStep5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep3]           << 4 )
+            + (   piSrcTmp[iSrcStep4]           << 6 );
+      
+      piDst   [x * iDstStep] = Clip( (iSum +  2048) >>  12 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__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 )
+{
+  Int*  piDst = rpiDst;
+  Pel*  piDstPel = rpiDstPel;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[          0]+piSrcTmp[iSrcStride7];
+      iTmp1 = piSrcTmp[iSrcStride ]+piSrcTmp[iSrcStride6];
+      iTmp2 = piSrcTmp[iSrcStride2]+piSrcTmp[iSrcStride5];
+      iTmp3 = piSrcTmp[iSrcStride3]+piSrcTmp[iSrcStride4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;
+      
+      piDst[x * iDstStep]    = iSum;
+      piDstPel[x * iDstStep] = Clip( (iSum +  32) >>  6 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+    piDstPel += iDstStridePel;
+  }
+ return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+{
+  Int*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[          0]+piSrcTmp[iSrcStride7];
+      iTmp1 = piSrcTmp[iSrcStride ]+piSrcTmp[iSrcStride6];
+      iTmp2 = piSrcTmp[iSrcStride2]+piSrcTmp[iSrcStride5];
+      iTmp3 = piSrcTmp[iSrcStride3]+piSrcTmp[iSrcStride4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;        
+      
+      piDst[x * iDstStep] = iSum;
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[          0]+piSrcTmp[iSrcStride7];
+      iTmp1 = piSrcTmp[iSrcStride ]+piSrcTmp[iSrcStride6];
+      iTmp2 = piSrcTmp[iSrcStride2]+piSrcTmp[iSrcStride5];
+      iTmp3 = piSrcTmp[iSrcStride3]+piSrcTmp[iSrcStride4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;        
+      
+      piDst[x * iDstStep] = Clip( (iSum +  32) >>  6 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+{
+  Int*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStride3] + piSrcTmp[iSrcStride5];
+      iTmp2 = piSrcTmp[iSrcStride6] + piSrcTmp[iSrcStride4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStride]             << 2 )
+            - ( ( piSrcTmp[iSrcStride2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride4]           << 4 )
+            + (   piSrcTmp[iSrcStride3]           << 6 );
+      
+      piDst[x * iDstStep] = iSum;
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStride3] + piSrcTmp[iSrcStride5];
+      iTmp2 = piSrcTmp[iSrcStride6] + piSrcTmp[iSrcStride4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStride]             << 2 )
+            - ( ( piSrcTmp[iSrcStride2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride4]           << 4 );
+      
+      piDst[x * iDstStep] = Clip( ((iSum +  32) >>  6) + piSrcTmp[iSrcStride3] );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+{
+  Int*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      /// {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      iTmp1 = piSrcTmp[iSrcStride4] + piSrcTmp[iSrcStride2];
+      iTmp2 = piSrcTmp[iSrcStride ] + piSrcTmp[iSrcStride3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStride6]           << 2 )
+            - ( ( piSrcTmp[iSrcStride5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride3]           << 4 )
+            + (   piSrcTmp[iSrcStride4]           << 6 );
+            
+      piDst[x * iDstStep] = iSum;
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      /// {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      iTmp1 = piSrcTmp[iSrcStride4] + piSrcTmp[iSrcStride2];
+      iTmp2 = piSrcTmp[iSrcStride ] + piSrcTmp[iSrcStride3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStride6]           << 2 )
+            - ( ( piSrcTmp[iSrcStride5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride3]           << 4 );
+            
+      piDst[x * iDstStep] = Clip( ((iSum +  32) >>  6) +  piSrcTmp[iSrcStride4] );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+// ------------------------------------------------------------------------------------------------
+// DCTIF filters for Chroma
+// ------------------------------------------------------------------------------------------------
+__inline Void TRenInterpFilter::xCTI_Filter2DVerC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Int*& rpiDst, Int iMV)
+{
+  Int*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT0( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA0( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:  
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA1( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:  
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT1( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT2( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT3( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4: 
+  {
+
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VPS04_C_HAL( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_Filter2DHorC(Int* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT0( piSrcTmp, 1 );
+          piDst   [x ] = Clip ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_QUA0( piSrcTmp, 1 );
+          piDst   [x ] = Clip ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_QUA1( piSrcTmp, 1 );
+          piDst   [x ] = Clip ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT1( piSrcTmp, 1 );
+          piDst   [x ] = Clip ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT2( piSrcTmp, 1 );
+          piDst   [x ] = Clip ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT3( piSrcTmp, 1 );
+          piDst   [x ] = Clip ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VIS04_C_HAL( piSrcTmp, 1 );
+          piDst   [x ] = Clip ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+  }
+
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_Filter1DVerC (Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
+{
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT0( piSrcTmp,  iSrcStride );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA0( piSrcTmp,  iSrcStride );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA1( piSrcTmp,  iSrcStride );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT1( piSrcTmp,  iSrcStride );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT2( piSrcTmp,  iSrcStride );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT3( piSrcTmp,  iSrcStride );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[-iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VPS04_C_HAL( piSrcTmp, iSrcStride );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_Filter1DHorC(Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride, Pel*& rpiDst, Int iMV)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT0( piSrcTmp,  1 );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_QUA0( piSrcTmp,  1 );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_QUA1( piSrcTmp,  1 );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT1( piSrcTmp,  1 );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT2( piSrcTmp,  1 );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT3( piSrcTmp,  1 );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VPS04_C_HAL( piSrcTmp,  1 );
+          piDst[x ] = Clip ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+ }
+  return;
+}
+
+#if HIGH_ACCURACY_BI
+__inline Void TRenInterpFilter::xCTI_Filter2DHorC_ha(Int* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+  Int shiftNum  = 6 + g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT0( piSrcTmp, 1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_QUA0( piSrcTmp, 1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_QUA1( piSrcTmp, 1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT1( piSrcTmp, 1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT2( piSrcTmp, 1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT3( piSrcTmp, 1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VIS04_C_HAL( piSrcTmp, 1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+  }
+
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_Filter1DVerC_ha (Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
+{
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int shiftNum  = g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+    
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT0( piSrcTmp,  iSrcStride );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA0( piSrcTmp,  iSrcStride );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA1( piSrcTmp,  iSrcStride );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT1( piSrcTmp,  iSrcStride );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT2( piSrcTmp,  iSrcStride );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT3( piSrcTmp,  iSrcStride );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[-iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VPS04_C_HAL( piSrcTmp, iSrcStride );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+  }    
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_Filter1DHorC_ha(Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride, Pel*& rpiDst, Int iMV)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int shiftNum  = g_uiBitIncrement + g_uiBitDepth - 8;
+  Int shiftOffset = (shiftNum > 0) ? ( 1 << (shiftNum - 1)) : 0 ;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT0( piSrcTmp,  1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA0( piSrcTmp,  1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_QUA1( piSrcTmp,  1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT1( piSrcTmp,  1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT2( piSrcTmp,  1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT3( piSrcTmp,  1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum    = xCTI_Filter_VPS04_C_HAL( piSrcTmp,  1 );
+#if REMOVE_INTERMEDIATE_CLIPPING
+          piDst[x ] = (iSum +  shiftOffset) >>  shiftNum;
+#else
+          piDst[x ] = Clip3(0,16383, (iSum +  shiftOffset) >>  shiftNum );
+#endif
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+
+ }
+  return;
+}
+#endif
+
+
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT0( Pel* pSrc,  Int iStride )
+{// {  -3,  60,   8,   -1,} // 1/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p1<<6) -((p1+p0)<<2) +p0 +(p2<<3) -p3;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT0( Int* pSrc, Int iStride )
+{ // {  -3,  60,   8,   -1,} //1/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p1<<6) -((p1+p0)<<2) +p0 +(p2<<3) -p3;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_QUA0( Pel* pSrc,  Int iStride )
+{// {  -4,  54,  16,   -2,} // 1/4
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p1 << 6) + (p2 << 4) - (p1 << 3) - ( p0 << 2) - ((p1 + p3) << 1);
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_QUA0( Int* pSrc, Int iStride )
+{ // {  -4,  54,  16,   -2,} //1/4
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p1 << 6) + (p2 << 4) - (p1 << 3) - ( p0 << 2) - ((p1 + p3) << 1);
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_QUA1( Pel* pSrc,  Int iStride )
+{// {  -2,  16,  54,   -4,}// 3/4
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p2 << 6) + (p1 << 4) - (p2 << 3) - ( p3 << 2) - ((p2 + p0) << 1);
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_QUA1( Int* pSrc, Int iStride )
+{// {  -2,  16,  54,   -4,}// 3/4
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p2 << 6) + (p1 << 4) - (p2 << 3) - ( p3 << 2) - ((p2 + p0) << 1);
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT1( Pel* pSrc,  Int iStride )
+{// {  -5,  46,  27,   -4,} // 3/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  Int t = p0 + p2;
+  iSum = ((p1 + p2) << 5) + (p1 << 4) - ( (t + p3) << 2) - ( p1 << 1) - t;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT1( Int* pSrc, Int iStride )
+{ // {  -5,  46,  27,   -4,} //3/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  Int t = p0 + p2;
+  iSum = ((p1 + p2) << 5) + (p1 << 4) - ( (t + p3) << 2) - ( p1 << 1) - t;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VPS04_C_HAL( Pel* pSrc, Int iStride )
+{
+  // {  -4,  36,  36,   -4,}, // 1/2
+  Int iSum;
+  Int iTemp0 = pSrc[iStride*1]+pSrc[iStride*2];
+  Int iTemp1 = pSrc[        0]+pSrc[iStride*3];
+
+  iSum  = ((iTemp0<<3) + iTemp0 -iTemp1)<<2;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VIS04_C_HAL( Int* pSrc, Int iStride )
+{
+  // {  -4,  36,  36,   -4,}, //1/2
+  Int iSum;
+  Int iTemp0 = pSrc[iStride*1]+pSrc[iStride*2];
+  Int iTemp1 = pSrc[        0]+pSrc[iStride*3];
+
+  iSum  = ((iTemp0<<3) + iTemp0 -iTemp1)<<2;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT2( Pel* pSrc,  Int iStride )
+{// {  -4,  27,  46,   -5,}, // 5/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  Int t = p1 + p3;
+  iSum = ((p1 + p2) << 5) + (p2 << 4) - ( (t + p0) << 2) - ( p2 << 1) - t;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT2( Int* pSrc, Int iStride )
+{ // {  -4,  27,  46,   -5,}, // 5/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  Int t = p1 + p3;
+  iSum = ((p1 + p2) << 5) + (p2 << 4) - ( (t + p0) << 2) - ( p2 << 1) - t;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT3( Pel* pSrc,  Int iStride )
+{// {  -1,   8,  60,   -3,} // 7/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p2<<6) -((p2+p3)<<2) +p3 +(p1<<3) -p0;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT3( Int* pSrc, Int iStride )
+{ // {  -1,   8,  60,   -3,} // 7/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p2<<6) -((p2+p3)<<2) +p3 +(p1<<3) -p0;
+
+  return iSum;
+}
+
+#endif // __TRENINTERP__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 341)
@@ -0,0 +1,453 @@
+/* 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-2011, 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 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 "TRenImage.h"
+#include "TRenFilter.h"
+#include "TRenModSetupStrParser.h"
+#if !QC_MVHEVC_B0046
+Int
+TRenModSetupStrParser::getNumOfModels()
+{
+  return m_iNumberOfModels;
+}
+
+Int
+TRenModSetupStrParser::getNumOfBaseViews()
+{
+  return (Int) m_aiAllBaseViewIdx  .size();
+}
+
+Int
+TRenModSetupStrParser::getNumOfModelsForView( Int iViewIdx, Int iContent )
+{
+  return (Int) m_aaaiModelNums[iContent][iViewIdx].size();
+}
+
+Int
+TRenModSetupStrParser::getNumOfBaseViewsForView( Int iViewIdx, Int iContent )
+{
+  return (Int) m_aaaiBaseViewsIdx[iContent][iViewIdx].size();
+}
+
+Void
+TRenModSetupStrParser::getSingleModelData( Int iSrcViewIdx,
+                                           Int iSrcCnt,
+                                           Int iCurModel,
+                                           Int& riModelNum,
+                                           Int& riBlendMode,
+                                           Int& riLeftBaseViewIdx,
+                                           Int& riRightBaseViewIdx,
+                                           Int& riOrgRefBaseViewIdx,
+                                           Int& riSynthViewRelNum )
+{
+  Bool bExtrapolate    = m_aaabExtrapolate[iSrcCnt][iSrcViewIdx][iCurModel];
+  Bool bOrgRef         = m_aaabOrgRef     [iSrcCnt][iSrcViewIdx][iCurModel];
+
+  riOrgRefBaseViewIdx = bOrgRef ? m_aaaiSynthViewNums[iSrcCnt][iSrcViewIdx][iCurModel] / ( (Int) VIEW_NUM_PREC ) : -1;
+  riSynthViewRelNum    = m_aaaiSynthViewNums[iSrcCnt][iSrcViewIdx][iCurModel];
+  riModelNum           = m_aaaiModelNums    [iSrcCnt][iSrcViewIdx][iCurModel];
+  riBlendMode          = m_aaaiBlendMode    [iSrcCnt][iSrcViewIdx][iCurModel];
+
+
+  Int iSrcViewNum = iSrcViewIdx * ((Int) VIEW_NUM_PREC );
+  if ( iSrcViewNum < riSynthViewRelNum )
+  {
+    riLeftBaseViewIdx  = iSrcViewIdx;
+    riRightBaseViewIdx = -1;
+  }
+  else
+  {
+    riLeftBaseViewIdx = -1;
+    riRightBaseViewIdx  = iSrcViewIdx;
+  }
+
+  if ( !bExtrapolate )
+  {
+    std::vector<Int> cCurBaseViews = m_aaaiBaseViewsIdx[iSrcCnt][iSrcViewIdx];
+
+    Int iMinDist = MAX_INT;
+    Int iNearestNum = -1;
+
+    for (Int iCurBaseView = 0; iCurBaseView < cCurBaseViews.size(); iCurBaseView++ )
+    {
+      Int iCurBaseNum = m_aaaiBaseViewsIdx [iSrcCnt][iSrcViewIdx][iCurBaseView];
+
+      if ( iCurBaseNum == iSrcViewNum )
+        continue;
+
+      Int iDist = iCurBaseNum - riSynthViewRelNum;
+
+      if ( ( iDist <= 0  && riLeftBaseViewIdx == -1) || ( iDist >= 0  && riRightBaseViewIdx == -1 ) )
+      {
+        if ( abs(iDist) < iMinDist )
+        {
+          iMinDist = abs(iDist);
+          iNearestNum = iCurBaseNum;
+        }
+      }
+    }
+    xError(iNearestNum == -1);
+
+    if (riLeftBaseViewIdx == -1 )
+    {
+      riLeftBaseViewIdx = iNearestNum / (Int) (VIEW_NUM_PREC);
+    }
+    else
+    {
+      riRightBaseViewIdx = iNearestNum / (Int) (VIEW_NUM_PREC);
+    }
+
+    xError(riLeftBaseViewIdx  == -1 );
+    xError(riRightBaseViewIdx == -1 );
+    xError(riLeftBaseViewIdx  >= riRightBaseViewIdx );
+  }
+}
+
+Void
+TRenModSetupStrParser::getBaseViewData( Int iSourceViewIdx, Int iSourceContent, Int iCurView, Int& riBaseViewSIdx, Int& riVideoDistMode, Int& riDepthDistMode )
+{
+  riBaseViewSIdx = m_aaaiBaseViewsIdx  [iSourceContent][iSourceViewIdx][iCurView] / (Int) VIEW_NUM_PREC;
+  riVideoDistMode            = m_aaaiVideoDistMode [iSourceContent][iSourceViewIdx][iCurView];
+  riDepthDistMode            = m_aaaiDepthDistMode [iSourceContent][iSourceViewIdx][iCurView];
+}
+
+TRenModSetupStrParser::TRenModSetupStrParser()
+{
+  m_pchSetStr       = NULL;
+  m_iPosInStr       = 0;
+  m_iNumberOfModels = 0;
+  m_bCurrentViewSet = false;
+}
+
+Void
+TRenModSetupStrParser::setString( Int iNumOfBaseViews, Char* pchSetStr )
+{
+  for (Int iContent = 0; iContent < 2; iContent++)
+  {
+    m_aaaiBaseViewsIdx  [iContent].resize( iNumOfBaseViews );
+    m_aaaiDepthDistMode [iContent].resize( iNumOfBaseViews );
+    m_aaaiVideoDistMode [iContent].resize( iNumOfBaseViews );
+    m_aaaiSynthViewNums [iContent].resize( iNumOfBaseViews );
+    m_aaaiModelNums     [iContent].resize( iNumOfBaseViews );
+    m_aaabOrgRef        [iContent].resize( iNumOfBaseViews );
+    m_aaabExtrapolate   [iContent].resize( iNumOfBaseViews );
+    m_aaaiBlendMode     [iContent].resize( iNumOfBaseViews );
+  }
+
+  AOT( m_pchSetStr );
+  m_pchSetStr = pchSetStr;
+  m_iPosInStr       = 0;
+  m_bCurrentViewSet = false;
+
+  xParseString();
+}
+
+Void
+TRenModSetupStrParser::xParseString()
+{
+  Char cChar;
+  xGetNextChar(cChar);
+  while(  cChar != '\0' )
+  {
+    xParseSourceView();
+    xGetNextChar(cChar);
+  }
+  // CHECK
+  size_t iNumOfSrcViews = m_aaaiBaseViewsIdx[0].size();
+
+  for (Int iSrcView = 0; iSrcView < iNumOfSrcViews; iSrcView++)
+  {
+    for (Int iContent = 0; iContent < 2; iContent++ )
+    {
+      size_t iNumOfBase  = m_aaaiBaseViewsIdx  [iContent][iSrcView].size();
+      AOF( iNumOfBase   == m_aaaiDepthDistMode [iContent][iSrcView].size());
+      AOF( iNumOfBase   == m_aaaiVideoDistMode [iContent][iSrcView].size());
+
+      size_t iNumOfModels = m_aaaiSynthViewNums[iContent][iSrcView].size();
+      AOF( iNumOfModels == m_aaaiModelNums     [iContent][iSrcView].size());
+      AOF( iNumOfModels == m_aaabOrgRef        [iContent][iSrcView].size());
+      AOF( iNumOfModels == m_aaabExtrapolate   [iContent][iSrcView].size());
+    }
+  }
+
+  // SORT
+  std::vector<Int>::iterator cIterNewEnd;
+
+  std::sort( m_aiAllBaseViewIdx.begin(), m_aiAllBaseViewIdx.end() );
+  cIterNewEnd = std::unique( m_aiAllBaseViewIdx.begin(), m_aiAllBaseViewIdx.end() );
+  m_aiAllBaseViewIdx.erase( cIterNewEnd, m_aiAllBaseViewIdx.end() );
+
+  std::sort( m_aiAllSynthViewNums.begin(), m_aiAllSynthViewNums.end() );
+  cIterNewEnd = std::unique( m_aiAllSynthViewNums.begin(), m_aiAllSynthViewNums.end() );
+  m_aiAllSynthViewNums.erase( cIterNewEnd, m_aiAllSynthViewNums.end() );
+}
+
+Void
+TRenModSetupStrParser::xParseSourceView()
+{
+  m_bCurrentViewSet = false;
+
+  Char cChar;
+  xGetNextCharGoOn( cChar );
+  xError( cChar != '[' );
+  xReadViewInfo('B');
+
+  Bool bContinueReading = true;
+  while( bContinueReading )
+  {
+    xGetNextCharGoOn( cChar );
+    switch ( cChar )
+    {
+    case 'B':
+    case 'I':
+    case 'E':
+    case 'L':
+    case 'R':
+      xReadViews( cChar );
+      break;
+    case ']':
+      bContinueReading = false;
+      break;
+    default:
+      xError(true);
+      break;
+    }
+  }
+}
+
+Void
+TRenModSetupStrParser::xReadViews( Char cType )
+{
+  Char cChar;
+  xGetNextCharGoOn( cChar );
+  xError( cChar != '(' );
+
+  Bool bContinue = true;
+  while ( bContinue )
+  {
+    xGetNextChar( cChar );
+    if (cChar == ')')
+    {
+      xGetNextCharGoOn( cChar );
+      bContinue = false;
+    }
+    else
+    {
+      xReadViewInfo( cType );
+    }
+  }
+}
+
+Void
+TRenModSetupStrParser::xReadViewInfo( Char cType )
+{
+  std::vector<Int> aiViewNums;
+  aiViewNums.clear();
+
+  switch ( cType )
+  {
+  case 'B':
+    Char cVideoType;
+    Char cDepthType;
+
+    xGetNextCharGoOn   ( cVideoType );
+    xGetNextCharGoOn   ( cDepthType );
+    xGetViewNumberRange( aiViewNums );
+
+    if ( !m_bCurrentViewSet )
+    {
+      xError( aiViewNums.size() != 1 );
+      m_iCurrentView = aiViewNums[0] / (Int) VIEW_NUM_PREC;
+      if      ( cVideoType == 'x' )
+      {
+        m_iCurrentContent = 0;
+        m_bCurrentViewSet = true;
+      }
+      else if ( cDepthType == 'x' )
+      {
+        m_iCurrentContent = 1;
+        m_bCurrentViewSet = true;
+      }
+      else
+      {
+        xError( true );
+      }
+    }
+
+    for ( Int iIdx = 0; iIdx < aiViewNums.size(); iIdx++ )
+    {
+      xAddBaseView( aiViewNums[iIdx], cVideoType, cDepthType );
+    }
+    break;
+
+  case 'E':
+  case 'I':
+  case 'L':
+  case 'R':
+    Char cRefType;
+    xGetNextCharGoOn   ( cRefType   );
+    xGetViewNumberRange( aiViewNums );
+    for ( Int iIdx = 0; iIdx < aiViewNums.size(); iIdx++ )
+    {
+      xAddSynthView( aiViewNums[iIdx], cType, cRefType );
+    }
+  }
+}
+
+Void
+TRenModSetupStrParser::xAddBaseView( Int iViewIdx, Char cVideoType, Char cDepthType )
+{
+  AOF( m_bCurrentViewSet );
+
+  if ( cDepthType == 'x' ) cDepthType = 'o';
+  if ( cVideoType == 'x' ) cVideoType = 'o';
+
+
+
+  xError( cDepthType != 'o' && cDepthType != 'c' && cVideoType != 'r' );
+  xError( cVideoType != 'o' && cVideoType != 'c' && cVideoType != 'r' );
+  m_aiAllBaseViewIdx.push_back( iViewIdx );
+  m_aaaiBaseViewsIdx  [m_iCurrentContent][m_iCurrentView].push_back( iViewIdx          );
+  m_aaaiVideoDistMode [m_iCurrentContent][m_iCurrentView].push_back( ( cVideoType == 'c' ) ? 2 : ( (cVideoType == 'r') ? 1 :  0 ) );
+  m_aaaiDepthDistMode [m_iCurrentContent][m_iCurrentView].push_back( ( cDepthType == 'c' ) ? 2 : ( (cDepthType == 'r') ? 1 :  0 ) );
+}
+
+Void
+TRenModSetupStrParser::xAddSynthView( Int iViewNum, Char cType, Char cRefType )
+{
+  AOF( m_bCurrentViewSet );
+
+  xError( cRefType != 's' && cRefType != 'o' );
+
+  m_aiAllSynthViewNums.push_back( iViewNum );
+
+  Int iBlendMode;
+  switch ( cType )
+  {
+  case 'E':
+    iBlendMode = BLEND_NONE;
+    break;
+  case 'I':
+    iBlendMode = BLEND_AVRG;
+    break;
+  case 'L':
+    iBlendMode = BLEND_LEFT;
+    break;
+  case 'R':
+    iBlendMode = BLEND_RIGHT;
+    break;
+  default:
+    xError(false);
+    break;
+  }
+
+  m_aaaiBlendMode    [m_iCurrentContent][m_iCurrentView].push_back( iBlendMode        );
+  m_aaaiSynthViewNums[m_iCurrentContent][m_iCurrentView].push_back( iViewNum          );
+  m_aaabExtrapolate  [m_iCurrentContent][m_iCurrentView].push_back( cType    == 'E'   );
+  m_aaabOrgRef       [m_iCurrentContent][m_iCurrentView].push_back( cRefType == 'o'   );
+  m_aaaiModelNums    [m_iCurrentContent][m_iCurrentView].push_back( m_iNumberOfModels );
+
+  m_iNumberOfModels++;
+}
+
+Void
+TRenModSetupStrParser::xError( Bool bIsError )
+{
+  if ( bIsError )
+  {
+    std::cout << "RenModel setup string invalid. Last character read: " << m_iPosInStr << std::endl;
+    AOF( false );
+    exit(0);
+  }
+}
+
+Void
+TRenModSetupStrParser::xGetViewNumberRange( std::vector<Int>& raiViewNumbers )
+{
+  size_t iStartPos;
+  size_t iEndPos;
+  Char cChar;
+  xGetNextCharGoOn(cChar );
+  if (cChar == '{')
+  {
+    iStartPos = m_iPosInStr;
+    while( m_pchSetStr[m_iPosInStr] != '}' )
+    {
+      xError( m_iPosInStr == '\0' );
+      m_iPosInStr++;
+    }
+    iEndPos = m_iPosInStr - 1;
+    m_iPosInStr++;
+  }
+  else
+  {
+    iStartPos = m_iPosInStr - 1;
+    while( m_pchSetStr[m_iPosInStr] != ' ' && m_pchSetStr[m_iPosInStr] != ',' && m_pchSetStr[m_iPosInStr] != ')' )
+    {
+      xError( m_iPosInStr == '\0' );
+      m_iPosInStr++;
+    }
+    iEndPos = m_iPosInStr - 1;
+  }
+
+  size_t iNumElem = iEndPos - iStartPos + 1;
+  Char* pcTempBuffer = new Char[  iNumElem + 1];
+  strncpy( pcTempBuffer, m_pchSetStr + iStartPos, iNumElem );
+  pcTempBuffer[iNumElem] = '\0';
+
+  TAppComCamPara::convertNumberString( pcTempBuffer, raiViewNumbers, VIEW_NUM_PREC );
+  delete[] pcTempBuffer;
+}
+
+Void
+TRenModSetupStrParser::xGetNextCharGoOn( Char& rcNextChar )
+{
+  while ( m_pchSetStr[m_iPosInStr] == ' ' || m_pchSetStr[m_iPosInStr] == ',' )
+  {
+    xError( m_pchSetStr[m_iPosInStr] == '\0' );
+    m_iPosInStr++;
+  }
+  rcNextChar = m_pchSetStr[m_iPosInStr];
+  m_iPosInStr++;
+}
+
+Void
+TRenModSetupStrParser::xGetNextChar( Char& rcNextChar )
+{
+  size_t iPos = m_iPosInStr;
+  while ( ( m_pchSetStr[iPos] == ' ' || m_pchSetStr[iPos] == ',' ) && m_pchSetStr[iPos] != '\0' ) iPos++;
+  rcNextChar = m_pchSetStr[iPos];
+}
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModSetupStrParser.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 341)
@@ -0,0 +1,130 @@
+/* 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-2011, 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 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.
+ */
+#if !QC_MVHEVC_B0046
+#ifndef __TRENMODSETUPSTRPARSER__
+#define __TRENMODSETUPSTRPARSER__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "../TLibCommon/TypeDef.h"
+#include "../TAppCommon/TAppComCamPara.h"
+
+
+#include <list>
+#include <vector>
+#include <math.h>
+#include <errno.h>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+#include <functional>
+#include <string>
+#include <cstdio>
+#include <cstring>
+
+
+using namespace std;
+
+class TRenModSetupStrParser
+{
+public:
+
+  Int  getNumOfModels          ();
+  Int  getNumOfBaseViews       ();
+
+  Int  getNumOfModelsForView   ( Int iViewIdx, Int iContent );
+  Int  getNumOfBaseViewsForView( Int iViewIdx, Int iContent );
+
+  Void getSingleModelData      ( Int  iSrcViewIdx,
+                                 Int  iSrcCnt,
+                                 Int  iCurModel,
+                                 Int& riModelNum,
+                                 Int& riInterpolationType,
+                                 Int& riLeftBaseViewIdx,
+                                 Int& riRightBaseViewIdx,
+                                 Int& riOrgRefBaseViewIdx,
+                                 Int& riSynthViewRelNum
+                               );
+
+  Void getBaseViewData         ( Int   iSourceViewIdx,
+                                 Int   iSourceContent,
+                                 Int   iCurView,
+                                 Int&  riBaseViewSIdx,
+                                 Int&  riVideoDistMode,
+                                 Int&  riDepthDistMode
+                                );
+
+  std::vector<Int>* getSynthViews() { return &m_aiAllSynthViewNums;  }
+  std::vector<Int>* getBaseViews()  { return &m_aiAllBaseViewIdx;    }
+
+  TRenModSetupStrParser();
+
+  Void setString( Int iNumOfBaseViews, Char* pchSetStr );
+
+private:
+  std::vector< std::vector<Int > > m_aaaiBaseViewsIdx  [2];
+  std::vector< std::vector<Int > > m_aaaiVideoDistMode [2];
+  std::vector< std::vector<Int > > m_aaaiDepthDistMode [2];
+  std::vector< std::vector<Int > > m_aaaiModelNums     [2];
+  std::vector< std::vector<Int > > m_aaaiSynthViewNums [2];
+  std::vector< std::vector<Bool> > m_aaabOrgRef        [2];
+  std::vector< std::vector<Bool> > m_aaabExtrapolate   [2];
+  std::vector< std::vector<Int > > m_aaaiBlendMode     [2];
+
+  std::vector<Int>                 m_aiAllBaseViewIdx;
+  std::vector<Int>                 m_aiAllSynthViewNums;
+
+  Bool                             m_bCurrentViewSet;
+  Int                              m_iCurrentView;
+  Int                              m_iCurrentContent;
+  Int                              m_iNumberOfModels;
+
+  Char*                            m_pchSetStr;
+  size_t                           m_iPosInStr;
+
+private:
+  Void xParseString();
+  Void xParseSourceView();
+  Void xReadViews         ( Char cType );
+  Void xReadViewInfo      ( Char cType );
+  Void xAddBaseView       ( Int iViewIdx, Char cVideoType, Char cDepthType );
+  Void xAddSynthView      ( Int iViewNum, Char cType, Char cRefType );
+  Void xError             ( Bool bIsError );
+  Void xGetViewNumberRange( std::vector<Int>& raiViewNumbers );
+  Void xGetNextCharGoOn   ( Char& rcNextChar );
+  Void xGetNextChar       ( Char& rcNextChar );
+};
+
+#endif //__TRENMODEL__
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModel.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModel.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModel.cpp	(revision 341)
@@ -0,0 +1,700 @@
+/* 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-2011, 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 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 "TRenImage.h"
+#include "TRenFilter.h"
+#include "TRenModel.h"
+#if !QC_MVHEVC_B0046
+///////////  TRENMODEL //////////////////////
+TRenModel::TRenModel()
+{
+  m_iPad               = PICYUV_PAD;
+  m_iWidth             = -1;
+  m_iHeight            = -1;
+  m_iUsedHeight        = -1; 
+  m_iNumOfBaseViews    = -1;
+  m_iSampledWidth      = -1;
+  m_iShiftPrec         =  0;
+  m_iHoleMargin        =  1;
+  m_uiHorOff           = -1;
+#if LGE_VSO_EARLY_SKIP_A0093
+  m_bEarlySkip         = false; 
+#endif
+
+  // Current Error Type ///
+  m_iCurrentView       = -1;
+  m_iCurrentContent    = -1;
+  m_iCurrentPlane      = -1;
+
+  // Array of Models used to determine the Current Error ///
+  m_iNumOfCurRenModels = -1;
+  m_apcCurRenModels    = NULL;
+  m_aiCurPosInModels   = NULL;
+
+  // Array of Models ///
+  m_iNumOfRenModels    = -1;
+  m_apcRenModels       = NULL;
+
+  // Mapping from View number to models ///
+  m_aiNumOfModelsForDepthView = NULL;
+  m_aapcRenModelForDepthView  = NULL;
+  m_aaePosInModelForDepthView = NULL;
+
+  m_aiNumOfModelsForVideoView = NULL;
+  m_aapcRenModelForVideoView  = NULL;
+  m_aaePosInModelForVideoView = NULL;
+  m_aaeBaseViewPosInModel     = NULL;
+
+  // Data
+  m_aapiCurVideoPel      = NULL;
+  m_aaiCurVideoStrides   = NULL;
+  m_apiCurDepthPel       = NULL;
+  m_aiCurDepthStrides    = NULL;
+
+  m_aapiOrgVideoPel      = NULL;
+  m_aaiOrgVideoStrides   = NULL;
+  m_apiOrgDepthPel       = NULL;
+  m_aiOrgDepthStrides    = NULL;
+
+  m_aaaiSubPelShiftLut[0]= NULL;
+  m_aaaiSubPelShiftLut[1]= NULL;
+
+  /// Current Setup data ///
+  m_abSetupVideoFromOrgForView = NULL;
+  m_abSetupDepthFromOrgForView = NULL;
+}
+
+TRenModel::~TRenModel()
+{
+  if ( m_apcRenModels )
+  {
+    for (Int iNumModel = 0; iNumModel < m_iNumOfRenModels; iNumModel++)
+    {
+      if ( m_apcRenModels[iNumModel] ) delete m_apcRenModels[iNumModel];
+    }
+
+    delete[] m_apcRenModels;
+  }
+
+  for (Int iViewNum = 0; iViewNum < m_iNumOfBaseViews; iViewNum++)
+  {
+    if ( m_aapcRenModelForDepthView && m_aapcRenModelForDepthView [iViewNum] )
+    {
+      delete[]   m_aapcRenModelForDepthView [iViewNum];
+    }
+
+    if ( m_aaePosInModelForDepthView && m_aaePosInModelForDepthView[iViewNum] )
+    {
+      delete[]   m_aaePosInModelForDepthView[iViewNum];
+    }
+
+    if ( m_aapcRenModelForVideoView && m_aapcRenModelForVideoView[iViewNum] )
+    {
+      delete[]   m_aapcRenModelForVideoView[iViewNum];
+    }
+
+    if ( m_aaePosInModelForVideoView && m_aaePosInModelForVideoView[iViewNum] )
+    {
+      delete[]   m_aaePosInModelForVideoView[iViewNum];
+    }
+
+    if ( m_aaeBaseViewPosInModel && m_aaeBaseViewPosInModel[iViewNum] )
+    {
+      delete[]   m_aaeBaseViewPosInModel[iViewNum];
+    }
+
+    if ( m_aapiCurVideoPel && m_aapiCurVideoPel    [iViewNum] )
+    {
+      delete[] ( m_aapiCurVideoPel    [iViewNum][0] - m_iPad * m_aaiCurVideoStrides[iViewNum][0] - m_iPad );
+      delete[] ( m_aapiCurVideoPel    [iViewNum][1] - m_iPad * m_aaiCurVideoStrides[iViewNum][1] - m_iPad );
+      delete[] ( m_aapiCurVideoPel    [iViewNum][2] - m_iPad * m_aaiCurVideoStrides[iViewNum][2] - m_iPad );
+      delete[]   m_aapiCurVideoPel    [iViewNum];
+    }
+
+    if ( m_aaiCurVideoStrides && m_aaiCurVideoStrides [iViewNum] )
+    {
+      delete[]   m_aaiCurVideoStrides [iViewNum];
+    }
+
+    if ( m_apiCurDepthPel )
+    {
+      delete[] ( m_apiCurDepthPel     [iViewNum]    - m_iPad * m_aiCurDepthStrides [iViewNum]    - m_iPad );
+    }
+
+    if ( m_aapiOrgVideoPel && m_aapiOrgVideoPel    [iViewNum] )
+    {
+      delete[] ( m_aapiOrgVideoPel    [iViewNum][0] - m_iPad * m_aaiOrgVideoStrides[iViewNum][0] - m_iPad );
+      delete[] ( m_aapiOrgVideoPel    [iViewNum][1] - m_iPad * m_aaiOrgVideoStrides[iViewNum][1] - m_iPad );
+      delete[] ( m_aapiOrgVideoPel    [iViewNum][2] - m_iPad * m_aaiOrgVideoStrides[iViewNum][2] - m_iPad );
+      delete[]   m_aapiOrgVideoPel    [iViewNum];
+    }
+
+    if ( m_aaiOrgVideoStrides && m_aaiOrgVideoStrides [iViewNum] )
+    {
+      delete[]   m_aaiOrgVideoStrides [iViewNum];
+    }
+
+    if ( m_apiOrgDepthPel && m_apiOrgDepthPel     [iViewNum ] )
+    {
+      delete[] ( m_apiOrgDepthPel     [iViewNum]    - m_iPad * m_aiOrgDepthStrides [iViewNum]    - m_iPad );
+    }
+  }
+
+  if(m_aiNumOfModelsForDepthView) delete[] m_aiNumOfModelsForDepthView;
+  if(m_aapcRenModelForDepthView ) delete[] m_aapcRenModelForDepthView ;
+  if(m_aaePosInModelForDepthView) delete[] m_aaePosInModelForDepthView;
+
+  if(m_aiNumOfModelsForVideoView) delete[] m_aiNumOfModelsForVideoView;
+  if(m_aapcRenModelForVideoView ) delete[] m_aapcRenModelForVideoView ;
+  if(m_aaePosInModelForVideoView) delete[] m_aaePosInModelForVideoView;
+
+
+  if(m_aaeBaseViewPosInModel    ) delete[] m_aaeBaseViewPosInModel    ;
+  if(m_aapiCurVideoPel          ) delete[] m_aapiCurVideoPel          ;
+  if(m_aaiCurVideoStrides       ) delete[] m_aaiCurVideoStrides       ;
+
+  if(m_abSetupVideoFromOrgForView) delete[] m_abSetupVideoFromOrgForView;
+  if(m_abSetupDepthFromOrgForView) delete[] m_abSetupDepthFromOrgForView;
+
+  if(m_aapiOrgVideoPel          ) delete[] m_aapiOrgVideoPel          ;
+  if(m_aaiOrgVideoStrides       ) delete[] m_aaiOrgVideoStrides       ;
+
+  if(m_apiOrgDepthPel           ) delete[] m_apiOrgDepthPel           ;
+  if(m_aiOrgDepthStrides        ) delete[] m_aiOrgDepthStrides        ;
+
+  if(m_apiCurDepthPel           ) delete[] m_apiCurDepthPel           ;
+  if(m_aiCurDepthStrides        ) delete[] m_aiCurDepthStrides        ;
+
+  Int iNumEntries = (1 << ( m_iShiftPrec + 1) ) + 1 ;
+
+  for (UInt uiEntry = 0; uiEntry < iNumEntries; uiEntry++)
+  {
+    if ( m_aaaiSubPelShiftLut[0] && m_aaaiSubPelShiftLut[0][uiEntry] )
+      delete[] m_aaaiSubPelShiftLut[0][uiEntry];
+
+    if ( m_aaaiSubPelShiftLut[1] && m_aaaiSubPelShiftLut[1][uiEntry] )
+      delete[] m_aaaiSubPelShiftLut[1][uiEntry];
+  }
+
+  if( m_aaaiSubPelShiftLut[0] ) delete[] m_aaaiSubPelShiftLut[0];
+  if( m_aaaiSubPelShiftLut[1] ) delete[] m_aaaiSubPelShiftLut[1];
+}
+
+
+
+Void
+#if LGE_VSO_EARLY_SKIP_A0093
+TRenModel::create( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin, Bool bEarlySkip )
+#else
+TRenModel::create( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin )
+#endif
+{
+  m_iNumOfBaseViews     = iNumOfBaseViews;
+  m_iNumOfRenModels     = iNumOfModels;
+  m_iWidth              = iWidth;
+  m_iHeight             = iHeight;
+  m_iShiftPrec          = iShiftPrec;
+  m_iHoleMargin         = iHoleMargin;
+#if LGE_VSO_EARLY_SKIP_A0093
+  m_bEarlySkip          = bEarlySkip; 
+#endif
+
+
+// LUTs for sub pel shifting
+  Int iNumEntries = (1 << ( m_iShiftPrec + 1) ) + 1 ;
+  m_aaaiSubPelShiftLut[0] = new Int*[ iNumEntries ];
+  m_aaaiSubPelShiftLut[1] = new Int*[ iNumEntries ];
+  for (UInt uiEntry = 0; uiEntry < iNumEntries; uiEntry++)
+  {
+    m_aaaiSubPelShiftLut[0][uiEntry] = new Int[ iNumEntries ];
+    m_aaaiSubPelShiftLut[1][uiEntry] = new Int[ iNumEntries ];
+  }
+
+  TRenFilter::setSubPelShiftLUT( m_iShiftPrec, m_aaaiSubPelShiftLut[0], 0 );
+  TRenFilter::setSubPelShiftLUT( m_iShiftPrec, m_aaaiSubPelShiftLut[1], 0 );
+
+  m_iSampledWidth       = iWidth << m_iShiftPrec;
+
+
+  m_aapiCurVideoPel     = new Pel**     [m_iNumOfBaseViews];
+  m_aaiCurVideoStrides  = new Int*      [m_iNumOfBaseViews];
+  m_apiCurDepthPel      = new Pel*      [m_iNumOfBaseViews];
+  m_aiCurDepthStrides   = new Int       [m_iNumOfBaseViews];
+
+  m_aapiOrgVideoPel     = new Pel**     [m_iNumOfBaseViews];
+  m_aaiOrgVideoStrides  = new Int*      [m_iNumOfBaseViews];
+
+  m_apiOrgDepthPel      = new Pel*      [m_iNumOfBaseViews];
+  m_aiOrgDepthStrides   = new Int       [m_iNumOfBaseViews];
+
+  m_abSetupVideoFromOrgForView = new Bool[m_iNumOfBaseViews];
+  m_abSetupDepthFromOrgForView = new Bool[m_iNumOfBaseViews];
+
+  m_iNumOfCurRenModels   = 0;
+  m_apcCurRenModels      = NULL;
+  m_aiCurPosInModels     = NULL;
+
+  m_apcRenModels         = new TRenSingleModel*       [m_iNumOfRenModels];
+
+  m_aiNumOfModelsForDepthView = new Int               [m_iNumOfBaseViews];
+  m_aapcRenModelForDepthView  = new TRenSingleModel** [m_iNumOfBaseViews];
+  m_aaePosInModelForDepthView = new Int*              [m_iNumOfBaseViews];
+
+  m_aiNumOfModelsForVideoView = new Int               [m_iNumOfBaseViews];
+  m_aapcRenModelForVideoView  = new TRenSingleModel** [m_iNumOfBaseViews];
+  m_aaePosInModelForVideoView = new Int*              [m_iNumOfBaseViews];
+  m_aaeBaseViewPosInModel     = new Int*              [m_iNumOfBaseViews];
+
+
+  for (Int iModelNum = 0; iModelNum < m_iNumOfRenModels; iModelNum++)
+  {
+    m_apcRenModels         [iModelNum] = NULL;
+  }
+
+  for (Int iViewNum = 0; iViewNum < m_iNumOfBaseViews; iViewNum++ )
+  {
+    m_aiNumOfModelsForDepthView[ iViewNum ] = 0;
+    m_aiNumOfModelsForVideoView[ iViewNum ] = 0;
+
+    m_aapcRenModelForDepthView [iViewNum] = new TRenSingleModel*[m_iNumOfRenModels];
+    m_aapcRenModelForVideoView [iViewNum] = new TRenSingleModel*[m_iNumOfRenModels];
+
+    m_aaePosInModelForDepthView[iViewNum] = new Int             [m_iNumOfRenModels];
+    m_aaePosInModelForVideoView[iViewNum] = new Int             [m_iNumOfRenModels];
+    m_aaeBaseViewPosInModel    [iViewNum] = new Int             [m_iNumOfRenModels];
+
+    for (Int iModelNum = 0; iModelNum< m_iNumOfRenModels; iModelNum++)
+    {
+      m_aapcRenModelForDepthView [iViewNum] [iModelNum] = NULL;
+      m_aapcRenModelForVideoView [iViewNum] [iModelNum] = NULL;
+      m_aaePosInModelForDepthView[iViewNum] [iModelNum] = VIEWPOS_INVALID;
+      m_aaePosInModelForVideoView[iViewNum] [iModelNum] = VIEWPOS_INVALID;
+      m_aaeBaseViewPosInModel    [iViewNum] [iModelNum] = VIEWPOS_INVALID;
+    };
+
+    m_aaiCurVideoStrides  [iViewNum]     =  new Int[3];
+    m_aaiCurVideoStrides  [iViewNum][0]  =  m_iSampledWidth + (m_iPad << 1);
+    m_aaiCurVideoStrides  [iViewNum][1]  =  m_iSampledWidth + (m_iPad << 1);
+    m_aaiCurVideoStrides  [iViewNum][2]  =  m_iSampledWidth + (m_iPad << 1);
+
+    m_aapiCurVideoPel     [iViewNum]     = new Pel*[3];
+    m_aapiCurVideoPel     [iViewNum][0]  = new Pel [ m_aaiCurVideoStrides[iViewNum][0] * ( m_iHeight  + (m_iPad << 1) )];
+    m_aapiCurVideoPel     [iViewNum][1]  = new Pel [ m_aaiCurVideoStrides[iViewNum][1] * ( m_iHeight  + (m_iPad << 1) )];
+    m_aapiCurVideoPel     [iViewNum][2]  = new Pel [ m_aaiCurVideoStrides[iViewNum][2] * ( m_iHeight  + (m_iPad << 1) )];
+
+    m_aapiCurVideoPel     [iViewNum][0] += m_aaiCurVideoStrides[iViewNum][0] * m_iPad + m_iPad;
+    m_aapiCurVideoPel     [iViewNum][1] += m_aaiCurVideoStrides[iViewNum][1] * m_iPad + m_iPad;
+    m_aapiCurVideoPel     [iViewNum][2] += m_aaiCurVideoStrides[iViewNum][2] * m_iPad + m_iPad;
+
+    m_aiCurDepthStrides   [iViewNum]     = m_iWidth + (m_iPad << 1);
+    m_apiCurDepthPel      [iViewNum]     = new Pel[ m_aiCurDepthStrides[iViewNum] * ( m_iHeight  + (m_iPad << 1) ) ];
+    m_apiCurDepthPel      [iViewNum]    += m_aiCurDepthStrides[iViewNum] * m_iPad + m_iPad;
+
+    m_aaiOrgVideoStrides  [iViewNum]    =  new Int[3];
+    m_aaiOrgVideoStrides  [iViewNum][0] = m_iSampledWidth + (m_iPad << 1);
+    m_aaiOrgVideoStrides  [iViewNum][1] = m_iSampledWidth + (m_iPad << 1);
+    m_aaiOrgVideoStrides  [iViewNum][2] = m_iSampledWidth + (m_iPad << 1);
+
+    m_aapiOrgVideoPel     [iViewNum]     = new Pel*[3];
+    m_aapiOrgVideoPel     [iViewNum][0]  = new Pel [ m_aaiOrgVideoStrides[iViewNum][0] * ( m_iHeight  + (m_iPad << 1) )];
+    m_aapiOrgVideoPel     [iViewNum][1]  = new Pel [ m_aaiOrgVideoStrides[iViewNum][1] * ( m_iHeight  + (m_iPad << 1) )];
+    m_aapiOrgVideoPel     [iViewNum][2]  = new Pel [ m_aaiOrgVideoStrides[iViewNum][2] * ( m_iHeight  + (m_iPad << 1) )];
+
+    m_aapiOrgVideoPel     [iViewNum][0] += m_aaiOrgVideoStrides[iViewNum][0] * m_iPad + m_iPad;
+    m_aapiOrgVideoPel     [iViewNum][1] += m_aaiOrgVideoStrides[iViewNum][1] * m_iPad + m_iPad;
+    m_aapiOrgVideoPel     [iViewNum][2] += m_aaiOrgVideoStrides[iViewNum][2] * m_iPad + m_iPad;
+
+    m_aiOrgDepthStrides   [iViewNum]     = m_iWidth + (m_iPad << 1);
+    m_apiOrgDepthPel      [iViewNum]     = new Pel[ m_aiOrgDepthStrides[iViewNum] * ( m_iHeight  + (m_iPad << 1) ) ];
+    m_apiOrgDepthPel      [iViewNum]    += m_aiOrgDepthStrides[iViewNum] * m_iPad + m_iPad;
+
+    m_abSetupVideoFromOrgForView[iViewNum] = false;
+    m_abSetupDepthFromOrgForView[iViewNum] = false;
+  }
+}
+
+Void
+TRenModel::createSingleModel( Int iBaseViewNum, Int iContent, Int iModelNum, Int iLeftViewNum, Int iRightViewNum, Bool bUseOrgRef, Int iBlendMode )
+{
+  Int iMode = ( (iLeftViewNum != -1) && ( iRightViewNum != -1 ) ) ? 2 : ( iLeftViewNum != -1 ? 0 : ( iRightViewNum != -1  ? 1 : -1 ) );
+
+  AOT( iMode == -1);
+  AOT( iModelNum < 0 || iModelNum > m_iNumOfRenModels );  
+  AOT( iLeftViewNum  < -1 || iLeftViewNum  > m_iNumOfBaseViews );
+  AOT( iRightViewNum < -1 || iRightViewNum > m_iNumOfBaseViews );
+  AOT( iBaseViewNum  < -1 || iBaseViewNum  > m_iNumOfBaseViews );
+  AOT( iBaseViewNum != -1 && iBaseViewNum != iLeftViewNum && iBaseViewNum != iRightViewNum );
+  AOT( iContent      < -1 || iContent > 1 );
+  AOT( iBlendMode < -1 || iBlendMode > 2 );
+
+  Bool bBitInc = (g_uiBitIncrement != 0);
+
+  AOT( m_apcRenModels[iModelNum] );
+
+  if ( bBitInc )
+  { 
+    if ( iMode != 2 ) 
+    { // No Blending
+      m_apcRenModels[iModelNum]   = new TRenSingleModelC<BLEND_NONE, true>; 
+    }
+    else
+    {
+      switch ( iBlendMode )
+      {
+      case BLEND_AVRG: // average
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_AVRG, true>;       
+        break;
+      case BLEND_LEFT: // left  view is main view
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_LEFT, true>;       
+        break;
+      case BLEND_RIGHT: // right view is main view
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_RIGHT, true>;       
+        break;
+      default: 
+        AOT(true);
+        break;
+      }    
+    }
+  }
+  else
+  {
+    if ( iMode != 2 ) 
+    { // No Blending
+      m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_NONE, false>; 
+    }
+    else
+    {
+      switch ( iBlendMode )
+      {
+      case BLEND_AVRG: // average
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_AVRG, false>;       
+        break;
+      case BLEND_LEFT: // left  view is main view
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_LEFT, false>;       
+        break;
+      case BLEND_RIGHT: // right view is main view
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_RIGHT, false>;       
+        break;
+      default: 
+        AOT(true);
+        break;
+      }    
+    }
+  }
+
+
+#if LGE_VSO_EARLY_SKIP_A0093
+  m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, iBlendMode, m_bEarlySkip );
+#else
+  m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, iBlendMode );
+#endif
+
+  if ( iLeftViewNum != -1 )
+  {
+    xSetLRViewAndAddModel( iModelNum, iLeftViewNum, iContent,  VIEWPOS_LEFT,  (iBaseViewNum == -1  || iBaseViewNum == iLeftViewNum   ) );
+  }
+
+  if ( iRightViewNum != -1)
+  {
+    xSetLRViewAndAddModel( iModelNum, iRightViewNum, iContent, VIEWPOS_RIGHT, (iBaseViewNum == -1  || iBaseViewNum == iRightViewNum  ) );
+  }
+}
+
+Void
+TRenModel::setBaseView( Int iViewNum, TComPicYuv* pcPicYuvVideoData, TComPicYuv* pcPicYuvDepthData, TComPicYuv* pcPicYuvOrgVideoData, TComPicYuv* pcPicYuvOrgDepthData )
+{
+  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 );
+
+  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]    );
+
+  // Used for rendering reference pic from original video data
+  m_abSetupVideoFromOrgForView[iViewNum] = (pcPicYuvOrgVideoData != NULL);
+  m_abSetupDepthFromOrgForView[iViewNum] = (pcPicYuvOrgDepthData != NULL);
+
+  if ( m_abSetupVideoFromOrgForView[iViewNum] )
+  {
+    AOF( pcPicYuvOrgVideoData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvOrgVideoData->getWidth() == 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] );
+  }
+
+  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]    );
+  }
+}
+
+Void
+TRenModel::setSingleModel( Int iModelNum, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight, Int** ppiBaseShiftLutRight, Int iDistToLeft, TComPicYuv* pcPicYuvRefView )
+{
+  AOT( iModelNum < 0 || iModelNum > m_iNumOfRenModels );
+
+  m_apcRenModels[iModelNum]->setupPart( m_uiHorOff, m_iUsedHeight );
+
+  // Switch model  to original data for setup if given to render reference
+  Bool bAnyRefFromOrg = false;
+  for (Int iBaseViewIdx = 0; iBaseViewIdx < m_iNumOfBaseViews; iBaseViewIdx++ )
+  {
+    Bool bSetupFromOrgVideo = m_abSetupVideoFromOrgForView[iBaseViewIdx];
+    Bool bSetupFromOrgDepth = m_abSetupDepthFromOrgForView[iBaseViewIdx];
+    bAnyRefFromOrg          = bAnyRefFromOrg || bSetupFromOrgVideo || bSetupFromOrgDepth;
+
+    if ( m_aaeBaseViewPosInModel[iBaseViewIdx][iModelNum] != VIEWPOS_INVALID )
+    {
+      bAnyRefFromOrg = true;
+      m_apcRenModels[iModelNum]->setLRView( m_aaeBaseViewPosInModel[iBaseViewIdx][iModelNum],
+        ( bSetupFromOrgVideo ? m_aapiOrgVideoPel   : m_aapiCurVideoPel   ) [iBaseViewIdx],
+        ( bSetupFromOrgVideo ? m_aaiOrgVideoStrides: m_aaiCurVideoStrides) [iBaseViewIdx],
+        ( bSetupFromOrgDepth ? m_apiOrgDepthPel    : m_apiCurDepthPel    ) [iBaseViewIdx],
+        ( bSetupFromOrgDepth ? m_aiOrgDepthStrides : m_aiCurDepthStrides ) [iBaseViewIdx] );
+    }
+  }
+
+  m_apcRenModels[iModelNum]->setup     ( pcPicYuvRefView, ppiShiftLutLeft, ppiBaseShiftLutLeft, ppiShiftLutRight, ppiBaseShiftLutRight, iDistToLeft, false );
+
+  // Setup to Org
+  if ( bAnyRefFromOrg )
+  {
+    // Restore old values
+    for (Int iBaseViewIdx = 0; iBaseViewIdx < m_iNumOfBaseViews; iBaseViewIdx++ )
+    {
+      if ( m_aaeBaseViewPosInModel[iBaseViewIdx][iModelNum] != VIEWPOS_INVALID )
+      {
+        m_apcRenModels[iModelNum]->setLRView(
+          m_aaeBaseViewPosInModel[iBaseViewIdx][iModelNum],
+          m_aapiCurVideoPel      [iBaseViewIdx],
+          m_aaiCurVideoStrides   [iBaseViewIdx],
+          m_apiCurDepthPel       [iBaseViewIdx],
+          m_aiCurDepthStrides    [iBaseViewIdx]
+        );
+      }
+    }
+
+    // setup keeping reference rendered from original data
+    m_apcRenModels[iModelNum]->setup     ( pcPicYuvRefView, ppiShiftLutLeft, ppiBaseShiftLutLeft, ppiShiftLutRight, ppiBaseShiftLutRight, iDistToLeft, true );
+  }
+}
+
+Void
+TRenModel::setErrorMode( Int iView, Int iContent, int iPlane )
+{
+  AOT(iView > m_iNumOfBaseViews || iView < 0);
+  AOT(iContent != 0  &&  iContent != 1);
+  AOT(iPlane < 0     || iPlane > 3);
+
+  m_iCurrentView    = iView;
+  m_iCurrentContent = iContent;
+  m_iCurrentPlane   = iPlane;
+
+  if ( iContent == 1 )
+  {
+    m_iNumOfCurRenModels  = m_aiNumOfModelsForDepthView[iView];
+    m_apcCurRenModels     = m_aapcRenModelForDepthView [iView];
+    m_aiCurPosInModels    = m_aaePosInModelForDepthView[iView];
+  }
+  else
+  {
+    m_iNumOfCurRenModels  = m_aiNumOfModelsForVideoView[iView];
+    m_apcCurRenModels     = m_aapcRenModelForVideoView [iView];
+    m_aiCurPosInModels    = m_aaePosInModelForVideoView[iView];
+  }
+}
+
+
+Void
+TRenModel::setupPart ( UInt uiHorOff, Int iUsedHeight )
+{
+  AOT( iUsedHeight > m_iHeight );     
+  m_uiHorOff    = uiHorOff; 
+  m_iUsedHeight = iUsedHeight; 
+}
+
+#if LGE_VSO_EARLY_SKIP_A0093
+RMDist
+TRenModel::getDist( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel * piOrgData, Int iOrgStride)
+#else
+RMDist
+TRenModel::getDist( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+#endif
+{
+  iStartPosY -= m_uiHorOff; 
+
+  AOT( iWidth  + iStartPosX > m_iWidth  );
+  AOT( iHeight + iStartPosY > m_iUsedHeight );
+
+  AOT( iStartPosX < 0);
+  AOT( iStartPosY < 0);
+  AOT( iWidth     < 0);
+  AOT( iHeight    < 0);
+
+  RMDist iDist = 0;
+
+  for (Int iModelNum = 0; iModelNum < m_iNumOfCurRenModels; iModelNum++ )
+  {
+    if (m_iCurrentContent == 1)
+    {
+#if LGE_VSO_EARLY_SKIP_A0093
+      iDist +=  m_apcCurRenModels[iModelNum]->getDistDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY,  iWidth,  iHeight,  iStride,  piNewData , piOrgData, iOrgStride);
+#else
+      iDist +=  m_apcCurRenModels[iModelNum]->getDistDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY,  iWidth,  iHeight,  iStride,  piNewData );
+#endif
+    }
+    else
+    {
+      iDist +=  m_apcCurRenModels[iModelNum]->getDistVideo  ( m_aiCurPosInModels[iModelNum], m_iCurrentPlane ,iStartPosX, iStartPosY, iWidth, iHeight, iStride, piNewData );
+    }
+  }
+
+  return ( iDist + (m_iNumOfCurRenModels >> 1) ) / m_iNumOfCurRenModels;
+}
+
+Void
+TRenModel::setData( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  iStartPosY -= m_uiHorOff; 
+
+  iWidth  = min(iWidth , m_iWidth  - iStartPosX );
+  iHeight = min(iHeight, m_iUsedHeight - iStartPosY );
+
+  AOT( iStartPosX < 0);
+  AOT( iStartPosY < 0);
+  AOT( iWidth     < 0);
+  AOT( iHeight    < 0);
+
+  for (Int iModelNum = 0; iModelNum < m_iNumOfCurRenModels; iModelNum++ )
+  {
+    if (m_iCurrentContent == 1)
+    {
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+      Int iTargetStride = m_aiCurDepthStrides[ m_iCurrentView ];
+      m_apcCurRenModels[iModelNum]->setDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY, iWidth, iHeight, iStride, piNewData,m_apiCurDepthPel[ m_iCurrentView ] + iStartPosY * iTargetStride + iStartPosX ,iTargetStride );
+#else
+      m_apcCurRenModels[iModelNum]->setDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY, iWidth, iHeight, iStride, piNewData );
+#endif
+    }
+    else
+    {
+      m_apcCurRenModels[iModelNum]->setVideo  ( m_aiCurPosInModels[iModelNum], m_iCurrentPlane ,iStartPosX, iStartPosY,  iWidth,  iHeight,  iStride, piNewData );
+    }
+  }
+
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  if (m_iCurrentContent == 1)
+  {
+    Int iTargetStride = m_aiCurDepthStrides[ m_iCurrentView ];
+    TRenFilter::copy( piNewData, iStride, iWidth, iHeight,  m_apiCurDepthPel[ m_iCurrentView ] + iStartPosY * iTargetStride + iStartPosX, iTargetStride );
+  }
+#endif
+}
+
+Void
+TRenModel::getSynthVideo( Int iModelNum, Int iViewNum, TComPicYuv* pcPicYuv )
+{
+  m_apcRenModels[iModelNum]->getSynthVideo(iViewNum, pcPicYuv );
+}
+
+Void
+TRenModel::getSynthDepth( Int iModelNum, Int iViewNum, TComPicYuv* pcPicYuv )
+{
+  m_apcRenModels[iModelNum]->getSynthDepth(iViewNum, pcPicYuv );
+}
+
+Void
+TRenModel::getTotalSSE( Int64& riSSEY, Int64& riSSEU, Int64& riSSEV )
+{
+  TComPicYuv cPicYuvSynth;
+  cPicYuvSynth.create( m_iWidth, m_iUsedHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+
+  TComPicYuv cPicYuvTempRef;
+  cPicYuvTempRef.create( m_iWidth, m_iUsedHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+
+  Int64 iSSEY = 0;
+  Int64 iSSEU = 0;
+  Int64 iSSEV = 0;
+
+  for (Int iCurModel = 0; iCurModel < m_iNumOfCurRenModels; iCurModel++)
+  {
+    m_apcCurRenModels[iCurModel]->getSynthVideo( m_aiCurPosInModels[iCurModel], &cPicYuvSynth );    
+    m_apcCurRenModels[iCurModel]->getRefVideo  ( m_aiCurPosInModels[iCurModel], &cPicYuvTempRef   );
+
+    iSSEY += TRenFilter::SSE( cPicYuvSynth.getLumaAddr(), cPicYuvSynth.getStride(),  m_iWidth,      m_iUsedHeight     , cPicYuvTempRef.getLumaAddr(), cPicYuvTempRef.getStride() );
+    iSSEU += TRenFilter::SSE( cPicYuvSynth.getCbAddr()  , cPicYuvSynth.getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, cPicYuvTempRef.getCbAddr()  , cPicYuvTempRef.getCStride());
+    iSSEV += TRenFilter::SSE( cPicYuvSynth.getCrAddr()  , cPicYuvSynth.getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, cPicYuvTempRef.getCrAddr()  , cPicYuvTempRef.getCStride());
+  }
+
+  riSSEY = ( iSSEY + (m_iNumOfCurRenModels >> 1) ) / m_iNumOfCurRenModels;
+  riSSEU = ( iSSEU + (m_iNumOfCurRenModels >> 1) ) / m_iNumOfCurRenModels;
+  riSSEV = ( iSSEV + (m_iNumOfCurRenModels >> 1) ) / m_iNumOfCurRenModels;
+
+  cPicYuvTempRef.destroy();
+  cPicYuvSynth  .destroy();
+}
+
+Void
+TRenModel::xSetLRViewAndAddModel( Int iModelNum, Int iBaseViewNum, Int iContent, Int iViewPos, Bool bAdd )
+{
+  AOF(iViewPos == VIEWPOS_LEFT  || iViewPos == VIEWPOS_RIGHT);
+  AOF(iContent == -1 || iContent == 0 || iContent == 1);
+  AOT( iBaseViewNum  < 0 || iBaseViewNum  > m_iNumOfBaseViews );
+  AOT( m_aaeBaseViewPosInModel[iBaseViewNum][iModelNum] != VIEWPOS_INVALID );
+  m_aaeBaseViewPosInModel[iBaseViewNum][iModelNum] = iViewPos;
+
+  if (bAdd)
+  {
+    if (iContent == 0 || iContent == -1 )
+    {
+      Int iNewModelIdxForView = m_aiNumOfModelsForVideoView[iBaseViewNum]++;
+      m_aapcRenModelForVideoView [ iBaseViewNum ][ iNewModelIdxForView ] = m_apcRenModels[iModelNum];
+      m_aaePosInModelForVideoView[ iBaseViewNum ][ iNewModelIdxForView ] = iViewPos;
+    }
+
+    if (iContent == 1 || iContent == -1 )
+    {
+      Int iNewModelIdxForView = m_aiNumOfModelsForDepthView[iBaseViewNum]++;
+      m_aapcRenModelForDepthView [ iBaseViewNum ][ iNewModelIdxForView ] = m_apcRenModels[iModelNum];
+      m_aaePosInModelForDepthView[ iBaseViewNum ][ iNewModelIdxForView ] = iViewPos;
+    }
+  }
+}
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModel.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModel.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenModel.h	(revision 341)
@@ -0,0 +1,159 @@
+/* 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-2011, 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 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.
+ */
+
+#if !QC_MVHEVC_B0046
+#ifndef __TRENMODEL__
+#define __TRENMODEL__
+
+#include "TRenImage.h"
+#include "TRenSingleModel.h"
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "../TLibCommon/TypeDef.h"
+
+class TRenModel
+{
+public:
+
+  TRenModel();
+  ~TRenModel();
+
+  // Creation
+#if LGE_VSO_EARLY_SKIP_A0093
+  Void  create           ( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin, Bool bEarlySkip );
+#else
+  Void  create           ( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin );
+#endif
+  Void  createSingleModel( Int iBaseViewNum, Int iContent, Int iModelNum, Int iLeftViewNum, Int iRightViewNum, Bool bUseOrgRef, Int iBlendMode );
+
+  // Set new Frame
+  Void  setBaseView      ( Int iViewNum, TComPicYuv* pcPicYuvVideoData, TComPicYuv* pcPicYuvDepthData, TComPicYuv* pcPicYuvOrgVideoData, TComPicYuv* pcPicYuvOrgDepthData  );
+  Void  setSingleModel   ( Int iModelNum, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight, Int** ppiBaseShiftLutRight, Int iDistToLeft, TComPicYuv* pcPicYuvRefView );
+
+  // Set horizontal offset
+  Void  setupPart        ( UInt uiHorOff, Int iUsedHeight );
+
+  // Set Mode
+  Void  setErrorMode     ( Int iView, Int iContent, Int iPlane );
+
+  // Get Distortion, set Data
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  Int64 getDist          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel * piOrgData, Int iOrgStride);
+#else
+  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  );
+
+  // Get Rendered View
+
+  Void  getSynthVideo    ( Int iModelNum, Int iViewNum, TComPicYuv* pcPicYuvSynthVideo );
+  Void  getSynthDepth    ( Int iModelNum, Int iViewNum, TComPicYuv* pcPicYuvSynthDepth );
+
+  // Get Total Distortion
+  Void  getTotalSSE      (Int64& riSSEY, Int64& riSSEU, Int64& riSSEV );
+
+private:
+  // helpers
+  Void xSetLRViewAndAddModel( Int iModelNum, Int iBaseViewNum, Int iContent, Int iViewPos, Bool bAdd );
+
+  // Settings
+  Int    m_iShiftPrec;
+  Int**  m_aaaiSubPelShiftLut[2];
+  Int    m_iHoleMargin;
+#if LGE_VSO_EARLY_SKIP_A0093
+  Bool   m_bEarlySkip; 
+#endif
+
+  /// Size of Video and Depth
+  Int m_iWidth;
+  Int m_iHeight;
+  Int m_iSampledWidth;
+  Int m_iPad;
+  Int m_iUsedHeight;   // height currently used in buffer, whereas m_iHeight is the total height of the buffer
+
+
+  Int m_iNumOfBaseViews;
+
+  // Horizontal Offset in input data
+  UInt m_uiHorOff;          
+
+  /// Current Error Type ///
+  Int m_iCurrentView;
+  Int m_iCurrentContent;
+  Int m_iCurrentPlane;
+
+  /// Array of Models used to determine the Current Error ///
+  Int                m_iNumOfCurRenModels;
+  TRenSingleModel**  m_apcCurRenModels;   // Array of pointers used for determination of current error
+  Int*               m_aiCurPosInModels;  // Position of Current View in Model
+
+  /// Array of Models ///
+  Int                m_iNumOfRenModels;
+  TRenSingleModel**  m_apcRenModels;   // Array of pointers to all created models
+
+  /// Mapping from View number and Content type to models ///
+  Int*               m_aiNumOfModelsForDepthView;
+  TRenSingleModel*** m_aapcRenModelForDepthView;   // Dim1: ViewNumber
+  Int**              m_aaePosInModelForDepthView; // Position in Model ( Left or Right)
+
+  Int*               m_aiNumOfModelsForVideoView;
+  TRenSingleModel*** m_aapcRenModelForVideoView;   // Dim1: ViewNumber
+  Int**              m_aaePosInModelForVideoView; // Position in Model ( Left or Right) (local model numbering)
+
+  /// Position of Base Views in Models ( global model numbering )
+  Int**              m_aaeBaseViewPosInModel;
+
+  /// Current Setup data ///
+  Bool*              m_abSetupVideoFromOrgForView;  //: Dim1: ViewNumber, 0 ... use org; 1 ... use coded; 2; use org ref and coded in RDO
+  Bool*              m_abSetupDepthFromOrgForView;
+
+  /// DATA //
+  // Cur
+
+  /// Number of Base Views
+  Pel*** m_aapiCurVideoPel   ; // Dim1: ViewNumber: Plane  0-> Y, 1->U, 2->V
+  Int**  m_aaiCurVideoStrides; // Dim1: ViewPosition 0->Left, 1->Right; Dim2: Plane  0-> Y, 1->U, 2->V
+
+  Pel**  m_apiCurDepthPel    ; // Dim1: ViewPosition
+  Int*   m_aiCurDepthStrides ; // Dim1: ViewPosition
+
+  Pel*** m_aapiOrgVideoPel   ; // Dim1: ViewPosition  Dim2: Plane  0-> Y, 1->U, 2->V
+  Int**  m_aaiOrgVideoStrides; // Dim1: ViewPosition  Dim2: Plane  0-> Y, 1->U, 2->V
+
+  Pel**  m_apiOrgDepthPel    ;    // Dim1: ViewPosition
+  Int*   m_aiOrgDepthStrides ;    // Dim1: ViewPosition
+};
+
+#endif //__TRENMODEL__
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenSingleModel.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 341)
@@ -0,0 +1,1960 @@
+/* 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-2011, 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 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 "TRenImage.h"
+#include "TRenFilter.h"
+#include "TRenSingleModel.h"
+
+#if !QC_MVHEVC_B0046
+////////////// TRENSINGLE MODEL ///////////////
+template <BlenMod iBM, Bool bBitInc>
+TRenSingleModelC<iBM,bBitInc>::TRenSingleModelC()
+:  m_iDistShift ( g_uiBitIncrement << 1 )
+{
+  m_iWidth  = -1;
+  m_iHeight = -1;
+  m_iStride = -1;
+  m_iUsedHeight = -1; 
+  m_iHorOffset  = -1; 
+  m_iMode   = -1;
+  m_iPad    = PICYUV_PAD;
+  m_iGapTolerance = -1;
+  m_bUseOrgRef = false;
+
+  m_pcPicYuvRef          = NULL;
+
+  m_pcOutputSamples      = NULL; 
+  m_pcOutputSamplesRow   = NULL;   
+  m_iOutputSamplesStride = -1; 
+
+  m_ppiCurLUT            = NULL;
+  m_piInvZLUTLeft        = NULL;
+  m_piInvZLUTRight       = NULL;
+
+  m_aapiRefVideoPel[0]   = NULL;
+  m_aapiRefVideoPel[1]   = NULL;
+  m_aapiRefVideoPel[2]   = NULL;
+
+  m_aiRefVideoStrides[0] = -1;
+  m_aiRefVideoStrides[1] = -1;
+  m_aiRefVideoStrides[2] = -1;
+
+
+  for (UInt uiViewNum = 0 ; uiViewNum < 2; uiViewNum++)
+  {
+    // LUT
+    m_appiShiftLut[uiViewNum] = NULL;
+
+    m_pcInputSamples[uiViewNum] = NULL; 
+    m_iInputSamplesStride       = -1; 
+
+    m_ppiCurLUT               = NULL;
+    m_piInvZLUTLeft           = NULL;
+    m_piInvZLUTRight          = NULL;
+  }
+
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  m_pbHorSkip = NULL;
+#endif
+}
+
+template <BlenMod iBM, Bool bBitInc>
+TRenSingleModelC<iBM,bBitInc>::~TRenSingleModelC()
+{
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  if ( m_pbHorSkip ) 
+  {
+    delete[] m_pbHorSkip;
+    m_pbHorSkip = NULL;
+  }
+#endif
+
+  if ( m_pcInputSamples [0] ) delete[] m_pcInputSamples [0];
+  if ( m_pcInputSamples [1] ) delete[] m_pcInputSamples [1];
+
+  if ( m_pcOutputSamples    ) delete[] m_pcOutputSamples   ;
+
+  if ( m_piInvZLUTLeft  ) delete[] m_piInvZLUTLeft ;
+  if ( m_piInvZLUTRight ) delete[] m_piInvZLUTRight;
+
+  if ( m_aapiRefVideoPel[0] ) delete[] ( m_aapiRefVideoPel[0] - ( m_aiRefVideoStrides[0] * m_iPad + m_iPad ) );
+  if ( m_aapiRefVideoPel[1] ) delete[] ( m_aapiRefVideoPel[1] - ( m_aiRefVideoStrides[1] * m_iPad + m_iPad ) );
+  if ( m_aapiRefVideoPel[2] ) delete[] ( m_aapiRefVideoPel[2] - ( m_aiRefVideoStrides[2] * m_iPad + m_iPad ) );
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+#if LGE_VSO_EARLY_SKIP_A0093
+TRenSingleModelC<iBM,bBitInc>::create( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode, Bool bEarlySkip )
+#else
+TRenSingleModelC<iBM,bBitInc>::create( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode )
+#endif
+
+{
+#if LGE_VSO_EARLY_SKIP_A0093
+  m_pbHorSkip     = new Bool [MAX_CU_SIZE];
+  m_bEarlySkip    = bEarlySkip; 
+#endif
+
+  AOF( iBlendMode == iBM ); 
+
+  m_iMode = iMode;
+
+  m_iWidth  = iWidth;
+  m_iHeight = iHeight;
+  m_iStride = iWidth;
+
+  m_iSampledWidth  = m_iWidth  << iShiftPrec;
+  m_iSampledStride = m_iStride << iShiftPrec;
+
+  m_iShiftPrec     = iShiftPrec;
+  m_aaiSubPelShiftL = aaaiSubPelShiftTable[0];
+  m_aaiSubPelShiftR = aaaiSubPelShiftTable[1];
+
+  if (m_iMode == 2)
+  {
+    m_piInvZLUTLeft  = new Int[257];
+    m_piInvZLUTRight = new Int[257];
+  }
+
+  m_iGapTolerance  = ( 2 << iShiftPrec );
+  m_iHoleMargin    =  iHoleMargin;
+
+  m_bUseOrgRef = bUseOrgRef;
+
+  m_aiRefVideoStrides[0] = m_iStride + (m_iPad << 1);
+  m_aiRefVideoStrides[1] = m_iStride + (m_iPad << 1);
+  m_aiRefVideoStrides[2] = m_iStride + (m_iPad << 1);
+
+  m_aapiRefVideoPel  [0] = new Pel[ m_aiRefVideoStrides[0] * (m_iHeight + (m_iPad << 1))];
+  m_aapiRefVideoPel  [1] = new Pel[ m_aiRefVideoStrides[1] * (m_iHeight + (m_iPad << 1))];
+  m_aapiRefVideoPel  [2] = new Pel[ m_aiRefVideoStrides[2] * (m_iHeight + (m_iPad << 1))];
+
+  m_aapiRefVideoPel  [0] += m_aiRefVideoStrides[0] * m_iPad + m_iPad;
+  m_aapiRefVideoPel  [1] += m_aiRefVideoStrides[1] * m_iPad + m_iPad;
+  m_aapiRefVideoPel  [2] += m_aiRefVideoStrides[2] * m_iPad + m_iPad;
+
+  m_iInputSamplesStride  = m_iWidth+1;
+  m_iOutputSamplesStride = m_iWidth;
+
+  m_pcInputSamples[0]     = new RenModelInPels[m_iInputSamplesStride*m_iHeight];
+  m_pcInputSamples[1]     = new RenModelInPels[m_iInputSamplesStride*m_iHeight];
+
+  m_pcOutputSamples       = new RenModelOutPels[m_iOutputSamplesStride*m_iHeight];  
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setLRView( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride )
+{
+  AOF(( iViewPos == 0) || (iViewPos == 1) );
+
+  RenModelInPels* pcCurInputSampleRow = m_pcInputSamples[iViewPos];
+  
+  Pel* piDRow = piCurDepthPel;
+  Pel* piYRow = apiCurVideoPel[0];
+#if HHI_VSO_COLOR_PLANES
+  Pel* piURow = apiCurVideoPel[1];
+  Pel* piVRow = apiCurVideoPel[2];
+#endif  
+
+
+  Int iOffsetX = ( iViewPos == VIEWPOS_RIGHT ) ? 1 : 0;
+
+  for ( Int iPosY = 0; iPosY < m_iUsedHeight; iPosY++ )
+  {
+    if ( iViewPos == VIEWPOS_RIGHT )
+    {
+      Int iSubPosX = (1 << m_iShiftPrec); 
+      pcCurInputSampleRow[0].aiY[iSubPosX] = piYRow[0];
+#if HHI_VSO_COLOR_PLANES 
+      pcCurInputSampleRow[0].aiU[iSubPosX] = piURow[0];
+      pcCurInputSampleRow[0].aiV[iSubPosX] = piVRow[0];
+#endif
+    }
+
+    for ( Int iPosX = 0; iPosX < m_iWidth; iPosX++ )
+    {
+      pcCurInputSampleRow[iPosX].iD = piDRow[iPosX];
+
+      for (Int iSubPosX = 0; iSubPosX < (1 << m_iShiftPrec)+1; iSubPosX++ )
+      { 
+        Int iShift = (iPosX << m_iShiftPrec) + iSubPosX;
+        pcCurInputSampleRow[iPosX+iOffsetX].aiY[iSubPosX] = piYRow[iShift];
+#if HHI_VSO_COLOR_PLANES 
+        pcCurInputSampleRow[iPosX+iOffsetX].aiU[iSubPosX] = piURow[iShift];
+        pcCurInputSampleRow[iPosX+iOffsetX].aiV[iSubPosX] = piVRow[iShift];
+#endif
+      }
+    } 
+
+    pcCurInputSampleRow += m_iInputSamplesStride; 
+
+    piDRow += iCurDepthStride;
+    piYRow += aiCurVideoStride[0];
+#if HHI_VSO_COLOR_PLANES
+    piURow += aiCurVideoStride[1];
+    piVRow += aiCurVideoStride[2];
+#endif
+  }
+
+  
+  m_aapiBaseVideoPel      [iViewPos] = apiCurVideoPel;
+  m_aaiBaseVideoStrides   [iViewPos] = aiCurVideoStride;
+  m_apiBaseDepthPel       [iViewPos] = piCurDepthPel;
+  m_aiBaseDepthStrides    [iViewPos] = iCurDepthStride;
+
+}
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setupPart ( UInt uiHorOffset,       Int iUsedHeight )
+{
+  AOT( iUsedHeight > m_iHeight );   
+
+  m_iUsedHeight =       iUsedHeight; 
+  m_iHorOffset  = (Int) uiHorOffset;
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setup( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft, Bool bKeepReference )
+{
+  AOT( !m_bUseOrgRef && pcOrgVideo );
+  AOT( (ppiShiftLutLeft  == NULL) && (m_iMode == 0 || m_iMode == 2) );
+  AOT( (ppiShiftLutRight == NULL) && (m_iMode == 1 || m_iMode == 2) );
+
+  m_appiShiftLut[0] = ppiShiftLutLeft;
+  m_appiShiftLut[1] = ppiShiftLutRight;
+
+  // Copy Reference
+  m_pcPicYuvRef = pcOrgVideo;
+
+  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]);    
+    xSetStructRefView();
+  }
+
+  // Initial Rendering
+  xResetStructError();
+  xInitSampleStructs();
+  switch ( m_iMode )
+  {  
+  case 0:   
+#if LGE_VSO_EARLY_SKIP_A0093
+    xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0],false );
+#else
+    xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0] );
+#endif   
+    break;
+  case 1:    
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+    xRenderR<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1],false);
+#else
+    xRenderR<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1] );
+#endif
+    break;
+  case 2:
+    TRenFilter::setupZLUT( true, 30, iDistToLeft, ppiBaseShiftLutLeft, ppiBaseShiftLutRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight );
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+    xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0],false);
+    xRenderR<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1],false);
+#else      
+    xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0] );
+    xRenderR<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1] );
+#endif
+    break;
+  default:
+    AOT(true);
+  }
+
+  // Get Rendered View as Reference
+  if ( !pcOrgVideo && !bKeepReference )
+  {
+    xResetStructError();
+    xSetStructSynthViewAsRefView();
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+#if HHI_VSO_COLOR_PLANES
+TRenSingleModelC<iBM,bBitInc>::xGetSampleStrTextPtrs( Int iViewNum, Pel RenModelOutPels::*& rpiSrcY, Pel RenModelOutPels::*& rpiSrcU, Pel RenModelOutPels::*& rpiSrcV )
+#else
+TRenSingleModelC<iBM,bBitInc>::xGetSampleStrTextPtrs( Int iViewNum, Pel RenModelOutPels::*& rpiSrcY )
+#endif
+{
+  switch ( iViewNum )
+  {
+  case 0:
+    rpiSrcY = &RenModelOutPels::iYLeft;
+#if HHI_VSO_COLOR_PLANES  
+    rpiSrcU = &RenModelOutPels::iULeft;
+    rpiSrcV = &RenModelOutPels::iVLeft;
+#endif
+    break;
+  case 1:
+    rpiSrcY = &RenModelOutPels::iYRight;
+#if HHI_VSO_COLOR_PLANES  
+    rpiSrcU = &RenModelOutPels::iURight;
+    rpiSrcV = &RenModelOutPels::iVRight;
+#endif
+    break;
+  case 2:
+    rpiSrcY = &RenModelOutPels::iYBlended;
+#if HHI_VSO_COLOR_PLANES  
+    rpiSrcU = &RenModelOutPels::iUBlended;
+    rpiSrcV = &RenModelOutPels::iVBlended;
+#endif
+    break;
+  }
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xGetSampleStrDepthPtrs( Int iViewNum, Pel RenModelOutPels::*& rpiSrcD )
+{
+  AOT(iViewNum != 0 && iViewNum != 1);  
+  rpiSrcD = (iViewNum == 1) ? &RenModelOutPels::iDRight : &RenModelOutPels::iDLeft; 
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetStructRefView( )
+{
+  RenModelOutPels* pcCurOutSampleRow = m_pcOutputSamples;
+  
+  Pel* piYRow = m_aapiRefVideoPel[0];
+#if HHI_VSO_COLOR_PLANES
+  Pel* piURow = m_aapiRefVideoPel[1];
+  Pel* piVRow = m_aapiRefVideoPel[2];
+#endif  
+
+  for ( Int iPosY = 0; iPosY < m_iUsedHeight; iPosY++ )
+  {
+    for ( Int iPosX = 0; iPosX < m_iWidth; iPosX++ )
+    {      
+      pcCurOutSampleRow[iPosX].iYRef = piYRow[iPosX];
+#if HHI_VSO_COLOR_PLANES
+      pcCurOutSampleRow[iPosX].iURef = piURow[iPosX];
+      pcCurOutSampleRow[iPosX].iVRef = piVRow[iPosX];
+#endif
+    } 
+
+    pcCurOutSampleRow += m_iOutputSamplesStride; 
+    
+    piYRow += m_aiRefVideoStrides[0];
+#if HHI_VSO_COLOR_PLANES
+    piURow += m_aiRefVideoStrides[1];
+    piVRow += m_aiRefVideoStrides[2];
+#endif
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xResetStructError( )
+{
+  RenModelOutPels* pcCurOutSampleRow = m_pcOutputSamples;
+
+  for ( Int iPosY = 0; iPosY < m_iHeight; iPosY++ )
+  {
+    for ( Int iPosX = 0; iPosX < m_iWidth; iPosX++ )
+    {      
+      pcCurOutSampleRow[iPosX].iError = 0;
+    } 
+    pcCurOutSampleRow += m_iOutputSamplesStride; 
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetStructSynthViewAsRefView( )
+{
+  AOT( m_iMode < 0 || m_iMode > 2);
+
+  RenModelOutPels* pcCurOutSampleRow = m_pcOutputSamples;
+
+  Pel RenModelOutPels::* piSrcY = NULL;
+
+#if HHI_VSO_COLOR_PLANES  
+  Pel RenModelOutPels::* piSrcU = NULL;
+  Pel RenModelOutPels::* piSrcV = NULL;
+  xGetSampleStrTextPtrs( m_iMode, piSrcY, piSrcU, piSrcV );
+#else
+  xGetSampleStrTextPtrs( m_iMode, piSrcY );
+#endif
+
+  for ( Int iPosY = 0; iPosY < m_iUsedHeight; iPosY++ )
+  {
+    for ( Int iPosX = 0; iPosX < m_iWidth; iPosX++ )
+    {      
+      pcCurOutSampleRow[iPosX].iYRef = pcCurOutSampleRow[iPosX].*piSrcY;
+#if HHI_VSO_COLOR_PLANES
+      pcCurOutSampleRow[iPosX].iURef = pcCurOutSampleRow[iPosX].*piSrcU;
+      pcCurOutSampleRow[iPosX].iVRef = pcCurOutSampleRow[iPosX].*piSrcV;
+#endif
+    } 
+    pcCurOutSampleRow += m_iOutputSamplesStride; 
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xInitSampleStructs()
+{
+  RenModelOutPels* pcOutSampleRow      = m_pcOutputSamples;
+  RenModelInPels * pcLeftInSampleRow   = m_pcInputSamples[0];
+  RenModelInPels * pcRightInSampleRow  = m_pcInputSamples[1];
+
+
+  for (Int iPosY = 0; iPosY < m_iHeight; iPosY++)
+  {
+    for (Int iPosX = 0; iPosX < m_iWidth; iPosX++)
+    {
+      //// Output Samples
+      pcOutSampleRow[iPosX].iFilledLeft   = REN_IS_HOLE;
+      pcOutSampleRow[iPosX].iFilledRight  = REN_IS_HOLE;
+
+      pcOutSampleRow[iPosX].iDLeft        = 0;
+      pcOutSampleRow[iPosX].iDRight       = 0;
+      pcOutSampleRow[iPosX].iDBlended     = 0;      
+                                     
+      // Y Planes                    
+      pcOutSampleRow[iPosX].iYLeft        = 0;
+      pcOutSampleRow[iPosX].iYRight       = 0;
+      pcOutSampleRow[iPosX].iYBlended     = 0;
+#if HHI_VSO_COLOR_PLANES             
+      // U Planes                    
+      pcOutSampleRow[iPosX].iULeft        = 128 << g_uiBitIncrement;
+      pcOutSampleRow[iPosX].iURight       = 128 << g_uiBitIncrement;
+      pcOutSampleRow[iPosX].iUBlended     = 128 << g_uiBitIncrement;
+                                     
+      // V Planes                    
+      pcOutSampleRow[iPosX].iVLeft        = 128 << g_uiBitIncrement;
+      pcOutSampleRow[iPosX].iVRight       = 128 << g_uiBitIncrement;
+      pcOutSampleRow[iPosX].iVBlended     = 128 << g_uiBitIncrement;
+#endif
+      //// Input Samples
+      pcLeftInSampleRow [iPosX].bOccluded = false;
+      pcRightInSampleRow[iPosX].bOccluded = false;
+    }
+
+    pcOutSampleRow     += m_iOutputSamplesStride;
+    pcLeftInSampleRow  += m_iInputSamplesStride;
+    pcRightInSampleRow += m_iInputSamplesStride;
+  }  
+}
+
+
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+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 )
+#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 )
+#endif
+{
+  RMDist iSSE = 0;
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  Bool   bEarlySkip;
+#endif
+  switch ( iViewPos )
+  {
+  case 0:
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+    bEarlySkip = m_bEarlySkip ? xDetectEarlySkipL(iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, piOrgData, iOrgStride) : false;
+    if( !bEarlySkip )
+    {
+      iSSE = xRenderL<false>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData,true );
+    }    
+#else
+    iSSE = xRenderL<false>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData );
+#endif
+    break;
+  case 1:
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+    bEarlySkip = m_bEarlySkip ? xDetectEarlySkipR(iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, piOrgData, iOrgStride) : false;
+    if( !bEarlySkip )
+    {
+      iSSE = xRenderR<false>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData,true );
+    }    
+#else
+    iSSE = xRenderR<false>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData );
+#endif
+    break;
+  default:
+    assert(0);
+  }
+
+  return iSSE;
+}
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+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 )
+#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 )
+#endif
+{
+#ifdef  LGE_VSO_EARLY_SKIP_A0093
+  Bool bEarlySkip;
+#endif
+  switch ( iViewPos )
+  {
+  case 0:
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+    bEarlySkip = m_bEarlySkip ? xDetectEarlySkipL(iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, piOrgData,iOrgStride) : false;
+    if( !bEarlySkip )
+    {
+      xRenderL<true>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData,true );
+    }    
+#else
+    xRenderL<true>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData );
+#endif     
+    break;
+  case 1:
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+    bEarlySkip = m_bEarlySkip ? xDetectEarlySkipR(iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, piOrgData,iOrgStride) : false;
+    if( !bEarlySkip )
+    {
+      xRenderR<true>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData,true ); 
+    }    
+#else
+    xRenderR<true>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData );
+#endif     
+    break;
+  default:
+    assert(0);
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::getSynthVideo( Int iViewPos, TComPicYuv* pcPicYuv )
+{  
+  AOT( pcPicYuv->getWidth() != m_iWidth );
+  AOT( pcPicYuv->getHeight() < m_iUsedHeight + m_iHorOffset );
+
+#if HHI_VSO_COLOR_PLANES
+  Pel RenModelOutPels::* piText[3] = { NULL, NULL, NULL };
+  xGetSampleStrTextPtrs(iViewPos, piText[0], piText[1], piText[2]); 
+
+  // Temp image for chroma down sampling
+  PelImage cTempImage( m_iWidth, m_iUsedHeight, 3, 0);
+
+  Int  aiStrides[3]; 
+  Pel* apiData  [3]; 
+
+  cTempImage.getDataAndStrides( apiData, aiStrides ); 
+
+  for (UInt uiCurPlane = 0; uiCurPlane < 3; uiCurPlane++ )
+  {
+    xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piText[uiCurPlane], apiData[uiCurPlane], aiStrides[uiCurPlane] , m_iWidth, m_iUsedHeight);
+  }  
+  xCopy2PicYuv( apiData, aiStrides, pcPicYuv );
+#else
+  Pel RenModelOutPels::* piY;
+  xGetSampleStrTextPtrs(iViewPos, piY); 
+  xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piY, pcPicYuv->getLumaAddr() + m_iHorOffset * pcPicYuv->getStride(), pcPicYuv->getStride(), m_iWidth, m_iUsedHeight );
+  pcPicYuv->setChromaTo( 128 << g_uiBitIncrement );   
+#endif  
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::getSynthDepth( Int iViewPos, TComPicYuv* pcPicYuv )
+{  
+  AOT( iViewPos != 0 && iViewPos != 1); 
+  AOT( pcPicYuv->getWidth()  != m_iWidth  );
+  AOT( pcPicYuv->getHeight() < 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( 128 << g_uiBitIncrement );   
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::getRefVideo ( Int iViewPos, TComPicYuv* pcPicYuv )
+{  
+  AOT( pcPicYuv->getWidth()  != m_iWidth  );
+  AOT( pcPicYuv->getHeight() <  m_iUsedHeight + m_iHorOffset);
+
+#if HHI_VSO_COLOR_PLANES
+  Pel RenModelOutPels::* piText[3];
+  piText[0] = &RenModelOutPels::iYRef;
+  piText[1] = &RenModelOutPels::iURef;
+  piText[2] = &RenModelOutPels::iVRef;
+
+  // Temp image for chroma down sampling
+
+  PelImage cTempImage( m_iWidth, m_iUsedHeight, 3, 0);
+  Int  aiStrides[3]; 
+  Pel* apiData  [3]; 
+
+  cTempImage.getDataAndStrides( apiData, aiStrides ); 
+
+  for (UInt uiCurPlane = 0; uiCurPlane < 3; uiCurPlane++ )
+  {
+    xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piText[uiCurPlane], apiData[uiCurPlane], aiStrides[uiCurPlane] , m_iWidth, m_iUsedHeight);
+  }  
+
+  xCopy2PicYuv( apiData, aiStrides, pcPicYuv );
+#else
+  xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, &RenModelOutPels::iYRef, pcPicYuv->getLumaAddr() *  pcPicYuv->getStride() + m_iHorOffset, pcPicYuv->getStride(), m_iWidth, m_iUsedHeight );
+  pcPicYuv->setChromaTo( 128 << g_uiBitIncrement );   
+#endif  
+}
+
+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 )
+{
+  AOF(false);
+  return 0;
+}
+
+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 )
+{
+  AOF(false);
+}
+
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetViewRow( Int iPosY )
+{
+  m_pcInputSamplesRow[0] = m_pcInputSamples[0] + m_iInputSamplesStride  * iPosY;
+  m_pcInputSamplesRow[1] = m_pcInputSamples[1] + m_iInputSamplesStride  * iPosY;
+  m_pcOutputSamplesRow   = m_pcOutputSamples   + m_iOutputSamplesStride * iPosY;  
+
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xIncViewRow( )
+{
+  m_pcInputSamplesRow[0] += m_iInputSamplesStride ;
+  m_pcInputSamplesRow[1] += m_iInputSamplesStride ;
+  m_pcOutputSamplesRow   += m_iOutputSamplesStride;  
+}
+#if LGE_VSO_EARLY_SKIP_A0093
+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)
+#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)
+#endif
+{
+  const Int iCurViewPos   = 0;
+  const Int iOtherViewPos = 1;
+
+  m_iCurViewPos   = iCurViewPos  ; 
+  m_iOtherViewPos = iOtherViewPos;
+
+  m_piNewDepthData   = piNewData;
+  m_iNewDataWidth    = iWidth;
+  m_iStartChangePosX = iStartPosX;
+
+  if ((iWidth == 0) || (iHeight == 0))
+    return 0;
+
+  // Get Data
+  m_ppiCurLUT      = m_appiShiftLut   [iCurViewPos];
+  xSetViewRow      ( iStartPosY);
+
+  // Init Start
+  RMDist iError = 0;
+  Int   iStartChangePos;
+
+  iStartChangePos = m_iStartChangePosX;
+
+  for (Int iPosY = iStartPosY; iPosY < iStartPosY + iHeight; iPosY++ )
+  {
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+    if( m_bEarlySkip && bFast )
+    {
+      if ( m_pbHorSkip[iPosY-iStartPosY] )
+      {
+        xIncViewRow();
+        m_piNewDepthData += iStride;
+        continue;
+      }
+    }
+#endif
+    m_bInOcclusion = false;
+
+    Int iLastSPos;
+    Int iEndChangePos         = m_iStartChangePosX + iWidth - 1;
+    Int iPosXinNewData        = iWidth - 1;
+    Int iMinChangedSPos       = m_iSampledWidth;
+
+    if ( iEndChangePos == ( m_iWidth -1 )) // Special processing for rightmost depth sample
+    {
+      m_iCurDepth           = m_piNewDepthData[iPosXinNewData];
+      Int iCurSPos          = xShiftNewData(iEndChangePos, iPosXinNewData);
+      m_iLastOccludedSPos   = iCurSPos + 1;
+      m_iLastOccludedSPosFP = xRangeLeftL( m_iLastOccludedSPos );
+      xExtrapolateMarginL<bSet>  ( iCurSPos, iEndChangePos, iError );
+
+      iMinChangedSPos       = Min( iMinChangedSPos, (iEndChangePos << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( Max(m_pcInputSamplesRow[iCurViewPos][iEndChangePos].iD, m_piNewDepthData[iPosXinNewData] )) ]);
+      iLastSPos             = iCurSPos;
+      m_iLastDepth          = m_iCurDepth;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][iEndChangePos].iD = m_piNewDepthData[iPosXinNewData];
+      }
+
+      iPosXinNewData--;
+      iEndChangePos--;
+    }
+    else
+    {
+      iLastSPos    = xShift(iEndChangePos+1);
+      m_iLastDepth = m_pcInputSamplesRow [iCurViewPos][iEndChangePos+1].iD;
+      xInitRenderPartL( iEndChangePos, iLastSPos );
+    }
+
+    //// RENDER NEW DATA
+    Int iCurPosX;
+    for ( iCurPosX = iEndChangePos; iCurPosX >= iStartChangePos; iCurPosX-- )
+    {
+      // Get minimal changed sample position
+
+      iMinChangedSPos = Min( iMinChangedSPos, (iCurPosX << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( Max(m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD, m_piNewDepthData[iPosXinNewData] )) ]);
+      Int iCurSPos    = xShiftNewData(iCurPosX,iPosXinNewData);
+      m_iCurDepth     = m_piNewDepthData[iPosXinNewData];
+      xRenderRangeL<bSet>(iCurSPos, iLastSPos, iCurPosX, iError );
+      iLastSPos       = iCurSPos;
+      m_iLastDepth    = m_iCurDepth;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD = m_piNewDepthData[iPosXinNewData];
+      }
+
+      iPosXinNewData--;
+    }
+
+    //// RE-RENDER DATA LEFT TO NEW DATA
+    while ( iCurPosX >= 0 )
+    {
+      Int iCurSPos = xShift(iCurPosX);
+
+      m_iCurDepth  = m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD;
+      xRenderRangeL<bSet>( iCurSPos, iLastSPos, iCurPosX, iError );
+
+      if ( iCurSPos < iMinChangedSPos )
+      {
+          break;
+      }
+
+      iCurPosX--;
+      iLastSPos    = iCurSPos;
+      m_iLastDepth = m_iCurDepth;
+    }
+
+
+    xIncViewRow();
+    m_piNewDepthData += iStride;
+  }
+  return iError;
+}
+
+#ifdef  LGE_VSO_EARLY_SKIP_A0093
+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)
+#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 )
+#endif
+{
+
+  const Int iCurViewPos   = 1;
+  const Int iOtherViewPos = 0;
+
+  m_iCurViewPos      = iCurViewPos;
+  m_iOtherViewPos    = iOtherViewPos;
+
+  m_piNewDepthData   = piNewData;
+  m_iNewDataWidth    = iWidth;
+  m_iStartChangePosX = iStartPosX;
+
+  if ((iWidth == 0) || (iHeight == 0))
+    return 0;
+
+  // Get Data
+  m_ppiCurLUT      = m_appiShiftLut   [iCurViewPos];
+  xSetViewRow      ( iStartPosY);
+
+  // Init Start
+  RMDist iError = 0;
+  Int   iEndChangePos;
+
+  iEndChangePos = m_iStartChangePosX + iWidth - 1;
+
+  for (Int iPosY = iStartPosY; iPosY < iStartPosY + iHeight; iPosY++ )
+  {
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+    if( m_bEarlySkip && bFast )
+    {
+      if ( m_pbHorSkip[iPosY-iStartPosY] )
+      {
+        xIncViewRow();
+        m_piNewDepthData += iStride;
+        continue;
+      }
+    }
+#endif
+    m_bInOcclusion = false;
+
+    Int iLastSPos;
+    Int iStartChangePos       = m_iStartChangePosX;
+    Int iPosXinNewData        = 0;
+    Int iMaxChangedSPos = -1;
+
+    if ( iStartChangePos == 0 ) // Special processing for leftmost depth sample
+    {
+      m_iCurDepth           = m_piNewDepthData[iPosXinNewData];
+      Int iCurSPos          = xShiftNewData(iStartChangePos, iPosXinNewData);
+      m_iLastOccludedSPos   = iCurSPos - 1;
+      m_iLastOccludedSPosFP = xRangeRightR( m_iLastOccludedSPos );
+      xExtrapolateMarginR<bSet>     ( iCurSPos, iStartChangePos, iError );
+
+      iMaxChangedSPos       = Max( iMaxChangedSPos, (iStartChangePos << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( Max(m_pcInputSamplesRow[iCurViewPos][iStartChangePos].iD, m_piNewDepthData[iPosXinNewData] )) ]);
+      iLastSPos             = iCurSPos;
+      m_iLastDepth          = m_iCurDepth;
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][iStartChangePos].iD = m_piNewDepthData[iPosXinNewData];
+      }
+
+
+      iPosXinNewData++;
+      iStartChangePos++;
+    }
+    else
+    {
+      iLastSPos   = xShift(iStartChangePos-1);
+
+      m_iLastDepth = m_pcInputSamplesRow[iCurViewPos][iStartChangePos-1].iD;
+      xInitRenderPartR( iStartChangePos, iLastSPos );
+    }
+
+    //// RENDER NEW DATA
+    Int iCurPosX;
+    for ( iCurPosX = iStartChangePos; iCurPosX <= iEndChangePos; iCurPosX++ )
+    {
+      // Get minimal changed sample position
+
+      iMaxChangedSPos = Max( iMaxChangedSPos, (iCurPosX << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( Max(m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD, m_piNewDepthData[iPosXinNewData] )) ]);
+      Int iCurSPos    = xShiftNewData(iCurPosX,iPosXinNewData);
+      m_iCurDepth     = m_piNewDepthData[iPosXinNewData];
+      xRenderRangeR<bSet>(iCurSPos, iLastSPos, iCurPosX, iError );
+      iLastSPos      = iCurSPos;
+      m_iLastDepth    = m_iCurDepth;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD = m_piNewDepthData[iPosXinNewData];
+      }
+
+      iPosXinNewData++;
+    }
+
+    //// RE-RENDER DATA LEFT TO NEW DATA
+    while ( iCurPosX < m_iWidth )
+    {
+      Int iCurSPos = xShift(iCurPosX);
+
+      m_iCurDepth  = m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD;
+      xRenderRangeR<bSet>( iCurSPos, iLastSPos, iCurPosX, iError );
+
+      if ( iCurSPos > iMaxChangedSPos )
+      {
+          break;
+        }
+      iCurPosX++;
+      iLastSPos    = iCurSPos;
+      m_iLastDepth = m_iCurDepth;
+    }
+
+    xIncViewRow();
+    m_piNewDepthData += iStride;
+  }
+  return iError;
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xInitRenderPartL(  Int iEndChangePos, Int iLastSPos )
+{
+  const Int iCurViewPos = 0; 
+  // GET MINIMAL OCCLUDED SAMPLE POSITION
+  Int iCurPosX           = iEndChangePos;
+
+
+  if ( ( iCurPosX + 1 < m_iWidth ) && (m_pcInputSamplesRow[iCurViewPos][ iCurPosX + 1].bOccluded ) )
+  {
+    iCurPosX++;
+
+    while ( (iCurPosX + 1 < m_iWidth) &&  (m_pcInputSamplesRow[iCurViewPos][ iCurPosX + 1].bOccluded  )  )
+
+      iCurPosX++;
+
+    if ( iCurPosX + 1 < m_iWidth )
+    {
+      iCurPosX++;
+      m_iLastOccludedSPos = xShift(iCurPosX);
+    }
+    else
+    {
+      m_iLastOccludedSPos = xShift(iCurPosX) + 1;
+    }
+
+    m_iLastOccludedSPosFP = xRoundL( m_iLastOccludedSPos );
+  }
+  else
+  {
+    m_iLastOccludedSPos   = iLastSPos+1;
+    m_iLastOccludedSPosFP = xRangeLeftL( m_iLastOccludedSPos );
+  }
+
+  m_bInOcclusion = iLastSPos >= m_iLastOccludedSPos;
+};
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xInitRenderPartR(  Int iStartChangePos, Int iLastSPos )
+{
+    const Int iCurViewPos = 1; 
+  // GET MINIMAL OCCLUDED SAMPLE POSITION
+  Int iCurPosX           = iStartChangePos;
+
+  if ( ( iCurPosX - 1 > -1 ) && (m_pcInputSamplesRow[iCurViewPos][ iCurPosX - 1].bOccluded  ) )
+  {
+    iCurPosX--;
+
+    while ( (iCurPosX - 1 > -1 ) &&  (m_pcInputSamplesRow[iCurViewPos][ iCurPosX - 1].bOccluded  )  )
+      iCurPosX--;
+
+    if ( iCurPosX - 1 > -1 )
+    {
+      iCurPosX--;
+      m_iLastOccludedSPos = xShift(iCurPosX);
+    }
+    else
+    {
+      m_iLastOccludedSPos = xShift(iCurPosX) - 1;
+    }
+    m_iLastOccludedSPosFP = xRoundR( m_iLastOccludedSPos );
+  }
+  else
+  {
+    m_iLastOccludedSPos   = iLastSPos-1;
+    m_iLastOccludedSPosFP = xRangeRightR( m_iLastOccludedSPos );
+  }
+
+  m_bInOcclusion = iLastSPos <= m_iLastOccludedSPos;
+};
+
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xRenderShiftedRangeL(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  assert( iCurSPos <= iLastSPos );
+  //assert( iRightSPos < m_iWidth );
+
+  Int iDeltaSPos = iLastSPos - iCurSPos;
+  if ( iDeltaSPos > m_iGapTolerance )
+  {
+    xFillHoleL<bSet>( iCurSPos, iLastSPos, iCurPos, riError );
+  }
+  else
+  {
+    if (iLastSPos < 0 )
+      return;
+
+    RM_AOT( iDeltaSPos    > m_iGapTolerance );
+
+    m_iThisDepth = m_iCurDepth;
+    for (Int iFillSPos = Max(0, xRangeLeftL(iCurSPos) ); iFillSPos <= min(xRangeRightL( iLastSPos ) ,m_iLastOccludedSPosFP-1); iFillSPos++ )
+    {
+      Int iDeltaCurSPos  = (iFillSPos << m_iShiftPrec) - iCurSPos;
+
+      RM_AOT( iDeltaCurSPos > iDeltaSPos );
+      RM_AOT( iDeltaCurSPos < 0 );
+      RM_AOT( m_aaiSubPelShiftL[iDeltaSPos][iDeltaCurSPos] == 0xdeaddead);
+
+      xSetShiftedPelL<bSet>( iCurPos, m_aaiSubPelShiftL[iDeltaSPos][iDeltaCurSPos], iFillSPos, REN_IS_FILLED, riError );
+    }
+  };
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xRenderShiftedRangeR(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  assert( iCurSPos >= iLastSPos );
+
+  Int iDeltaSPos = iCurSPos - iLastSPos;
+  if ( iDeltaSPos > m_iGapTolerance )
+  {
+    xFillHoleR<bSet>( iCurSPos, iLastSPos, iCurPos, riError );
+  }
+  else
+  {
+    if (iLastSPos > m_iSampledWidth - 1 )
+      return;
+
+    m_iThisDepth = m_iCurDepth;
+    RM_AOT( iDeltaSPos    > m_iGapTolerance );
+    for (Int iFillSPos = max(m_iLastOccludedSPosFP+1, xRangeLeftR(iLastSPos) ); iFillSPos <= min(xRangeRightR( iCurSPos ) ,m_iWidth -1); iFillSPos++ )
+    {
+      Int iDeltaCurSPos  = (iFillSPos << m_iShiftPrec) - iLastSPos;
+
+      RM_AOT( iDeltaCurSPos > iDeltaSPos );
+      RM_AOT( iDeltaCurSPos < 0 );
+      RM_AOT( m_aaiSubPelShiftR[iDeltaSPos][iDeltaCurSPos] == 0xdeaddead);
+
+      xSetShiftedPelR<bSet>( iCurPos, m_aaiSubPelShiftR[iDeltaSPos][iDeltaCurSPos], iFillSPos, REN_IS_FILLED, riError );
+    }
+  };
+}
+
+
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xRenderRangeL(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  const Int iCurViewPos = 0; 
+  if (  !m_bInOcclusion )
+  {
+    if ( iCurSPos >= iLastSPos )
+    {
+      m_iLastOccludedSPos = iLastSPos;
+
+      Int iRightSPosFP = xRoundL( iLastSPos );
+      if ( ( iRightSPosFP == xRangeRightL(iLastSPos)) && (iRightSPosFP >= 0) )
+      {
+        m_iThisDepth = m_iLastDepth;
+
+        xSetShiftedPelL<bSet>( iCurPos+1, 0, iRightSPosFP, REN_IS_FILLED, riError );
+      }
+      m_iLastOccludedSPosFP = iRightSPosFP;
+
+      m_bInOcclusion = true;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = true;
+      }
+    }
+    else
+    {
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = false;
+      }
+
+      xRenderShiftedRangeL<bSet>(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+  }
+  else
+  {
+    if ( iCurSPos < m_iLastOccludedSPos )
+    {
+      m_bInOcclusion = false;
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = false;
+      }
+
+      xRenderShiftedRangeL<bSet>(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+    else
+    {
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = true;
+      }
+    }
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xRenderRangeR(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  const Int iCurViewPos = 1; 
+  // Find out if current sample is occluded
+  if (  !m_bInOcclusion )
+  {
+    if ( iCurSPos <= iLastSPos )
+    {
+      m_iLastOccludedSPos = iLastSPos;
+
+      Int iLeftSPosFP = xRoundR( iLastSPos );
+      if ( ( iLeftSPosFP == xRangeLeftR(iLastSPos)) && (iLeftSPosFP <= m_iWidth - 1) )
+      {
+        m_iThisDepth = m_iLastDepth;
+        xSetShiftedPelR<bSet>( iCurPos-1,1 << m_iShiftPrec , iLeftSPosFP, REN_IS_FILLED, riError );
+      }
+      m_iLastOccludedSPosFP = iLeftSPosFP;
+
+      m_bInOcclusion = true;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = true;
+      }
+    }
+    else
+    {
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = false;
+      }
+
+      xRenderShiftedRangeR<bSet>(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+  }
+  else
+  {
+    if ( iCurSPos > m_iLastOccludedSPos )
+    {
+      m_bInOcclusion = false;
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = false;
+      }
+
+      xRenderShiftedRangeR<bSet>(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+    else
+    {
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = true;
+      }
+    }
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xFillHoleL( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  if (iLastSPos < 0)
+    return;
+
+  Int iStartFillSPos = iCurSPos;
+  Int iStartFillPos  = iCurPos;
+  Int iLastPos      = iCurPos + 1;
+
+  Int iStartFillSPosFP = xRangeLeftL(iStartFillSPos);
+
+  if (iStartFillSPosFP == xRoundL(iStartFillSPos))
+  {
+    if ((iStartFillSPosFP >= 0) && (iStartFillSPosFP < m_iLastOccludedSPosFP) )
+    {
+      m_iThisDepth = m_iCurDepth;
+      xSetShiftedPelL<bSet>    ( iStartFillPos, 0, iStartFillSPosFP, REN_IS_FILLED, riError );
+    }
+  }
+  else
+  {
+    iStartFillSPosFP--;
+  }
+
+  m_iThisDepth = m_iLastDepth;
+  for (Int iFillSPos = Max(iStartFillSPosFP+1,0); iFillSPos <= min(xRangeRightL( iLastSPos ), m_iLastOccludedSPosFP-1 ); iFillSPos++ )
+  {
+    xSetShiftedPelL<bSet>( iLastPos, 0,  iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xFillHoleR( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  if (iLastSPos < 0)
+    return;
+
+  Int iStartFillSPos = iCurSPos;
+  Int iEndFillPos    = iCurPos;
+  Int iLastPos       = iCurPos - 1;
+
+  Int iStartFillSPosFP = xRangeRightR(iStartFillSPos);
+
+  if (iStartFillSPosFP == xRoundR(iStartFillSPos))
+  {
+    if ((iStartFillSPosFP < m_iWidth) && (iStartFillSPosFP > m_iLastOccludedSPosFP) )
+    {
+      m_iThisDepth = m_iCurDepth;
+      xSetShiftedPelR<bSet>( iEndFillPos, 1 << m_iShiftPrec , iStartFillSPosFP, REN_IS_FILLED, riError );
+    }
+  }
+  else
+  {
+    iStartFillSPosFP++;
+  }
+
+  m_iThisDepth = m_iLastDepth;
+  for (Int iFillSPos = max(xRangeLeftR( iLastSPos ), m_iLastOccludedSPosFP+1); iFillSPos <= min(iStartFillSPosFP,m_iWidth)-1 ; iFillSPos++ )
+  {
+    xSetShiftedPelR<bSet>( iLastPos, 1 << m_iShiftPrec, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xExtrapolateMarginL(Int iCurSPos, Int iCurPos, RMDist& riError )
+{
+//  if (iLeftSPos < 0 )
+//    return;
+
+  Int iSPosFullPel = Max(0,xRangeLeftL(iCurSPos));
+
+  m_iThisDepth = m_iCurDepth;
+  if (iSPosFullPel < m_iWidth)
+  {
+    xSetShiftedPelL<bSet>( iCurPos, 0, iSPosFullPel, REN_IS_FILLED, riError );
+  }
+
+  for (Int iFillSPos = iSPosFullPel +1; iFillSPos < m_iWidth; iFillSPos++ )
+  {
+    xSetShiftedPelL<bSet>( iCurPos, 0, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xExtrapolateMarginR(Int iCurSPos, Int iCurPos, RMDist& riError )
+{
+  //  if (iLeftSPos < 0 )
+  //    return;
+
+  Int iSPosFullPel = Min(m_iWidth-1,xRangeRightR(iCurSPos));
+
+  m_iThisDepth = m_iCurDepth;
+  if (iSPosFullPel > -1)
+  {
+    xSetShiftedPelR<bSet>( iCurPos, 1 << m_iShiftPrec, iSPosFullPel, REN_IS_FILLED, riError );
+  }
+
+  for (Int iFillSPos = iSPosFullPel -1; iFillSPos > -1; iFillSPos-- )
+  {
+    xSetShiftedPelR<bSet>( iCurPos , 1 << m_iShiftPrec, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xShiftNewData( Int iPosX, Int iPosInNewData )
+{
+  RM_AOT( iPosInNewData <               0 );
+  RM_AOF( iPosInNewData < m_iNewDataWidth );
+
+  return (iPosX << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( m_piNewDepthData[iPosInNewData] )];
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xShift( Int iPosX )
+{
+ RM_AOT( iPosX <        0);
+ RM_AOF( iPosX < m_iWidth);
+
+ return (iPosX  << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( m_pcInputSamplesRow[m_iCurViewPos][iPosX].iD )];
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xShift( Int iPos, Int iPosInNewData )
+{
+  if ( (iPosInNewData >= 0) && (iPosInNewData < m_iNewDataWidth) )
+  {
+    return xShiftNewData(iPos ,iPosInNewData );
+  }
+  else
+  {
+    return xShift(iPos);
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRangeLeftL( Int iPos )
+{
+  return  ( iPos +  (1 << m_iShiftPrec) - 1) >> m_iShiftPrec;
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRangeLeftR( Int iPos )
+{
+
+  return  xRangeRightR( iPos ) + 1;
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRangeRightL( Int iPos )
+{
+  return xRangeLeftL(iPos) - 1;
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRangeRightR( Int iPos )
+{
+  return iPos >> m_iShiftPrec;
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRoundL( Int iPos )
+{
+  return  (iPos + (( 1 << m_iShiftPrec ) >> 1 )) >> m_iShiftPrec;
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRoundR( Int iPos )
+{
+  return  (m_iShiftPrec == 0) ? iPos : xRoundL(iPos - 1);
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetPels( Pel* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal )
+{
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for (Int iXPos = 0; iXPos < iWidth; iXPos++)
+    {
+      piPelSource[iXPos] = iVal;
+    }
+    piPelSource += iSourceStride;
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetInts( Int* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Int iVal )
+{
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for (Int iXPos = 0; iXPos < iWidth; iXPos++)
+    {
+      piPelSource[iXPos] = iVal;
+    }
+    piPelSource += iSourceStride;
+  }
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetBools( Bool* pbPelSource , Int iSourceStride, Int iWidth, Int iHeight, Bool bVal )
+{
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for (Int iXPos = 0; iXPos < iWidth; iXPos++)
+    {
+      pbPelSource[iXPos] = bVal;
+    }
+    pbPelSource += iSourceStride;
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelL(Int iSourcePos, Int iSubSourcePos, Int iTargetSPos, Pel iFilled, RMDist& riError )
+{
+  RM_AOT( iSourcePos    <  0                   );
+  RM_AOT( iSourcePos    >= m_iWidth            );
+  RM_AOT( iSubSourcePos < 0                    );
+  RM_AOT( iSubSourcePos >  (1 << m_iShiftPrec) );
+  RM_AOT( iTargetSPos   < 0                    );
+  RM_AOT( iTargetSPos   >= m_iWidth            );  
+
+  RenModelOutPels* pcOutSample = m_pcOutputSamplesRow              + iTargetSPos;
+  RenModelInPels * pcInSample  = m_pcInputSamplesRow[VIEWPOS_LEFT] + iSourcePos ;
+
+  if ( iBM != BLEND_NONE )
+  {
+    xSetShiftedPelBlendL<bSet>  (pcInSample, iSubSourcePos, pcOutSample, iFilled, riError);
+  }
+  else
+  {
+    xSetShiftedPelNoBlendL<bSet>(pcInSample, iSubSourcePos, pcOutSample, iFilled, riError);
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelNoBlendL(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError )
+{
+  if ( bSet )
+  { 
+    // Filled
+    pcOutSample->iFilledLeft = iFilled;
+
+    // Yuv
+    pcOutSample->iYLeft  = pcInSample->aiY[iSubSourcePos];
+#if HHI_VSO_COLOR_PLANES
+    pcOutSample->iULeft  = pcInSample->aiU[iSubSourcePos];
+    pcOutSample->iVLeft  = pcInSample->aiV[iSubSourcePos];
+
+    pcOutSample->iError = xGetDist( pcOutSample->iYLeft - pcOutSample->iYRef,
+                                    pcOutSample->iULeft - pcOutSample->iURef,    
+                                    pcOutSample->iVLeft - pcOutSample->iVRef
+                                  );    
+#else
+    pcOutSample->iError = xGetDist( pcOutSample->iYLeft - pcOutSample->iYRef );    
+#endif    
+    
+  }
+  else
+  { 
+#if HHI_VSO_COLOR_PLANES
+    riError += xGetDist( pcInSample->aiY[iSubSourcePos] - pcOutSample->iYRef,
+                         pcInSample->aiU[iSubSourcePos] - pcOutSample->iURef,
+                         pcInSample->aiV[iSubSourcePos] - pcOutSample->iVRef
+                       );
+#else               
+    riError += xGetDist( pcInSample->aiY[iSubSourcePos] - pcOutSample->iYRef );
+#endif
+
+    riError -= pcOutSample->iError;
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelBlendL(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError )
+{
+  Pel piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+  Pel piBlendedValueU;
+  Pel piBlendedValueV;
+#endif
+
+  xGetBlendedValue (
+    pcInSample ->aiY[iSubSourcePos],
+    pcOutSample->iYRight,    
+#if HHI_VSO_COLOR_PLANES
+    pcInSample ->aiU[iSubSourcePos],
+    pcOutSample->iURight,    
+    pcInSample ->aiV[iSubSourcePos],
+    pcOutSample->iVRight,    
+#endif
+    m_piInvZLUTLeft [RenModRemoveBitInc(m_iThisDepth)        ],
+    m_piInvZLUTRight[RenModRemoveBitInc(pcOutSample->iDRight)],
+    iFilled,
+    pcOutSample->iFilledRight  ,
+    piBlendedValueY
+#if HHI_VSO_COLOR_PLANES
+    , piBlendedValueU,
+    piBlendedValueV
+#endif
+    );
+
+  if ( bSet )
+  {    
+    // Set values
+    pcOutSample->iDLeft      = m_iThisDepth;
+    pcOutSample->iYLeft      = pcInSample ->aiY[iSubSourcePos];
+    pcOutSample->iYBlended   = piBlendedValueY;    
+#if HHI_VSO_COLOR_PLANES  
+    pcOutSample->iULeft      = pcInSample ->aiU[iSubSourcePos];
+    pcOutSample->iUBlended   = piBlendedValueU;    
+    pcOutSample->iVLeft      = pcInSample ->aiV[iSubSourcePos];
+    pcOutSample->iVBlended   = piBlendedValueV;    
+#endif
+    pcOutSample->iFilledLeft = iFilled;
+
+    // Get Error
+    Int iDiffY = pcOutSample->iYRef - piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+    Int iDiffU = pcOutSample->iURef - piBlendedValueU;
+    Int iDiffV = pcOutSample->iVRef - piBlendedValueV;
+    pcOutSample->iError  = xGetDist(iDiffY, iDiffU, iDiffV );
+#else
+    pcOutSample->iError  = xGetDist(iDiffY );
+#endif
+  }
+  else
+  {
+    Int iDiffY = pcOutSample->iYRef - piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+    Int iDiffU = pcOutSample->iURef - piBlendedValueU;
+    Int iDiffV = pcOutSample->iVRef - piBlendedValueV;
+    riError   += ( xGetDist( iDiffY, iDiffU, iDiffV ) - pcOutSample->iError );
+
+#else
+    riError   += ( xGetDist( iDiffY ) - pcOutSample->iError  );
+#endif
+
+  }
+}
+
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelR(Int iSourcePos, Int iSubSourcePos, Int iTargetSPos, Pel iFilled, RMDist& riError )
+{
+  RM_AOT( iSourcePos    <  0                     );
+  RM_AOT( iSourcePos    >= m_iWidth              );
+  RM_AOT( iSubSourcePos <  0                     );
+  RM_AOT( iSubSourcePos >= (1 << m_iShiftPrec)+1 );
+  RM_AOT( iTargetSPos   < 0                      );
+  RM_AOT( iTargetSPos   >= m_iWidth              );  
+
+  RenModelOutPels* pcOutSample = m_pcOutputSamplesRow               + iTargetSPos;
+  RenModelInPels * pcInSample  = m_pcInputSamplesRow[VIEWPOS_RIGHT] + iSourcePos ;
+
+  if ( iBM != BLEND_NONE )
+  {
+    xSetShiftedPelBlendR<bSet>   (pcInSample, iSubSourcePos, pcOutSample, iFilled, riError);
+  }
+  else
+  {
+    xSetShiftedPelNoBlendR<bSet> (pcInSample, iSubSourcePos, pcOutSample, iFilled, riError);
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelNoBlendR(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError )
+{
+  if ( bSet )
+  { 
+    // Filled
+    pcOutSample->iFilledRight = iFilled;
+
+    // Yuv
+    pcOutSample->iYRight  = pcInSample->aiY[iSubSourcePos];
+#if HHI_VSO_COLOR_PLANES
+    pcOutSample->iURight  = pcInSample->aiU[iSubSourcePos];
+    pcOutSample->iVRight  = pcInSample->aiV[iSubSourcePos];
+
+    pcOutSample->iError = xGetDist( 
+      pcOutSample->iYRight - pcOutSample->iYRef,
+      pcOutSample->iURight - pcOutSample->iURef,    
+      pcOutSample->iVRight - pcOutSample->iVRef
+      );    
+#else
+    pcOutSample->iError = xGetDist( pcOutSample->iYRight - pcOutSample->iYRef );    
+#endif    
+
+  }
+  else
+  { 
+#if HHI_VSO_COLOR_PLANES
+    riError += xGetDist( pcInSample->aiY[iSubSourcePos] - pcOutSample->iYRef,
+      pcInSample->aiU[iSubSourcePos] - pcOutSample->iURef,
+      pcInSample->aiV[iSubSourcePos] - pcOutSample->iVRef
+      );
+#else               
+    riError += xGetDist( pcInSample->aiY[iSubSourcePos] - pcOutSample->iYRef );
+#endif
+
+    riError -= pcOutSample->iError;
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelBlendR(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError )
+{
+  Pel piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+  Pel piBlendedValueU;
+  Pel piBlendedValueV;
+#endif
+
+  xGetBlendedValue (
+    pcOutSample->iYLeft, 
+    pcInSample ->aiY[iSubSourcePos],        
+#if HHI_VSO_COLOR_PLANES
+    pcOutSample->iULeft,    
+    pcInSample ->aiU[iSubSourcePos],
+    pcOutSample->iVLeft,    
+    pcInSample ->aiV[iSubSourcePos],
+#endif
+    m_piInvZLUTLeft  [RenModRemoveBitInc(pcOutSample->iDLeft)],
+    m_piInvZLUTRight [RenModRemoveBitInc(m_iThisDepth)       ],
+    pcOutSample->iFilledLeft,
+    iFilled,
+    piBlendedValueY
+#if HHI_VSO_COLOR_PLANES
+    , piBlendedValueU,
+    piBlendedValueV
+#endif
+    );
+
+  if ( bSet )
+  {    
+    // Set values
+    pcOutSample->iDRight     = m_iThisDepth;
+    pcOutSample->iYRight     = pcInSample ->aiY[iSubSourcePos];
+    pcOutSample->iYBlended   = piBlendedValueY;    
+#if HHI_VSO_COLOR_PLANES  
+    pcOutSample->iURight     = pcInSample ->aiU[iSubSourcePos];
+    pcOutSample->iUBlended   = piBlendedValueU;    
+    pcOutSample->iVRight     = pcInSample ->aiV[iSubSourcePos];
+    pcOutSample->iVBlended   = piBlendedValueV;    
+#endif
+    pcOutSample->iFilledRight = iFilled;
+
+    // Get Error
+    Int iDiffY = pcOutSample->iYRef - piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+    Int iDiffU = pcOutSample->iURef - piBlendedValueU;
+    Int iDiffV = pcOutSample->iVRef - piBlendedValueV;
+    pcOutSample->iError  = xGetDist(iDiffY, iDiffU, iDiffV );
+#else
+    pcOutSample->iError  = xGetDist(iDiffY );
+#endif
+  }
+  else
+  {
+    Int iDiffY = pcOutSample->iYRef - piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+    Int iDiffU = pcOutSample->iURef - piBlendedValueU;
+    Int iDiffV = pcOutSample->iVRef - piBlendedValueV;
+    riError   += ( xGetDist( iDiffY, iDiffU, iDiffV ) - pcOutSample->iError );
+#else
+    riError   += ( xGetDist( iDiffY ) -  pcOutSample->iError  );
+#endif
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xGetDist( Int iDiffY, Int iDiffU, Int iDiffV )
+{
+
+  if ( !bBitInc )
+  {
+    return (          (iDiffY * iDiffY )
+               +  ((( (iDiffU * iDiffU )
+                     +(iDiffV * iDiffV )
+                    )
+                   ) >> 2
+                  )
+           );
+  }
+  else
+  {
+    return (          ((iDiffY * iDiffY) >> m_iDistShift)
+               +  ((( ((iDiffU * iDiffU) >> m_iDistShift)
+                     +((iDiffV * iDiffV) >> m_iDistShift)
+                    )
+                   ) >> 2
+                  )
+           );
+  
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xGetDist( Int iDiffY )
+{
+  if ( !bBitInc )
+  {
+    return (iDiffY * iDiffY);
+  }
+  else
+  {
+    return ((iDiffY * iDiffY) >> m_iDistShift);
+  }
+
+}
+
+
+#if HHI_VSO_COLOR_PLANES
+template <BlenMod iBM, Bool bBitInc>  __inline Void
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValue( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV )
+#else
+template <BlenMod iBM, Bool bBitInc>  __inline Void
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValue( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY )
+#endif
+{
+
+  RM_AOT( iBM != BLEND_AVRG && iBM != BLEND_LEFT && iBM != BLEND_RIGHT );
+
+  if (iBM != BLEND_AVRG )
+  {
+    if (iBM == BLEND_LEFT )
+    {
+#if HHI_VSO_COLOR_PLANES
+      xGetBlendedValueBM1(  iYL,  iYR,  iUL,  iUR,  iVL,  iVR,  iDepthL,  iDepthR,  iFilledL,  iFilledR,  riY,  riU, riV );
+#else
+      xGetBlendedValueBM1(  iYL,  iYR,  iDepthL,  iDepthR,  iFilledL,  iFilledR,  riY );
+#endif
+    }
+    else
+    {
+#if HHI_VSO_COLOR_PLANES
+      xGetBlendedValueBM2(  iYL,  iYR,  iUL,  iUR,  iVL,  iVR,  iDepthL,  iDepthR,  iFilledL,  iFilledR,  riY,  riU, riV );
+#else
+      xGetBlendedValueBM2(  iYL,  iYR, iDepthL,  iDepthR,  iFilledL,  iFilledR,  riY );
+#endif
+    }
+    return;
+  }
+
+  if (  (iFilledL != REN_IS_HOLE ) && ( iFilledR != REN_IS_HOLE) )
+  {
+    Int iDepthDifference = iDepthR - iDepthL;
+
+    if ( abs ( iDepthDifference ) <= m_iBlendZThres )
+    {
+      if      ((iFilledL == REN_IS_FILLED) && ( iFilledR != REN_IS_FILLED))
+      {
+        riY = xBlend( iYL, iYR, iFilledR >> 1 );
+#if HHI_VSO_COLOR_PLANES
+        riU = xBlend( iUL, iUR, iFilledR >> 1 );
+        riV = xBlend( iVL, iVR, iFilledR >> 1 );
+#endif
+
+      }
+      else if ((iFilledL != REN_IS_FILLED) && ( iFilledR == REN_IS_FILLED))
+      {
+        riY = xBlend( iYR, iYL, (iFilledL >> 1) );
+#if HHI_VSO_COLOR_PLANES
+        riU = xBlend( iUR, iUL, (iFilledL >> 1) );
+        riV = xBlend( iVR, iVL, (iFilledL >> 1) );
+#endif
+      }
+      else
+      {
+        riY = xBlend( iYL, iYR, m_iBlendDistWeight );
+#if HHI_VSO_COLOR_PLANES    
+        riU = xBlend( iUL, iUR, m_iBlendDistWeight );
+        riV = xBlend( iVL, iVR, m_iBlendDistWeight );
+#endif
+      }
+    }
+    else if ( iDepthDifference < 0 )
+    {
+      riY = iYL;
+#if HHI_VSO_COLOR_PLANES
+      riU = iUL;
+      riV = iVL;
+#endif
+    }
+    else
+    {
+      riY = iYR;
+#if HHI_VSO_COLOR_PLANES
+      riU = iUR;
+      riV = iVR;
+#endif
+    }
+  }
+  else if ( (iFilledL == REN_IS_HOLE) && (iFilledR == REN_IS_HOLE))
+  {
+    if ( iDepthR < iDepthL )
+    {
+        riY =  iYR;
+#if HHI_VSO_COLOR_PLANES
+        riU =  iUR;
+        riV =  iVR;
+#endif
+    }
+    else
+    {
+        riY =  iYL;
+#if HHI_VSO_COLOR_PLANES
+        riU =  iUL;
+        riV =  iVL;
+#endif
+    }
+  }
+  else
+  {
+    if (iFilledR == REN_IS_HOLE)
+    {
+        riY = iYL;
+#if HHI_VSO_COLOR_PLANES
+        riU = iUL;
+        riV = iVL;
+#endif
+    }
+    else
+    {
+      riY = iYR;
+#if HHI_VSO_COLOR_PLANES
+      riU = iUR;
+      riV = iVR;
+#endif
+    }
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+#if HHI_VSO_COLOR_PLANES
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValueBM1( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV )
+#else
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValueBM1( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY )
+#endif
+{
+  if ( iFilledL == REN_IS_FILLED ||  iFilledR == REN_IS_HOLE )
+  {
+    riY = iYL;
+#if HHI_VSO_COLOR_PLANES
+    riU = iUL;
+    riV = iVL;
+#endif
+  }
+  else if ( iFilledL == REN_IS_HOLE  )
+  {
+    riY = iYR;
+#if HHI_VSO_COLOR_PLANES
+    riU = iUR;
+    riV = iVR;
+#endif
+  }
+  else
+  {
+    riY = xBlend( iYR, iYL, iFilledL );
+#if HHI_VSO_COLOR_PLANES
+    riU = xBlend( iUR, iUL, iFilledL );
+    riV = xBlend( iVR, iUL, iFilledL );
+#endif
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+#if HHI_VSO_COLOR_PLANES
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValueBM2( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV )
+#else
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValueBM2( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY )
+#endif
+{
+  if      ( iFilledR == REN_IS_FILLED ||  iFilledL == REN_IS_HOLE )
+  {
+    riY = iYR;
+#if HHI_VSO_COLOR_PLANES
+    riU = iUR;
+    riV = iVR;
+#endif
+  }
+  else if ( iFilledR == REN_IS_HOLE  )
+  {
+    riY = iYL;
+#if HHI_VSO_COLOR_PLANES
+    riU = iUL;
+    riV = iVL;
+#endif
+  }
+  else
+  {
+    riY = xBlend( iYL, iYR, iFilledR );
+#if HHI_VSO_COLOR_PLANES
+    riU = xBlend( iUL, iUR, iFilledR );
+    riV = xBlend( iVL, iUR, iFilledR );
+#endif
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Pel
+TRenSingleModelC<iBM,bBitInc>::xBlend( Pel pVal1, Pel pVal2, Int iWeightVal2 )
+{
+  return pVal1  +  (Pel) (  ( (Int) ( pVal2 - pVal1) * iWeightVal2 + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+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() );
+}
+
+template class TRenSingleModelC<BLEND_NONE ,true>;
+template class TRenSingleModelC<BLEND_AVRG ,true>;
+template class TRenSingleModelC<BLEND_LEFT ,true>;
+template class TRenSingleModelC<BLEND_RIGHT,true>;
+
+template class TRenSingleModelC<BLEND_NONE ,false>;
+template class TRenSingleModelC<BLEND_AVRG ,false>;
+template class TRenSingleModelC<BLEND_LEFT ,false>;
+template class TRenSingleModelC<BLEND_RIGHT,false>;
+
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+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)
+{
+  RM_AOF( m_bEarlySkip ); 
+  const Int iCurViewPos = 0;
+  Int** ppiCurLUT       = m_appiShiftLut   [ iCurViewPos ];
+  
+  Bool bNoDiff          = true;   
+  
+  for (Int iPosY=0; iPosY < iHeight; iPosY++)
+  {
+    m_pbHorSkip[iPosY] = true;
+
+    for (Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      Int iDisparityRec = abs(ppiCurLUT[0][ RenModRemoveBitInc(piNewData[iPosX])]);
+      Int iDispartyOrg  = abs(ppiCurLUT[0][ RenModRemoveBitInc(piOrgData[iPosX])]);
+
+      if( iDispartyOrg != iDisparityRec)
+      {
+        m_pbHorSkip[iPosY] = false;
+        bNoDiff            = false;
+        break;
+      }
+    }
+    piNewData += iStride;
+    piOrgData += iOrgStride;
+  }
+  return bNoDiff;
+}
+
+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)
+{
+  RM_AOF( m_bEarlySkip ); 
+  Bool bNoDiff  = true;
+
+  const Int iCurViewPos = 1;
+  Int** ppiCurLUT       = m_appiShiftLut   [ iCurViewPos ];
+
+  for ( Int iPosY = 0; iPosY < iHeight; iPosY++ )
+  {
+    m_pbHorSkip[iPosY] = true;
+
+    for (Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      Int iDisparityRec = abs( ppiCurLUT[0][ RenModRemoveBitInc(piNewData[iPosX])] );
+      Int iDisparityOrg = abs( ppiCurLUT[0][ RenModRemoveBitInc(piOrgData[iPosX])] );
+
+      if( iDisparityRec != iDisparityOrg )
+      {
+        m_pbHorSkip[iPosY] = false;
+        bNoDiff            = false;
+        break;
+      }
+    }
+
+    piNewData += iStride;
+    piOrgData += iOrgStride;
+  }
+  return bNoDiff;
+}
+#endif
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenSingleModel.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 341)
@@ -0,0 +1,394 @@
+/* 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-2011, 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 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.
+ */
+
+#if !QC_MVHEVC_B0046
+#ifndef __TRENSINGLEMODEL__ 
+#define __TRENSINGLEMODEL__
+
+#include "TRenImage.h"
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "../TLibCommon/TypeDef.h"
+#include "../TAppCommon/TAppComCamPara.h"
+
+
+#include <math.h>
+#include <errno.h>
+#include <iostream>
+
+#include <string>
+#include <cstdio>
+#include <cstring>
+
+
+using namespace std;
+
+
+#if HHI_VSO_RM_ASSERTIONS
+#define RM_AOT( exp ) AOT ( exp )
+#define RM_AOF( exp ) AOF ( exp )
+#else
+#define RM_AOT( exp ) ((void)0)
+#define RM_AOF( exp ) ((void)0)
+#endif
+
+#define RenModRemoveBitInc( exp ) bBitInc ? ( RemoveBitIncrement( exp ) ) : ( exp ) 
+
+class TRenSingleModel
+{
+public: 
+
+  virtual ~TRenSingleModel() { }  
+#if LGE_VSO_EARLY_SKIP_A0093
+  virtual Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode, Bool bEarlySkip ) = 0;
+#else
+  virtual Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode ) = 0;
+#endif
+
+  // Set Frame dependent data
+  virtual Void   setLRView ( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride ) = 0;
+  virtual Void   setupPart ( UInt uiHorOffset,       Int iUsedHeight ) = 0;
+  virtual Void   setup     ( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft, Bool bKeepReference ) = 0;
+
+  // Set Data
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  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;
+
+  // Get Distortion
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  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 Void   getSynthVideo  ( Int iViewPos, TComPicYuv* pcPicYuv ) = 0;  
+  virtual Void   getSynthDepth  ( Int iViewPos, TComPicYuv* pcPicYuv ) = 0;
+  virtual Void   getRefVideo    ( Int iViewPos, TComPicYuv* pcPicYuv ) = 0;
+};
+
+template < BlenMod iBM, Bool bBitInc >
+class TRenSingleModelC : public TRenSingleModel
+{
+  struct RenModelInPels
+  {
+    // video
+    Pel aiY[5]    ; // y-value
+#if HHI_VSO_COLOR_PLANES
+    Pel aiU[5]    ; // u-value
+    Pel aiV[5]    ; // v-value
+#endif
+    // depth
+    Pel iD        ; // depth
+
+    // state
+    Bool bOccluded; // Occluded
+  };
+
+  struct RenModelOutPels
+  {
+    // video
+    Pel iYLeft    ; 
+    Pel iYRight   ; 
+    Pel iYBlended ; 
+#if HHI_VSO_COLOR_PLANES
+    Pel iULeft    ; 
+    Pel iURight   ; 
+    Pel iUBlended ; 
+    Pel iVLeft    ; 
+    Pel iVRight   ; 
+    Pel iVBlended ; 
+#endif
+    // depth
+    Pel iDLeft    ;
+    Pel iDRight   ; 
+    Pel iDBlended ; 
+
+    // state
+    Int iFilledLeft ; 
+    Int iFilledRight; 
+
+    // error
+    Int  iError   ;
+
+    // reference
+    Pel iYRef    ; 
+#if HHI_VSO_COLOR_PLANES
+    Pel iURef    ; 
+    Pel iVRef    ; 
+#endif        
+  };
+
+
+
+public:
+  TRenSingleModelC();
+  ~TRenSingleModelC();
+
+  // Create Model
+#if LGE_VSO_EARLY_SKIP_A0093
+  Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode, Bool bEarlySkip  );
+#else
+  Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode );
+#endif
+
+  // Set Frame dependent data
+  Void   setLRView ( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride );
+  Void   setupPart ( UInt uiHorOffset,       Int uiUsedHeight );
+  Void   setup     ( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft, Bool bKeepReference );
+
+#if LGE_VSO_EARLY_SKIP_A0093
+  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
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  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   getSynthVideo  ( Int iViewPos, TComPicYuv* pcPicYuv );  
+  Void   getSynthDepth  ( Int iViewPos, TComPicYuv* pcPicYuv );
+  Void   getRefVideo    ( Int iViewPos, TComPicYuv* pcPicYuv );
+
+private:
+  // Set and inc Current Row
+  __inline Void   xSetViewRow(  Int iPosY );
+  __inline Void   xIncViewRow();
+
+  /////  Rendering /////
+  // Left to Right
+#if LGE_VSO_EARLY_SKIP_A0093
+                      __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 );
+#endif
+                      __inline Void   xInitRenderPartL    ( Int iEndChangePos, Int iLastSPos  );
+  template<Bool bSet> __inline Void   xRenderRangeL       ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xRenderShiftedRangeL( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xFillHoleL          ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xExtrapolateMarginL ( Int iCurSPos,                Int iCurPos, RMDist& riError );
+                      __inline Int    xRangeLeftL         ( Int iPos );
+                      __inline Int    xRangeRightL        ( Int iPos );
+                      __inline Int    xRoundL             ( Int iPos );
+
+  // Right to Left
+                      __inline Void   xInitRenderPartR    ( Int iStartChangePos, Int iLastSPos );
+  template<Bool bSet> __inline Void   xRenderShiftedRangeR( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xRenderRangeR       ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xFillHoleR          ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xExtrapolateMarginR ( Int iCurSPos,                Int iCurPos, RMDist& riError );
+                      __inline Int    xRangeLeftR         ( Int iPos );
+                      __inline Int    xRangeRightR        ( Int iPos );
+                      __inline Int    xRoundR             ( Int iPos );
+
+  // Blending
+  template<Bool bSet> __inline Void   xSetShiftedPelBlend ( Int iSourcePos, Int iTargetSPos, Pel iFilled, RMDist& riError );
+
+#if HHI_VSO_COLOR_PLANES
+  __inline Void   xGetBlendedValue    ( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV );
+  __inline Void   xGetBlendedValueBM1 ( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV );
+  __inline Void   xGetBlendedValueBM2 ( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV );
+#else
+  __inline Void   xGetBlendedValue    ( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY );
+  __inline Void   xGetBlendedValueBM1 ( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY );
+  __inline Void   xGetBlendedValueBM2 ( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY );
+#endif
+  __inline Pel    xBlend              ( Pel pVal1, Pel pVal2, Int iWeightVal2 );
+
+  // General
+  template<Bool bSet> __inline Void xSetShiftedPelL       (Int iSourcePos,             Int iSubSourcePos, Int iTargetSPos,              Pel iFilled, RMDist& riError );
+  template<Bool bSet> __inline Void xSetShiftedPelBlendL  (RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError );
+  template<Bool bSet> __inline Void xSetShiftedPelNoBlendL(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError );
+
+  template<Bool bSet> __inline Void xSetShiftedPelR       (Int iSourcePos,             Int iSubSourcePos, Int iTargetSPos,              Pel iFilled, RMDist& riError );
+  template<Bool bSet> __inline Void xSetShiftedPelBlendR  (RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError );
+  template<Bool bSet> __inline Void xSetShiftedPelNoBlendR(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError );
+
+  __inline Int    xShiftNewData      ( Int iPos, Int iPosInNewData );
+  __inline Int    xShift             ( Int iPos );
+  __inline Int    xShift             ( Int iPos, Int iPosInNewData );
+  __inline Int    xGetDist           ( Int iDiffY, Int iDiffU, Int iDiffV );
+  __inline Int    xGetDist           ( Int iDiffY );
+
+  // Utilities
+  __inline Void   xSetPels   ( Pel*  piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal );
+  __inline Void   xSetBools  ( Bool* pbSource    , Int iSourceStride, Int iWidth, Int iHeight, Bool bVal );
+  __inline Void   xSetInts   ( Int*  piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Int iVal );
+
+#if HHI_VSO_COLOR_PLANES
+  Void            xGetSampleStrTextPtrs ( Int iViewNum, Pel RenModelOutPels::*& rpiSrcY, Pel RenModelOutPels::*& rpiSrcU, Pel RenModelOutPels::*& rpiSrcV );
+#else  
+  Void            xGetSampleStrTextPtrs ( Int iViewNum, Pel RenModelOutPels::*& rpiSrcY );
+#endif 
+  Void            xGetSampleStrDepthPtrs( Int iViewNum, Pel RenModelOutPels::*& rpiSrcD );
+       
+  Void            xSetStructRefView            ();
+  Void            xResetStructError            ();
+  Void            xInitSampleStructs           ();
+  Void            xSetStructSynthViewAsRefView ();
+  Void            xCopy2PicYuv                ( Pel** ppiSrcVideoPel, Int* piStrides, TComPicYuv* rpcPicYuvTarget );
+
+  template< typename S, typename T> 
+  Void   xCopyFromSampleStruct ( S* ptSource , Int iSourceStride, T S::* ptSourceElement, T* ptTarget, Int iTargetStride, Int iWidth, Int iHeight )
+  {
+    AOT( iWidth != m_iWidth ); 
+    for (Int iPosY = 0; iPosY < iHeight; iPosY++)
+    {
+      for (Int iPosX = 0; iPosX < m_iWidth; iPosX++)
+      {
+        ptTarget[iPosX] = ptSource[iPosX].*ptSourceElement;
+      }
+      ptSource += iSourceStride;
+      ptTarget += iTargetStride;
+    }    
+  }  
+
+  template< typename S, typename T> 
+  Void   xCopyToSampleStruct ( T* ptSource , Int iSourceStride, S* ptTarget, Int iTargetStride, T S::* ptSourceElement, Int iWidth, Int iHeight )
+  {
+    AOT( iWidth != m_iWidth ); 
+    for (Int iPosY = 0; iPosY < iHeight; iPosY++)
+    {
+      for (Int iPosX = 0; iPosX < m_iWidth; iPosX++)
+      {
+        ptTarget[iPosX] = ptSource[iPosX].*ptSourceElement;
+      }
+      ptSource += iSourceStride;
+      ptTarget += iTargetStride;
+    }    
+  }   
+
+private:
+
+  // Image sizes
+  Int   m_iWidth;
+  Int   m_iHeight;
+  Int   m_iStride;
+  Int   m_iPad;
+  Int   m_iUsedHeight;
+  Int   m_iHorOffset; 
+
+  Int   m_iSampledWidth;
+  Int   m_iSampledStride;
+
+  RenModelInPels* m_pcInputSamples[2];
+  Int             m_iInputSamplesStride;
+
+  // Base
+  Pel** m_aapiBaseVideoPel     [2]; // Dim1: ViewPosition 0->Left, 1->Right; Dim2: Plane  0-> Y, 1->U, 2->V
+  Int*  m_aaiBaseVideoStrides  [2]; // Dim1: ViewPosition 0->Left, 1->Right; Dim2: Plane  0-> Y, 1->U, 2->V
+
+  Pel*  m_apiBaseDepthPel      [2]; // Dim1: ViewPosition
+  Int   m_aiBaseDepthStrides   [2]; // Dim1: ViewPosition
+
+
+  // LUT
+  Int** m_appiShiftLut         [2];
+  Int** m_ppiCurLUT;
+  Int** m_aaiSubPelShiftL;
+  Int** m_aaiSubPelShiftR;
+
+  Int*  m_piInvZLUTLeft;
+  Int*  m_piInvZLUTRight;
+
+
+  //// Reference Data  ////
+  TComPicYuv* m_pcPicYuvRef       ;    // Reference PIcYuv
+
+  //// Output Samples
+  RenModelOutPels* m_pcOutputSamples;
+  Int                   m_iOutputSamplesStride;
+
+  Pel*  m_aapiRefVideoPel      [3];    // Dim1: Plane  0-> Y, 1->U, 2->V
+  Int   m_aiRefVideoStrides    [3];    // Dim1: Plane  0-> Y, 1->U, 2->V
+
+  // Rendering State
+  Bool  m_bInOcclusion;                // Currently rendering in occluded area
+  Int   m_iLastOccludedSPos;           // Position of last topmost shifted position
+  Int   m_iLastOccludedSPosFP;         // Position of last topmost shifted position in FullPels
+
+  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
+  Int   m_iStartChangePosX;            // Start Position of new data
+  Int   m_iNewDataWidth;               // Width of new data
+  Pel   m_iCurDepth;                   // Current Depth Value
+  Pel   m_iLastDepth;                  // Last Depth Value
+  Pel   m_iThisDepth;                  // Depth value to use for setting
+
+  //// Settings ////
+  // Input
+  Int   m_iMode;                       // 0: Left to Right, 1: Right to Left, 2: Merge
+  Bool  m_bUseOrgRef;
+  Int   m_iShiftPrec;
+  Int   m_iHoleMargin;
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  Bool  m_bEarlySkip; 
+#endif
+
+  // Derived settings
+  Int   m_iGapTolerance;
+  Int   m_iBlendZThres;
+  Int   m_iBlendDistWeight;
+
+  //// Current Pointers ////
+
+  RenModelInPels*  m_pcInputSamplesRow [2];
+  RenModelOutPels* m_pcOutputSamplesRow;
+
+  //// MISC ////
+  const Int m_iDistShift;                  // Shift in Distortion computation
+
+  //// Early Skip 
+#ifdef LGE_VSO_EARLY_SKIP_A0093
+  Bool* m_pbHorSkip;
+#endif
+};
+
+#endif //__TRENSINGLEMODEL__
+#endif
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenTop.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenTop.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenTop.cpp	(revision 341)
@@ -0,0 +1,2222 @@
+/* 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-2011, 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 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 "TRenImage.h"
+#include "TRenTop.h"
+
+#include "TRenFilter.h"
+#include <iostream>
+#include <math.h>
+#include "../TLibCommon/CommonDef.h"
+
+Void TRenTop::xGetDataPointers( PelImage*& rpcInputImage, PelImage*& rpcOutputImage, PelImage*& rpcInputDepth, PelImage*& rpcOutputDepth, PelImage*& rpcFilled, Bool bRenderDepth )
+{
+  UInt uiWidth = m_auiInputResolution[0] << m_iLog2SamplingFactor;
+
+  UInt uiSubPelWidth  = uiWidth;
+
+  if ( m_iInterpolationMode == eRenInt8Tap )
+  {
+    uiSubPelWidth <<= m_iRelShiftLUTPrec;
+  }
+
+  UInt uiHeight = m_auiInputResolution[1];
+
+  if ( m_bUVUp )
+  {
+    rpcInputDepth  = new PelImage(uiSubPelWidth, uiHeight,1,0);
+    rpcInputImage  = new PelImage(uiSubPelWidth, uiHeight,3,0);
+    rpcOutputImage = new PelImage(uiWidth,        uiHeight,3,0);
+    rpcOutputDepth = bRenderDepth  ? new PelImage(uiWidth, uiHeight,1,0) : 0;
+    rpcFilled      = new PelImage(uiWidth, uiHeight,1,0);
+  }
+  else
+  {
+    rpcInputDepth  = new PelImage(uiSubPelWidth, uiHeight,1,1);
+    rpcInputImage  = new PelImage(uiSubPelWidth, uiHeight,1,2);
+    rpcOutputImage = new PelImage(uiWidth,        uiHeight,1,2);
+    rpcOutputDepth = bRenderDepth ? new PelImage(uiWidth, uiHeight,1,1) : 0;
+    rpcFilled      = new PelImage(uiWidth,        uiHeight,1,1);
+  }
+
+}
+
+Void TRenTop::xGetDataPointerOutputImage( PelImage*& rpcOutputImage, PelImage*& rpcOutputDepth )
+{
+
+  UInt uiWidth  = m_auiInputResolution[0] << m_iLog2SamplingFactor;
+  UInt uiHeight = m_auiInputResolution[1];
+
+  if ( m_bUVUp )
+  {
+    rpcOutputImage = new PelImage(uiWidth, uiHeight,3,0);
+    rpcOutputDepth = (m_iBlendMode == eRenBlendDepthFirst ) ? new PelImage(uiWidth, uiHeight,1,0) : NULL;
+  }
+  else
+  {
+    rpcOutputImage = new PelImage(uiWidth, uiHeight,1,2);
+    rpcOutputDepth = (m_iBlendMode == eRenBlendDepthFirst ) ? new PelImage(uiWidth, uiHeight,1,1) : NULL;
+  }
+}
+
+Void TRenTop::xConvertInputVideo( PelImage* pcOrgInputImage, PelImage* pcConvInputImage)
+{
+  TRenImagePlane<Pel>*  pcOrgPlane ;
+  TRenImagePlane<Pel>*  pcConvPlane;
+
+  Int iLog2SamplingFactor = m_iLog2SamplingFactor;
+
+  if ( m_iInterpolationMode == eRenInt8Tap)
+  {
+    iLog2SamplingFactor += m_iRelShiftLUTPrec;
+  }
+
+  AOT( iLog2SamplingFactor > 2);
+
+  for (UInt uiPlane = 0; uiPlane < 3; uiPlane++)
+  {
+    pcOrgPlane  = pcOrgInputImage ->getPlane(uiPlane);
+    pcConvPlane = pcConvInputImage->getPlane(uiPlane);
+
+    if (uiPlane == 0)
+    {
+      TRenFilter::sampleHorUp    ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+    }
+    else
+    {
+      if ( m_bUVUp )
+      {
+        TRenFilter::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());
+      }
+    }
+  }
+}
+
+Void TRenTop::xConvertInputDepth( PelImage* pcOrgInputImage, PelImage* pcConvInputImage)
+{
+  PelImagePlane*  pcOrgPlane ;
+  PelImagePlane*  pcConvPlane;
+
+  // Full Plane
+  pcOrgPlane  = pcOrgInputImage ->getPlane(0);
+  pcConvPlane = pcConvInputImage->getPlane(0);
+
+  Int iLog2SamplingFactor = m_iLog2SamplingFactor;
+
+  if ( m_iInterpolationMode == eRenInt8Tap)
+  {
+    iLog2SamplingFactor += m_iRelShiftLUTPrec;
+  }
+  AOT( iLog2SamplingFactor > 2);
+
+  TRenFilter::sampleHorUp(iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+
+  if ( !m_bUVUp ) //GT: depth down
+  {
+    // Quarter Plane
+    PelImagePlane* pcTempPlane = new PelImagePlane(pcOrgInputImage->getPlane(0)->getWidth(), ( pcOrgInputImage->getPlane(0)->getHeight() >> 1), REN_LUMA_MARGIN );
+
+    TRenFilter::sampleVerDown2Tap13(pcOrgInputImage->getPlane(0), pcTempPlane, PICYUV_PAD);
+    pcConvPlane = pcConvInputImage->getPlane(1);
+
+    if ( iLog2SamplingFactor == 0 )
+    {
+      TRenFilter::sampleHorDown2Tap13(pcTempPlane, pcConvPlane, 0 );
+    }
+    else
+    {
+      TRenFilter::sampleHorUp    ( iLog2SamplingFactor - 1, pcTempPlane->getPlaneData(), pcTempPlane->getStride(), pcTempPlane->getWidth(), pcTempPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+    }
+    delete pcTempPlane;
+  }
+}
+
+Void TRenTop::xConvertInputData( PelImage* pcOrgInputImage, PelImage* pcOrgInputDepth, PelImage* pcConvInputImage, PelImage* pcConvInputDepth, Bool bMirror )
+{
+  //ToDo: remove unnecessary copying
+  if ( bMirror )
+  {
+    m_pcTempImage->assign( pcOrgInputImage );
+    TRenFilter::mirrorHor( m_pcTempImage );
+    m_pcTempImage->extendMargin();
+    xConvertInputVideo(    m_pcTempImage, pcConvInputImage );
+
+    m_pcTempImage->getPlane(0)->assign( pcOrgInputDepth->getPlane(0) );
+    TRenFilter::mirrorHor( m_pcTempImage->getPlane(0) );
+    m_pcTempImage->getPlane(0)->extendMargin();
+    xConvertInputDepth( m_pcTempImage, pcConvInputDepth );
+  }
+  else
+  {
+    m_pcTempImage->assign( pcOrgInputImage );
+    m_pcTempImage->extendMargin();
+    xConvertInputVideo( m_pcTempImage, pcConvInputImage );
+
+    m_pcTempImage->getPlane(0)->assign( pcOrgInputDepth->getPlane(0) );
+    m_pcTempImage->getPlane(0)->extendMargin();
+    xConvertInputDepth( m_pcTempImage, pcConvInputDepth );
+  }
+}
+
+Void TRenTop::xConvertOutputData( PelImage* pcOrgOutputImage, PelImage* pcConvOutputImage, Bool bMirror )
+{
+  Int iLog2SamplingFactor = m_iLog2SamplingFactor;
+
+  for ( UInt uiPlane = 0; uiPlane < 3; uiPlane++)
+  {
+    PelImagePlane* pcOrgPlane  = pcOrgOutputImage ->getPlane(uiPlane);
+    PelImagePlane* pcConvPlane = pcConvOutputImage->getPlane(uiPlane);
+
+    pcOrgPlane->extendMargin();
+
+    if ( uiPlane == 0 )
+    {
+      TRenFilter::sampleHorDown( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+    }
+    else
+    {
+      if ( m_bUVUp )
+      {
+        TRenFilter::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());
+      }
+    }
+  }
+
+  if ( bMirror )
+  {
+    TRenFilter::mirrorHor( pcConvOutputImage );
+  }
+
+}
+
+Void TRenTop::setShiftLUTs( Double** ppdShiftLUTLeft, Int** ppiShiftLUTLeft, Int** ppiBaseShiftLUTLeft, Double** ppdShiftLUTRight, Int** ppiShiftLUTRight, Int** ppiBaseShiftLUTRight,  Int iRelDistToLeft )
+{
+  m_ppdShiftLUTLeft  = ppdShiftLUTLeft;
+  m_ppdShiftLUTRight = ppdShiftLUTRight;
+
+  m_ppiShiftLUTLeft  = ppiShiftLUTLeft;
+  m_ppiShiftLUTRight = ppiShiftLUTRight;
+
+  if (  m_ppdShiftLUTRight != NULL && m_ppiShiftLUTRight != NULL )
+  {
+    for( UInt uiPlane = 0; uiPlane < 2; uiPlane++)
+    {
+      for (UInt uiDepthValue = 0; uiDepthValue <= 256; uiDepthValue++)
+      {
+        m_ppdShiftLUTRightMirror[uiPlane][uiDepthValue] = - m_ppdShiftLUTRight[uiPlane][uiDepthValue];
+        m_ppiShiftLUTRightMirror[uiPlane][uiDepthValue] = - m_ppiShiftLUTRight[uiPlane][uiDepthValue];
+      }
+    }
+  }
+
+  if ( !m_bExtrapolate )
+  {
+    TRenFilter::setupZLUT( m_bBlendUseDistWeight, m_iBlendZThresPerc, iRelDistToLeft, ppiBaseShiftLUTLeft, ppiBaseShiftLUTRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight);
+  }
+}
+
+Void TRenTop::extrapolateView( TComPicYuv* pcPicYuvVideo, TComPicYuv* pcPicYuvDepth, TComPicYuv* pcPicYuvSynthOut, Bool bRenderFromLeft )
+{
+  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());
+
+  PelImage cInputImage ( pcPicYuvVideo    );
+  PelImage cInputDepth ( pcPicYuvDepth    , true);
+  PelImage cOutputImage( pcPicYuvSynthOut );
+
+  m_pcOutputImage->init();
+  m_pcFilled     ->assign(REN_IS_HOLE);
+
+  xPreProcessDepth ( &cInputDepth,  &cInputDepth);
+  xConvertInputData( &cInputImage, &cInputDepth, m_pcInputImage, m_pcInputDepth, !bRenderFromLeft );
+  xShiftPixels(m_pcInputImage, m_pcInputDepth, m_pcOutputImage, m_pcFilled, bRenderFromLeft);
+  xRemBoundaryNoise ( m_pcOutputImage, m_pcFilled, m_pcOutputImage, bRenderFromLeft); // Erode
+  xFillHoles        ( m_pcOutputImage, m_pcFilled, m_pcOutputImage, bRenderFromLeft);
+  xConvertOutputData( m_pcOutputImage, &cOutputImage, !bRenderFromLeft );
+  xPostProcessImage (&cOutputImage, &cOutputImage);
+  xCutMargin        ( &cOutputImage );
+};
+
+Void TRenTop::getUsedSamplesMap( TComPicYuv* pcPicYuvDepth, TComPicYuv* pcUsedSampleMap, Bool bRenderFromLeft )
+{
+  AOF( bRenderFromLeft ? m_ppiShiftLUTLeft && m_ppdShiftLUTLeft : m_ppiShiftLUTRight && m_ppdShiftLUTRight );
+  AOF(m_auiInputResolution[0] == pcPicYuvDepth->getWidth ());
+  AOF(m_auiInputResolution[1] == pcPicYuvDepth->getHeight());
+
+  PelImage cInputDepth ( pcPicYuvDepth    , true);
+  PelImage cOutputImage( pcUsedSampleMap );
+  PelImage cInputImage ( m_auiInputResolution[0], m_auiInputResolution[1], 1, 2 );
+  cInputImage.assign(0);
+
+  m_pcFilled     ->assign(REN_IS_HOLE);
+  xConvertInputData(  &cInputImage,  &cInputDepth,   m_pcInputImage,  m_pcInputDepth, !bRenderFromLeft );
+  xShiftPixels     (m_pcInputImage, m_pcInputDepth, m_pcOutputImage, m_pcFilled, bRenderFromLeft);
+
+  xCreateAlphaMap  ( m_pcFilled, m_pcFilled, bRenderFromLeft );
+
+  if ( !bRenderFromLeft )
+  {
+    TRenFilter::mirrorHor( m_pcFilled );
+  }
+
+  TRenFilter::filledToUsedPelMap( m_pcFilled, &cOutputImage, m_iUsedPelMapMarExt );
+};
+
+
+Void TRenTop::interpolateView( TComPicYuv* pcPicYuvVideoLeft, TComPicYuv* pcPicYuvDepthLeft, TComPicYuv* pcPicYuvVideoRight, TComPicYuv* pcPicYuvDepthRight, TComPicYuv* pcPicYuvSynthOut, Int iBlendMode, Int iSimEnhBaseView )
+{
+  assert( !m_bExtrapolate );
+  assert( m_auiInputResolution[0] == pcPicYuvVideoLeft ->getWidth () );
+  assert( m_auiInputResolution[1] == pcPicYuvVideoRight->getHeight() );
+
+  AOT( iBlendMode == 3);
+  m_iBlendMode = iBlendMode;
+  m_iSimEnhBaseView = iSimEnhBaseView;
+
+  PelImage cLeftInputImage   ( pcPicYuvVideoLeft  );
+  PelImage cLeftInputDepth   ( pcPicYuvDepthLeft,  true );
+  PelImage cRightInputImage  ( pcPicYuvVideoRight );
+  PelImage cRightInputDepth  ( pcPicYuvDepthRight, true );
+  PelImage cOutputImage      ( pcPicYuvSynthOut   );
+
+  m_pcLeftOutputImage ->init();
+  m_pcRightOutputImage->init();
+  m_pcOutputImage     ->init();
+
+  if ( m_iBlendMode == eRenBlendDepthFirst )
+  {
+    m_pcOutputDepth->init();
+  }
+
+  m_pcLeftFilled ->assign(REN_IS_HOLE);
+  m_pcRightFilled->assign(REN_IS_HOLE);
+
+  xPreProcessDepth(&cLeftInputDepth , &cLeftInputDepth );
+  xPreProcessDepth(&cRightInputDepth, &cRightInputDepth);
+
+  xConvertInputData( &cLeftInputImage,  &cLeftInputDepth,  m_pcLeftInputImage,  m_pcLeftInputDepth  ,false );
+  xConvertInputData( &cRightInputImage, &cRightInputDepth, m_pcRightInputImage, m_pcRightInputDepth ,true  );
+
+  // Render from Left View to Right view
+  if ( m_iBlendMode != eRenBlendDepthFirst )
+  {
+    xShiftPixels(m_pcLeftInputImage,  m_pcLeftInputDepth, m_pcLeftOutputImage, m_pcLeftFilled, true );
+    xFillHoles  (m_pcLeftOutputImage, m_pcLeftFilled,     m_pcLeftOutputImage, true );
+  }
+
+  xShiftPixels(m_pcLeftInputDepth,  m_pcLeftInputDepth, m_pcLeftOutputDepth, m_pcLeftFilled, true );
+  xFillHoles     ( m_pcLeftOutputDepth, m_pcLeftFilled,     m_pcLeftOutputDepth, true);
+  xCreateAlphaMap( m_pcLeftFilled,      m_pcLeftFilled,     true );
+
+  // Render from Right View to Left view
+  if ( m_iBlendMode != eRenBlendDepthFirst )
+  {
+    xShiftPixels(m_pcRightInputImage , m_pcRightInputDepth, m_pcRightOutputImage, m_pcRightFilled, false );
+    xFillHoles  (m_pcRightOutputImage, m_pcRightFilled,     m_pcRightOutputImage, false);
+  }
+
+  xShiftPixels(m_pcRightInputDepth,  m_pcRightInputDepth, m_pcRightOutputDepth, m_pcRightFilled, false);
+  xFillHoles     ( m_pcRightOutputDepth, m_pcRightFilled,     m_pcRightOutputDepth, false);
+  xCreateAlphaMap( m_pcRightFilled,      m_pcRightFilled, false );
+
+  TRenFilter::mirrorHor( m_pcRightOutputImage );
+  TRenFilter::mirrorHor( m_pcRightOutputDepth );
+  TRenFilter::mirrorHor( m_pcRightFilled      );
+
+  xEnhSimilarity( m_pcLeftOutputImage, m_pcRightOutputImage, m_pcLeftFilled, m_pcRightFilled );
+
+  if ( m_iBlendMode == eRenBlendDepthFirst )
+  {
+    xBlend               ( m_pcLeftOutputDepth,  m_pcRightOutputDepth, m_pcLeftFilled,       m_pcRightFilled, m_pcLeftOutputDepth, m_pcRightOutputDepth, m_pcOutputDepth);
+
+    xBackShiftPixels     ( m_pcLeftInputImage,   m_pcOutputDepth,      m_pcLeftOutputImage,  m_pcLeftFilled  , false);
+    xFillHoles           ( m_pcLeftOutputImage,  m_pcLeftFilled,       m_pcLeftOutputImage, false);
+    xCreateAlphaMap      ( m_pcLeftFilled,       m_pcLeftFilled,       true );
+
+    TRenFilter::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 );
+    xCreateAlphaMap      ( m_pcRightFilled,      m_pcRightFilled,      true );
+    TRenFilter::mirrorHor( m_pcRightFilled );
+  }
+
+  xBlend(m_pcLeftOutputImage, m_pcRightOutputImage, m_pcLeftFilled, m_pcRightFilled, m_pcLeftOutputDepth, m_pcRightOutputDepth, m_pcOutputImage);
+  xConvertOutputData( m_pcOutputImage, &cOutputImage , false );
+
+  xPostProcessImage  ( &cOutputImage, &cOutputImage);
+  xCutMargin( &cOutputImage );
+};
+
+
+Void TRenTop::xPreProcessDepth( PelImage* pcInImage, PelImage* pcOutImage )
+{
+  if ( m_iPreProcMode == eRenPreProNone )
+    return;
+
+  PelImage* pcTemp;
+
+  if (pcInImage == pcOutImage)
+  {
+    pcTemp = pcOutImage->create();
+  }
+  else
+  {
+    pcTemp = pcOutImage;
+  }
+
+  pcTemp->assign(pcInImage);
+
+  switch ( m_iPreProcMode )
+  {
+    case eRenPreProBinom:
+      TRenFilter::binominal(pcOutImage, pcTemp, m_iPreFilterSize);
+      break;
+    case eRenPreProNone:
+      break;
+    default:
+      assert(0);
+      break;
+  }
+
+  if (pcInImage == pcOutImage)
+  {
+    pcOutImage->setData(pcTemp, true);
+    delete pcTemp;
+  };
+
+}
+
+Void TRenTop::xShiftPlanePixelsLinInt( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes )
+{
+  Int iWidth        = apcInputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes[0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  pcFilledPlane->assign(REN_IS_HOLE);
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    assert( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    assert( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    assert( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    Int iPrevShiftedPos = -1;
+    Int iShiftedPos = -1;
+
+    for(Int iPosX = 0; iPosX < iWidth; iPosX ++ )
+    {
+      Bool bExtrapolate = false;
+
+      // compute disparity and shift
+      iShiftedPos  = ( iPosX << m_iRelShiftLUTPrec ) - m_aiShiftLUTCur[RemoveBitIncrement( pcDepthData[iPosX])];
+
+      if (iPosX == 0)
+      {
+        // in first iteration only get dLeftPos
+        iPrevShiftedPos = iShiftedPos;
+        continue;
+      };
+
+      Int iDeltaPos = iShiftedPos - iPrevShiftedPos;
+
+      if ( iDeltaPos <= 0 || (iDeltaPos > (2 << m_iRelShiftLUTPrec)))
+      {
+        // skip Interpolation if pixel is shifted forwards (gap) or if  pixel is shifted backwards (foreground object)
+        bExtrapolate = true;
+      };
+
+      Int iInterPolPos;
+      if (!bExtrapolate)
+      {  // Interpolate between j1 and j2
+        for (iInterPolPos = ( iPrevShiftedPos + (1 << m_iRelShiftLUTPrec) - 1 ) >> m_iRelShiftLUTPrec  ; iInterPolPos <= (iShiftedPos >> m_iRelShiftLUTPrec); iInterPolPos++)
+        {
+          if ( (iInterPolPos >= iWidth) || (iInterPolPos < (Int) 0))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            continue;
+          };
+
+          // Interpolate
+          Int iDeltaCurPos  = (iInterPolPos << m_iRelShiftLUTPrec) - iPrevShiftedPos;
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            Pel cVal  = (( apcInputData[uiCurPlane][iPosX - 1] * iDeltaPos +  ( apcInputData[uiCurPlane][iPosX] - apcInputData[uiCurPlane][iPosX - 1] ) * iDeltaCurPos ) / iDeltaPos );
+            apcOutputData[uiCurPlane][iInterPolPos]  = cVal;
+          }
+
+          pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+        }
+      }
+      else
+      { // Extrapolate right from dLeftPos and left from dRightPos
+        Int iShiftedPosCeiled = (( iPrevShiftedPos + (1 << m_iRelShiftLUTPrec) - 1) >> m_iRelShiftLUTPrec ) << m_iRelShiftLUTPrec;
+        if ( (iPrevShiftedPos + (m_iRelShiftLUTPrec >> 1) ) > iShiftedPosCeiled )
+        {
+          iInterPolPos = iShiftedPosCeiled >> m_iRelShiftLUTPrec;
+
+          if ( (iInterPolPos >= iWidth) || (iInterPolPos < (Int) 0))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            iPrevShiftedPos = iShiftedPos;
+            continue;
+          };
+
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX - 1];
+          }
+
+          pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+        }
+
+        Int iPrevShiftedPosFloor = (iShiftedPos >> m_iRelShiftLUTPrec) << m_iRelShiftLUTPrec;
+        if (iShiftedPos - (m_iRelShiftLUTPrec > 1) < iPrevShiftedPosFloor )
+        {
+          iInterPolPos = iPrevShiftedPosFloor >> m_iRelShiftLUTPrec;
+
+          if ( (iInterPolPos >= iWidth) || (iInterPolPos < (Int) 0))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            iPrevShiftedPos = iShiftedPos;
+            continue;
+          };
+
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX ];
+          }
+
+          pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+        }
+      }
+      iPrevShiftedPos = iShiftedPos;
+    }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+  delete[] apcInputData;
+  delete[] apcOutputData;
+};
+
+
+Void TRenTop::xShiftPlanePixelsLinReal( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes )
+{
+  Int iWidth        = apcInputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes[0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  pcFilledPlane->assign( REN_IS_HOLE );
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    assert( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    assert( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    assert( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+  ///// FEM Stuff /////
+  const UInt  cuiMaxPlaneNum = 6;  AOT( uiNumberOfPlanes > cuiMaxPlaneNum );
+  IntImagePlane* apcDiffPlane[ cuiMaxPlaneNum ];
+  Int*          ppiDiffPlanes[ cuiMaxPlaneNum ];
+  Int             iDiffStride = 0;
+
+  if ( m_iInterpolationMode == eRenIntFEM )
+  {
+    AOT( uiNumberOfPlanes > cuiMaxPlaneNum );
+    for ( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
+    {
+      apcDiffPlane[uiCurPlane] = new IntImagePlane( iWidth, iHeight, apcInputPlanes[uiCurPlane]->getPad());
+      TRenFilter::diffHorSym(apcInputPlanes[uiCurPlane] , apcDiffPlane[uiCurPlane]);
+      ppiDiffPlanes[uiCurPlane] = apcDiffPlane[uiCurPlane]->getPlaneData();
+    }
+    iDiffStride = apcDiffPlane[0]->getStride();
+  }
+  ///// FEM Stuff End /////
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    Double dShiftedPos = 0;
+    Double dPrevShiftedPos = 0;
+
+    for(Int iPosX = 0; iPosX < iWidth; iPosX ++ )
+    {
+        Bool bExtrapolate = false;
+
+        // compute disparity and shift
+        assert( RemoveBitIncrement(pcDepthData[iPosX]) >= 0 && RemoveBitIncrement(pcDepthData[iPosX]) <= 256 );
+        dPrevShiftedPos  = (Double) iPosX - m_adShiftLUTCur[ RemoveBitIncrement(pcDepthData[iPosX])];
+
+        if (iPosX == 0)
+        {
+          // in first iteration only get dLeftPos
+          dShiftedPos = dPrevShiftedPos;
+          continue;
+        };
+
+        Double dDeltaPos = dPrevShiftedPos - dShiftedPos;
+
+        if ((dDeltaPos <= 0) || ( dDeltaPos > 2 ))
+        {
+          // skip Interpolation if pixel is shifted backwards (foreground object)  or if pixel is shifted forwards (gap)
+          bExtrapolate = true;
+        };
+
+        Int iInterPolPos;
+        if (!bExtrapolate)
+        {  // Interpolate between j1 and j2
+          for (iInterPolPos = (Int) ceil(dShiftedPos); iInterPolPos <= floor(dPrevShiftedPos); iInterPolPos++)
+          {
+            if ( (iInterPolPos >= (Int) iWidth) || (iInterPolPos < (Int) 0 ))
+            {
+              // skip Interpolation if Interpolation position is outside frame
+              continue;
+            };
+
+            // Interpolate
+            Pel cVal;
+            if ( m_iInterpolationMode == eRenIntFEM ) //FEM Interpolation
+            {
+              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] );
+                apcOutputData[uiCurPlane][iInterPolPos]  = cVal;
+              }
+            }
+            else
+            {
+              Double dDeltaJ  = (Double) iInterPolPos - dShiftedPos;
+
+              for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+              {
+                cVal  = (UChar) ( (Double) apcInputData[uiCurPlane][iPosX - 1] +  ( (Double) apcInputData[uiCurPlane][iPosX] - (Double) apcInputData[uiCurPlane][iPosX - 1] ) / dDeltaPos * dDeltaJ + 0.5);
+                apcOutputData[uiCurPlane][iInterPolPos]  = cVal;
+              }
+            };
+
+            pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+          }
+        }
+        else
+        { // Extrapolate right from dLeftPos and left from dRightPos
+          if (dShiftedPos + 0.5 > ceil(dShiftedPos))
+          {
+            iInterPolPos = (Int) ceil(dShiftedPos);
+
+            if ( (iInterPolPos >= (Int) iWidth) || (iInterPolPos < (Int) 0))
+            {
+              // skip Interpolation if Interpolation position is outside frame
+              dShiftedPos = dPrevShiftedPos;
+              continue;
+            };
+
+            for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+            {
+              apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX - 1];
+            }
+
+            pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+          }
+
+          if (dPrevShiftedPos - 0.5 < floor(dPrevShiftedPos))
+          {
+            iInterPolPos = (Int) floor(dPrevShiftedPos);
+
+            if ( (iInterPolPos >= (Int) iWidth) || (iInterPolPos < (Int) 0))
+            {
+              // skip Interpolation if Interpolation position is outside frame
+              dShiftedPos = dPrevShiftedPos;
+              continue;
+            };
+
+            for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+            {
+              apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX ];
+            }
+
+            pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+          }
+        }
+        dShiftedPos = dPrevShiftedPos;
+      }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+
+      if (m_iInterpolationMode ==  eRenIntFEM)
+      {
+        ppiDiffPlanes[ uiCurPlane ] += iDiffStride;
+      }
+    }
+
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+
+  if (m_iInterpolationMode ==  eRenIntFEM)
+  {
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      delete apcDiffPlane[uiCurPlane];
+    }
+  }
+
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+
+Void TRenTop::xShiftPlanePixels( PelImagePlane** apcInPlane, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutPlane, PelImagePlane* pcPlaneFilled, UInt uiNumberOfPlanes )
+{
+  switch ( m_iInterpolationMode)
+  {
+  case eRenIntFullPel:
+    xShiftPlanePixelsFullPel( apcInPlane, pcDepthPlane, apcOutPlane, pcPlaneFilled, uiNumberOfPlanes);
+    break;
+  case eRenIntFEM:
+  case eRenIntLinReal:
+    xShiftPlanePixelsLinReal( apcInPlane, pcDepthPlane, apcOutPlane, pcPlaneFilled, uiNumberOfPlanes);
+    break;
+  case eRenIntLinInt:
+    xShiftPlanePixelsLinInt ( apcInPlane, pcDepthPlane, apcOutPlane, pcPlaneFilled, uiNumberOfPlanes);
+    break;
+  case eRenInt8Tap:
+    xShiftPlanePixels8Tap   ( apcInPlane, pcDepthPlane, apcOutPlane, pcPlaneFilled, uiNumberOfPlanes );
+    break;
+  default:
+    AOF( false );
+  }
+}
+
+
+Void TRenTop::xShiftPlanePixelsFullPel( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes )
+{
+  Int iWidth        = apcInputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes[0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  pcFilledPlane->assign(REN_IS_HOLE);
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    assert( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    assert( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    assert( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    Int iPrevShiftedPos = -1;
+
+    for(Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      assert( RemoveBitIncrement(pcDepthData[iPosX]) >= 0 && RemoveBitIncrement(pcDepthData[iPosX]) <= 256 );
+      Int iShiftedPos = iPosX - m_aiShiftLUTCur[ RemoveBitIncrement(pcDepthData[iPosX])] ;
+      if (iShiftedPos < iWidth && iShiftedPos >= 0)
+      {
+        Int iDiff = iShiftedPos - iPrevShiftedPos;
+        if (( iDiff <= 2) && (iDiff > 0) )
+        {
+          for (Int iCurPos = iPrevShiftedPos+1; iCurPos <= iShiftedPos; iCurPos++)
+          {
+            for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+            {
+              apcOutputData[uiCurPlane][iCurPos] = apcInputData[uiCurPlane][iPosX];    // Only small gaps, therefor not necessary NN
+            }
+            pcFilledData[iCurPos] = REN_IS_FILLED;
+          }
+        }
+        else
+        {
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iShiftedPos] = apcInputData[uiCurPlane][iPosX];
+          }
+          pcFilledData[iShiftedPos] = REN_IS_FILLED;
+        }
+        iPrevShiftedPos = iShiftedPos;
+      }
+    }
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+Void TRenTop::xBackShiftPlanePixels( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes )
+{
+  Int iOutputWidth  = apcOutputPlanes[0]->getWidth();
+  Int iInputWidth   = apcInputPlanes [0]->getWidth();
+  Int iHeight       = apcInputPlanes [0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  Int iStep         = (1 << m_iRelShiftLUTPrec);
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    AOF( iInputWidth   == apcInputPlanes [uiCurPlane]->getWidth()  && iOutputWidth  == apcOutputPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    AOF( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+    AOF( iInputWidth   == iOutputWidth * iStep );
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    for(Int iPosX = 0; iPosX < iOutputWidth; iPosX ++)
+    {
+      Int iBackShiftedPos = (iPosX << m_iRelShiftLUTPrec) - m_aiShiftLUTCur[ RemoveBitIncrement( pcDepthData[iPosX] )];
+      if( ( pcFilledData[iPosX] == REN_IS_FILLED )  && (iBackShiftedPos >= 0 ) && ( iBackShiftedPos < iInputWidth ) )
+      {
+        for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+        {
+          apcOutputData[uiCurPlane][iPosX] = apcInputData[uiCurPlane][iBackShiftedPos];
+        }
+      }
+      else
+      {
+        for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+        {
+          apcOutputData[uiCurPlane][iPosX] = 0;
+        }
+        pcFilledData[iPosX] = REN_IS_HOLE;
+      }
+    }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+Void TRenTop::xShiftPlanePixels8Tap( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes  )
+{
+  Bool bRenderDepth = (apcInputPlanes[0] == pcDepthPlane);
+
+  Int iOutputWidth  = apcOutputPlanes[0]->getWidth();
+  Int iInputWidth   = apcInputPlanes [0]->getWidth();
+  Int iHeight       = apcInputPlanes [0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  Int iStep         = (1 << m_iRelShiftLUTPrec);
+
+  pcFilledPlane->assign(REN_IS_HOLE);
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    AOF( iInputWidth   == apcInputPlanes [uiCurPlane]->getWidth()  && iOutputWidth  == apcOutputPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    AOF( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+    AOF( iInputWidth   == iOutputWidth * iStep );
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    Int iPrevShiftedPos = -1;
+    Int iShiftedPos     = -1;
+
+    for(Int iPosX = 0; iPosX < iInputWidth; iPosX += iStep )
+    {
+      // compute disparity and shift
+      iShiftedPos  =  iPosX - m_aiShiftLUTCur[RemoveBitIncrement(pcDepthData[iPosX])];
+
+      if ( iPosX == 0 )
+      {
+        // in first iteration only get dLeftPos
+        iPrevShiftedPos = iShiftedPos;
+        continue;
+      };
+
+      Int iDeltaPos = iShiftedPos - iPrevShiftedPos;
+
+      Bool bDisocclusion = ( iDeltaPos > (2 << m_iRelShiftLUTPrec) );
+      Bool bOcclusion    = ( iDeltaPos <= 0 );
+
+      Int iInterPolPos;
+      if ( !bDisocclusion && !bOcclusion )
+      {  // Interpolate between previous shifted pos and shifted pos
+        for (iInterPolPos = xCeil( iPrevShiftedPos ); iInterPolPos <= xCeil (iShiftedPos ) -1 ; iInterPolPos++)
+        {
+          if ( (iInterPolPos < (Int) 0) || (iInterPolPos >= iOutputWidth))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            continue;
+          };
+
+          // Interpolate
+          Int iDeltaCurPos  = (iInterPolPos << m_iRelShiftLUTPrec) - iPrevShiftedPos;
+
+          AOF( (iDeltaCurPos <= iDeltaPos) && ( iDeltaCurPos >= 0));
+          AOF( iDeltaPos    <= (2 <<  m_iRelShiftLUTPrec)  );
+          AOF( m_aaiSubPelShift[iDeltaPos][iDeltaCurPos] != 0xdeaddead);
+
+          Int iSourcePos;
+
+          if ( bRenderDepth )
+          {
+            iSourcePos = iPosX - iStep; // Render depth with Full Pel accuracy to avoid ringing at sharp depth edges;
+          }
+          else
+          {
+            iSourcePos = iPosX +  m_aaiSubPelShift[iDeltaPos][iDeltaCurPos];   // GT:  = iPosX - iStep + ( iStep * iDeltaCurPos + ( iDeltaPos >> 1) ) / iDeltaPos;
+          }
+
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iInterPolPos] = apcInputData[uiCurPlane][iSourcePos];
+          }
+
+          pcFilledData[ iInterPolPos]  = REN_IS_FILLED;
+        }
+      }
+      else
+        {
+        // Fill Disocclusion Edge
+
+        if ( bDisocclusion )
+        {
+          Int iPrevShiftedPosCeiled =  xCeil(iPrevShiftedPos) << m_iRelShiftLUTPrec;
+          iInterPolPos = iPrevShiftedPosCeiled >> m_iRelShiftLUTPrec;
+
+          if ((iPrevShiftedPos + (iStep >> 1) ) > iPrevShiftedPosCeiled )
+          {
+            if ( !((iInterPolPos < (Int) 0) || (iInterPolPos >= iOutputWidth)))
+            {
+
+              for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+              {
+                apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX - iStep];
+              }
+              pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+
+            }           
+            iInterPolPos++;
+          }          
+
+          // Fill Disocclusion
+          if ( m_bInstantHoleFilling )
+          {
+            for ( ; iInterPolPos <= xCeil (iShiftedPos ) -1 ; iInterPolPos++)
+            {
+              for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+              {
+                if ( ( iInterPolPos >= 0 ) && ( iInterPolPos < iOutputWidth ) )
+                {
+                  apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX];
+                }
+              }
+            }
+          }
+        }
+
+        //// Last sample next to occlusion
+        Int iShiftedPosFloor = ( iShiftedPos >> m_iRelShiftLUTPrec ) << m_iRelShiftLUTPrec;
+        if ( bOcclusion && (iShiftedPos - (iStep >> 1) < iShiftedPosFloor) )
+        {
+          iInterPolPos = iShiftedPosFloor >> m_iRelShiftLUTPrec;
+          if ( !((iInterPolPos < (Int) 0) || (iInterPolPos >= iOutputWidth)))
+          {        
+            for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+            {
+              apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX ];
+            }
+
+            pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+          }
+        }
+      }
+      iPrevShiftedPos = iShiftedPos;
+    }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+  delete[] apcInputData;
+  delete[] apcOutputData;
+};
+
+Void TRenTop::xShiftPixels(PelImage* pcInImage, PelImage* pcDepth, PelImage* pcOutImage, PelImage* pcFilledImage, Bool bShiftFromLeft )
+{
+  PelImage*  pcTemp = 0;
+
+  if (pcInImage == pcOutImage)
+  {
+    pcTemp = pcOutImage->create();
+  }
+  else
+  {
+    pcTemp = pcOutImage;
+  }
+
+  Double ** ppdShiftLUT = bShiftFromLeft ? m_ppdShiftLUTLeft : m_ppdShiftLUTRightMirror;
+  Int    ** ppiShiftLUT = bShiftFromLeft ? m_ppiShiftLUTLeft : m_ppiShiftLUTRightMirror;
+
+  UInt uiNumFullPlanes = pcInImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcInImage->getNumberOfQuaterPlanes();
+
+  assert( uiNumFullPlanes == pcOutImage->getNumberOfFullPlanes  () );
+  assert( uiNumQuatPlanes == pcOutImage->getNumberOfQuaterPlanes() );
+
+  m_aiShiftLUTCur = ppiShiftLUT[ 0 ];
+  m_adShiftLUTCur = ppdShiftLUT[ 0 ];
+
+  xShiftPlanePixels( pcInImage->getPlanes(), pcDepth->getPlane(0),  pcOutImage->getPlanes(), pcFilledImage->getPlane(0),  uiNumFullPlanes  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert( pcDepth->getNumberOfPlanes() > 1 && pcFilledImage->getNumberOfPlanes() > 1);
+    m_aiShiftLUTCur = ppiShiftLUT[ 1 ];
+    m_adShiftLUTCur = ppdShiftLUT[ 1 ];
+    xShiftPlanePixels( pcInImage->getPlanes()+uiNumFullPlanes,pcDepth->getPlane(1),  pcOutImage->getPlanes() + uiNumFullPlanes, pcFilledImage->getPlane(1),  uiNumQuatPlanes );
+  }
+
+  if (pcInImage == pcOutImage)
+  {
+    pcOutImage->assign(pcTemp);
+    delete pcTemp;
+  };
+};
+
+Void TRenTop::xBackShiftPixels(PelImage* pcInImage, PelImage* pcDepth, PelImage* pcOutImage, PelImage* pcFilledImage, Bool bShiftFromLeft )
+{
+  PelImage*  pcTemp = 0;
+
+  if (pcInImage == pcOutImage)
+  {
+    pcTemp = pcOutImage->create();
+  }
+  else
+  {
+    pcTemp = pcOutImage;
+  }
+
+  Double ** ppdShiftLUT = bShiftFromLeft ? m_ppdShiftLUTLeft : m_ppdShiftLUTRight;
+  Int    ** ppiShiftLUT = bShiftFromLeft ? m_ppiShiftLUTLeft : m_ppiShiftLUTRight;
+
+  UInt uiNumFullPlanes = pcInImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcInImage->getNumberOfQuaterPlanes();
+
+  assert( uiNumFullPlanes == pcOutImage->getNumberOfFullPlanes  () );
+  assert( uiNumQuatPlanes == pcOutImage->getNumberOfQuaterPlanes() );
+
+  m_aiShiftLUTCur = ppiShiftLUT[ 0 ];
+  m_adShiftLUTCur = ppdShiftLUT[ 0 ];
+
+  xBackShiftPlanePixels( pcInImage->getPlanes(), pcDepth->getPlane(0),  pcOutImage->getPlanes(), pcFilledImage->getPlane(0),  uiNumFullPlanes  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert( pcDepth->getNumberOfPlanes() > 1 && pcFilledImage->getNumberOfPlanes() > 1);
+    m_aiShiftLUTCur = ppiShiftLUT[ 1 ];
+    m_adShiftLUTCur = ppdShiftLUT[ 1 ];
+    xBackShiftPlanePixels( pcInImage->getPlanes()+uiNumFullPlanes,pcDepth->getPlane(1),  pcOutImage->getPlanes() + uiNumFullPlanes, pcFilledImage->getPlane(1),  uiNumQuatPlanes );
+  }
+
+  if (pcInImage == pcOutImage)
+  {
+    pcOutImage->assign(pcTemp);
+    delete pcTemp;
+  };
+};
+
+Void TRenTop::xFillHoles(PelImage* pcInImage, PelImage* pcFilled, PelImage* pcOutImage, Bool bRenderFromLeft )
+{
+  if (pcInImage != pcOutImage)
+  {
+    pcOutImage->assign(pcInImage);
+  }
+
+  switch (m_iHoleFillingMode)
+  {
+    case eRenHFNone:
+      break;
+    case eRenHFLWBackExt:
+      xFillLWBackExt( pcInImage, pcFilled, pcOutImage, bRenderFromLeft);
+      break;
+    default:
+      break;
+  }
+};
+
+Void TRenTop::xFillLWBackExt( PelImage* pcInImage, PelImage* pcFilledImage, PelImage* pcOutImage, Bool bRenderFromLeft )
+{
+  UInt uiNumFullPlanes = pcInImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcInImage->getNumberOfQuaterPlanes();
+
+  assert( uiNumFullPlanes == pcOutImage->getNumberOfFullPlanes  () );
+  assert( uiNumQuatPlanes == pcOutImage->getNumberOfQuaterPlanes() );
+
+  xFillPlaneHoles( pcInImage->getPlanes(), pcFilledImage->getPlane(0), pcOutImage->getPlanes(),  uiNumFullPlanes, bRenderFromLeft  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert(  pcFilledImage->getNumberOfPlanes() > 1);
+    xFillPlaneHoles( pcInImage->getPlanes()+uiNumFullPlanes, pcFilledImage->getPlane(1), pcOutImage->getPlanes() + uiNumFullPlanes,  uiNumQuatPlanes, bRenderFromLeft );
+  }
+};
+
+Void TRenTop::xCreateAlphaMap(PelImage* pcFilledImage, PelImage* pcAlphaMapImage, Bool bRenderFromLeft )
+{
+  UInt uiNumFullPlanes = pcFilledImage  ->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcFilledImage->getNumberOfQuaterPlanes();
+
+  AOF( uiNumFullPlanes == pcAlphaMapImage->getNumberOfFullPlanes  () );
+  AOF( uiNumQuatPlanes == pcAlphaMapImage->getNumberOfQuaterPlanes() );
+
+  xCreateAlphaMapPlane( pcFilledImage->getPlanes(),  pcAlphaMapImage->getPlanes(),  uiNumFullPlanes, bRenderFromLeft  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    AOF(  pcFilledImage->getNumberOfPlanes() > 1);
+    xCreateAlphaMapPlane( pcFilledImage->getPlanes()+ uiNumFullPlanes, pcAlphaMapImage->getPlanes()+uiNumFullPlanes,  uiNumQuatPlanes, bRenderFromLeft );
+  }
+};
+
+Void TRenTop::xCreateAlphaMapPlane(PelImagePlane** apcFilledPlanes,  PelImagePlane** apcAlphaPlanes,  UInt uiNumberOfPlanes, Bool bRenderFromLeft)
+{
+  Int iWidth            = apcFilledPlanes [0]->getWidth();
+  Int iHeight           = apcFilledPlanes [0]->getHeight();
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    AOF( iWidth         == apcFilledPlanes [uiCurPlane]->getWidth()  && iWidth        == apcAlphaPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight        == apcFilledPlanes [uiCurPlane]->getHeight() && iHeight       == apcAlphaPlanes[uiCurPlane]->getHeight());
+  }
+
+  Int iBlendWidth  = m_iBlendHoleMargin;
+  Int iMaxBlendLevel;
+
+  if (!m_bBlendUseDistWeight )
+  {
+    iMaxBlendLevel = ( 1 <<  REN_VDWEIGHT_PREC ) ;
+
+    if ( m_iBlendMode == 0)
+    {
+      iMaxBlendLevel >>= 1;
+    }
+  }
+  else
+  {
+    if ( m_iBlendMode == 0)
+    {
+      iMaxBlendLevel = bRenderFromLeft ? (1 << REN_VDWEIGHT_PREC) - m_iBlendDistWeight :  m_iBlendDistWeight;
+    }
+    else
+    {
+      iMaxBlendLevel  = ( 1 <<  REN_VDWEIGHT_PREC );
+    }
+  }
+
+  Int iWeightStep = (iBlendWidth > 0) ? ( iMaxBlendLevel + (iBlendWidth >> 1) ) / iBlendWidth : 0;
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    Int iFilledStride   = apcFilledPlanes [uiCurPlane]->getStride();
+    Int iAlphaStride    = apcAlphaPlanes  [uiCurPlane]->getStride();
+
+    Pel* pcFilledData = apcFilledPlanes   [uiCurPlane]->getPlaneData();
+    Pel* pcAlphaData  = apcAlphaPlanes    [uiCurPlane]->getPlaneData();
+
+    for(Int iYPos = 0; iYPos < iHeight; iYPos++)
+    {
+      for(Int iXPos = 0 ; iXPos < iWidth; iXPos++ )
+      {
+        if (pcFilledData[iXPos] == REN_IS_HOLE)
+        {
+          while( (pcFilledData[iXPos] == REN_IS_HOLE) && (iXPos < iWidth) )
+          {
+            pcAlphaData[iXPos] = REN_IS_HOLE;
+            iXPos++;
+          }
+
+          if ( iXPos >= iWidth )
+            continue;
+
+          Int iWeight = 0;
+          Int iLastFillPos = iXPos + iBlendWidth;
+
+          while( (pcFilledData[iXPos] != REN_IS_HOLE) && (iXPos < iWidth) && (iXPos < iLastFillPos) )
+          {
+            AOF(  iWeight <= (1 << REN_VDWEIGHT_PREC) );
+            pcAlphaData[iXPos]  = (iWeight == 0) ? 1 : iWeight;
+            iWeight += iWeightStep;
+            iXPos++;
+          }
+        }
+        else
+        {
+          pcAlphaData[iXPos] = REN_IS_FILLED;
+        }
+      }
+      pcAlphaData    += iAlphaStride;
+      pcFilledData   += iFilledStride;
+    }
+  }
+}
+
+Void TRenTop::xRemBoundaryNoise(PelImage* pcInImage, PelImage* pcFilledImage, PelImage* pcOutImage, Bool bRenderFromLeft )
+{
+  if (pcInImage != pcOutImage)
+  {
+    pcOutImage->assign(pcInImage);
+  }
+
+  UInt uiNumFullPlanes = pcInImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcInImage->getNumberOfQuaterPlanes();
+
+  AOF( uiNumFullPlanes == pcOutImage->getNumberOfFullPlanes  () );
+  AOF( uiNumQuatPlanes == pcOutImage->getNumberOfQuaterPlanes() );
+
+  xRemBoundaryNoisePlane( pcInImage->getPlanes(), pcFilledImage->getPlane(0), pcOutImage->getPlanes(),  uiNumFullPlanes, bRenderFromLeft  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    AOF(  pcFilledImage->getNumberOfPlanes() > 1);
+    xRemBoundaryNoisePlane( pcInImage->getPlanes()+uiNumFullPlanes, pcFilledImage->getPlane(1), pcOutImage->getPlanes() + uiNumFullPlanes,  uiNumQuatPlanes, bRenderFromLeft );
+  }
+};
+
+Void TRenTop::xRemBoundaryNoisePlane(PelImagePlane** apcInputPlanes,  PelImagePlane* pcFilledPlane, PelImagePlane** apcOutputPlanes, UInt uiNumberOfPlanes, Bool bRenderFromLeft)
+{
+  Int iWidth        = apcOutputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes [0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+  Pel*   pcFilledData = pcFilledPlane->getPlaneData();
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    AOF( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    AOF( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  Int iRemovalWidth  = m_iBlendHoleMargin;
+  AOT(iRemovalWidth > 6);  // GT: insufficent padding
+
+  for(Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for(Int iXPos = iWidth-1; iXPos >= 0; iXPos-- )
+    {
+      if (pcFilledData[iXPos] == REN_IS_HOLE)
+      {
+        Int iSourcePos = iXPos + 1;
+
+        // Get New Value
+        while( (pcFilledData[iSourcePos] != REN_IS_HOLE) && ( iSourcePos < iWidth) && ( iSourcePos < iXPos + iRemovalWidth  ) ) iSourcePos++;
+
+        if (iSourcePos == iWidth || pcFilledData[iSourcePos] != REN_IS_HOLE )
+          iSourcePos--;
+
+        Int iXPosRem = iSourcePos - 1;
+
+        // Remove
+        while( iXPosRem > iXPos)
+        {
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iXPosRem] = apcInputData[uiCurPlane][iSourcePos];
+          }
+
+          iXPosRem--;
+        }
+
+        // Skip Hole
+        while( (pcFilledData[iXPos] == REN_IS_HOLE) && ( iXPos > 0) ) iXPos--;
+      }
+    }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+  }
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+Void TRenTop::xFillPlaneHoles(PelImagePlane** apcInputPlanes,  PelImagePlane* pcFilledPlane, PelImagePlane** apcOutputPlanes, UInt uiNumberOfPlanes, Bool bRenderFromLeft)
+{
+  Int iWidth        = apcOutputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes [0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+  Pel*   pcFilledData = pcFilledPlane->getPlaneData();
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    AOF( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    AOF( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  for(Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    if ( !m_bInstantHoleFilling )
+    {
+    for(Int iXPos = 0 ; iXPos < iWidth; iXPos++ )
+    {
+      if (pcFilledData[iXPos] == REN_IS_HOLE)
+      {
+          Int iSourcePos;
+          Int iLastFillPos;
+
+        Int iXPosSearch = iXPos;
+        while( (pcFilledData[iXPosSearch] == REN_IS_HOLE) && (iXPosSearch < iWidth) ) iXPosSearch++;
+
+          if ( iXPosSearch >= iWidth )
+        {
+            continue;
+          }
+          else
+          {
+            iSourcePos   = iXPosSearch;
+            iLastFillPos = iXPosSearch-1;
+          }
+
+        while( iXPos <= iLastFillPos)
+        {
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iXPos] = apcInputData[uiCurPlane][iSourcePos];
+          }
+          iXPos++;
+        }
+        }
+      }
+    }
+
+    // Fill Right Gap
+    Int iXPosSearch = iWidth -1;
+    while( (pcFilledData[iXPosSearch] == REN_IS_HOLE) && (iXPosSearch >= 0) ) iXPosSearch--;
+    if ( iXPosSearch < 0) iXPosSearch++;
+
+    Int iSourcePos = iXPosSearch;
+
+    for( Int iXPos = iSourcePos + 1; iXPos <  iWidth; iXPos++)
+    {
+      for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+      {
+        apcOutputData[uiCurPlane][iXPos] = apcInputData[uiCurPlane][iSourcePos];
+      }
+    }
+
+    // Fill Left Gap
+    iXPosSearch = 0;
+    while( (pcFilledData[iXPosSearch] == REN_IS_HOLE) && (iXPosSearch < iWidth) ) iXPosSearch++;
+    if ( iXPosSearch >= iWidth) iXPosSearch--;
+
+    iSourcePos = iXPosSearch;
+
+    for( Int iXPos = iSourcePos - 1; iXPos >= 0; iXPos--)
+    {
+      for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+      {
+        apcOutputData[uiCurPlane][iXPos] = apcInputData[uiCurPlane][iSourcePos];
+      }
+    }
+
+    // Go to next line
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+  }
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+Void TRenTop::xPostProcessImage(PelImage* pcInImage, PelImage* pcOutImage)
+{
+  if ( m_iPostProcMode == eRenPostProNone )
+    return;
+
+  PelImage* pcTemp;
+
+  if (pcInImage == pcOutImage)
+  {
+    pcTemp = pcOutImage->create();
+  }
+  else
+  {
+    pcTemp = pcOutImage;
+  }
+
+  pcTemp->assign(pcInImage);
+
+  switch ( m_iPostProcMode )
+  {
+  case eRenPostProMed:
+    TRenFilter::lineMedian3(pcTemp);
+    break;
+  case eRenPostProNone:
+    break;
+  default:
+    assert(0);
+  }
+
+  if (pcInImage == pcOutImage)
+  {
+    pcOutImage->assign(pcTemp);
+    delete pcTemp;
+  };
+}
+
+
+Void TRenTop::xCutPlaneMargin( PelImagePlane* pcImagePlane, Pel cFill, UInt uiScale )
+{
+  UInt uiWidth  = pcImagePlane->getWidth();
+  UInt uiHeight = pcImagePlane->getHeight();
+
+  UInt uiStride    = pcImagePlane->getStride();
+  Pel* pcPlaneData = pcImagePlane->getPlaneData();
+
+  UInt uiCutLeft  =           m_auiCut[0] / uiScale;
+  UInt uiCutRight = uiWidth - m_auiCut[1] / uiScale;
+
+  for(UInt uiYPos = 0; uiYPos < uiHeight; uiYPos++)
+  {
+    for(UInt uiXPos = 0; uiXPos < (UInt) uiWidth ; uiXPos++)
+    {
+      if ( ( uiXPos < uiCutLeft  )  || (  uiXPos >=  uiCutRight )  )
+      {
+        pcPlaneData[uiXPos ] = cFill;
+      }
+    }
+    pcPlaneData += uiStride;
+  }
+};
+
+Void TRenTop::xCutMargin( PelImage* pcInputImage )
+{
+  if  ( ( m_auiCut[0] == 0 ) && ( m_auiCut[1] == 0 ) )
+  {
+    return;
+  };
+
+  UInt uiCurPlane = 0;
+  for (; uiCurPlane < pcInputImage->getNumberOfFullPlanes(); uiCurPlane++ )
+  {
+    xCutPlaneMargin( pcInputImage->getPlane(uiCurPlane), (Pel) 0  , 1 );
+  }
+
+  for (; uiCurPlane < pcInputImage->getNumberOfPlanes(); uiCurPlane++ )
+  {
+    xCutPlaneMargin( pcInputImage->getPlane(uiCurPlane), (Pel) 128  , 2 );
+  }
+
+};
+
+
+Void TRenTop::xEnhSimilarity( PelImage* pcLeftImage, PelImage* pcRightImage, PelImage* pcFilledLeft, PelImage* pcFilledRight )
+{
+  if (m_iSimEnhBaseView == 0)
+    return;
+
+  UInt uiNumFullPlanes = pcLeftImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcLeftImage->getNumberOfQuaterPlanes();
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert( pcFilledLeft ->getNumberOfPlanes() > 1);
+    assert( pcFilledRight->getNumberOfPlanes() > 1);
+  };
+
+  xEnhSimilarityPlane ( pcLeftImage->getPlanes()                , pcRightImage->getPlanes()                , pcFilledLeft->getPlane(0), pcFilledRight->getPlane(0), uiNumFullPlanes);
+  if (uiNumQuatPlanes > 0)
+  {
+    xEnhSimilarityPlane ( pcLeftImage->getPlanes()+uiNumFullPlanes, pcRightImage->getPlanes()+uiNumFullPlanes, pcFilledLeft->getPlane(1), pcFilledRight->getPlane(1), uiNumQuatPlanes);
+  }
+}
+
+Void TRenTop::xEnhSimilarityPlane       ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, UInt uiNumberOfPlanes )
+{
+  AOT( m_iSimEnhBaseView != 1 && m_iSimEnhBaseView != 2 );
+  Int iWidth  = (*apcRightPlane)->getWidth ();
+  Int iHeight = (*apcRightPlane)->getHeight();
+
+  Int* aiHistLeft  = new Int[ g_uiIBDI_MAX + 1 ];
+  Int* aiHistRight = new Int[ g_uiIBDI_MAX + 1 ];
+  Pel* aiConvLUT   = new Pel[ g_uiIBDI_MAX + 1 ];
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
+  {
+    for (Int iCurVal = 0 ; iCurVal <= g_uiIBDI_MAX; iCurVal++)
+    {
+      aiHistLeft [iCurVal] = 0;
+      aiHistRight[iCurVal] = 0;
+    }
+
+    Pel* pcFilledRightData = pcFilledRightPlane    ->getPlaneData();
+    Pel* pcRightImageData  = (*apcRightPlane )     ->getPlaneData();
+
+    Pel* pcFilledLeftData  = pcFilledLeftPlane     ->getPlaneData();
+    Pel* pcLeftImageData   = (*apcLeftPlane)       ->getPlaneData();
+
+ 
+
+    for (UInt uiYPos = 0; uiYPos < iHeight; uiYPos++ )
+    {
+      for (UInt uiXPos = 0; uiXPos < iWidth; uiXPos++ )
+      {
+          if      ( pcFilledLeftData[uiXPos] == REN_IS_FILLED &&  pcFilledRightData[uiXPos] == REN_IS_FILLED )
+          {
+            aiHistLeft [pcLeftImageData   [uiXPos] ]++;
+            aiHistRight[pcRightImageData  [uiXPos] ]++;
+          }
+      }
+
+
+      pcFilledRightData +=    pcFilledRightPlane  ->getStride();
+      pcRightImageData  += (*apcRightPlane)       ->getStride();
+
+      pcFilledLeftData  +=    pcFilledLeftPlane   ->getStride();
+      pcLeftImageData   +=  (*apcLeftPlane)       ->getStride();
+    }
+
+    Int iCumSumChange  = 0;
+    Int iCumSumBase    = 0;
+    Int iCurBaseVal    = 0;
+    Int iCurChangeVal  = 0;
+
+    Int* aiHistChange  = (m_iSimEnhBaseView == 2 ) ? aiHistLeft  : aiHistRight;
+    Int* aiHistBase    = (m_iSimEnhBaseView == 2 ) ? aiHistRight : aiHistLeft ;
+
+    iCumSumChange += aiHistChange[iCurChangeVal];
+    iCumSumBase   += aiHistBase  [iCurBaseVal]  ;
+
+    Int iCheckSumLeft  = 0;
+    Int iCheckSumRight = 0;
+
+    for (Int iCurVal = 0 ; iCurVal <= g_uiIBDI_MAX; iCurVal++)
+    {
+      iCheckSumLeft  += aiHistLeft [iCurVal];
+      iCheckSumRight += aiHistRight[iCurVal];
+    }
+
+
+    while( iCurChangeVal <= g_uiIBDI_MAX )
+    {
+      if ( iCumSumBase == iCumSumChange )
+      {
+        aiConvLUT[iCurChangeVal] = Min(iCurBaseVal, g_uiIBDI_MAX);
+        iCurBaseVal  ++;
+        iCurChangeVal++;
+        iCumSumChange += aiHistChange[iCurChangeVal];
+        if (iCurBaseVal <= g_uiIBDI_MAX )
+        {
+          iCumSumBase   += aiHistBase  [iCurBaseVal]  ;
+        }
+      }
+      else if ( iCumSumBase < iCumSumChange )
+      {
+        iCurBaseVal++;
+        if (iCurBaseVal <= g_uiIBDI_MAX )
+        {
+          iCumSumBase   += aiHistBase  [iCurBaseVal]  ;
+        }
+      }
+      else if ( iCumSumBase > iCumSumChange)
+      {
+        aiConvLUT[iCurChangeVal] = Min(iCurBaseVal, g_uiIBDI_MAX);
+        iCurChangeVal++;
+        iCumSumChange += aiHistChange  [iCurChangeVal]  ;
+      }
+    }
+
+    Pel* pcChangeImageData   = ( ( m_iSimEnhBaseView == 2 ) ? (*apcLeftPlane) : (*apcRightPlane) )->getPlaneData();
+    Int  iChangeImageStride  = ( ( m_iSimEnhBaseView == 2 ) ? (*apcLeftPlane) : (*apcRightPlane) )->getStride   ();
+
+    for (UInt uiYPos = 0; uiYPos < iHeight; uiYPos++ )
+    {
+      for (UInt uiXPos = 0; uiXPos < iWidth; uiXPos++ )
+      {
+          pcChangeImageData  [uiXPos] = aiConvLUT[ pcChangeImageData[uiXPos]];
+      }
+      pcChangeImageData   +=  iChangeImageStride;
+    }
+
+    apcRightPlane ++;
+    apcLeftPlane  ++;
+
+  }
+
+delete[] aiHistLeft ;
+delete[] aiHistRight;
+delete[] aiConvLUT  ;
+}
+
+
+Void TRenTop::xBlend( PelImage* pcLeftImage, PelImage* pcRightImage, PelImage* pcFilledLeft, PelImage* pcFilledRight, PelImage* pcLeftDepth, PelImage* pcRightDepth, PelImage* pcOutputImage )
+{
+  UInt uiNumFullPlanes = pcLeftImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcLeftImage->getNumberOfQuaterPlanes();
+
+  assert( uiNumFullPlanes == pcRightImage->getNumberOfFullPlanes  () && uiNumFullPlanes == pcOutputImage->getNumberOfFullPlanes    ());
+  assert( uiNumQuatPlanes == pcRightImage->getNumberOfQuaterPlanes() && uiNumQuatPlanes == pcOutputImage->getNumberOfQuaterPlanes  ());
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert( pcLeftDepth ->getNumberOfPlanes() > 1 || pcFilledLeft ->getNumberOfPlanes() > 1);
+    assert( pcRightDepth->getNumberOfPlanes() > 1 || pcFilledRight->getNumberOfPlanes() > 1);
+  };
+
+  switch (m_iBlendMode)
+  {
+  case eRenBlendAverg:
+  case eRenBlendDepthFirst:
+    xBlendPlanesAvg( pcLeftImage->getPlanes()                , pcRightImage->getPlanes()                , pcFilledLeft->getPlane(0), pcFilledRight->getPlane(0), pcLeftDepth->getPlane(0), pcRightDepth->getPlane(0), pcOutputImage->getPlanes(), uiNumFullPlanes);
+    if (uiNumQuatPlanes > 0)
+    {
+      xBlendPlanesAvg( pcLeftImage->getPlanes()+uiNumFullPlanes, pcRightImage->getPlanes()+uiNumFullPlanes, pcFilledLeft->getPlane(1), pcFilledRight->getPlane(1), pcLeftDepth->getPlane(1), pcRightDepth->getPlane(1), pcOutputImage->getPlanes()+uiNumFullPlanes, uiNumQuatPlanes);
+    }
+    break;
+  case eRenBlendLeft:
+  case eRenBlendRight:
+    xBlendPlanesOneView( pcLeftImage->getPlanes()                , pcRightImage->getPlanes()                , pcFilledLeft->getPlane(0), pcFilledRight->getPlane(0), pcLeftDepth->getPlane(0), pcRightDepth->getPlane(0), pcOutputImage->getPlanes(), uiNumFullPlanes);
+    if (uiNumQuatPlanes > 0)
+    {
+      xBlendPlanesOneView( pcLeftImage->getPlanes()+uiNumFullPlanes, pcRightImage->getPlanes()+uiNumFullPlanes, pcFilledLeft->getPlane(1), pcFilledRight->getPlane(1), pcLeftDepth->getPlane(1), pcRightDepth->getPlane(1), pcOutputImage->getPlanes()+uiNumFullPlanes, uiNumQuatPlanes);
+    }
+    break;
+  }
+}
+
+Void TRenTop::xBlendPlanesOneView( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, PelImagePlane* pcLeftDepthPlane, PelImagePlane* pcRightDepthPlane, PelImagePlane** apcOutputImagePlane, UInt uiNumberOfPlanes )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
+  {
+    Pel* pcFilledRightData = pcFilledRightPlane    ->getPlaneData();
+    Pel* pcRightImageData  = (*apcRightPlane )     ->getPlaneData();
+    Pel* pcRightDepthData  = pcRightDepthPlane     ->getPlaneData();
+
+    Pel* pcFilledLeftData  = pcFilledLeftPlane     ->getPlaneData();
+    Pel* pcLeftImageData   = (*apcLeftPlane)       ->getPlaneData();
+    Pel* pcLeftDepthData   = pcLeftDepthPlane      ->getPlaneData();
+    Pel* pcOutputData      = (*apcOutputImagePlane)->getPlaneData();
+
+    for (UInt uiYPos = 0; uiYPos < (*apcOutputImagePlane)->getHeight(); uiYPos++ )
+    {
+      for (UInt uiXPos = 0; uiXPos < (*apcOutputImagePlane)->getWidth(); uiXPos++ )
+      {
+        if      (m_iBlendMode == eRenBlendLeft  )
+        {
+          if      ( pcFilledLeftData[uiXPos] == REN_IS_FILLED ||  pcFilledRightData[uiXPos] == REN_IS_HOLE )
+          {
+            pcOutputData[uiXPos] = pcLeftImageData[uiXPos];
+          }
+          else if ( pcFilledLeftData[uiXPos] == REN_IS_HOLE )
+          {
+            pcOutputData[uiXPos] = pcRightImageData[uiXPos];
+          }
+          else
+          {
+            pcOutputData[uiXPos] = pcRightImageData[uiXPos] +  (Pel) (  ( (Int) ( pcLeftImageData[uiXPos] - pcRightImageData[uiXPos] ) * pcFilledLeftData[uiXPos] + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+          }
+        }
+        else if ( m_iBlendMode == eRenBlendRight )
+        {
+          if      ( pcFilledRightData[uiXPos] == REN_IS_FILLED || pcFilledLeftData[uiXPos] == REN_IS_HOLE )
+          {
+            pcOutputData[uiXPos] = pcRightImageData[uiXPos];
+          }
+          else if ( pcFilledRightData[uiXPos] == REN_IS_HOLE )
+          {
+            pcOutputData[uiXPos] = pcLeftImageData[uiXPos];
+          }
+          else
+          {
+            pcOutputData[uiXPos] = pcLeftImageData[uiXPos] +  (Pel) (  ( (Int) ( pcRightImageData[uiXPos] - pcLeftImageData[uiXPos] ) * pcFilledRightData[uiXPos] + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+          }
+        }
+        else
+        {
+          AOT(true);
+        }
+      }
+
+      pcFilledRightData +=    pcFilledRightPlane  ->getStride();
+      pcRightImageData  += (*apcRightPlane)       ->getStride();
+      pcRightDepthData  +=    pcRightDepthPlane   ->getStride();
+
+      pcFilledLeftData  +=    pcFilledLeftPlane   ->getStride();
+      pcLeftImageData   +=  (*apcLeftPlane)       ->getStride();
+      pcLeftDepthData   +=    pcLeftDepthPlane    ->getStride();
+      pcOutputData      +=  (*apcOutputImagePlane)->getStride();
+    }
+
+    apcRightPlane ++;
+    apcLeftPlane  ++;
+    apcOutputImagePlane++;
+  }
+}
+
+Void TRenTop::xBlendPlanesAvg( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, PelImagePlane* pcLeftDepthPlane, PelImagePlane* pcRightDepthPlane, PelImagePlane** apcOutputImagePlane, UInt uiNumberOfPlanes )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
+  {
+    Pel* pcFilledRightData = pcFilledRightPlane   ->getPlaneData();
+    Pel* pcRightVideoData  = (*apcRightPlane )    ->getPlaneData();
+    Pel* pcRightDepthData  = pcRightDepthPlane    ->getPlaneData();
+
+    Pel* pcFilledLeftData  = pcFilledLeftPlane    ->getPlaneData();
+    Pel* pcLeftVideoData   = (*apcLeftPlane)      ->getPlaneData();
+    Pel* pcLeftDepthData   = pcLeftDepthPlane     ->getPlaneData();
+
+    Pel* pcOutputData      = (*apcOutputImagePlane)->getPlaneData();
+
+    for (UInt uiYPos = 0; uiYPos < (*apcOutputImagePlane)->getHeight(); uiYPos++ )
+    {
+      for (UInt uiXPos = 0; uiXPos < (*apcOutputImagePlane)->getWidth(); uiXPos++ )
+      {
+        if      (  (pcFilledRightData[uiXPos] != REN_IS_HOLE ) && ( pcFilledLeftData[uiXPos] != REN_IS_HOLE) )
+        {
+          Int iDepthDifference  = m_piInvZLUTLeft[RemoveBitIncrement(pcLeftDepthData[uiXPos])] - m_piInvZLUTRight[RemoveBitIncrement(pcRightDepthData[uiXPos])];
+
+          if ( abs ( iDepthDifference ) <= m_iBlendZThres )
+          {
+            if      ((pcFilledRightData[uiXPos] == REN_IS_FILLED) && ( pcFilledLeftData[uiXPos] != REN_IS_FILLED))
+            {
+              pcOutputData[uiXPos] = pcRightVideoData[uiXPos] +  (Pel) (  ( (Int) ( pcLeftVideoData[uiXPos] - pcRightVideoData[uiXPos] ) * (pcFilledLeftData[uiXPos]) + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+            }
+            else if ((pcFilledRightData[uiXPos] != REN_IS_FILLED) && ( pcFilledLeftData[uiXPos] == REN_IS_FILLED))
+            {
+              pcOutputData[uiXPos] = pcLeftVideoData[uiXPos]  +  (Pel) (  ( (Int) ( pcRightVideoData[uiXPos] - pcLeftVideoData[uiXPos] ) * (pcFilledRightData[uiXPos]) + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+            }
+            else
+            {
+              pcOutputData[uiXPos] = pcLeftVideoData[uiXPos]  +  (Pel) (  ( (Int) ( pcRightVideoData[uiXPos] - pcLeftVideoData[uiXPos] ) * m_iBlendDistWeight               + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+            }
+
+          }
+          else if ( iDepthDifference < 0 )
+          {
+            pcOutputData[uiXPos] = pcRightVideoData[uiXPos];
+          }
+          else
+          {
+            pcOutputData[uiXPos] = pcLeftVideoData[uiXPos];
+          }
+        }
+        else if ( (pcFilledRightData[uiXPos] == REN_IS_HOLE) && (pcFilledLeftData[uiXPos] == REN_IS_HOLE))
+        {
+          pcOutputData[uiXPos] = m_piInvZLUTLeft[RemoveBitIncrement( pcLeftDepthData[uiXPos])]  < m_piInvZLUTRight[RemoveBitIncrement(pcRightDepthData[uiXPos])] ? pcLeftVideoData[uiXPos] : pcRightVideoData[uiXPos];
+        }
+        else
+        {
+          pcOutputData[uiXPos] =  (pcFilledLeftData[uiXPos] == REN_IS_HOLE) ? pcRightVideoData[uiXPos] : pcLeftVideoData[uiXPos];
+        }
+      }
+
+      pcFilledRightData +=    pcFilledRightPlane  ->getStride();
+      pcRightVideoData  += (*apcRightPlane)      ->getStride();
+      pcRightDepthData  +=    pcRightDepthPlane   ->getStride();
+
+      pcFilledLeftData  +=    pcFilledLeftPlane   ->getStride();
+      pcLeftVideoData   +=  (*apcLeftPlane)       ->getStride();
+      pcLeftDepthData   +=    pcLeftDepthPlane    ->getStride();
+      pcOutputData      +=  (*apcOutputImagePlane)->getStride();
+    };
+
+    apcRightPlane ++;
+    apcLeftPlane  ++;
+    apcOutputImagePlane++;
+  }
+}
+
+// Temporal Filter from Zhejiang University: (a little different from m16041: Temporal Improvement Method in View Synthesis)
+Void TRenTop::temporalFilterVSRS( TComPicYuv* pcPicYuvVideoCur, TComPicYuv* pcPicYuvDepthCur, TComPicYuv* pcPicYuvVideoLast, TComPicYuv* pcPicYuvDepthLast, Bool bFirstFrame )
+{
+  Int iSADThres  = 100 ;  //threshold of sad in 4*4 block motion detection
+
+  Int iWidth  = m_auiInputResolution[0];
+  Int iHeight = m_auiInputResolution[1];
+
+  //internal variables
+  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();
+
+  Pel* pcVideoCurDataFrm  = pcVideoCurData ;
+  Pel* pcVideoLastDataFrm = pcVideoLastData;
+  Pel* pcDepthCurDataFrm  = pcDepthCurData ;
+  Pel* pcDepthLastDataFrm = pcDepthLastData;
+
+
+  if( !bFirstFrame ) // first frame need not the weighting, but need to prepare the data
+  {
+    for ( Int iPosY = 0; iPosY < (iHeight >> 2); iPosY++)
+    {
+      //motion detection by SAD
+      for ( Int iPosX = 0; iPosX < (iWidth >> 2);  iPosX++)
+      {
+        Int iSAD = 0;
+
+        Pel* pcVideoCurDataBlk  = pcVideoCurDataFrm  + (iPosX << 2);
+        Pel* pcVideoLastDataBlk = pcVideoLastDataFrm + (iPosX << 2);
+
+        //GT: Check difference of block compared to last frame
+        for( Int iCurPosY = 0; iCurPosY < 4; iCurPosY++)
+        {
+          for( Int iCurPosX = 0; iCurPosX < 4; iCurPosX++)
+          {
+            iSAD += abs( pcVideoLastDataBlk[iCurPosX] - pcVideoCurDataBlk[iCurPosX] );   //SAD
+          }
+          pcVideoLastDataBlk += iVideoLastStride;
+          pcVideoCurDataBlk  += iVideoCurStride;
+        }
+
+        piFlagMoving[iPosX] = ( iSAD < iSADThres ) ? 0 : 1;
+      }
+
+      //temporal weighting according to motion detection result -- do a line
+      for ( Int iPosX = 0; iPosX < (iWidth >> 2);  iPosX++)
+      {
+        //5 block
+       Int iSumMoving = piFlagMoving[iPosX-2] + piFlagMoving[iPosX-1] + piFlagMoving[iPosX]   + piFlagMoving[iPosX+1] + piFlagMoving[iPosX+2];
+
+        if( iSumMoving == 0 ) // if not moving
+        {
+          Pel* pcDepthCurDataBlk  = pcDepthCurDataFrm  + (iPosX << 2);
+          Pel* pcDepthLastDataBlk = pcDepthLastDataFrm + (iPosX << 2);
+
+          for( Int iCurPosY = 0; iCurPosY < 4; iCurPosY++)
+          {
+            for( Int iCurPosX = 0; iCurPosX < 4; iCurPosX++)
+            { //Weight: 0.75
+              Int iFilt = (( (pcDepthLastDataBlk[iCurPosX] << 1 ) + pcDepthLastDataBlk[iCurPosX] + pcDepthCurDataBlk[iCurPosX] + 2 ) >> 2 );
+              assert( (iFilt >= 0) && (iFilt <=  g_uiIBDI_MAX) );
+              pcDepthCurDataBlk[iCurPosX] = pcDepthLastDataBlk[iCurPosX];
+              pcDepthCurDataBlk[iCurPosX] = iFilt;
+            }
+
+            pcDepthCurDataBlk  += iDepthCurStride;
+            pcDepthLastDataBlk += iDepthLastStride;
+          }
+        }
+      }
+
+      pcDepthCurDataFrm  += ( iDepthCurStride  << 2);
+      pcDepthLastDataFrm += ( iDepthLastStride << 2);
+      pcVideoCurDataFrm  += ( iVideoCurStride  << 2);
+      pcVideoLastDataFrm += ( iVideoLastStride << 2);
+    }
+  }
+  pcPicYuvVideoCur->copyToPic( pcPicYuvVideoLast );
+  pcPicYuvDepthCur->copyToPic( pcPicYuvDepthLast );
+}
+
+TRenTop::TRenTop()
+{
+  m_auiInputResolution[0] = 0;
+  m_auiInputResolution[1] = 0;
+
+  // Sub Pel Rendering
+  m_iLog2SamplingFactor = 0;
+
+  // ColorPlaneHandling
+  m_bUVUp = true;
+
+
+  //PreProcessing
+  m_iPreProcMode         = eRenPreProNone;
+  m_iPreFilterSize = 2;
+
+  // Interpolation
+  m_iInterpolationMode   = eRenIntFullPel;
+
+  // Sim Enhancement
+  m_iSimEnhBaseView      = 0;
+
+  // Blending
+  m_iBlendMode           = eRenBlendAverg;
+  m_iBlendZThresPerc     = -1;
+  m_bBlendUseDistWeight  = false;
+  m_iBlendHoleMargin     = -1;
+
+  m_iBlendZThres         = -1;
+  m_iBlendDistWeight     = -1;
+
+  // Hole Filling
+  m_iHoleFillingMode     = eRenHFLWBackExt;
+  m_bInstantHoleFilling  = false;
+
+  // PostProcessing
+  m_iPostProcMode        = eRenPostProNone;
+
+  // Cut
+  m_auiCut[0] = 0;
+  m_auiCut[1] = 0;
+
+  // Data
+  m_uiSampledWidth = -1;
+
+  // LUTs
+  m_ppdShiftLUTLeft  = 0;
+  m_ppdShiftLUTRight = 0;
+
+  m_ppdShiftLUTRightMirror    = new Double*[2];
+  m_ppdShiftLUTRightMirror[0] = new Double [257];
+  m_ppdShiftLUTRightMirror[1] = new Double [257];
+
+  m_adShiftLUTCur    = 0;
+
+  m_ppiShiftLUTLeft  = 0;
+  m_ppiShiftLUTRight = 0;
+  m_ppiShiftLUTRightMirror    = new Int*[2];
+  m_ppiShiftLUTRightMirror[0] = new Int[257];
+  m_ppiShiftLUTRightMirror[1] = new Int[257];
+
+  m_aiShiftLUTCur    = 0;
+  m_piInvZLUTLeft  = new Int[257];
+  m_piInvZLUTRight = new Int[257];
+
+  // Buffers
+  m_pcLeftInputImage   = 0;
+  m_pcLeftInputDepth   = 0;
+  m_pcLeftOutputImage  = 0;
+  m_pcLeftOutputDepth  = 0;
+  m_pcLeftFilled       = 0;
+
+  m_pcRightInputImage  = 0;
+  m_pcRightInputDepth  = 0;
+  m_pcRightOutputImage = 0;
+  m_pcRightOutputDepth = 0;
+  m_pcRightFilled      = 0;
+
+  m_pcOutputImage      = 0;
+  m_pcOutputDepth      = 0;
+
+  //Extrapolation
+  m_pcInputImage       = 0;
+  m_pcInputDepth       = 0;
+  m_pcFilled           = 0;
+
+  // SubPel
+  m_aaiSubPelShift     = 0;
+
+  // Temp
+  m_pcTempImage        = 0;
+
+  //Temporal Filter
+  m_aiBlkMoving        = 0;
+}
+
+
+Void TRenTop::init(UInt uiImageWidth,
+                   UInt uiImageHeight,
+                   Bool  bExtrapolate,
+                   UInt uiLog2SamplingFactor,
+                   Int   iShiftLUTPrec,
+                   Bool  bUVUp,
+                   Int   iPreProcMode,
+                   Int   iPreFilterKernelSize,
+                   Int   iBlendMode,
+                   Int   iBlendZThresPerc,
+                   Bool  bBlendUseDistWeight,
+                   Int   iBlendHoleMargin,
+                   Int   iInterpolationMode,
+                   Int   iHoleFillingMode,
+                   Int   iPostProcMode,
+                   Int   iUsedPelMapMarExt
+                   )
+
+{
+  // Shift LUT Prec
+  m_iRelShiftLUTPrec = iShiftLUTPrec - (Int) uiLog2SamplingFactor;
+
+  // Sub Pel Rendering
+  m_iLog2SamplingFactor = uiLog2SamplingFactor;
+
+  // Extrapolation ?
+  m_bExtrapolate = bExtrapolate;
+
+  // ColorPlaneHandling
+  m_bUVUp = bUVUp;
+
+  //PreProcessing
+  m_iPreProcMode = iPreProcMode;
+  m_iPreFilterSize = iPreFilterKernelSize;
+
+  // Interpolation
+  m_iInterpolationMode = iInterpolationMode;
+
+  //Blending
+  m_iBlendMode          = iBlendMode;
+  m_iBlendZThresPerc    = iBlendZThresPerc;
+  m_bBlendUseDistWeight = bBlendUseDistWeight;
+  m_iBlendHoleMargin    = iBlendHoleMargin;
+
+  // Hole Filling
+  m_iHoleFillingMode = iHoleFillingMode;
+
+  m_bInstantHoleFilling   = (m_iInterpolationMode == eRenInt8Tap ) && (m_iHoleFillingMode != 0 );
+
+  // PostProcessing
+  m_iPostProcMode    = iPostProcMode;
+
+  // Used pel map
+  m_iUsedPelMapMarExt     = iUsedPelMapMarExt;
+
+  // Cut
+  m_auiCut[0] = 0;
+  m_auiCut[1] = 0;
+
+  m_auiInputResolution[0] = uiImageWidth;
+  m_auiInputResolution[1] = uiImageHeight;
+
+  if ( m_bExtrapolate )
+  {
+    PelImage*    pcDump        = 0;
+    xGetDataPointers( m_pcInputImage, m_pcOutputImage, m_pcInputDepth, pcDump, m_pcFilled, false );
+  }
+  else
+  {
+    xGetDataPointers(m_pcLeftInputImage,  m_pcLeftOutputImage,  m_pcLeftInputDepth,  m_pcLeftOutputDepth,  m_pcLeftFilled,  true);
+    xGetDataPointers(m_pcRightInputImage, m_pcRightOutputImage, m_pcRightInputDepth, m_pcRightOutputDepth, m_pcRightFilled, true);
+    xGetDataPointerOutputImage(m_pcOutputImage, m_pcOutputDepth );
+  }
+
+  m_pcTempImage = new PelImage( m_auiInputResolution[0],m_auiInputResolution[1],1,2);
+
+  // SubPelShiftLUT
+  if (iInterpolationMode == eRenInt8Tap)
+  {
+    // SubPel Shift LUT
+    Int iNumEntries = (1 << ( m_iRelShiftLUTPrec + 1) ) + 1 ;
+    m_aaiSubPelShift = new Int*[ iNumEntries ];
+    for (UInt uiEntry = 0; uiEntry < iNumEntries; uiEntry++)
+    {
+      m_aaiSubPelShift[uiEntry] = new Int[ iNumEntries ];
+    }
+
+    TRenFilter::setSubPelShiftLUT(m_iRelShiftLUTPrec, m_aaiSubPelShift, -1);
+  }
+
+  // Zheijang temporal filter
+  m_aiBlkMoving    = new Int[ ( m_auiInputResolution[0] >> 2 ) + 4 ];
+  m_aiBlkMoving[0] = 0;
+  m_aiBlkMoving[1] = 0;
+  m_aiBlkMoving[ ( m_auiInputResolution[0] >> 2 ) + 2 ] = 0;
+  m_aiBlkMoving[ ( m_auiInputResolution[0] >> 2 ) + 3 ] = 0;
+}
+
+
+TRenTop::~TRenTop()
+{
+  if ( m_ppdShiftLUTRightMirror != NULL )
+  {
+    delete[] m_ppdShiftLUTRightMirror[0];
+    delete[] m_ppdShiftLUTRightMirror[1];
+    delete[] m_ppdShiftLUTRightMirror;
+  };
+
+  if ( m_ppiShiftLUTRightMirror != NULL )
+  {
+    delete[] m_ppiShiftLUTRightMirror[0];
+    delete[] m_ppiShiftLUTRightMirror[1];
+    delete[] m_ppiShiftLUTRightMirror;
+  };
+
+  if (m_piInvZLUTLeft      != NULL ) delete[] m_piInvZLUTLeft   ;
+  if (m_piInvZLUTLeft      != NULL ) delete[] m_piInvZLUTRight  ;
+
+  if (m_pcLeftInputImage   != NULL ) delete m_pcLeftInputImage  ;
+  if (m_pcLeftInputDepth   != NULL ) delete m_pcLeftInputDepth  ;
+  if (m_pcLeftOutputImage  != NULL ) delete m_pcLeftOutputImage ;
+  if (m_pcLeftOutputDepth  != NULL ) delete m_pcLeftOutputDepth ;
+  if (m_pcLeftFilled       != NULL ) delete m_pcLeftFilled      ;
+
+  if (m_pcRightInputImage  != NULL ) delete m_pcRightInputImage ;
+  if (m_pcRightInputDepth  != NULL ) delete m_pcRightInputDepth ;
+  if (m_pcRightOutputImage != NULL ) delete m_pcRightOutputImage;
+  if (m_pcRightOutputDepth != NULL ) delete m_pcRightOutputDepth;
+  if (m_pcRightFilled      != NULL ) delete m_pcRightFilled     ;
+
+  if (m_pcOutputImage      != NULL ) delete m_pcOutputImage     ;
+  if (m_pcOutputDepth      != NULL ) delete m_pcOutputDepth     ;
+
+  if (m_pcInputImage       != NULL ) delete m_pcInputImage      ;
+  if (m_pcInputDepth       != NULL ) delete m_pcInputDepth      ;
+  if (m_pcFilled           != NULL ) delete m_pcFilled          ;
+
+  if (m_pcTempImage        != NULL ) delete m_pcTempImage       ;
+
+  // SubPel LUT
+  if ( m_aaiSubPelShift != NULL)
+  {
+    Int iNumEntries = (1 << ( m_iRelShiftLUTPrec + 1) ) + 1;
+    for (UInt uiEntry = 0; uiEntry < iNumEntries; uiEntry++)
+    {
+      delete[] m_aaiSubPelShift[uiEntry];
+    }
+    delete[] m_aaiSubPelShift;
+  }
+
+  // Zheijang temporal filter
+  if(m_aiBlkMoving         != NULL ) delete[] m_aiBlkMoving;
+}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenTop.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenTop.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibRenderer/TRenTop.h	(revision 341)
@@ -0,0 +1,270 @@
+/* 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-2011, 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 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 __TRENTOP__
+#define __TRENTOP__
+
+#include "TRenImage.h"
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include <list>
+#include <vector>
+
+using namespace std;
+
+class TRenTop
+{
+// ENUM Modes
+
+
+  // Interpolation Modes
+
+  enum { eRenIntFullPel = 0, eRenIntLinInt = 1, eRenIntLinReal = 2, eRenIntFEM = 3, eRenInt8Tap = 4 };
+
+  // HoleFilling
+  enum { eRenHFNone = 0, eRenHFLWBackExt = 1};
+
+  // Pre-Processing
+  enum { eRenPreProNone = 0, eRenPreProBinom = 1};
+
+  // Post-Processing
+  enum { eRenPostProNone = 0, eRenPostProMed = 1};
+
+  // Merging
+  enum { eRenBlendAverg = 0, eRenBlendLeft = 1, eRenBlendRight = 2, eRenBlendDepthFirst = 5 };
+
+public:
+  TRenTop();
+  ~TRenTop();
+
+  // Init
+  Void init              ( UInt uiImageWitdh,
+                           UInt uiImageHeight,
+                           Bool bExtrapolate,
+                           UInt uiLog2SamplingFactor,
+                           Int  iLUTPrec,
+                           Bool bUVUp,
+                           Int  iPreProcMode,
+                           Int  iPreFilterKernelSize,
+                           Int  iBlendMode,
+                           Int  iBlendZThresPerc,
+                           Bool bBlendUseDistWeight,
+                           Int  iBlendHoleMargin,
+                           Int  iInterpolationMode,
+                           Int  iHoleFillingMode,
+                           Int  iPostProcMode,
+                           Int  iUsedPelMapMarExt );
+
+  Void setShiftLUTs      ( Double** ppdShiftLUTLeft,
+                           Int**    ppiShiftLUTLeft,
+                           Int**    ppiBaseShiftLUTLeft,
+                           Double** ppdShiftLUTRight,
+                           Int**    ppiShiftLUTRight,
+                           Int**    ppiBaseShiftLUTRight,
+                           Int      iRelDistLeft );
+
+  // View Synthesis
+  Void extrapolateView   ( TComPicYuv* pcPicYuvVideo,
+                           TComPicYuv* pcPicYuvDepth,
+                           TComPicYuv* pcPicYuvSynthOut,
+                           Bool bRenderFromLeft );
+
+  Void interpolateView   ( TComPicYuv* pcPicYuvVideoLeft,
+                           TComPicYuv* pcPicYuvDepthLeft,
+                           TComPicYuv* pcPicYuvVideoRight,
+                           TComPicYuv* pcPicYuvDepthRight,
+                           TComPicYuv* pcPicYuvSynthOut,
+                           Int         iBlendMode,
+                           Int         iSimEnhBaseView );
+  // Tools
+  Void getUsedSamplesMap ( TComPicYuv* pcPicYuvDepth,
+                           TComPicYuv* pcUsedSampleMap,
+                           Bool bRenderFromLeft );
+
+  // Zhejiang Temporal Improvement
+  Void temporalFilterVSRS( TComPicYuv* pcPicYuvVideoCur,
+                           TComPicYuv* pcPicYuvDepthCur,
+                           TComPicYuv* pcPicYuvVideoLast,
+                           TComPicYuv* pcPicYuvDepthLast,
+                           Bool bFirstFrame );
+
+private:
+  // Depth PreProcessing
+  Void xPreProcessDepth(PelImage* pcInImage, PelImage* pcOutImage);
+
+  // Pixel Shifting
+  Void xShiftPixels              ( PelImage*        pcInImage,     PelImage*      pcDepth     , PelImage*        pcOutImage    , PelImage*      pcFilledImage, Bool bShiftFromLeft  );
+  Void xShiftPlanePixels         ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcPlaneFilled, UInt uiNumberOfPlanes);
+  Void xShiftPlanePixelsLinReal  ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcPlaneFilled, UInt uiNumberOfPlanes);
+  Void xShiftPlanePixelsFullPel  ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcPlaneFilled, UInt uiNumberOfPlanes);
+  Void xShiftPlanePixelsLinInt   ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes);
+  Void xShiftPlanePixels8Tap     ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes);
+
+  Void xBackShiftPixels          ( PelImage*            pcInImage, PelImage*      pcDepth     , PelImage*            pcOutImage, PelImage*      pcFilledImage, Bool bShiftFromLeft   );
+  Void xBackShiftPlanePixels     ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes );
+
+  Int  xCeil                     ( Int iVal ) { return (( iVal + ( (1 << m_iRelShiftLUTPrec) - 1 ) ) >> m_iRelShiftLUTPrec);  }
+
+  // Hole Filling
+  Void xFillHoles                ( PelImage*       pcInImage,      PelImage*      pcFilled,      PelImage*       pcOutImage                            , Bool bRenderFromLeft );
+  Void xFillLWBackExt            ( PelImage*       pcInImage,      PelImage*      pcFilled,      PelImage*       pcOutImage                            , Bool bRenderFromLeft );
+  Void xFillPlaneHoles           ( PelImagePlane** apcInputPlanes, PelImagePlane* pcPlaneFilled, PelImagePlane** apcOutputPlanes, UInt uiNumberOfPlanes, Bool bRenderFromLeft );
+
+  // Alpha Map Creation
+  Void xCreateAlphaMap           (PelImage* pcFilledImage,         PelImage*       pcAlphaMapImage, Bool bRenderFromLeft );
+  Void xCreateAlphaMapPlane      (PelImagePlane** apcFilledPlanes, PelImagePlane** apcAlphaPlanes,  UInt uiNumberOfPlanes, Bool bRenderFromLeft);
+
+  // BoundaryNoiseErosion
+  Void xRemBoundaryNoise            ( PelImage*       pcInImage,      PelImage*      pcFilled,      PelImage*       pcOutImage                            , Bool bRenderFromLeft );
+  Void xRemBoundaryNoisePlane       ( PelImagePlane** apcInputPlanes, PelImagePlane* pcPlaneFilled, PelImagePlane** apcOutputPlanes, UInt uiNumberOfPlanes, Bool bRenderFromLeft );
+
+  // Similarity Enhancement
+  Void xEnhSimilarity            ( PelImage*      pcLeftImage,   PelImage*        pcRightImage, PelImage*      pcFilledLeft,      PelImage*      pcFilledRight      );
+  Void xEnhSimilarityPlane       ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, UInt uNumPlanes );
+
+  // View Blending
+  Void xBlend                    ( PelImage*       pcLeftImage,  PelImage*        pcRightImage, PelImage*      pcFilledLeft,      PelImage*      pcFilledRight,      PelImage* pcLeftDepth,           PelImage* pcRightDepth,           PelImage* pcOutputImage);
+  Void xBlendPlanesAvg           ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, PelImagePlane* pcLeftDepthPlane, PelImagePlane* pcRightDepthPlane, PelImagePlane** apcOutputImagePlane, UInt uNumPlanes );
+  Void xBlendPlanesOneView       ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, PelImagePlane* pcLeftDepthPlane, PelImagePlane* pcRightDepthPlane, PelImagePlane** apcOutputImagePlane, UInt uNumPlanes );
+
+  // PostProcessing
+  Void xCutMargin                ( PelImage* pcInputImage );
+  Void xCutPlaneMargin           ( PelImagePlane* pcImagePlane, Pel cFill, UInt uiScale);
+  Void xPostProcessImage         ( PelImage* pcInImage,       PelImage* pCOutImage);
+
+  // Input Output Data Conversion
+  Void xConvertInputData         ( PelImage* pcOrgInputImage, PelImage* pcOrgInputDepth, PelImage* pcConvInputImage, PelImage* pcConvInputDepth, Bool bMirror);
+  Void xConvertOutputData        ( PelImage* pOrgOutputImage, PelImage* pConvOutputImage, Bool bMirror);
+
+  Void xGetDataPointers          ( PelImage*& rpcInputImage,  PelImage*& rpcOutputImage, PelImage*& rpcInputDepth, PelImage*& rpcOutputDepth, PelImage*& rpcFilled, Bool bRenderDepth );
+  Void xGetDataPointerOutputImage( PelImage*& rpcOutputImage, PelImage*& rpcOutputDepth );
+
+  Void xConvertInputVideo        ( PelImage* pcOrgInputImage, PelImage* pcConvInputImage);
+  Void xConvertInputDepth        ( PelImage* pcOrgInputImage, PelImage* pcConvInputImage);
+
+
+  // Data
+  UInt m_uiSampledWidth;    // Width after UPsampling
+
+  // Resolution of input view
+  UInt  m_auiInputResolution[2];
+
+  // Extrapolation
+  Bool m_bExtrapolate;
+
+  // Input Conversion
+  Int  m_iLog2SamplingFactor;
+  Bool m_bUVUp;
+
+  // PreProcessing
+  Int  m_iPreProcMode;         //0: none, 1: binominal
+  Int  m_iPreFilterSize;       // Half size
+
+  // Similarity Enhancement
+  Int  m_iSimEnhBaseView;      // 0: none, 1: left, 2: right
+
+  // Blending
+  Int  m_iBlendMode;           // 0: average;
+  Int  m_iBlendZThresPerc;     // in percent of total depth
+  Bool m_bBlendUseDistWeight;  // use weighting depending on viewing distance
+  Int  m_iBlendHoleMargin;     // blending margin next to holes
+
+  Int  m_iBlendZThres;         // absoluteInt  m_iBlendWeight;
+  Int  m_iBlendDistWeight;     // Weight for view distance depending blending
+
+  // Interpolation
+  Int  m_iInterpolationMode;   //0: none; 1: Linear (Double), 2: FEM (Double)
+
+  // Hole Filling
+  Int  m_iHoleFillingMode;     //0: none; 1: LW Background extension
+  Int  m_bInstantHoleFilling;  // perform hole filling while pixel shifting ( only supported for interpolation mode 4 )
+
+  // Post Processing
+  Int  m_iPostProcMode;        //0: none; 1: Median
+
+  // Precision in LUT
+  Int  m_iRelShiftLUTPrec;
+
+  // Cut
+  UInt m_auiCut[2];
+
+  // Look up tables Shift
+  Double** m_ppdShiftLUTLeft;
+  Double** m_ppdShiftLUTRight;
+  Double** m_ppdShiftLUTRightMirror; // For rendering the mirrored view
+  Double*  m_adShiftLUTCur;
+
+  Int**    m_ppiShiftLUTLeft;
+  Int**    m_ppiShiftLUTRight;
+  Int**    m_ppiShiftLUTRightMirror; // For rendering the mirrored view
+  Int*     m_aiShiftLUTCur;
+
+  // Look up tables Z
+  Int*     m_piInvZLUTLeft;          // Look up table entry is proportional to Z
+  Int*     m_piInvZLUTRight;
+
+  // Look up tables sub pel shift
+  Int**    m_aaiSubPelShift;
+
+   // Zhejiang Temporal Improvement
+  Int*    m_aiBlkMoving;
+
+  // Used pel map generation
+  Int      m_iUsedPelMapMarExt;
+
+  // Buffers
+
+  // Interpolation
+  PelImage* m_pcLeftInputImage  ;
+  PelImage* m_pcLeftInputDepth  ;
+  PelImage* m_pcLeftOutputImage ;
+  PelImage* m_pcLeftOutputDepth ;
+  PelImage* m_pcLeftFilled      ;
+  PelImage* m_pcRightInputImage ;
+  PelImage* m_pcRightInputDepth ;
+  PelImage* m_pcRightOutputImage;
+  PelImage* m_pcRightOutputDepth;
+  PelImage* m_pcRightFilled     ;
+  PelImage* m_pcOutputImage     ;
+  PelImage* m_pcOutputDepth     ;
+
+  // Extrapolation
+  PelImage* m_pcInputImage      ;
+  PelImage* m_pcInputDepth      ;
+  PelImage* m_pcFilled          ;
+
+  //Temp
+  PelImage* m_pcTempImage       ;
+};
+
+#endif //__TRENTOP__
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 341)
@@ -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-2012, 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     TVideoIOYuv.cpp
+    \brief    YUV file I/O class
+*/
+
+#include <cstdlib>
+#include <fcntl.h>
+#include <assert.h>
+#include <sys/stat.h>
+#include <fstream>
+#include <iostream>
+
+#include "TLibCommon/TComRom.h"
+#include "TVideoIOYuv.h"
+
+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, unsigned int stride, unsigned int width, unsigned int height,
+                       unsigned int shiftbits, Pel minval, Pel maxval)
+{
+  Pel offset = 1 << (shiftbits-1);
+  for (unsigned int y = 0; y < height; y++)
+  {
+    for (unsigned int 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, unsigned int stride, unsigned int width, unsigned int height,
+                       unsigned int shiftbits)
+{
+  for (unsigned int y = 0; y < height; y++)
+  {
+    for (unsigned int x = 0; x < width; x++)
+    {
+      img[x] <<= shiftbits;
+    }
+    img += stride;
+  }
+}
+
+/**
+ * Scale all pixels in img depending upon sign of shiftbits by a factor of
+ * 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 if zero, no operation performed
+ *                  if > 0, multiply by 2<sup>shiftbits</sup>, see scalePlane()
+ *                  if < 0, divide and round by 2<sup>shiftbits</sup> and clip,
+ *                          see invScalePlane().
+ * @param minval  minimum clipping value when dividing.
+ * @param maxval  maximum clipping value when dividing.
+ */
+static void scalePlane(Pel* img, unsigned int stride, unsigned int width, unsigned int height,
+                       int shiftbits, Pel minval, Pel maxval)
+{
+  if (shiftbits == 0)
+  {
+    return;
+  }
+
+  if (shiftbits > 0)
+  {
+    scalePlane(img, stride, width, height, shiftbits);
+  }
+  else
+  {
+    invScalePlane(img, stride, width, height, -shiftbits, minval, maxval);
+  }
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * Open file for reading/writing Y'CbCr frames.
+ *
+ * Frames read/written have bitdepth fileBitDepth, and are automatically
+ * formatted as 8 or 16 bit word values (see TVideoIOYuv::write()).
+ *
+ * Image data read or written is converted to/from internalBitDepth
+ * (See scalePlane(), TVideoIOYuv::read() and TVideoIOYuv::write() for
+ * further details).
+ *
+ * \param pchFile          file name string
+ * \param bWriteMode       file open mode: true=read, false=write
+ * \param fileBitDepth     bit-depth of input/output file data.
+ * \param internalBitDepth bit-depth to scale image data to/from when reading/writing.
+ */
+Void TVideoIOYuv::open( char* pchFile, Bool bWriteMode, unsigned int fileBitDepth, unsigned int internalBitDepth )
+{
+  m_bitdepthShift = internalBitDepth - fileBitDepth;
+  m_fileBitdepth = fileBitDepth;
+
+  if ( bWriteMode )
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::out );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to write reconstructed YUV file\n");
+      exit(0);
+    }
+  }
+  else
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::in );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to open Input YUV file\n");
+      exit(0);
+    }
+  }
+  
+  return;
+}
+
+Void TVideoIOYuv::close()
+{
+  m_cHandle.close();
+}
+
+Bool TVideoIOYuv::isEof()
+{
+  return m_cHandle.eof();
+}
+
+Bool TVideoIOYuv::isFail()
+{
+  return m_cHandle.fail();
+}
+
+/**
+ * Skip numFrames in input.
+ *
+ * This function correctly handles cases where the input file is not
+ * seekable, by consuming bytes.
+ */
+void TVideoIOYuv::skipFrames(unsigned int numFrames, unsigned int width, unsigned int height)
+{
+  if (!numFrames)
+    return;
+
+  const unsigned int wordsize = m_fileBitdepth > 8 ? 2 : 1;
+  const streamoff framesize = wordsize * width * height * 3 / 2;
+  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 unsigned offset_mod_bufsize = offset % sizeof(buf);
+  for (streamoff i = 0; i < offset - offset_mod_bufsize; i += sizeof(buf))
+  {
+    m_cHandle.read(buf, sizeof(buf));
+  }
+  m_cHandle.read(buf, offset_mod_bufsize);
+}
+
+/**
+ * Read width*height pixels from fd into dst, optionally
+ * padding the left and right edges by edge-extension.  Input may be
+ * 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.
+ * @return true for success, false in case of error
+ */
+static bool readPlane(Pel* dst, istream& fd, bool is16bit,
+                      unsigned int stride,
+                      unsigned int width, unsigned int height,
+                      unsigned int pad_x, unsigned int pad_y)
+{
+  int read_len = width * (is16bit ? 2 : 1);
+  unsigned char *buf = new unsigned char[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;
+  }
+  delete[] buf;
+  return true;
+}
+
+/**
+ * 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.
+ * @return true for success, false in case of error
+ */
+static bool writePlane(ostream& fd, Pel* src, bool is16bit,
+                       unsigned int stride,
+                       unsigned int width, unsigned int height)
+{
+  int write_len = width * (is16bit ? 2 : 1);
+  unsigned char *buf = new unsigned char[write_len];
+  for (int y = 0; y < height; y++)
+  {
+    if (!is16bit) 
+    {
+      for (int x = 0; x < width; x++) 
+      {
+        buf[x] = (unsigned char) 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;
+  }
+  delete[] buf;
+  return true;
+}
+
+/**
+ * Read one Y'CbCr frame, performing any required input scaling to change
+ * from the bitdepth of the input file to the internal bit-depth.
+ *
+ * If a bit-depth reduction is required, and internalBitdepth >= 8, then
+ * the input file is assumed to be ITU-R BT.601/709 compliant, and the
+ * resulting data is clipped to the appropriate legal range, as if the
+ * 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
+ * @return true for success, false in case of error
+ */
+bool TVideoIOYuv::read ( TComPicYuv*  pPicYuv, Int aiPad[2], Bool bRewind )
+{
+  // check end-of-file
+  if ( isEof() ) return false;
+  
+  Int   iStride = pPicYuv->getStride();
+  
+  // compute actual YUV width & height excluding padding size
+  unsigned int pad_h = aiPad[0];
+  unsigned int pad_v = aiPad[1];
+  unsigned int width_full = pPicYuv->getWidth();
+  unsigned int height_full = pPicYuv->getHeight();
+  unsigned int width  = width_full - pad_h;
+  unsigned int height = height_full - pad_v;
+  bool is16bit = m_fileBitdepth > 8;
+
+  int desired_bitdepth = m_fileBitdepth + m_bitdepthShift;
+  Pel minval = 0;
+  Pel maxval = (1 << desired_bitdepth) - 1;
+#if CLIP_TO_709_RANGE
+  if (m_bitdepthShift < 0 && desired_bitdepth >= 8)
+  {
+    /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+    minval = 1 << (desired_bitdepth - 8);
+    maxval = (0xff << (desired_bitdepth - 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_bitdepthShift, minval, maxval);
+
+  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_bitdepthShift, minval, maxval);
+
+  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_bitdepthShift, minval, maxval);
+
+  if( bRewind )
+  {
+    Int iFrameSize = ( is16bit ? 2 : 1 ) * 6 * width * height;
+    m_cHandle.seekg( -iFrameSize, std::ios_base::cur );
+  }
+
+  return true;
+}
+
+/**
+ * Write one Y'CbCr frame. No bit-depth conversion is performed, pcPicYuv is
+ * 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
+ * @return true for success, false in case of error
+ */
+Bool TVideoIOYuv::write( TComPicYuv* pPicYuv, Int cropLeft, Int cropRight, Int cropTop, Int cropBottom )
+{
+  // compute actual YUV frame size excluding padding size
+  Int   iStride = pPicYuv->getStride();
+  UInt  width  = pPicYuv->getWidth()  - cropLeft - cropRight;
+  UInt  height = pPicYuv->getHeight() - cropTop  - cropBottom;
+  bool is16bit = m_fileBitdepth > 8;
+  TComPicYuv *dstPicYuv = NULL;
+  bool retval = true;
+
+  if (m_bitdepthShift != 0)
+  {
+    dstPicYuv = new TComPicYuv;
+    dstPicYuv->create( pPicYuv->getWidth(), pPicYuv->getHeight(), 1, 1, 0 );
+    pPicYuv->copyToPic(dstPicYuv);
+
+    Pel minval = 0;
+    Pel maxval = (1 << m_fileBitdepth) - 1;
+#if CLIP_TO_709_RANGE
+    if (-m_bitdepthShift < 0 && m_fileBitdepth >= 8)
+    {
+      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      minval = 1 << (m_fileBitdepth - 8);
+      maxval = (0xff << (m_fileBitdepth - 8)) -1;
+    }
+#endif
+    scalePlane(dstPicYuv->getLumaAddr(), dstPicYuv->getStride(), dstPicYuv->getWidth(), dstPicYuv->getHeight(), -m_bitdepthShift, minval, maxval);
+    scalePlane(dstPicYuv->getCbAddr(), dstPicYuv->getCStride(), dstPicYuv->getWidth()>>1, dstPicYuv->getHeight()>>1, -m_bitdepthShift, minval, maxval);
+    scalePlane(dstPicYuv->getCrAddr(), dstPicYuv->getCStride(), dstPicYuv->getWidth()>>1, dstPicYuv->getHeight()>>1, -m_bitdepthShift, minval, maxval);
+  }
+  else
+  {
+    dstPicYuv = pPicYuv;
+  }
+  // location of upper left pel in a plane
+  Int planeOffset = 0; //cropLeft + cropTop * iStride;
+  
+  if (! writePlane(m_cHandle, dstPicYuv->getLumaAddr() + planeOffset, is16bit, iStride, width, height))
+  {
+    retval=false; 
+    goto exit;
+  }
+
+  width >>= 1;
+  height >>= 1;
+  iStride >>= 1;
+  cropLeft >>= 1;
+  cropRight >>= 1;
+
+  planeOffset = 0; // cropLeft + cropTop * 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_bitdepthShift != 0)
+  {
+    dstPicYuv->destroy();
+    delete dstPicYuv;
+  }  
+  return retval;
+}
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 341)
@@ -0,0 +1,79 @@
+/* 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-2012, 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     TVideoIOYuv.h
+    \brief    YUV file I/O class (header)
+*/
+
+#ifndef __TVIDEOIOYUV__
+#define __TVIDEOIOYUV__
+
+#include <stdio.h>
+#include <fstream>
+#include <iostream>
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+
+using namespace std;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// YUV file I/O class
+class TVideoIOYuv
+{
+private:
+  fstream   m_cHandle;                                      ///< file handle
+  unsigned int m_fileBitdepth; ///< bitdepth of input/output video file
+  int m_bitdepthShift;  ///< number of bits to increase or decrease image by before/after write/read
+  
+public:
+  TVideoIOYuv()           {}
+  virtual ~TVideoIOYuv()  {}
+  
+  Void  open  ( char* pchFile, Bool bWriteMode, unsigned int fileBitDepth, unsigned int internalBitDepth ); ///< open or create file
+  Void  close ();                                           ///< close file
+
+  void skipFrames(unsigned int numFrames, unsigned int width, unsigned int height);
+  
+  bool  read  ( TComPicYuv*   pPicYuv, Int aiPad[2], Bool bRewind = false );     ///< read  one YUV frame with padding parameter
+  Bool  write( TComPicYuv*    pPicYuv, Int cropLeft=0, Int cropRight=0, Int cropTop=0, Int cropBottom=0 );
+  
+  bool  isEof ();                                           ///< check for end-of-file
+  bool  isFail();                                           ///< check for failure
+  
+};
+
+#endif // __TVIDEOIOYUV__
+
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/MD5.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/MD5.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/MD5.h	(revision 341)
@@ -0,0 +1,87 @@
+/* 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-2012, 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
+#include "libmd5.h"
+
+//! \ingroup libMD5
+//! \{
+
+class MD5 {
+public:
+  /**
+   * initialize digest state
+   */
+  MD5()
+  {
+    MD5Init(&m_state);
+  }
+
+  /**
+   * compute digest over buf of length len.
+   * multiple calls may extend the digest over more data.
+   */
+  void update(unsigned char *buf, unsigned len)
+  {
+    MD5Update(&m_state, buf, len);
+  }
+
+  /**
+   * flush any outstanding MD5 data, write the digest into digest.
+   */
+  void finalize(unsigned char digest[16])
+  {
+    MD5Final(digest, &m_state);
+  }
+
+private:
+  context_md5_t m_state;
+};
+
+/**
+ * Produce an ascii(hex) representation of the 128bit digest.
+ *
+ * Returns: a statically allocated null-terminated string.  DO NOT FREE.
+ */
+inline const char*
+digestToString(unsigned char digest[16])
+{
+  const char* hex = "0123456789abcdef";
+  static char string[33];
+  for (int i = 0; i < 16; i++)
+  {
+    string[i*2+0] = hex[digest[i] >> 4];
+    string[i*2+1] = hex[digest[i] & 0xf];
+  }
+  return string;
+}
+//! \}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/libmd5.c
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/libmd5.c	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/libmd5.c	(revision 341)
@@ -0,0 +1,255 @@
+/*
+ * This code implements the MD5 message-digest algorithm.  The algorithm was
+ * written by Ron Rivest.  This code was written by Colin Plumb in 1993, our
+ * understanding is that no copyright is claimed and that this code is in the
+ * public domain.
+ *
+ * Equivalent code is available from RSA Data Security, Inc.
+ * This code has been tested against that, and is functionally equivalent,
+ *
+ * To compute the message digest of a chunk of bytes, declare an MD5Context
+ * structure, pass it to MD5Init, call MD5Update as needed on buffers full of
+ * bytes, and then call MD5Final, which will fill a supplied 16-byte array with
+ * the digest.
+ */
+
+#include <stdint.h>
+#include <string.h>
+#include "libmd5.h"
+
+//! \ingroup libMD5
+//! \{
+
+static void MD5Transform(uint32_t buf[4], uint32_t const in[16]);
+
+#ifndef __BIG_ENDIAN__
+# define byteReverse(buf, len)    /* Nothing */
+#else
+void byteReverse(unsigned char *buf, unsigned longs);
+/*
+ * Note: this code is harmless on little-endian machines.
+ */
+void byteReverse(unsigned char *buf, unsigned longs)
+{
+  uint32_t t;
+  do {
+    t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
+        ((unsigned) buf[1] << 8 | buf[0]);
+    *(uint32_t *) buf = t;
+    buf += 4;
+  } while (--longs);
+}
+#endif
+
+/*
+ * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
+ * initialization constants.
+ */
+void MD5Init(context_md5_t *ctx)
+{
+  ctx->buf[0] = 0x67452301;
+  ctx->buf[1] = 0xefcdab89;
+  ctx->buf[2] = 0x98badcfe;
+  ctx->buf[3] = 0x10325476;
+
+  ctx->bits[0] = 0;
+  ctx->bits[1] = 0;
+}
+
+/*
+ * Update context to reflect the concatenation of another buffer full
+ * of bytes.
+ */
+void MD5Update(context_md5_t *ctx, unsigned char *buf, unsigned len)
+{
+  uint32_t t;
+
+  /* Update bitcount */
+
+  t = ctx->bits[0];
+  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
+    ctx->bits[1]++;        /* Carry from low to high */
+  ctx->bits[1] += len >> 29;
+
+  t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
+
+  /* Handle any leading odd-sized chunks */
+
+  if (t) {
+    unsigned char *p = (unsigned char *) ctx->in + t;
+
+    t = 64 - t;
+    if (len < t) {
+      memcpy(p, buf, len);
+      return;
+    }
+    memcpy(p, buf, t);
+    byteReverse(ctx->in, 16);
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+    buf += t;
+    len -= t;
+  }
+  /* Process data in 64-byte chunks */
+
+  while (len >= 64) {
+    memcpy(ctx->in, buf, 64);
+    byteReverse(ctx->in, 16);
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+    buf += 64;
+    len -= 64;
+  }
+
+    /* Handle any remaining bytes of data. */
+
+  memcpy(ctx->in, buf, len);
+}
+
+/*
+ * Final wrapup - pad to 64-byte boundary with the bit pattern
+ * 1 0* (64-bit count of bits processed, MSB-first)
+ */
+void MD5Final(unsigned char digest[16], context_md5_t *ctx)
+{
+  unsigned count;
+  unsigned char *p;
+
+  /* Compute number of bytes mod 64 */
+  count = (ctx->bits[0] >> 3) & 0x3F;
+
+  /* Set the first char of padding to 0x80.  This is safe since there is
+     always at least one byte free */
+  p = ctx->in + count;
+  *p++ = 0x80;
+
+  /* Bytes of padding needed to make 64 bytes */
+  count = 64 - 1 - count;
+
+  /* Pad out to 56 mod 64 */
+  if (count < 8) {
+    /* Two lots of padding:  Pad the first block to 64 bytes */
+    memset(p, 0, count);
+    byteReverse(ctx->in, 16);
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+
+    /* Now fill the next block with 56 bytes */
+    memset(ctx->in, 0, 56);
+  } else {
+    /* Pad block to 56 bytes */
+    memset(p, 0, count - 8);
+  }
+  byteReverse(ctx->in, 14);
+
+  /* Append length in bits and transform */
+  ((uint32_t *) ctx->in)[14] = ctx->bits[0];
+  ((uint32_t *) ctx->in)[15] = ctx->bits[1];
+
+  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+  byteReverse((unsigned char *) ctx->buf, 4);
+  memcpy(digest, ctx->buf, 16);
+
+  memset(ctx, 0, sizeof(* ctx));    /* In case it's sensitive */
+  /* The original version of this code omitted the asterisk. In
+     effect, only the first part of ctx was wiped with zeros, not
+     the whole thing. Bug found by Derek Jones. Original line: */
+  // memset(ctx, 0, sizeof(ctx));    /* In case it's sensitive */
+}
+
+/* The four core functions - F1 is optimized somewhat */
+
+/* #define F1(x, y, z) (x & y | ~x & z) */
+#define F1(x, y, z) (z ^ (x & (y ^ z)))
+#define F2(x, y, z) F1(z, x, y)
+#define F3(x, y, z) (x ^ y ^ z)
+#define F4(x, y, z) (y ^ (x | ~z))
+
+/* This is the central step in the MD5 algorithm. */
+#define MD5STEP(f, w, x, y, z, data, s) \
+    ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
+
+/*
+ * The core of the MD5 algorithm, this alters an existing MD5 hash to
+ * reflect the addition of 16 longwords of new data.  MD5Update blocks
+ * the data and converts bytes into longwords for this routine.
+ */
+static void MD5Transform(uint32_t buf[4], uint32_t const in[16])
+{
+  register uint32_t a, b, c, d;
+
+  a = buf[0];
+  b = buf[1];
+  c = buf[2];
+  d = buf[3];
+
+  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
+  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
+  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
+  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
+  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
+  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
+  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
+  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
+  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
+  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
+  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
+  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
+  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
+  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
+  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
+  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
+
+  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
+  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
+  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
+  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
+  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
+  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
+  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
+  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
+  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
+  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
+  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
+  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
+  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
+  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
+  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
+  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
+
+  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
+  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
+  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
+  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
+  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
+  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
+  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
+  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
+  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
+  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
+  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
+  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
+  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
+  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
+  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
+  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
+
+  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
+  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
+  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
+  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
+  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
+  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
+  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
+  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
+  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
+  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
+  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
+  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
+  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
+  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
+  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
+  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
+
+  buf[0] += a;
+  buf[1] += b;
+  buf[2] += c;
+  buf[3] += d;
+}
Index: branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/libmd5.h
===================================================================
--- branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/libmd5.h	(revision 341)
+++ branches/HTM-6.2-dev1-Samsung/source/Lib/libmd5/libmd5.h	(revision 341)
@@ -0,0 +1,55 @@
+/* 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-2012, 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
+#include <stdint.h>
+
+//! \ingroup libMD5
+//! \{
+
+typedef struct _context_md5_t {
+  uint32_t buf[4];
+  uint32_t bits[2];
+  unsigned char in[64];
+} context_md5_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+void MD5Init(context_md5_t *ctx);
+void MD5Update(context_md5_t *ctx, unsigned char *buf, unsigned len);
+void MD5Final(unsigned char digest[16], context_md5_t *ctx);
+#ifdef __cplusplus
+}
+#endif
+
+//! \}
