Index: /tags/0.2r1/COPYING
===================================================================
--- /tags/0.2r1/COPYING	(revision 19)
+++ /tags/0.2r1/COPYING	(revision 19)
@@ -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-2011, 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: /tags/0.2r1/HM.xcodeproj/project.pbxproj
===================================================================
--- /tags/0.2r1/HM.xcodeproj/project.pbxproj	(revision 19)
+++ /tags/0.2r1/HM.xcodeproj/project.pbxproj	(revision 19)
@@ -0,0 +1,1303 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 45;
+	objects = {
+
+/* Begin PBXBuildFile section */
+		65EA1B88135744C400988950 /* libmd5.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B85135744C400988950 /* libmd5.h */; };
+		65EA1B89135744C400988950 /* libmd5.c in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B86135744C400988950 /* libmd5.c */; };
+		65EA1B8A135744C400988950 /* MD5.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B87135744C400988950 /* MD5.h */; };
+		65EA1B8E135744EA00988950 /* SEIread.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B8C135744EA00988950 /* SEIread.h */; };
+		65EA1B8F135744EA00988950 /* SEIread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B8D135744EA00988950 /* SEIread.cpp */; };
+		65EA1B92135744FE00988950 /* SEIwrite.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B90135744FE00988950 /* SEIwrite.h */; };
+		65EA1B93135744FE00988950 /* SEIwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B91135744FE00988950 /* SEIwrite.cpp */; };
+		65EA1B951357451300988950 /* SEI.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B941357451300988950 /* SEI.h */; };
+		65EA1B97135745D500988950 /* TComPicYuvMD5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */; };
+		671E0D4911B6AD8C00F3747B /* ContextModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D3811B6AD8C00F3747B /* ContextModel.cpp */; };
+		671E0D4A11B6AD8C00F3747B /* ContextModel.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D3911B6AD8C00F3747B /* ContextModel.h */; };
+		671E0D4B11B6AD8C00F3747B /* ContextModel3DBuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D3A11B6AD8C00F3747B /* ContextModel3DBuffer.cpp */; };
+		671E0D4C11B6AD8C00F3747B /* ContextModel3DBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D3B11B6AD8C00F3747B /* ContextModel3DBuffer.h */; };
+		671E0D4F11B6AD8C00F3747B /* TComBitCounter.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D3E11B6AD8C00F3747B /* TComBitCounter.h */; };
+		671E0D5011B6AD8C00F3747B /* TComCABACTables.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D3F11B6AD8C00F3747B /* TComCABACTables.cpp */; };
+		671E0D5111B6AD8C00F3747B /* TComCABACTables.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D4011B6AD8C00F3747B /* TComCABACTables.h */; };
+		671E0D5211B6AD8C00F3747B /* TComMv.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D4111B6AD8C00F3747B /* TComMv.h */; };
+		671E0D6411B6ADD300F3747B /* TDecBinCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D5611B6ADD300F3747B /* TDecBinCoder.h */; };
+		671E0D6511B6ADD300F3747B /* TDecBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D5711B6ADD300F3747B /* TDecBinCoderCABAC.cpp */; };
+		671E0D6611B6ADD300F3747B /* TDecBinCoderCABAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D5811B6ADD300F3747B /* TDecBinCoderCABAC.h */; };
+		671E0D8011B6ADE900F3747B /* TEncBinCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D7211B6ADE900F3747B /* TEncBinCoder.h */; };
+		671E0D8111B6ADE900F3747B /* TEncBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D7311B6ADE900F3747B /* TEncBinCoderCABAC.cpp */; };
+		671E0D8211B6ADE900F3747B /* TEncBinCoderCABAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D7411B6ADE900F3747B /* TEncBinCoderCABAC.h */; };
+		676795C411AD61FC00421804 /* CommonDef.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767959911AD61FC00421804 /* CommonDef.h */; };
+		676795C511AD61FC00421804 /* ContextTables.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767959A11AD61FC00421804 /* ContextTables.h */; };
+		676795CB11AD61FC00421804 /* TComAdaptiveLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795A011AD61FC00421804 /* TComAdaptiveLoopFilter.cpp */; };
+		676795CC11AD61FC00421804 /* TComAdaptiveLoopFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A111AD61FC00421804 /* TComAdaptiveLoopFilter.h */; };
+		676795CE11AD61FC00421804 /* TComBitStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795A311AD61FC00421804 /* TComBitStream.cpp */; };
+		676795CF11AD61FC00421804 /* TComBitStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A411AD61FC00421804 /* TComBitStream.h */; };
+		676795D011AD61FC00421804 /* TComDataCU.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795A511AD61FC00421804 /* TComDataCU.cpp */; };
+		676795D111AD61FC00421804 /* TComDataCU.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A611AD61FC00421804 /* TComDataCU.h */; };
+		676795D211AD61FC00421804 /* TComList.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A711AD61FC00421804 /* TComList.h */; };
+		676795D311AD61FC00421804 /* TComLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795A811AD61FC00421804 /* TComLoopFilter.cpp */; };
+		676795D411AD61FC00421804 /* TComLoopFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A911AD61FC00421804 /* TComLoopFilter.h */; };
+		676795D511AD61FC00421804 /* TComMotionInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795AA11AD61FC00421804 /* TComMotionInfo.cpp */; };
+		676795D611AD61FC00421804 /* TComMotionInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795AB11AD61FC00421804 /* TComMotionInfo.h */; };
+		676795D811AD61FC00421804 /* TComPattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795AD11AD61FC00421804 /* TComPattern.cpp */; };
+		676795D911AD61FC00421804 /* TComPattern.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795AE11AD61FC00421804 /* TComPattern.h */; };
+		676795DA11AD61FC00421804 /* TComPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795AF11AD61FC00421804 /* TComPic.cpp */; };
+		676795DB11AD61FC00421804 /* TComPic.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B011AD61FC00421804 /* TComPic.h */; };
+		676795DC11AD61FC00421804 /* TComPicSym.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B111AD61FC00421804 /* TComPicSym.cpp */; };
+		676795DD11AD61FC00421804 /* TComPicSym.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B211AD61FC00421804 /* TComPicSym.h */; };
+		676795DE11AD61FC00421804 /* TComPicYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B311AD61FC00421804 /* TComPicYuv.cpp */; };
+		676795DF11AD61FC00421804 /* TComPicYuv.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B411AD61FC00421804 /* TComPicYuv.h */; };
+		676795E011AD61FC00421804 /* TComPredFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B511AD61FC00421804 /* TComPredFilter.cpp */; };
+		676795E111AD61FC00421804 /* TComPredFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B611AD61FC00421804 /* TComPredFilter.h */; };
+		676795E211AD61FC00421804 /* TComPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B711AD61FC00421804 /* TComPrediction.cpp */; };
+		676795E311AD61FC00421804 /* TComPrediction.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B811AD61FC00421804 /* TComPrediction.h */; };
+		676795E411AD61FC00421804 /* TComRdCost.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B911AD61FC00421804 /* TComRdCost.cpp */; };
+		676795E511AD61FC00421804 /* TComRdCost.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795BA11AD61FC00421804 /* TComRdCost.h */; };
+		676795E611AD61FC00421804 /* TComRom.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795BB11AD61FC00421804 /* TComRom.cpp */; };
+		676795E711AD61FC00421804 /* TComRom.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795BC11AD61FC00421804 /* TComRom.h */; };
+		676795E811AD61FC00421804 /* TComSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795BD11AD61FC00421804 /* TComSlice.cpp */; };
+		676795E911AD61FC00421804 /* TComSlice.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795BE11AD61FC00421804 /* TComSlice.h */; };
+		676795EA11AD61FC00421804 /* TComTrQuant.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795BF11AD61FC00421804 /* TComTrQuant.cpp */; };
+		676795EB11AD61FC00421804 /* TComTrQuant.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795C011AD61FC00421804 /* TComTrQuant.h */; };
+		676795EC11AD61FC00421804 /* TComYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795C111AD61FC00421804 /* TComYuv.cpp */; };
+		676795ED11AD61FC00421804 /* TComYuv.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795C211AD61FC00421804 /* TComYuv.h */; };
+		676795EE11AD61FC00421804 /* TypeDef.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795C311AD61FC00421804 /* TypeDef.h */; };
+		6767960611AD623900421804 /* TDecCAVLC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795F811AD623900421804 /* TDecCAVLC.cpp */; };
+		6767960711AD623900421804 /* TDecCAVLC.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795F911AD623900421804 /* TDecCAVLC.h */; };
+		6767960811AD623900421804 /* TDecCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795FA11AD623900421804 /* TDecCu.cpp */; };
+		6767960911AD623900421804 /* TDecCu.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795FB11AD623900421804 /* TDecCu.h */; };
+		6767960A11AD623900421804 /* TDecEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795FC11AD623900421804 /* TDecEntropy.cpp */; };
+		6767960B11AD623900421804 /* TDecEntropy.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795FD11AD623900421804 /* TDecEntropy.h */; };
+		6767960C11AD623900421804 /* TDecGop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795FE11AD623900421804 /* TDecGop.cpp */; };
+		6767960D11AD623900421804 /* TDecGop.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795FF11AD623900421804 /* TDecGop.h */; };
+		6767960E11AD623900421804 /* TDecSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767960011AD623900421804 /* TDecSbac.cpp */; };
+		6767960F11AD623900421804 /* TDecSbac.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767960111AD623900421804 /* TDecSbac.h */; };
+		6767961011AD623900421804 /* TDecSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767960211AD623900421804 /* TDecSlice.cpp */; };
+		6767961111AD623900421804 /* TDecSlice.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767960311AD623900421804 /* TDecSlice.h */; };
+		6767961211AD623900421804 /* TDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767960411AD623900421804 /* TDecTop.cpp */; };
+		6767961311AD623900421804 /* TDecTop.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767960511AD623900421804 /* TDecTop.h */; };
+		6767963111AD628100421804 /* TEncAdaptiveLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767961C11AD628100421804 /* TEncAdaptiveLoopFilter.cpp */; };
+		6767963211AD628100421804 /* TEncAdaptiveLoopFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767961D11AD628100421804 /* TEncAdaptiveLoopFilter.h */; };
+		6767963311AD628100421804 /* TEncAnalyze.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767961E11AD628100421804 /* TEncAnalyze.cpp */; };
+		6767963411AD628100421804 /* TEncAnalyze.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767961F11AD628100421804 /* TEncAnalyze.h */; };
+		6767963511AD628100421804 /* TEncCavlc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962011AD628100421804 /* TEncCavlc.cpp */; };
+		6767963611AD628100421804 /* TEncCavlc.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962111AD628100421804 /* TEncCavlc.h */; };
+		6767963711AD628100421804 /* TEncCfg.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962211AD628100421804 /* TEncCfg.h */; };
+		6767963811AD628100421804 /* TEncCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962311AD628100421804 /* TEncCu.cpp */; };
+		6767963911AD628100421804 /* TEncCu.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962411AD628100421804 /* TEncCu.h */; };
+		6767963A11AD628100421804 /* TEncEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962511AD628100421804 /* TEncEntropy.cpp */; };
+		6767963B11AD628100421804 /* TEncEntropy.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962611AD628100421804 /* TEncEntropy.h */; };
+		6767963C11AD628100421804 /* TEncGOP.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962711AD628100421804 /* TEncGOP.cpp */; };
+		6767963D11AD628100421804 /* TEncGOP.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962811AD628100421804 /* TEncGOP.h */; };
+		6767963E11AD628100421804 /* TEncSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962911AD628100421804 /* TEncSbac.cpp */; };
+		6767963F11AD628100421804 /* TEncSbac.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962A11AD628100421804 /* TEncSbac.h */; };
+		6767964011AD628100421804 /* TEncSearch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962B11AD628100421804 /* TEncSearch.cpp */; };
+		6767964111AD628100421804 /* TEncSearch.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962C11AD628100421804 /* TEncSearch.h */; };
+		6767964211AD628100421804 /* TEncSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962D11AD628100421804 /* TEncSlice.cpp */; };
+		6767964311AD628100421804 /* TEncSlice.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962E11AD628100421804 /* TEncSlice.h */; };
+		6767964411AD628100421804 /* TEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962F11AD628100421804 /* TEncTop.cpp */; };
+		6767964511AD628100421804 /* TEncTop.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767963011AD628100421804 /* TEncTop.h */; };
+		6767965411AD62AC00421804 /* TVideoIOBits.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767965011AD62AC00421804 /* TVideoIOBits.cpp */; };
+		6767965511AD62AC00421804 /* TVideoIOBits.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767965111AD62AC00421804 /* TVideoIOBits.h */; };
+		6767965611AD62AC00421804 /* TVideoIOYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767965211AD62AC00421804 /* TVideoIOYuv.cpp */; };
+		6767965711AD62AC00421804 /* TVideoIOYuv.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767965311AD62AC00421804 /* TVideoIOYuv.h */; };
+		6767967711AD66FD00421804 /* encmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767967011AD66FD00421804 /* encmain.cpp */; };
+		6767967811AD66FD00421804 /* TAppEncCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767967111AD66FD00421804 /* TAppEncCfg.cpp */; };
+		6767967A11AD66FD00421804 /* TAppEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767967511AD66FD00421804 /* TAppEncTop.cpp */; };
+		6782E0E211AD692000E8FFB8 /* libTLibDecoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 676795F411AD621A00421804 /* libTLibDecoder.a */; };
+		6782E0E311AD692300E8FFB8 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		6782E0E411AD692700E8FFB8 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		6782E0EE11AD694400E8FFB8 /* decmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6782E0E711AD694400E8FFB8 /* decmain.cpp */; };
+		6782E0EF11AD694400E8FFB8 /* TAppDecCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6782E0E811AD694400E8FFB8 /* TAppDecCfg.cpp */; };
+		6782E0F111AD694400E8FFB8 /* TAppDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6782E0EC11AD694400E8FFB8 /* TAppDecTop.cpp */; };
+		7104E1DF12005B0E00F42AA8 /* program_options_lite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7104E1DD12005B0E00F42AA8 /* program_options_lite.cpp */; };
+		7104E1E012005B0E00F42AA8 /* program_options_lite.h in Headers */ = {isa = PBXBuildFile; fileRef = 7104E1DE12005B0E00F42AA8 /* program_options_lite.h */; };
+		7104E1E312005B5600F42AA8 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */; };
+		710DD68B1335295200BE8EDE /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */; };
+		71AD603911EBC28500F5F1FE /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		71AD603A11EBC28D00F5F1FE /* libTLibEncoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767961911AD626F00421804 /* libTLibEncoder.a */; };
+		71AD603B11EBC29600F5F1FE /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXContainerItemProxy section */
+		6745C42711AD7709007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 676795F311AD621A00421804;
+			remoteInfo = TLibDecoder;
+		};
+		6745C42911AD770E007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		6745C42B11AD7711007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		6745C43111AD7747007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767961811AD626F00421804;
+			remoteInfo = TLibEncoder;
+		};
+		6745C43311AD774C007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		6745C43511AD774F007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		7104E1E112005B4B00F42AA8 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7104E1CC12005ABA00F42AA8;
+			remoteInfo = TAppCommon;
+		};
+		710DD69A133529A100BE8EDE /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7104E1CC12005ABA00F42AA8;
+			remoteInfo = TAppCommon;
+		};
+/* End PBXContainerItemProxy section */
+
+/* Begin PBXFileReference section */
+		65EA1B85135744C400988950 /* libmd5.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = libmd5.h; path = source/Lib/libmd5/libmd5.h; sourceTree = "<group>"; };
+		65EA1B86135744C400988950 /* libmd5.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = libmd5.c; path = source/Lib/libmd5/libmd5.c; sourceTree = "<group>"; };
+		65EA1B87135744C400988950 /* MD5.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MD5.h; path = source/Lib/libmd5/MD5.h; sourceTree = "<group>"; };
+		65EA1B8C135744EA00988950 /* SEIread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEIread.h; path = source/Lib/TLibDecoder/SEIread.h; sourceTree = "<group>"; };
+		65EA1B8D135744EA00988950 /* SEIread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEIread.cpp; path = source/Lib/TLibDecoder/SEIread.cpp; sourceTree = "<group>"; };
+		65EA1B90135744FE00988950 /* SEIwrite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEIwrite.h; path = source/Lib/TLibEncoder/SEIwrite.h; sourceTree = "<group>"; };
+		65EA1B91135744FE00988950 /* SEIwrite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEIwrite.cpp; path = source/Lib/TLibEncoder/SEIwrite.cpp; sourceTree = "<group>"; };
+		65EA1B941357451300988950 /* SEI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEI.h; path = source/Lib/TLibCommon/SEI.h; sourceTree = "<group>"; };
+		65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPicYuvMD5.cpp; path = source/Lib/TLibCommon/TComPicYuvMD5.cpp; sourceTree = "<group>"; };
+		671E0D3811B6AD8C00F3747B /* ContextModel.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ContextModel.cpp; path = source/Lib/TLibCommon/ContextModel.cpp; sourceTree = "<group>"; };
+		671E0D3911B6AD8C00F3747B /* ContextModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ContextModel.h; path = source/Lib/TLibCommon/ContextModel.h; sourceTree = "<group>"; };
+		671E0D3A11B6AD8C00F3747B /* ContextModel3DBuffer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ContextModel3DBuffer.cpp; path = source/Lib/TLibCommon/ContextModel3DBuffer.cpp; sourceTree = "<group>"; };
+		671E0D3B11B6AD8C00F3747B /* ContextModel3DBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ContextModel3DBuffer.h; path = source/Lib/TLibCommon/ContextModel3DBuffer.h; sourceTree = "<group>"; };
+		671E0D3E11B6AD8C00F3747B /* TComBitCounter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComBitCounter.h; path = source/Lib/TLibCommon/TComBitCounter.h; sourceTree = "<group>"; };
+		671E0D3F11B6AD8C00F3747B /* TComCABACTables.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComCABACTables.cpp; path = source/Lib/TLibCommon/TComCABACTables.cpp; sourceTree = "<group>"; };
+		671E0D4011B6AD8C00F3747B /* TComCABACTables.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComCABACTables.h; path = source/Lib/TLibCommon/TComCABACTables.h; sourceTree = "<group>"; };
+		671E0D4111B6AD8C00F3747B /* TComMv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComMv.h; path = source/Lib/TLibCommon/TComMv.h; sourceTree = "<group>"; };
+		671E0D5611B6ADD300F3747B /* TDecBinCoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecBinCoder.h; path = source/Lib/TLibDecoder/TDecBinCoder.h; sourceTree = "<group>"; };
+		671E0D5711B6ADD300F3747B /* TDecBinCoderCABAC.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecBinCoderCABAC.cpp; path = source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		671E0D5811B6ADD300F3747B /* TDecBinCoderCABAC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecBinCoderCABAC.h; path = source/Lib/TLibDecoder/TDecBinCoderCABAC.h; sourceTree = "<group>"; };
+		671E0D7211B6ADE900F3747B /* TEncBinCoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncBinCoder.h; path = source/Lib/TLibEncoder/TEncBinCoder.h; sourceTree = "<group>"; };
+		671E0D7311B6ADE900F3747B /* TEncBinCoderCABAC.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncBinCoderCABAC.cpp; path = source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		671E0D7411B6ADE900F3747B /* TEncBinCoderCABAC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncBinCoderCABAC.h; path = source/Lib/TLibEncoder/TEncBinCoderCABAC.h; sourceTree = "<group>"; };
+		6767959411AD61BB00421804 /* libTLibCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibCommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767959911AD61FC00421804 /* CommonDef.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CommonDef.h; path = source/Lib/TLibCommon/CommonDef.h; sourceTree = "<group>"; };
+		6767959A11AD61FC00421804 /* ContextTables.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ContextTables.h; path = source/Lib/TLibCommon/ContextTables.h; sourceTree = "<group>"; };
+		676795A011AD61FC00421804 /* TComAdaptiveLoopFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComAdaptiveLoopFilter.cpp; path = source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp; sourceTree = "<group>"; };
+		676795A111AD61FC00421804 /* TComAdaptiveLoopFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComAdaptiveLoopFilter.h; path = source/Lib/TLibCommon/TComAdaptiveLoopFilter.h; sourceTree = "<group>"; };
+		676795A311AD61FC00421804 /* TComBitStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComBitStream.cpp; path = source/Lib/TLibCommon/TComBitStream.cpp; sourceTree = "<group>"; };
+		676795A411AD61FC00421804 /* TComBitStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComBitStream.h; path = source/Lib/TLibCommon/TComBitStream.h; sourceTree = "<group>"; };
+		676795A511AD61FC00421804 /* TComDataCU.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComDataCU.cpp; path = source/Lib/TLibCommon/TComDataCU.cpp; sourceTree = "<group>"; };
+		676795A611AD61FC00421804 /* TComDataCU.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComDataCU.h; path = source/Lib/TLibCommon/TComDataCU.h; sourceTree = "<group>"; };
+		676795A711AD61FC00421804 /* TComList.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComList.h; path = source/Lib/TLibCommon/TComList.h; sourceTree = "<group>"; };
+		676795A811AD61FC00421804 /* TComLoopFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComLoopFilter.cpp; path = source/Lib/TLibCommon/TComLoopFilter.cpp; sourceTree = "<group>"; };
+		676795A911AD61FC00421804 /* TComLoopFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComLoopFilter.h; path = source/Lib/TLibCommon/TComLoopFilter.h; sourceTree = "<group>"; };
+		676795AA11AD61FC00421804 /* TComMotionInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComMotionInfo.cpp; path = source/Lib/TLibCommon/TComMotionInfo.cpp; sourceTree = "<group>"; };
+		676795AB11AD61FC00421804 /* TComMotionInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComMotionInfo.h; path = source/Lib/TLibCommon/TComMotionInfo.h; sourceTree = "<group>"; };
+		676795AD11AD61FC00421804 /* TComPattern.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPattern.cpp; path = source/Lib/TLibCommon/TComPattern.cpp; sourceTree = "<group>"; };
+		676795AE11AD61FC00421804 /* TComPattern.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPattern.h; path = source/Lib/TLibCommon/TComPattern.h; sourceTree = "<group>"; };
+		676795AF11AD61FC00421804 /* TComPic.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPic.cpp; path = source/Lib/TLibCommon/TComPic.cpp; sourceTree = "<group>"; };
+		676795B011AD61FC00421804 /* TComPic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPic.h; path = source/Lib/TLibCommon/TComPic.h; sourceTree = "<group>"; };
+		676795B111AD61FC00421804 /* TComPicSym.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPicSym.cpp; path = source/Lib/TLibCommon/TComPicSym.cpp; sourceTree = "<group>"; };
+		676795B211AD61FC00421804 /* TComPicSym.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPicSym.h; path = source/Lib/TLibCommon/TComPicSym.h; sourceTree = "<group>"; };
+		676795B311AD61FC00421804 /* TComPicYuv.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPicYuv.cpp; path = source/Lib/TLibCommon/TComPicYuv.cpp; sourceTree = "<group>"; };
+		676795B411AD61FC00421804 /* TComPicYuv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPicYuv.h; path = source/Lib/TLibCommon/TComPicYuv.h; sourceTree = "<group>"; };
+		676795B511AD61FC00421804 /* TComPredFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPredFilter.cpp; path = source/Lib/TLibCommon/TComPredFilter.cpp; sourceTree = "<group>"; };
+		676795B611AD61FC00421804 /* TComPredFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPredFilter.h; path = source/Lib/TLibCommon/TComPredFilter.h; sourceTree = "<group>"; };
+		676795B711AD61FC00421804 /* TComPrediction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPrediction.cpp; path = source/Lib/TLibCommon/TComPrediction.cpp; sourceTree = "<group>"; };
+		676795B811AD61FC00421804 /* TComPrediction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPrediction.h; path = source/Lib/TLibCommon/TComPrediction.h; sourceTree = "<group>"; };
+		676795B911AD61FC00421804 /* TComRdCost.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComRdCost.cpp; path = source/Lib/TLibCommon/TComRdCost.cpp; sourceTree = "<group>"; };
+		676795BA11AD61FC00421804 /* TComRdCost.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComRdCost.h; path = source/Lib/TLibCommon/TComRdCost.h; sourceTree = "<group>"; };
+		676795BB11AD61FC00421804 /* TComRom.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComRom.cpp; path = source/Lib/TLibCommon/TComRom.cpp; sourceTree = "<group>"; };
+		676795BC11AD61FC00421804 /* TComRom.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComRom.h; path = source/Lib/TLibCommon/TComRom.h; sourceTree = "<group>"; };
+		676795BD11AD61FC00421804 /* TComSlice.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComSlice.cpp; path = source/Lib/TLibCommon/TComSlice.cpp; sourceTree = "<group>"; };
+		676795BE11AD61FC00421804 /* TComSlice.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComSlice.h; path = source/Lib/TLibCommon/TComSlice.h; sourceTree = "<group>"; };
+		676795BF11AD61FC00421804 /* TComTrQuant.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComTrQuant.cpp; path = source/Lib/TLibCommon/TComTrQuant.cpp; sourceTree = "<group>"; };
+		676795C011AD61FC00421804 /* TComTrQuant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComTrQuant.h; path = source/Lib/TLibCommon/TComTrQuant.h; sourceTree = "<group>"; };
+		676795C111AD61FC00421804 /* TComYuv.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComYuv.cpp; path = source/Lib/TLibCommon/TComYuv.cpp; sourceTree = "<group>"; };
+		676795C211AD61FC00421804 /* TComYuv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComYuv.h; path = source/Lib/TLibCommon/TComYuv.h; sourceTree = "<group>"; };
+		676795C311AD61FC00421804 /* TypeDef.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TypeDef.h; path = source/Lib/TLibCommon/TypeDef.h; sourceTree = "<group>"; };
+		676795F411AD621A00421804 /* libTLibDecoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibDecoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		676795F811AD623900421804 /* TDecCAVLC.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecCAVLC.cpp; path = source/Lib/TLibDecoder/TDecCAVLC.cpp; sourceTree = "<group>"; };
+		676795F911AD623900421804 /* TDecCAVLC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecCAVLC.h; path = source/Lib/TLibDecoder/TDecCAVLC.h; sourceTree = "<group>"; };
+		676795FA11AD623900421804 /* TDecCu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecCu.cpp; path = source/Lib/TLibDecoder/TDecCu.cpp; sourceTree = "<group>"; };
+		676795FB11AD623900421804 /* TDecCu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecCu.h; path = source/Lib/TLibDecoder/TDecCu.h; sourceTree = "<group>"; };
+		676795FC11AD623900421804 /* TDecEntropy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecEntropy.cpp; path = source/Lib/TLibDecoder/TDecEntropy.cpp; sourceTree = "<group>"; };
+		676795FD11AD623900421804 /* TDecEntropy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecEntropy.h; path = source/Lib/TLibDecoder/TDecEntropy.h; sourceTree = "<group>"; };
+		676795FE11AD623900421804 /* TDecGop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecGop.cpp; path = source/Lib/TLibDecoder/TDecGop.cpp; sourceTree = "<group>"; };
+		676795FF11AD623900421804 /* TDecGop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecGop.h; path = source/Lib/TLibDecoder/TDecGop.h; sourceTree = "<group>"; };
+		6767960011AD623900421804 /* TDecSbac.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecSbac.cpp; path = source/Lib/TLibDecoder/TDecSbac.cpp; sourceTree = "<group>"; };
+		6767960111AD623900421804 /* TDecSbac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecSbac.h; path = source/Lib/TLibDecoder/TDecSbac.h; sourceTree = "<group>"; };
+		6767960211AD623900421804 /* TDecSlice.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecSlice.cpp; path = source/Lib/TLibDecoder/TDecSlice.cpp; sourceTree = "<group>"; };
+		6767960311AD623900421804 /* TDecSlice.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecSlice.h; path = source/Lib/TLibDecoder/TDecSlice.h; sourceTree = "<group>"; };
+		6767960411AD623900421804 /* TDecTop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecTop.cpp; path = source/Lib/TLibDecoder/TDecTop.cpp; sourceTree = "<group>"; };
+		6767960511AD623900421804 /* TDecTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecTop.h; path = source/Lib/TLibDecoder/TDecTop.h; sourceTree = "<group>"; };
+		6767961911AD626F00421804 /* libTLibEncoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibEncoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767961C11AD628100421804 /* TEncAdaptiveLoopFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncAdaptiveLoopFilter.cpp; path = source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp; sourceTree = "<group>"; };
+		6767961D11AD628100421804 /* TEncAdaptiveLoopFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncAdaptiveLoopFilter.h; path = source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h; sourceTree = "<group>"; };
+		6767961E11AD628100421804 /* TEncAnalyze.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncAnalyze.cpp; path = source/Lib/TLibEncoder/TEncAnalyze.cpp; sourceTree = "<group>"; };
+		6767961F11AD628100421804 /* TEncAnalyze.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncAnalyze.h; path = source/Lib/TLibEncoder/TEncAnalyze.h; sourceTree = "<group>"; };
+		6767962011AD628100421804 /* TEncCavlc.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncCavlc.cpp; path = source/Lib/TLibEncoder/TEncCavlc.cpp; sourceTree = "<group>"; };
+		6767962111AD628100421804 /* TEncCavlc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncCavlc.h; path = source/Lib/TLibEncoder/TEncCavlc.h; sourceTree = "<group>"; };
+		6767962211AD628100421804 /* TEncCfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncCfg.h; path = source/Lib/TLibEncoder/TEncCfg.h; sourceTree = "<group>"; };
+		6767962311AD628100421804 /* TEncCu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncCu.cpp; path = source/Lib/TLibEncoder/TEncCu.cpp; sourceTree = "<group>"; };
+		6767962411AD628100421804 /* TEncCu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncCu.h; path = source/Lib/TLibEncoder/TEncCu.h; sourceTree = "<group>"; };
+		6767962511AD628100421804 /* TEncEntropy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncEntropy.cpp; path = source/Lib/TLibEncoder/TEncEntropy.cpp; sourceTree = "<group>"; };
+		6767962611AD628100421804 /* TEncEntropy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncEntropy.h; path = source/Lib/TLibEncoder/TEncEntropy.h; sourceTree = "<group>"; };
+		6767962711AD628100421804 /* TEncGOP.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncGOP.cpp; path = source/Lib/TLibEncoder/TEncGOP.cpp; sourceTree = "<group>"; };
+		6767962811AD628100421804 /* TEncGOP.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncGOP.h; path = source/Lib/TLibEncoder/TEncGOP.h; sourceTree = "<group>"; };
+		6767962911AD628100421804 /* TEncSbac.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncSbac.cpp; path = source/Lib/TLibEncoder/TEncSbac.cpp; sourceTree = "<group>"; };
+		6767962A11AD628100421804 /* TEncSbac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncSbac.h; path = source/Lib/TLibEncoder/TEncSbac.h; sourceTree = "<group>"; };
+		6767962B11AD628100421804 /* TEncSearch.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncSearch.cpp; path = source/Lib/TLibEncoder/TEncSearch.cpp; sourceTree = "<group>"; };
+		6767962C11AD628100421804 /* TEncSearch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncSearch.h; path = source/Lib/TLibEncoder/TEncSearch.h; sourceTree = "<group>"; };
+		6767962D11AD628100421804 /* TEncSlice.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncSlice.cpp; path = source/Lib/TLibEncoder/TEncSlice.cpp; sourceTree = "<group>"; };
+		6767962E11AD628100421804 /* TEncSlice.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncSlice.h; path = source/Lib/TLibEncoder/TEncSlice.h; sourceTree = "<group>"; };
+		6767962F11AD628100421804 /* TEncTop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncTop.cpp; path = source/Lib/TLibEncoder/TEncTop.cpp; sourceTree = "<group>"; };
+		6767963011AD628100421804 /* TEncTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncTop.h; path = source/Lib/TLibEncoder/TEncTop.h; sourceTree = "<group>"; };
+		6767964B11AD629200421804 /* libTLibVideoIO.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibVideoIO.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767965011AD62AC00421804 /* TVideoIOBits.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TVideoIOBits.cpp; path = source/Lib/TLibVideoIO/TVideoIOBits.cpp; sourceTree = "<group>"; };
+		6767965111AD62AC00421804 /* TVideoIOBits.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TVideoIOBits.h; path = source/Lib/TLibVideoIO/TVideoIOBits.h; sourceTree = "<group>"; };
+		6767965211AD62AC00421804 /* TVideoIOYuv.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TVideoIOYuv.cpp; path = source/Lib/TLibVideoIO/TVideoIOYuv.cpp; sourceTree = "<group>"; };
+		6767965311AD62AC00421804 /* TVideoIOYuv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TVideoIOYuv.h; path = source/Lib/TLibVideoIO/TVideoIOYuv.h; sourceTree = "<group>"; };
+		6767966A11AD635600421804 /* TAppEncoder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppEncoder; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767967011AD66FD00421804 /* encmain.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = encmain.cpp; path = source/App/TAppEncoder/encmain.cpp; sourceTree = "<group>"; };
+		6767967111AD66FD00421804 /* TAppEncCfg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppEncCfg.cpp; path = source/App/TAppEncoder/TAppEncCfg.cpp; sourceTree = "<group>"; };
+		6767967211AD66FD00421804 /* TAppEncCfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppEncCfg.h; path = source/App/TAppEncoder/TAppEncCfg.h; sourceTree = "<group>"; };
+		6767967511AD66FD00421804 /* TAppEncTop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppEncTop.cpp; path = source/App/TAppEncoder/TAppEncTop.cpp; sourceTree = "<group>"; };
+		6767967611AD66FD00421804 /* TAppEncTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppEncTop.h; path = source/App/TAppEncoder/TAppEncTop.h; sourceTree = "<group>"; };
+		6782E0DE11AD691A00E8FFB8 /* TAppDecoder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppDecoder; sourceTree = BUILT_PRODUCTS_DIR; };
+		6782E0E711AD694400E8FFB8 /* decmain.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = decmain.cpp; path = source/App/TAppDecoder/decmain.cpp; sourceTree = "<group>"; };
+		6782E0E811AD694400E8FFB8 /* TAppDecCfg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppDecCfg.cpp; path = source/App/TAppDecoder/TAppDecCfg.cpp; sourceTree = "<group>"; };
+		6782E0E911AD694400E8FFB8 /* TAppDecCfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppDecCfg.h; path = source/App/TAppDecoder/TAppDecCfg.h; sourceTree = "<group>"; };
+		6782E0EC11AD694400E8FFB8 /* TAppDecTop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppDecTop.cpp; path = source/App/TAppDecoder/TAppDecTop.cpp; sourceTree = "<group>"; };
+		6782E0ED11AD694400E8FFB8 /* TAppDecTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppDecTop.h; path = source/App/TAppDecoder/TAppDecTop.h; sourceTree = "<group>"; };
+		7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTAppCommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		7104E1DD12005B0E00F42AA8 /* program_options_lite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = program_options_lite.cpp; path = source/App/TAppCommon/program_options_lite.cpp; sourceTree = "<group>"; };
+		7104E1DE12005B0E00F42AA8 /* program_options_lite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = program_options_lite.h; path = source/App/TAppCommon/program_options_lite.h; sourceTree = "<group>"; };
+/* 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 = (
+				71AD603911EBC28500F5F1FE /* libTLibCommon.a in Frameworks */,
+				71AD603A11EBC28D00F5F1FE /* libTLibEncoder.a in Frameworks */,
+				71AD603B11EBC29600F5F1FE /* libTLibVideoIO.a in Frameworks */,
+				7104E1E312005B5600F42AA8 /* libTAppCommon.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DC11AD691A00E8FFB8 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6782E0E211AD692000E8FFB8 /* libTLibDecoder.a in Frameworks */,
+				6782E0E311AD692300E8FFB8 /* libTLibCommon.a in Frameworks */,
+				6782E0E411AD692700E8FFB8 /* libTLibVideoIO.a in Frameworks */,
+				710DD68B1335295200BE8EDE /* libTAppCommon.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7104E1CB12005ABA00F42AA8 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		08FB7794FE84155DC02AAC07 /* Trinity */ = {
+			isa = PBXGroup;
+			children = (
+				08FB7795FE84155DC02AAC07 /* Source */,
+				C6859E8C029090F304C91782 /* Documentation */,
+				1AB674ADFE9D54B511CA2CBB /* Products */,
+			);
+			name = Trinity;
+			sourceTree = "<group>";
+		};
+		08FB7795FE84155DC02AAC07 /* Source */ = {
+			isa = PBXGroup;
+			children = (
+				7104E1DC12005AE200F42AA8 /* TAppCommon */,
+				6782E0E511AD692F00E8FFB8 /* TAppDecoder */,
+				6767966F11AD66E600421804 /* TAppEncoder */,
+				6767959711AD61D700421804 /* TLibCommon */,
+				676795EF11AD620B00421804 /* TLibDecoder */,
+				6767961411AD624B00421804 /* TLibEncoder */,
+				6767964E11AD629700421804 /* TLibVideoIO */,
+			);
+			name = Source;
+			sourceTree = "<group>";
+		};
+		1AB674ADFE9D54B511CA2CBB /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				6767959411AD61BB00421804 /* libTLibCommon.a */,
+				676795F411AD621A00421804 /* libTLibDecoder.a */,
+				6767961911AD626F00421804 /* libTLibEncoder.a */,
+				6767964B11AD629200421804 /* libTLibVideoIO.a */,
+				6767966A11AD635600421804 /* TAppEncoder */,
+				6782E0DE11AD691A00E8FFB8 /* TAppDecoder */,
+				7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+		6767959711AD61D700421804 /* TLibCommon */ = {
+			isa = PBXGroup;
+			children = (
+				65EA1B85135744C400988950 /* libmd5.h */,
+				65EA1B86135744C400988950 /* libmd5.c */,
+				65EA1B87135744C400988950 /* MD5.h */,
+				6767959911AD61FC00421804 /* CommonDef.h */,
+				6767959A11AD61FC00421804 /* ContextTables.h */,
+				671E0D3811B6AD8C00F3747B /* ContextModel.cpp */,
+				671E0D3911B6AD8C00F3747B /* ContextModel.h */,
+				671E0D3A11B6AD8C00F3747B /* ContextModel3DBuffer.cpp */,
+				671E0D3B11B6AD8C00F3747B /* ContextModel3DBuffer.h */,
+				671E0D3E11B6AD8C00F3747B /* TComBitCounter.h */,
+				671E0D3F11B6AD8C00F3747B /* TComCABACTables.cpp */,
+				671E0D4011B6AD8C00F3747B /* TComCABACTables.h */,
+				671E0D4111B6AD8C00F3747B /* TComMv.h */,
+				676795A011AD61FC00421804 /* TComAdaptiveLoopFilter.cpp */,
+				676795A111AD61FC00421804 /* TComAdaptiveLoopFilter.h */,
+				676795A311AD61FC00421804 /* TComBitStream.cpp */,
+				65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */,
+				676795A411AD61FC00421804 /* TComBitStream.h */,
+				676795A511AD61FC00421804 /* TComDataCU.cpp */,
+				676795A611AD61FC00421804 /* TComDataCU.h */,
+				676795A711AD61FC00421804 /* TComList.h */,
+				676795A811AD61FC00421804 /* TComLoopFilter.cpp */,
+				676795A911AD61FC00421804 /* TComLoopFilter.h */,
+				676795AA11AD61FC00421804 /* TComMotionInfo.cpp */,
+				676795AB11AD61FC00421804 /* TComMotionInfo.h */,
+				676795AD11AD61FC00421804 /* TComPattern.cpp */,
+				676795AE11AD61FC00421804 /* TComPattern.h */,
+				676795AF11AD61FC00421804 /* TComPic.cpp */,
+				676795B011AD61FC00421804 /* TComPic.h */,
+				676795B111AD61FC00421804 /* TComPicSym.cpp */,
+				676795B211AD61FC00421804 /* TComPicSym.h */,
+				676795B311AD61FC00421804 /* TComPicYuv.cpp */,
+				676795B411AD61FC00421804 /* TComPicYuv.h */,
+				676795B511AD61FC00421804 /* TComPredFilter.cpp */,
+				676795B611AD61FC00421804 /* TComPredFilter.h */,
+				676795B711AD61FC00421804 /* TComPrediction.cpp */,
+				676795B811AD61FC00421804 /* TComPrediction.h */,
+				676795B911AD61FC00421804 /* TComRdCost.cpp */,
+				676795BA11AD61FC00421804 /* TComRdCost.h */,
+				676795BB11AD61FC00421804 /* TComRom.cpp */,
+				676795BC11AD61FC00421804 /* TComRom.h */,
+				676795BD11AD61FC00421804 /* TComSlice.cpp */,
+				676795BE11AD61FC00421804 /* TComSlice.h */,
+				65EA1B941357451300988950 /* SEI.h */,
+				65EA1B90135744FE00988950 /* SEIwrite.h */,
+				65EA1B91135744FE00988950 /* SEIwrite.cpp */,
+				676795BF11AD61FC00421804 /* TComTrQuant.cpp */,
+				676795C011AD61FC00421804 /* TComTrQuant.h */,
+				676795C111AD61FC00421804 /* TComYuv.cpp */,
+				676795C211AD61FC00421804 /* TComYuv.h */,
+				676795C311AD61FC00421804 /* TypeDef.h */,
+			);
+			name = TLibCommon;
+			sourceTree = "<group>";
+		};
+		676795EF11AD620B00421804 /* TLibDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				65EA1B8C135744EA00988950 /* SEIread.h */,
+				65EA1B8D135744EA00988950 /* SEIread.cpp */,
+				671E0D5611B6ADD300F3747B /* TDecBinCoder.h */,
+				671E0D5711B6ADD300F3747B /* TDecBinCoderCABAC.cpp */,
+				671E0D5811B6ADD300F3747B /* TDecBinCoderCABAC.h */,
+				676795F811AD623900421804 /* TDecCAVLC.cpp */,
+				676795F911AD623900421804 /* TDecCAVLC.h */,
+				676795FA11AD623900421804 /* TDecCu.cpp */,
+				676795FB11AD623900421804 /* TDecCu.h */,
+				676795FC11AD623900421804 /* TDecEntropy.cpp */,
+				676795FD11AD623900421804 /* TDecEntropy.h */,
+				676795FE11AD623900421804 /* TDecGop.cpp */,
+				676795FF11AD623900421804 /* TDecGop.h */,
+				6767960011AD623900421804 /* TDecSbac.cpp */,
+				6767960111AD623900421804 /* TDecSbac.h */,
+				6767960211AD623900421804 /* TDecSlice.cpp */,
+				6767960311AD623900421804 /* TDecSlice.h */,
+				6767960411AD623900421804 /* TDecTop.cpp */,
+				6767960511AD623900421804 /* TDecTop.h */,
+			);
+			name = TLibDecoder;
+			sourceTree = "<group>";
+		};
+		6767961411AD624B00421804 /* TLibEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				671E0D7211B6ADE900F3747B /* TEncBinCoder.h */,
+				671E0D7311B6ADE900F3747B /* TEncBinCoderCABAC.cpp */,
+				671E0D7411B6ADE900F3747B /* TEncBinCoderCABAC.h */,
+				6767961C11AD628100421804 /* TEncAdaptiveLoopFilter.cpp */,
+				6767961D11AD628100421804 /* TEncAdaptiveLoopFilter.h */,
+				6767961E11AD628100421804 /* TEncAnalyze.cpp */,
+				6767961F11AD628100421804 /* TEncAnalyze.h */,
+				6767962011AD628100421804 /* TEncCavlc.cpp */,
+				6767962111AD628100421804 /* TEncCavlc.h */,
+				6767962211AD628100421804 /* TEncCfg.h */,
+				6767962311AD628100421804 /* TEncCu.cpp */,
+				6767962411AD628100421804 /* TEncCu.h */,
+				6767962511AD628100421804 /* TEncEntropy.cpp */,
+				6767962611AD628100421804 /* TEncEntropy.h */,
+				6767962711AD628100421804 /* TEncGOP.cpp */,
+				6767962811AD628100421804 /* TEncGOP.h */,
+				6767962911AD628100421804 /* TEncSbac.cpp */,
+				6767962A11AD628100421804 /* TEncSbac.h */,
+				6767962B11AD628100421804 /* TEncSearch.cpp */,
+				6767962C11AD628100421804 /* TEncSearch.h */,
+				6767962D11AD628100421804 /* TEncSlice.cpp */,
+				6767962E11AD628100421804 /* TEncSlice.h */,
+				6767962F11AD628100421804 /* TEncTop.cpp */,
+				6767963011AD628100421804 /* TEncTop.h */,
+			);
+			name = TLibEncoder;
+			sourceTree = "<group>";
+		};
+		6767964E11AD629700421804 /* TLibVideoIO */ = {
+			isa = PBXGroup;
+			children = (
+				6767965011AD62AC00421804 /* TVideoIOBits.cpp */,
+				6767965111AD62AC00421804 /* TVideoIOBits.h */,
+				6767965211AD62AC00421804 /* TVideoIOYuv.cpp */,
+				6767965311AD62AC00421804 /* TVideoIOYuv.h */,
+			);
+			name = TLibVideoIO;
+			sourceTree = "<group>";
+		};
+		6767966F11AD66E600421804 /* TAppEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				6767967011AD66FD00421804 /* encmain.cpp */,
+				6767967111AD66FD00421804 /* TAppEncCfg.cpp */,
+				6767967211AD66FD00421804 /* TAppEncCfg.h */,
+				6767967511AD66FD00421804 /* TAppEncTop.cpp */,
+				6767967611AD66FD00421804 /* TAppEncTop.h */,
+			);
+			name = TAppEncoder;
+			sourceTree = "<group>";
+		};
+		6782E0E511AD692F00E8FFB8 /* TAppDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				6782E0ED11AD694400E8FFB8 /* TAppDecTop.h */,
+				6782E0E911AD694400E8FFB8 /* TAppDecCfg.h */,
+				6782E0EC11AD694400E8FFB8 /* TAppDecTop.cpp */,
+				6782E0E811AD694400E8FFB8 /* TAppDecCfg.cpp */,
+				6782E0E711AD694400E8FFB8 /* decmain.cpp */,
+			);
+			name = TAppDecoder;
+			sourceTree = "<group>";
+		};
+		7104E1DC12005AE200F42AA8 /* TAppCommon */ = {
+			isa = PBXGroup;
+			children = (
+				7104E1DD12005B0E00F42AA8 /* program_options_lite.cpp */,
+				7104E1DE12005B0E00F42AA8 /* program_options_lite.h */,
+			);
+			name = TAppCommon;
+			sourceTree = "<group>";
+		};
+		C6859E8C029090F304C91782 /* Documentation */ = {
+			isa = PBXGroup;
+			children = (
+			);
+			name = Documentation;
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXHeadersBuildPhase section */
+		6767959011AD61BB00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				676795C411AD61FC00421804 /* CommonDef.h in Headers */,
+				676795C511AD61FC00421804 /* ContextTables.h in Headers */,
+				676795CC11AD61FC00421804 /* TComAdaptiveLoopFilter.h in Headers */,
+				676795CF11AD61FC00421804 /* TComBitStream.h in Headers */,
+				676795D111AD61FC00421804 /* TComDataCU.h in Headers */,
+				676795D211AD61FC00421804 /* TComList.h in Headers */,
+				676795D411AD61FC00421804 /* TComLoopFilter.h in Headers */,
+				676795D611AD61FC00421804 /* TComMotionInfo.h in Headers */,
+				676795D911AD61FC00421804 /* TComPattern.h in Headers */,
+				676795DB11AD61FC00421804 /* TComPic.h in Headers */,
+				676795DD11AD61FC00421804 /* TComPicSym.h in Headers */,
+				676795DF11AD61FC00421804 /* TComPicYuv.h in Headers */,
+				676795E111AD61FC00421804 /* TComPredFilter.h in Headers */,
+				676795E311AD61FC00421804 /* TComPrediction.h in Headers */,
+				676795E511AD61FC00421804 /* TComRdCost.h in Headers */,
+				676795E711AD61FC00421804 /* TComRom.h in Headers */,
+				676795E911AD61FC00421804 /* TComSlice.h in Headers */,
+				676795EB11AD61FC00421804 /* TComTrQuant.h in Headers */,
+				676795ED11AD61FC00421804 /* TComYuv.h in Headers */,
+				676795EE11AD61FC00421804 /* TypeDef.h in Headers */,
+				671E0D4A11B6AD8C00F3747B /* ContextModel.h in Headers */,
+				671E0D4C11B6AD8C00F3747B /* ContextModel3DBuffer.h in Headers */,
+				671E0D4F11B6AD8C00F3747B /* TComBitCounter.h in Headers */,
+				671E0D5111B6AD8C00F3747B /* TComCABACTables.h in Headers */,
+				671E0D5211B6AD8C00F3747B /* TComMv.h in Headers */,
+				65EA1B88135744C400988950 /* libmd5.h in Headers */,
+				65EA1B8A135744C400988950 /* MD5.h in Headers */,
+				65EA1B951357451300988950 /* SEI.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F011AD621A00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767960711AD623900421804 /* TDecCAVLC.h in Headers */,
+				6767960911AD623900421804 /* TDecCu.h in Headers */,
+				6767960B11AD623900421804 /* TDecEntropy.h in Headers */,
+				6767960D11AD623900421804 /* TDecGop.h in Headers */,
+				6767960F11AD623900421804 /* TDecSbac.h in Headers */,
+				6767961111AD623900421804 /* TDecSlice.h in Headers */,
+				6767961311AD623900421804 /* TDecTop.h in Headers */,
+				671E0D6411B6ADD300F3747B /* TDecBinCoder.h in Headers */,
+				671E0D6611B6ADD300F3747B /* TDecBinCoderCABAC.h in Headers */,
+				65EA1B8E135744EA00988950 /* SEIread.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961511AD626F00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767963211AD628100421804 /* TEncAdaptiveLoopFilter.h in Headers */,
+				6767963411AD628100421804 /* TEncAnalyze.h in Headers */,
+				6767963611AD628100421804 /* TEncCavlc.h in Headers */,
+				6767963711AD628100421804 /* TEncCfg.h in Headers */,
+				6767963911AD628100421804 /* TEncCu.h in Headers */,
+				6767963B11AD628100421804 /* TEncEntropy.h in Headers */,
+				6767963D11AD628100421804 /* TEncGOP.h in Headers */,
+				6767963F11AD628100421804 /* TEncSbac.h in Headers */,
+				6767964111AD628100421804 /* TEncSearch.h in Headers */,
+				6767964311AD628100421804 /* TEncSlice.h in Headers */,
+				6767964511AD628100421804 /* TEncTop.h in Headers */,
+				671E0D8011B6ADE900F3747B /* TEncBinCoder.h in Headers */,
+				671E0D8211B6ADE900F3747B /* TEncBinCoderCABAC.h in Headers */,
+				65EA1B92135744FE00988950 /* SEIwrite.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964711AD629200421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767965511AD62AC00421804 /* TVideoIOBits.h in Headers */,
+				6767965711AD62AC00421804 /* TVideoIOYuv.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7104E1C912005ABA00F42AA8 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				7104E1E012005B0E00F42AA8 /* program_options_lite.h in Headers */,
+			);
+			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 = (
+				6745C43211AD7747007D801A /* PBXTargetDependency */,
+				6745C43411AD774C007D801A /* PBXTargetDependency */,
+				6745C43611AD774F007D801A /* PBXTargetDependency */,
+				7104E1E212005B4B00F42AA8 /* 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 = (
+				6745C42811AD7709007D801A /* PBXTargetDependency */,
+				6745C42A11AD770E007D801A /* PBXTargetDependency */,
+				6745C42C11AD7711007D801A /* PBXTargetDependency */,
+				710DD69B133529A100BE8EDE /* PBXTargetDependency */,
+			);
+			name = TAppDecoder;
+			productName = TAppDecoder;
+			productReference = 6782E0DE11AD691A00E8FFB8 /* TAppDecoder */;
+			productType = "com.apple.product-type.tool";
+		};
+		7104E1CC12005ABA00F42AA8 /* TAppCommon */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7104E1D112005ACA00F42AA8 /* Build configuration list for PBXNativeTarget "TAppCommon" */;
+			buildPhases = (
+				7104E1C912005ABA00F42AA8 /* Headers */,
+				7104E1CA12005ABA00F42AA8 /* Sources */,
+				7104E1CB12005ABA00F42AA8 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TAppCommon;
+			productName = TAppCommon;
+			productReference = 7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		08FB7793FE84155DC02AAC07 /* Project object */ = {
+			isa = PBXProject;
+			attributes = {
+				BuildIndependentTargetsInParallel = YES;
+			};
+			buildConfigurationList = 1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "HM" */;
+			compatibilityVersion = "Xcode 3.1";
+			developmentRegion = English;
+			hasScannedForEncodings = 1;
+			knownRegions = (
+				English,
+				Japanese,
+				French,
+				German,
+			);
+			mainGroup = 08FB7794FE84155DC02AAC07 /* Trinity */;
+			projectDirPath = "";
+			projectRoot = "";
+			targets = (
+				6767959311AD61BB00421804 /* TLibCommon */,
+				676795F311AD621A00421804 /* TLibDecoder */,
+				6767961811AD626F00421804 /* TLibEncoder */,
+				6767964A11AD629200421804 /* TLibVideoIO */,
+				6767966911AD635600421804 /* TAppEncoder */,
+				6782E0DD11AD691A00E8FFB8 /* TAppDecoder */,
+				7104E1CC12005ABA00F42AA8 /* TAppCommon */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXSourcesBuildPhase section */
+		6767959111AD61BB00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				676795CB11AD61FC00421804 /* TComAdaptiveLoopFilter.cpp in Sources */,
+				676795CE11AD61FC00421804 /* TComBitStream.cpp in Sources */,
+				676795D011AD61FC00421804 /* TComDataCU.cpp in Sources */,
+				676795D311AD61FC00421804 /* TComLoopFilter.cpp in Sources */,
+				676795D511AD61FC00421804 /* TComMotionInfo.cpp in Sources */,
+				676795D811AD61FC00421804 /* TComPattern.cpp in Sources */,
+				676795DA11AD61FC00421804 /* TComPic.cpp in Sources */,
+				676795DC11AD61FC00421804 /* TComPicSym.cpp in Sources */,
+				676795DE11AD61FC00421804 /* TComPicYuv.cpp in Sources */,
+				676795E011AD61FC00421804 /* TComPredFilter.cpp in Sources */,
+				676795E211AD61FC00421804 /* TComPrediction.cpp in Sources */,
+				676795E411AD61FC00421804 /* TComRdCost.cpp in Sources */,
+				676795E611AD61FC00421804 /* TComRom.cpp in Sources */,
+				676795E811AD61FC00421804 /* TComSlice.cpp in Sources */,
+				676795EA11AD61FC00421804 /* TComTrQuant.cpp in Sources */,
+				676795EC11AD61FC00421804 /* TComYuv.cpp in Sources */,
+				671E0D4911B6AD8C00F3747B /* ContextModel.cpp in Sources */,
+				671E0D4B11B6AD8C00F3747B /* ContextModel3DBuffer.cpp in Sources */,
+				671E0D5011B6AD8C00F3747B /* TComCABACTables.cpp in Sources */,
+				65EA1B89135744C400988950 /* libmd5.c in Sources */,
+				65EA1B97135745D500988950 /* TComPicYuvMD5.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F111AD621A00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767960611AD623900421804 /* TDecCAVLC.cpp in Sources */,
+				6767960811AD623900421804 /* TDecCu.cpp in Sources */,
+				6767960A11AD623900421804 /* TDecEntropy.cpp in Sources */,
+				6767960C11AD623900421804 /* TDecGop.cpp in Sources */,
+				6767960E11AD623900421804 /* TDecSbac.cpp in Sources */,
+				6767961011AD623900421804 /* TDecSlice.cpp in Sources */,
+				6767961211AD623900421804 /* TDecTop.cpp in Sources */,
+				671E0D6511B6ADD300F3747B /* TDecBinCoderCABAC.cpp in Sources */,
+				65EA1B8F135744EA00988950 /* SEIread.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961611AD626F00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767963111AD628100421804 /* TEncAdaptiveLoopFilter.cpp in Sources */,
+				6767963311AD628100421804 /* TEncAnalyze.cpp in Sources */,
+				6767963511AD628100421804 /* TEncCavlc.cpp in Sources */,
+				6767963811AD628100421804 /* TEncCu.cpp in Sources */,
+				6767963A11AD628100421804 /* TEncEntropy.cpp in Sources */,
+				6767963C11AD628100421804 /* TEncGOP.cpp in Sources */,
+				6767963E11AD628100421804 /* TEncSbac.cpp in Sources */,
+				6767964011AD628100421804 /* TEncSearch.cpp in Sources */,
+				6767964211AD628100421804 /* TEncSlice.cpp in Sources */,
+				6767964411AD628100421804 /* TEncTop.cpp in Sources */,
+				671E0D8111B6ADE900F3747B /* TEncBinCoderCABAC.cpp in Sources */,
+				65EA1B93135744FE00988950 /* SEIwrite.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964811AD629200421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767965411AD62AC00421804 /* TVideoIOBits.cpp in Sources */,
+				6767965611AD62AC00421804 /* TVideoIOYuv.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767966711AD635600421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767967711AD66FD00421804 /* encmain.cpp in Sources */,
+				6767967811AD66FD00421804 /* TAppEncCfg.cpp in Sources */,
+				6767967A11AD66FD00421804 /* TAppEncTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DB11AD691A00E8FFB8 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6782E0EE11AD694400E8FFB8 /* decmain.cpp in Sources */,
+				6782E0EF11AD694400E8FFB8 /* TAppDecCfg.cpp in Sources */,
+				6782E0F111AD694400E8FFB8 /* TAppDecTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7104E1CA12005ABA00F42AA8 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				7104E1DF12005B0E00F42AA8 /* program_options_lite.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXTargetDependency section */
+		6745C42811AD7709007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 676795F311AD621A00421804 /* TLibDecoder */;
+			targetProxy = 6745C42711AD7709007D801A /* PBXContainerItemProxy */;
+		};
+		6745C42A11AD770E007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 6745C42911AD770E007D801A /* PBXContainerItemProxy */;
+		};
+		6745C42C11AD7711007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 6745C42B11AD7711007D801A /* PBXContainerItemProxy */;
+		};
+		6745C43211AD7747007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767961811AD626F00421804 /* TLibEncoder */;
+			targetProxy = 6745C43111AD7747007D801A /* PBXContainerItemProxy */;
+		};
+		6745C43411AD774C007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 6745C43311AD774C007D801A /* PBXContainerItemProxy */;
+		};
+		6745C43611AD774F007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 6745C43511AD774F007D801A /* PBXContainerItemProxy */;
+		};
+		7104E1E212005B4B00F42AA8 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7104E1CC12005ABA00F42AA8 /* TAppCommon */;
+			targetProxy = 7104E1E112005B4B00F42AA8 /* PBXContainerItemProxy */;
+		};
+		710DD69B133529A100BE8EDE /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7104E1CC12005ABA00F42AA8 /* TAppCommon */;
+			targetProxy = 710DD69A133529A100BE8EDE /* PBXContainerItemProxy */;
+		};
+/* End PBXTargetDependency section */
+
+/* Begin XCBuildConfiguration section */
+		1DEB923608733DC60010E9CD /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				ONLY_ACTIVE_ARCH = YES;
+				PREBINDING = NO;
+				SDKROOT = macosx10.6;
+			};
+			name = Debug;
+		};
+		1DEB923708733DC60010E9CD /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(NATIVE_ARCH_ACTUAL)";
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_OPTIMIZATION_LEVEL = 3;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES;
+				GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				PREBINDING = NO;
+				SDKROOT = macosx10.6;
+			};
+			name = Release;
+		};
+		6767959511AD61BC00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TLibCommon;
+			};
+			name = Debug;
+		};
+		6767959611AD61BC00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TLibCommon;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		676795F511AD621A00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TLibDecoder;
+			};
+			name = Debug;
+		};
+		676795F611AD621A00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TLibDecoder;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		6767961A11AD626F00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TLibEncoder;
+			};
+			name = Debug;
+		};
+		6767961B11AD626F00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TLibEncoder;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		6767964C11AD629200421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TLibVideoIO;
+			};
+			name = Debug;
+		};
+		6767964D11AD629200421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TLibVideoIO;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		6767966C11AD635600421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				INSTALL_PATH = /usr/local/bin;
+				LIBRARY_SEARCH_PATHS = (
+					"$(inherited)",
+					"\"$(SRCROOT)/build/Debug\"",
+				);
+				PREBINDING = NO;
+				PRODUCT_NAME = TAppEncoder;
+			};
+			name = Debug;
+		};
+		6767966D11AD635600421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				INSTALL_PATH = /usr/local/bin;
+				LIBRARY_SEARCH_PATHS = (
+					"$(inherited)",
+					"\"$(SRCROOT)/build/Debug\"",
+				);
+				PREBINDING = NO;
+				PRODUCT_NAME = TAppEncoder;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		6782E0E011AD691B00E8FFB8 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				INSTALL_PATH = /usr/local/bin;
+				PREBINDING = NO;
+				PRODUCT_NAME = TAppDecoder;
+			};
+			name = Debug;
+		};
+		6782E0E111AD691B00E8FFB8 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				INSTALL_PATH = /usr/local/bin;
+				PREBINDING = NO;
+				PRODUCT_NAME = TAppDecoder;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		7104E1CE12005ABB00F42AA8 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TAppCommon;
+			};
+			name = Debug;
+		};
+		7104E1CF12005ABB00F42AA8 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PREBINDING = NO;
+				PRODUCT_NAME = TAppCommon;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "HM" */ = {
+			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;
+		};
+		7104E1D112005ACA00F42AA8 /* Build configuration list for PBXNativeTarget "TAppCommon" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7104E1CE12005ABB00F42AA8 /* Debug */,
+				7104E1CF12005ABB00F42AA8 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+/* End XCConfigurationList section */
+	};
+	rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
+}
Index: /tags/0.2r1/README-changes.txt
===================================================================
--- /tags/0.2r1/README-changes.txt	(revision 19)
+++ /tags/0.2r1/README-changes.txt	(revision 19)
@@ -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: /tags/0.2r1/README-newconfig.txt
===================================================================
--- /tags/0.2r1/README-newconfig.txt	(revision 19)
+++ /tags/0.2r1/README-newconfig.txt	(revision 19)
@@ -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: /tags/0.2r1/README-usage.txt
===================================================================
--- /tags/0.2r1/README-usage.txt	(revision 19)
+++ /tags/0.2r1/README-usage.txt	(revision 19)
@@ -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: /tags/0.2r1/build/HM_vc10.sln
===================================================================
--- /tags/0.2r1/build/HM_vc10.sln	(revision 19)
+++ /tags/0.2r1/build/HM_vc10.sln	(revision 19)
@@ -0,0 +1,112 @@
+﻿
+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}"
+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}"
+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
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /tags/0.2r1/build/HM_vc8.sln
===================================================================
--- /tags/0.2r1/build/HM_vc8.sln	(revision 19)
+++ /tags/0.2r1/build/HM_vc8.sln	(revision 19)
@@ -0,0 +1,125 @@
+﻿
+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
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc8\TAppEncoder_vc8.vcproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A} = {5E87AD84-AC4F-4336-B4EE-549CA210EE4A}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1} = {47E90995-1FC5-4EE4-A94D-AD474169F0E1}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+	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}") = "TAppRenderer", "vc8\TAppRenderer_vc8.vcproj", "{CE149235-A923-4BA7-B552-3A02287CD3E4}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A} = {5E87AD84-AC4F-4336-B4EE-549CA210EE4A}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{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}") = "TLibRenderer", "vc8\TLibRenderer_vc8.vcproj", "{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}"
+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
+		{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
+		{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
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /tags/0.2r1/build/HM_vc9.sln
===================================================================
--- /tags/0.2r1/build/HM_vc9.sln	(revision 19)
+++ /tags/0.2r1/build/HM_vc9.sln	(revision 19)
@@ -0,0 +1,125 @@
+﻿
+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}") = "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}") = "TLibRenderer", "vc9\TLibRenderer_vc9.vcproj", "{457993C6-AE2C-4B9B-B5F9-71033279A0B9}"
+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
+		{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
+		{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
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /tags/0.2r1/build/linux/common/makefile.base
===================================================================
--- /tags/0.2r1/build/linux/common/makefile.base	(revision 19)
+++ /tags/0.2r1/build/linux/common/makefile.base	(revision 19)
@@ -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: /tags/0.2r1/build/linux/lib/TAppCommon/makefile
===================================================================
--- /tags/0.2r1/build/linux/lib/TAppCommon/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/lib/TAppCommon/makefile	(revision 19)
@@ -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/App/TAppCommon
+INC_DIR			= ../../../../source/App/TAppCommon
+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: /tags/0.2r1/build/linux/lib/TLibCommon/makefile
===================================================================
--- /tags/0.2r1/build/linux/lib/TLibCommon/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/lib/TLibCommon/makefile	(revision 19)
@@ -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/TLibCommon
+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)/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)/TComPredFilter.o \
+			$(OBJ_DIR)/TComPrediction.o \
+			$(OBJ_DIR)/TComRdCost.o \
+			$(OBJ_DIR)/TComRdCostWeightPrediction.o \
+			$(OBJ_DIR)/TComResidualGenerator.o \
+			$(OBJ_DIR)/TComRom.o \
+			$(OBJ_DIR)/TComSlice.o \
+			$(OBJ_DIR)/TComTrQuant.o \
+			$(OBJ_DIR)/TComYuv.o \
+			$(OBJ_DIR)/TComMVDRefData.o \
+			$(OBJ_DIR)/TComWedgelet.o \
+			$(OBJ_DIR)/TComWeightPrediction.o \
+			$(OBJ_DIR)/libmd5.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: /tags/0.2r1/build/linux/lib/TLibDecoder/makefile
===================================================================
--- /tags/0.2r1/build/linux/lib/TLibDecoder/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/lib/TLibDecoder/makefile	(revision 19)
@@ -0,0 +1,63 @@
+# 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/TLibDecoder
+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)/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: /tags/0.2r1/build/linux/lib/TLibEncoder/makefile
===================================================================
--- /tags/0.2r1/build/linux/lib/TLibEncoder/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/lib/TLibEncoder/makefile	(revision 19)
@@ -0,0 +1,68 @@
+# 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/TLibEncoder
+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)/SEIwrite.o \
+			$(OBJ_DIR)/TEncBinCoderCABAC.o \
+			$(OBJ_DIR)/TEncAdaptiveLoopFilter.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)/TEncFormattedStringParser.o \
+			$(OBJ_DIR)/TEncSeqStructure.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: /tags/0.2r1/build/linux/lib/TLibRenderer/makefile
===================================================================
--- /tags/0.2r1/build/linux/lib/TLibRenderer/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/lib/TLibRenderer/makefile	(revision 19)
@@ -0,0 +1,61 @@
+# 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/TLibRenderer
+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)/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: /tags/0.2r1/build/linux/lib/TLibVideoIO/makefile
===================================================================
--- /tags/0.2r1/build/linux/lib/TLibVideoIO/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/lib/TLibVideoIO/makefile	(revision 19)
@@ -0,0 +1,57 @@
+# 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/TLibVideoIO
+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)/TVideoIOBits.o \
+			$(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: /tags/0.2r1/build/linux/makefile
===================================================================
--- /tags/0.2r1/build/linux/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/makefile	(revision 19)
@@ -0,0 +1,50 @@
+### 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/TLibRenderer  MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon   MM32=$(M32)
+	$(MAKE) -C test/TAppDecoder MM32=$(M32)
+	$(MAKE) -C test/TAppEncoder MM32=$(M32)
+	$(MAKE) -C test/TAppRenderer MM32=$(M32)
+
+debug:
+	$(MAKE) -C lib/TLibVideoIO 	debug	MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	debug	MM32=$(M32)
+	$(MAKE) -C lib/TLibRenderer  debug	MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	debug	MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	debug	MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon   debug MM32=$(M32)
+	$(MAKE) -C test/TAppDecoder debug MM32=$(M32)
+	$(MAKE) -C test/TAppEncoder debug MM32=$(M32)
+	$(MAKE) -C test/TAppRenderer debug MM32=$(M32)
+
+release:
+	$(MAKE) -C lib/TLibVideoIO 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibRenderer  release MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	release MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon   release MM32=$(M32)
+	$(MAKE) -C test/TAppDecoder release MM32=$(M32)
+	$(MAKE) -C test/TAppEncoder release MM32=$(M32)
+	$(MAKE) -C test/TAppRenderer release MM32=$(M32)
+
+clean:
+	$(MAKE) -C lib/TLibVideoIO 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibRenderer  clean MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	clean MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon   clean MM32=$(M32)
+	$(MAKE) -C test/TAppDecoder clean MM32=$(M32)
+	$(MAKE) -C test/TAppEncoder clean MM32=$(M32)
+	$(MAKE) -C test/TAppRenderer clean MM32=$(M32)
+	
+	
Index: /tags/0.2r1/build/linux/test/TAppDecoder/makefile
===================================================================
--- /tags/0.2r1/build/linux/test/TAppDecoder/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/test/TAppDecoder/makefile	(revision 19)
@@ -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/App/TAppDecoder
+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: /tags/0.2r1/build/linux/test/TAppEncoder/makefile
===================================================================
--- /tags/0.2r1/build/linux/test/TAppEncoder/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/test/TAppEncoder/makefile	(revision 19)
@@ -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/App/TAppEncoder
+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
+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
+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: /tags/0.2r1/build/linux/test/TAppRenderer/makefile
===================================================================
--- /tags/0.2r1/build/linux/test/TAppRenderer/makefile	(revision 19)
+++ /tags/0.2r1/build/linux/test/TAppRenderer/makefile	(revision 19)
@@ -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/TAppRenderer
+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: /tags/0.2r1/build/vc10/TAppCommon_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TAppCommon_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TAppCommon_vc10.vcxproj	(revision 19)
@@ -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>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.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\App\TAppCommon\program_options_lite.cpp" />
+    <ClCompile Include="..\..\source\App\TAppCommon\TAppComCamPara.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppCommon\program_options_lite.h" />
+    <ClInclude Include="..\..\source\App\TAppCommon\TAppComCamPara.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TAppCommon_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,29 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{0654581b-4bd8-44de-8421-dc72d7209a8d}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{3fa4f95c-7286-415d-a2ce-7cd955ce8584}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppCommon\program_options_lite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppCommon\TAppComCamPara.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppCommon\program_options_lite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppCommon\TAppComCamPara.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TAppDecoder_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TAppDecoder_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TAppDecoder_vc10.vcxproj	(revision 19)
@@ -0,0 +1,196 @@
+﻿<?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.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\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>
+    </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: /tags/0.2r1/build/vc10/TAppDecoder_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,36 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{209c0d98-2ab1-44cb-a040-7772958a225f}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{8b0a93f1-2c16-4dda-a5c6-d6424140d870}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{8d3c7d97-3261-472a-bc5e-867178d72e22}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TAppEncoder_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TAppEncoder_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TAppEncoder_vc10.vcxproj	(revision 19)
@@ -0,0 +1,205 @@
+﻿<?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.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\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: /tags/0.2r1/build/vc10/TAppEncoder_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,36 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{00a09df2-4a54-42a0-9916-31d60c1d942b}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{e53f783d-c752-429c-98bf-52fd9d4db16a}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{cf3310d2-18cb-493e-842c-2b7a901eb0c0}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppEncoder\encmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TAppRenderer_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TAppRenderer_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TAppRenderer_vc10.vcxproj	(revision 19)
@@ -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>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>..\..\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\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: /tags/0.2r1/build/vc10/TAppRenderer_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TAppRenderer_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TAppRenderer_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,36 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{00a09df2-4a54-42a0-9916-31d60c1d942b}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{e53f783d-c752-429c-98bf-52fd9d4db16a}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{cf3310d2-18cb-493e-842c-2b7a901eb0c0}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppRenderer\RendererMain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppRenderer\TAppRendererCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppRenderer\TAppRendererTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppRenderer\TAppRendererCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppRenderer\TAppRendererTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TLibCommon_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TLibCommon_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibCommon_vc10.vcxproj	(revision 19)
@@ -0,0 +1,211 @@
+﻿<?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.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\libmd5\libmd5.c" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp" />
+    <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\TComLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMVDRefData.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\TComPredFilter.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\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\libmd5\libmd5.h" />
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.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\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\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\TComMVDRefData.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\TComPredFilter.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\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: /tags/0.2r1/build/vc10/TLibCommon_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,200 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMVDRefData.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPredFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWedgelet.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDepthMapGenerator.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComResidualGenerator.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComAdaptiveLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMVDRefData.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPredFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWedgelet.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDepthMapGenerator.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComResidualGenerator.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TLibDecoder_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TLibDecoder_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibDecoder_vc10.vcxproj	(revision 19)
@@ -0,0 +1,169 @@
+﻿<?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.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\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\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: /tags/0.2r1/build/vc10/TLibDecoder_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,74 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{33b27328-70b6-4ea4-a16b-455a567ce767}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{4411ec50-74e7-431c-b042-85ac4adb328a}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TLibEncoder_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TLibEncoder_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibEncoder_vc10.vcxproj	(revision 19)
@@ -0,0 +1,181 @@
+﻿<?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.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\TLibEncoder\SEIwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.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\TEncFormattedStringParser.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSeqStructure.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\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\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\TEncFormattedStringParser.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSeqStructure.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: /tags/0.2r1/build/vc10/TLibEncoder_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,110 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{d8edff82-68af-41c6-8947-937138748049}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{6c6190a1-22d8-487d-bdf2-47293c388c4d}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncFormattedStringParser.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSeqStructure.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncFormattedStringParser.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSeqStructure.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TLibRenderer_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TLibRenderer_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibRenderer_vc10.vcxproj	(revision 19)
@@ -0,0 +1,164 @@
+﻿<?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>..\..\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\TLibRenderer\TRenFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenImagePlane.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenImage.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\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: /tags/0.2r1/build/vc10/TLibRenderer_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TLibRenderer_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibRenderer_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,59 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{d8edff82-68af-41c6-8947-937138748049}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{6c6190a1-22d8-487d-bdf2-47293c388c4d}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenImagePlane.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenImage.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenModel.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenSingleModel.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenImagePlane.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenImage.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenModel.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenSingleModel.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TLibVideoIO_vc10.vcxproj
===================================================================
--- /tags/0.2r1/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 19)
@@ -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.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\TLibVideoIO\TVideoIOBits.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOBits.h" />
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /tags/0.2r1/build/vc10/TLibVideoIO_vc10.vcxproj.filters
===================================================================
--- /tags/0.2r1/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 19)
+++ /tags/0.2r1/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 19)
@@ -0,0 +1,29 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{5be05142-782f-40d1-a033-8469cfcac47a}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{cbb9b77c-4791-4642-bb9f-871e208e3027}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOBits.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOBits.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/0.2r1/build/vc8/TAppCommon_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TAppCommon_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TAppCommon_vc8.vcproj	(revision 19)
@@ -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"
+				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="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="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|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\App\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppCommon\TAppComCamPara.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppCommon\program_options_lite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppCommon\TAppComCamPara.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /tags/0.2r1/build/vc8/TAppDecoder_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TAppDecoder_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TAppDecoder_vc8.vcproj	(revision 19)
@@ -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"
+				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\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: /tags/0.2r1/build/vc8/TAppEncoder_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TAppEncoder_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TAppEncoder_vc8.vcproj	(revision 19)
@@ -0,0 +1,355 @@
+<?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"
+				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="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="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="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="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: /tags/0.2r1/build/vc8/TAppRenderer_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TAppRenderer_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TAppRenderer_vc8.vcproj	(revision 19)
@@ -0,0 +1,363 @@
+<?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"
+				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"
+				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"
+				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"
+				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: /tags/0.2r1/build/vc8/TLibCommon_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TLibCommon_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TLibCommon_vc8.vcproj	(revision 19)
@@ -0,0 +1,536 @@
+<?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="&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)\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="&quot;..\..\compat\msvc&quot;"
+				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"
+				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)\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"
+			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\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMVDRefData.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\TComPredFilter.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\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\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\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\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\TComMVDRefData.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\TComPredFilter.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\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: /tags/0.2r1/build/vc8/TLibDecoder_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TLibDecoder_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TLibDecoder_vc8.vcproj	(revision 19)
@@ -0,0 +1,366 @@
+<?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"
+				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\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\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: /tags/0.2r1/build/vc8/TLibEncoder_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TLibEncoder_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TLibEncoder_vc8.vcproj	(revision 19)
@@ -0,0 +1,414 @@
+<?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"
+				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\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\TEncCavlc.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncFormattedStringParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSeqStructure.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\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\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\TEncFormattedStringParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSeqStructure.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: /tags/0.2r1/build/vc8/TLibRenderer_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TLibRenderer_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TLibRenderer_vc8.vcproj	(revision 19)
@@ -0,0 +1,342 @@
+<?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"
+				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"
+				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"
+				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"
+				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\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\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: /tags/0.2r1/build/vc8/TLibVideoIO_vc8.vcproj
===================================================================
--- /tags/0.2r1/build/vc8/TLibVideoIO_vc8.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc8/TLibVideoIO_vc8.vcproj	(revision 19)
@@ -0,0 +1,307 @@
+<?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"
+	TargetFrameworkVersion="196613"
+	>
+	<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="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="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|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\TLibVideoIO\TVideoIOBits.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOBits.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /tags/0.2r1/build/vc9/TAppCommon_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TAppCommon_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TAppCommon_vc9.vcproj	(revision 19)
@@ -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"
+				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="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"
+				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>
+		<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\App\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppCommon\TAppComCamPara.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppCommon\program_options_lite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppCommon\TAppComCamPara.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /tags/0.2r1/build/vc9/TAppDecoder_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TAppDecoder_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TAppDecoder_vc9.vcproj	(revision 19)
@@ -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="&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="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="&quot;..\..\compat\msvc&quot;"
+				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="&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="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="&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="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: /tags/0.2r1/build/vc9/TAppEncoder_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TAppEncoder_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TAppEncoder_vc9.vcproj	(revision 19)
@@ -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="&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="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="&quot;..\..\compat\msvc&quot;"
+				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="&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="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="&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="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: /tags/0.2r1/build/vc9/TAppRenderer_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TAppRenderer_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TAppRenderer_vc9.vcproj	(revision 19)
@@ -0,0 +1,354 @@
+<?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"
+				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"
+				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"
+				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"
+				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: /tags/0.2r1/build/vc9/TLibCommon_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TLibCommon_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TLibCommon_vc9.vcproj	(revision 19)
@@ -0,0 +1,539 @@
+<?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="&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="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="&quot;..\..\compat\msvc&quot;"
+				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="&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="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="&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>
+	</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\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMVDRefData.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\TComPredFilter.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\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\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\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\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\TComMVDRefData.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\TComPredFilter.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\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.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TypeDef.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /tags/0.2r1/build/vc9/TLibDecoder_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TLibDecoder_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TLibDecoder_vc9.vcproj	(revision 19)
@@ -0,0 +1,369 @@
+<?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"
+				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="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"
+				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>
+		<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\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\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: /tags/0.2r1/build/vc9/TLibEncoder_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TLibEncoder_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TLibEncoder_vc9.vcproj	(revision 19)
@@ -0,0 +1,417 @@
+<?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="&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="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="&quot;..\..\compat\msvc&quot;"
+				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="&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="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="&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>
+	</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\SEIwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAdaptiveLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.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\TEncFormattedStringParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSeqStructure.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\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\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\TEncFormattedStringParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSeqStructure.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: /tags/0.2r1/build/vc9/TLibRenderer_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TLibRenderer_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TLibRenderer_vc9.vcproj	(revision 19)
@@ -0,0 +1,345 @@
+<?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"
+				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"
+				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"
+				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"
+				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\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\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: /tags/0.2r1/build/vc9/TLibVideoIO_vc9.vcproj
===================================================================
--- /tags/0.2r1/build/vc9/TLibVideoIO_vc9.vcproj	(revision 19)
+++ /tags/0.2r1/build/vc9/TLibVideoIO_vc9.vcproj	(revision 19)
@@ -0,0 +1,309 @@
+<?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"
+				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="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"
+				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>
+		<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\TLibVideoIO\TVideoIOBits.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOBits.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /tags/0.2r1/cfg/cam_balloons.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_balloons.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_balloons.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_bookarrival.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_bookarrival.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_bookarrival.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_gtfly.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_gtfly.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_gtfly.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_kendo.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_kendo.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_kendo.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_lovebird1.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_lovebird1.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_lovebird1.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_newspaper.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_newspaper.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_newspaper.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_para.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_para.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_para.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_poznanhall2.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_poznanhall2.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_poznanhall2.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_poznanstreet.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_poznanstreet.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_poznanstreet.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/cam_undodancer.cfg
===================================================================
--- /tags/0.2r1/cfg/cam_undodancer.cfg	(revision 19)
+++ /tags/0.2r1/cfg/cam_undodancer.cfg	(revision 19)
@@ -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: /tags/0.2r1/cfg/encoder_mvd.cfg
===================================================================
--- /tags/0.2r1/cfg/encoder_mvd.cfg	(revision 19)
+++ /tags/0.2r1/cfg/encoder_mvd.cfg	(revision 19)
@@ -0,0 +1,129 @@
+#======== File I/O =====================
+InputFile_0                   : BookArrival_256x192\video\BookArrival_256x192_15_08.yuv
+InputFile_1                   : BookArrival_256x192\video\BookArrival_256x192_15_10.yuv
+InputFile_2                   : BookArrival_256x192\video\BookArrival_256x192_15_06.yuv
+
+DepthInputFile_0              : BookArrival_256x192\depth\depth_BookArrival_256x192_15_08.yuv
+DepthInputFile_1              : BookArrival_256x192\depth\depth_BookArrival_256x192_15_10.yuv
+DepthInputFile_2              : BookArrival_256x192\depth\depth_BookArrival_256x192_15_06.yuv
+
+ReconFile_0                   : Output_Enc_0.yuv
+ReconFile_1                   : Output_Enc_1.yuv
+ReconFile_2                   : Output_Enc_2.yuv
+
+DepthReconFile_0              : Output_Depth_Enc_0.yuv
+DepthReconFile_1              : Output_Depth_Enc_1.yuv
+DepthReconFile_2              : Output_Depth_Enc_2.yuv
+
+BitstreamFile                 : BitStreamMV.bin
+
+
+#====== General Coding Parameters ======
+NumberOfViews                 : 3           # Number of views to be coded
+CodeDepthMaps                 : 1           # Encode depth maps
+FramesToBeEncoded             : 5           # Number of frames to be coded
+SourceWidth                   : 256         # Input  frame width
+SourceHeight                  : 192         # Input  frame height
+FrameRate                     : 15          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+InputBitDepth                 : 8           # Input bit-depth
+OutputBitDepth                : 8           # Output bit-depth
+InternalBitDepth              : 10          # Internal bit-depth
+
+#====== Camera Parameters ======
+CameraParameterFile           : BookArrival_256x192\cam_bookarrival.cfg   # Camera parameter file
+BaseViewCameraNumbers         : 8 10 6                                    # Cameras in coding order [only NumberOfViews values are used]
+CodedCamParsPrecision         : 5                                         # precision for camera parameter coding (max. disparity error = 2^(-x)) [default: 2]
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             :  4          # Maximum coding unit depth
+
+QuadtreeTULog2MaxSize         :  5          # Log2 of maximum transform size for
+QuadtreeTULog2MinSize         :  2          # Log2 of minimum transform size for
+QuadtreeTUMaxDepthInter       :  3
+QuadtreeTUMaxDepthIntra       :  3
+
+#======== Coding Structure =============
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+RateGOPSize                   : 8           # GOP size used for QP assignment
+LowDelayCoding                : 0           # Low-delay coding structure
+GOPFormatString               : IL0PL3(V0)_0*n{ *2{ PL0(-8)PL3(-8,V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 }*1{ IL0PL3(V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 } }
+CodedPictureStoreSize         : 9
+TemporalLayerQPOffset_L0      : 0           # QP offset for layer 0
+TemporalLayerQPOffset_L1      : 1           # QP offset for layer 1
+TemporalLayerQPOffset_L2      : 2           # QP offset for layer 2
+TemporalLayerQPOffset_L3      : 3           # QP offset for layer 3
+TemporalLayerQPOffset_L4      : 4           # QP offset for layer 4
+TemporalLayerQPOffset_L5      : 5           # QP offset for layer 5
+TemporalLayerQPOffset_L6      : 6           # QP offset for layer 6
+TemporalLayerQPOffset_L7      : 7           # QP offset for layer 7
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:EPZS
+SearchRange                   : 96          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bipred refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+
+#============= VSO =============
+VSO                           : 1           # View Synthesis Optimization
+VSOConfig                     : [cx0 B(cc1) I(s0.5)][cx1 B(oo0) B(oo2) I(s0.5 s1.5)][cx2 B(cc1) I(s1.5)]  #VSO Configuration (3-View) coding order 1 0 2 oder 1 2 0
+#VSOConfig                    : [cx0 B(cc1) I(s0.5)][cx1 B(oo0) I(s0.5)]                                  #VSO Configuration (2-View) coding order 1 0
+
+#======== Quantization =============
+QP                            : 32 34       # Quantization parameter(0-51), second QP for Depth
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1  1        # RDOQ
+
+#=========== Entropy Coding ============
+SymbolMode                    : 1           # 0:LCEC, 1:CABAC
+
+#=========== 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
+
+#=========== Coding Tools =================
+MRG                           : 1           # Merge mode                      (0: OFF, 1: ON)
+ALF                           : 1           # Adaptive loop filter  (0: OFF, 1: ON)
+ALFEncodePassReduction        : 0           # Reduce ALF encoding passes (0:Original 16-pass, 1: 1-pass, 2: 2-pass encoding)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. LCU per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+EntropySliceMode         : 0                # 0: Disable all entropy slice options.
+                                            # 1: Enforce maximum number of LCU in an entropy slice,
+                                            # 2: Enforce maximum number of bins/bits in an 'entropy slice'
+EntropySliceArgument     : 180000           # Argument for 'EntropySliceMode'.
+                                            # If EntropySliceMode==1 it represents max. LCU per entropy slice.
+                                            # If EntropySliceMode==2 it represents max. bins per entropy slice.
+DMM                           : 1           # Depth model modes intra luma (0: OFF, 1: ON)
+MVI                           : 1           # Motion vector inheritance for depth map coding (0: OFF, 1: ON)
+
+#====== multiview mv/res prediction ======
+PredDepthMapGen           : 1           # generation of predicted depth maps (0:off, 1:using coded MVs, 2:using coded depth, 3:coded MVS for non-random-access, coded depth for random access)
+MultiviewMvPred           : 7           # usage for predicted depth maps (sum of the following: 1:inter-view, 2:inter, 4:merge)
+MultiviewMvRegMode        : 1           # regularization (using original depth maps) for inter-view motion estimation
+MultiviewMvRegLambdaScale : 1.0         # lambda scale factor for inter-view motion vector regularization
+MultiviewResPred          : 1           # inter-view resiudal prediction (0:off, 1:on)
+
+#====== Qp Change ======
+QpChangeFrame             : 0           # start frame for QP change (note: given in coding order, not as POC value)
+QpChangeOffsetVideo       : 0           # QP change offset for video
+QpChangeOffsetDepth       : 0           # QP change offset for depth
+
+#====== InterViewSkip ==
+InterViewSkip             : 0
+InterViewSkipLambdaScale  : 8
+
Index: /tags/0.2r1/cfg/renderer.cfg
===================================================================
--- /tags/0.2r1/cfg/renderer.cfg	(revision 19)
+++ /tags/0.2r1/cfg/renderer.cfg	(revision 19)
@@ -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: /tags/0.2r1/compat/msvc/stdint.h
===================================================================
--- /tags/0.2r1/compat/msvc/stdint.h	(revision 19)
+++ /tags/0.2r1/compat/msvc/stdint.h	(revision 19)
@@ -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: /tags/0.2r1/doc/Doxyfile
===================================================================
--- /tags/0.2r1/doc/Doxyfile	(revision 19)
+++ /tags/0.2r1/doc/Doxyfile	(revision 19)
@@ -0,0 +1,1600 @@
+# Doxyfile 1.6.3
+
+# 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 a sequence of words surrounded 
+# by quotes) that should identify the project.
+
+PROJECT_NAME           = "Test Model under Consideration (TMuC)"
+
+# 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         = "Software implementation candidate"
+
+# 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-Cyrilic, 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        = 
+
+# 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 is your file systems 
+# 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               = 2
+
+# 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, C#, 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 make 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 to replace the get and set methods by a property in the 
+# documentation. This will only work if the methods are indeed getting or 
+# setting a simple type. If this is not the case, or you want to show the 
+# methods anyway, you should set this option to NO.
+
+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 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 penality. 
+# 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 rougly 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            = NO
+
+# 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 namespace 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
+
+# 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 define 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 defines 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            = 
+
+#---------------------------------------------------------------------------
+# 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
+
+# This WARN_NO_PARAMDOC option can be abled 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           = 
+
+#---------------------------------------------------------------------------
+# 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
+
+# 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++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx 
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
+
+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 \
+                         *.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.
+
+EXCLUDE                = 
+
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or 
+# directories that are symbolic links (a Unix filesystem 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       = 
+
+# 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, INPUT_FILTER 
+# is applied to all files.
+
+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
+
+#---------------------------------------------------------------------------
+# 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     = NO
+
+# 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.
+
+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        = 
+
+# 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
+
+# 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
+
+# This tag can be used to set the number of enum values (range [1..20]) 
+# that doxygen will group on one line in the generated HTML documentation.
+
+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
+
+# 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
+
+# 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 disadvances is 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, a4wide, letter, legal and 
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE             = a4wide
+
+# 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           = 
+
+# 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
+
+#---------------------------------------------------------------------------
+# 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        = NO
+
+# 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 
+# in the INCLUDE_PATH (see below) will be search if 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           = 
+
+# 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.
+
+EXPAND_AS_DEFINED      = 
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then 
+# doxygen's preprocessor will remove all function-like macros that are alone 
+# on a line, have an all uppercase name, and do not end with a semicolon. Such 
+# function macros are typically used for boiler-plate code, and will confuse 
+# the parser if not removed.
+
+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 is superseded by the HAVE_DOT option below. This is only a 
+# fallback. It is recommended to install and use dot, since it yields more 
+# powerful graphs.
+
+CLASS_DIAGRAMS         = YES
+
+# 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               = NO
+
+# By default doxygen will write a font called FreeSans.ttf to the output 
+# directory and reference it in all dot files that doxygen generates. This 
+# font does not include all possible unicode characters however, so when you need 
+# these (or just want a differently looking font) you can specify the font name 
+# using DOT_FONTNAME. You need 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           = FreeSans
+
+# 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 output directory to look for the 
+# FreeSans.ttf font (which doxygen will put there itself). If you specify a 
+# different font using DOT_FONTNAME you can set the path where dot 
+# can find it using this tag.
+
+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 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 png, jpg, or gif 
+# If left blank png will be used.
+
+DOT_IMAGE_FORMAT       = png
+
+# 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 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: /tags/0.2r1/encoder_cfg/_README.txt
===================================================================
--- /tags/0.2r1/encoder_cfg/_README.txt	(revision 19)
+++ /tags/0.2r1/encoder_cfg/_README.txt	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/baseCfg_2view+depth.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/baseCfg_2view+depth.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/baseCfg_2view+depth.cfg	(revision 19)
@@ -0,0 +1,120 @@
+
+
+#========== 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
+
+
+#========== 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 ==========
+CodedPictureStoreSize     : 9                                      # size of decoded picture buffer in frame buffers
+GOPFormatString           : IL0PL3(V0)_0*n{ *2{ PL0(-8)PL3(-8,V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 }*1{ IL0PL3(V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 } }
+                                                                   # string specifying the coding order and reference picture lists
+GOPSize                   : 8                                      # GOP size of temporal structures
+RateGOPSize               : 8                                      # GOP size of hierarchical QP assignment (-1: inherit GOPSize value)
+LowDelayCoding            : 0                                      # use low-delay mode
+TemporalLayerQPOffset_L0  : 0                                      # QP offset for temporal layer 0
+TemporalLayerQPOffset_L1  : 1                                      # QP offset for temporal layer 1
+TemporalLayerQPOffset_L2  : 2                                      # QP offset for temporal layer 2
+TemporalLayerQPOffset_L3  : 3                                      # QP offset for temporal layer 3
+TemporalLayerQPOffset_L4  : 4                                      # QP offset for temporal layer 4
+TemporalLayerQPOffset_L5  : 5                                      # QP offset for temporal layer 5
+TemporalLayerQPOffset_L6  : 6                                      # QP offset for temporal layer 6
+TemporalLayerQPOffset_L7  : 7                                      # QP offset for temporal layer 7
+
+
+#========== 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
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+QpChangeFrame             : 0                                      # frame number for Qp change
+QpChangeOffsetVideo       : 0                                      # change QP delta for video
+QpChangeOffsetDepth       : 0                                      # change QP delta for depth
+
+
+#========== entropy coding ==========
+SymbolMode                : 1                                      # entropy coding mode (0=CAVLC, 1=CABAC)
+
+
+#========== slices ==========
+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 ==========
+LoopFilterDisable         : 0                                      # disable deblocking filter
+LoopFilterAlphaC0Offset   : 0                                      # alpha offset for deblocking filter
+LoopFilterBetaOffset      : 0                                      # beta offset for deblocking filter
+
+
+#========== coding tools ==========
+MRG                       : 1                                      # use motion partition merging
+ALF                       : 1                                      # use adaptive loop filter
+ALFEncodePassReduction    : 0                                      # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+
+
+#========== 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
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+MVI                       : 1                                      # motion parameter inheritance
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(cc1) I(s0.5)][cx1 B(oo0) I(s0.5)]
+                                                                   # VSO configuration string
+
Index: /tags/0.2r1/encoder_cfg/baseCfg_2view.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/baseCfg_2view.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/baseCfg_2view.cfg	(revision 19)
@@ -0,0 +1,113 @@
+
+
+#========== 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
+
+
+#========== 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 ==========
+CodedPictureStoreSize     : 9                                      # size of decoded picture buffer in frame buffers
+GOPFormatString           : IL0PL3(V0)_0*n{ *2{ PL0(-8)PL3(-8,V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 }*1{ IL0PL3(V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 } }
+                                                                   # string specifying the coding order and reference picture lists
+GOPSize                   : 8                                      # GOP size of temporal structures
+RateGOPSize               : 8                                      # GOP size of hierarchical QP assignment (-1: inherit GOPSize value)
+LowDelayCoding            : 0                                      # use low-delay mode
+TemporalLayerQPOffset_L0  : 0                                      # QP offset for temporal layer 0
+TemporalLayerQPOffset_L1  : 1                                      # QP offset for temporal layer 1
+TemporalLayerQPOffset_L2  : 2                                      # QP offset for temporal layer 2
+TemporalLayerQPOffset_L3  : 3                                      # QP offset for temporal layer 3
+TemporalLayerQPOffset_L4  : 4                                      # QP offset for temporal layer 4
+TemporalLayerQPOffset_L5  : 5                                      # QP offset for temporal layer 5
+TemporalLayerQPOffset_L6  : 6                                      # QP offset for temporal layer 6
+TemporalLayerQPOffset_L7  : 7                                      # QP offset for temporal layer 7
+
+
+#========== 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
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+QpChangeFrame             : 0                                      # frame number for Qp change
+QpChangeOffsetVideo       : 0                                      # change QP delta for video
+QpChangeOffsetDepth       : 0                                      # change QP delta for depth
+
+
+#========== entropy coding ==========
+SymbolMode                : 1                                      # entropy coding mode (0=CAVLC, 1=CABAC)
+
+
+#========== slices ==========
+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 ==========
+LoopFilterDisable         : 0                                      # disable deblocking filter
+LoopFilterAlphaC0Offset   : 0                                      # alpha offset for deblocking filter
+LoopFilterBetaOffset      : 0                                      # beta offset for deblocking filter
+
+
+#========== coding tools ==========
+MRG                       : 1                                      # use motion partition merging
+ALF                       : 1                                      # use adaptive loop filter
+ALFEncodePassReduction    : 0                                      # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+
+
+#========== 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
+
+
+#========== depth coding tools ==========
+DMM                       : 0                                      # use depth intra modes (wedgelets)
+VSO                       : 0                                      # use of view synthesis optimization for depth coding
+MVI                       : 0                                      # motion parameter inheritance
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 :                                        # VSO configuration string
+
Index: /tags/0.2r1/encoder_cfg/baseCfg_3view+depth.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/baseCfg_3view+depth.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/baseCfg_3view+depth.cfg	(revision 19)
@@ -0,0 +1,124 @@
+
+
+#========== 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
+
+
+#========== 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 ==========
+CodedPictureStoreSize     : 9                                      # size of decoded picture buffer in frame buffers
+GOPFormatString           : IL0PL3(V0)_0*n{ *2{ PL0(-8)PL3(-8,V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 }*1{ IL0PL3(V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 } }
+                                                                   # string specifying the coding order and reference picture lists
+GOPSize                   : 8                                      # GOP size of temporal structures
+RateGOPSize               : 8                                      # GOP size of hierarchical QP assignment (-1: inherit GOPSize value)
+LowDelayCoding            : 0                                      # use low-delay mode
+TemporalLayerQPOffset_L0  : 0                                      # QP offset for temporal layer 0
+TemporalLayerQPOffset_L1  : 1                                      # QP offset for temporal layer 1
+TemporalLayerQPOffset_L2  : 2                                      # QP offset for temporal layer 2
+TemporalLayerQPOffset_L3  : 3                                      # QP offset for temporal layer 3
+TemporalLayerQPOffset_L4  : 4                                      # QP offset for temporal layer 4
+TemporalLayerQPOffset_L5  : 5                                      # QP offset for temporal layer 5
+TemporalLayerQPOffset_L6  : 6                                      # QP offset for temporal layer 6
+TemporalLayerQPOffset_L7  : 7                                      # QP offset for temporal layer 7
+
+
+#========== 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
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+QpChangeFrame             : 0                                      # frame number for Qp change
+QpChangeOffsetVideo       : 0                                      # change QP delta for video
+QpChangeOffsetDepth       : 0                                      # change QP delta for depth
+
+
+#========== entropy coding ==========
+SymbolMode                : 1                                      # entropy coding mode (0=CAVLC, 1=CABAC)
+
+
+#========== slices ==========
+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 ==========
+LoopFilterDisable         : 0                                      # disable deblocking filter
+LoopFilterAlphaC0Offset   : 0                                      # alpha offset for deblocking filter
+LoopFilterBetaOffset      : 0                                      # beta offset for deblocking filter
+
+
+#========== coding tools ==========
+MRG                       : 1                                      # use motion partition merging
+ALF                       : 1                                      # use adaptive loop filter
+ALFEncodePassReduction    : 0                                      # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+
+
+#========== 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
+
+
+#========== depth coding tools ==========
+DMM                       : 1                                      # use depth intra modes (wedgelets)
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+MVI                       : 1                                      # motion parameter inheritance
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(cc1) I(s0.5)][cx1 B(oo0) B(oo2) I(s0.5 s1.5)][cx2 B(cc1) I(s1.5)]
+                                                                   # VSO configuration string
+
Index: /tags/0.2r1/encoder_cfg/baseCfg_3view.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/baseCfg_3view.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/baseCfg_3view.cfg	(revision 19)
@@ -0,0 +1,115 @@
+
+
+#========== 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
+
+
+#========== 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 ==========
+CodedPictureStoreSize     : 9                                      # size of decoded picture buffer in frame buffers
+GOPFormatString           : IL0PL3(V0)_0*n{ *2{ PL0(-8)PL3(-8,V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 }*1{ IL0PL3(V0)_7 BL1(-4;+4)BL4(-4,V0;+4)_3 BL2(-2;+2,+6)BL5(-2,V0;+2,+6)_1 BL2(-2,-6;+2)BL5(-2,-6,V0;+2)_5 BL3(-1;+1,+3)BL6(-1,V0;+1,+3)_0 BL3(-1,-3;+1,+5)BL6(-1,-3,V0;+1,+5)_2 BL3(-1,-5;+1,+3)BL6(-1,-5,V0;+1,+3)_4 BL3(-1,-3;+1)BL6(-1,-3,V0;+1)_6 } }
+                                                                   # string specifying the coding order and reference picture lists
+GOPSize                   : 8                                      # GOP size of temporal structures
+RateGOPSize               : 8                                      # GOP size of hierarchical QP assignment (-1: inherit GOPSize value)
+LowDelayCoding            : 0                                      # use low-delay mode
+TemporalLayerQPOffset_L0  : 0                                      # QP offset for temporal layer 0
+TemporalLayerQPOffset_L1  : 1                                      # QP offset for temporal layer 1
+TemporalLayerQPOffset_L2  : 2                                      # QP offset for temporal layer 2
+TemporalLayerQPOffset_L3  : 3                                      # QP offset for temporal layer 3
+TemporalLayerQPOffset_L4  : 4                                      # QP offset for temporal layer 4
+TemporalLayerQPOffset_L5  : 5                                      # QP offset for temporal layer 5
+TemporalLayerQPOffset_L6  : 6                                      # QP offset for temporal layer 6
+TemporalLayerQPOffset_L7  : 7                                      # QP offset for temporal layer 7
+
+
+#========== 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
+
+
+#========== quantization ==========
+DeltaQpRD                 : 0                                      # maximum delta QP offset for a slice
+MaxDeltaQP                : 0                                      # maximum delta QP offset for a block
+RDOQ                      : 1 1                                    # use rate-distortion optimized quantization (RDOQ)
+QpChangeFrame             : 0                                      # frame number for Qp change
+QpChangeOffsetVideo       : 0                                      # change QP delta for video
+QpChangeOffsetDepth       : 0                                      # change QP delta for depth
+
+
+#========== entropy coding ==========
+SymbolMode                : 1                                      # entropy coding mode (0=CAVLC, 1=CABAC)
+
+
+#========== slices ==========
+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 ==========
+LoopFilterDisable         : 0                                      # disable deblocking filter
+LoopFilterAlphaC0Offset   : 0                                      # alpha offset for deblocking filter
+LoopFilterBetaOffset      : 0                                      # beta offset for deblocking filter
+
+
+#========== coding tools ==========
+MRG                       : 1                                      # use motion partition merging
+ALF                       : 1                                      # use adaptive loop filter
+ALFEncodePassReduction    : 0                                      # ALF encoding (0:original 16-pass, 1:one-pass, 2:two-pass)
+
+
+#========== 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
+
+
+#========== depth coding tools ==========
+DMM                       : 0                                      # use depth intra modes (wedgelets)
+VSO                       : 0                                      # use of view synthesis optimization for depth coding
+MVI                       : 0                                      # motion parameter inheritance
+
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 :                                        # VSO configuration string
+
Index: /tags/0.2r1/encoder_cfg/qpCfg_QP25.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/qpCfg_QP25.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/qpCfg_QP25.cfg	(revision 19)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25 34                                  # quantization parameter (view depth)
+
Index: /tags/0.2r1/encoder_cfg/qpCfg_QP30.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/qpCfg_QP30.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/qpCfg_QP30.cfg	(revision 19)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30 39                                  # quantization parameter (view depth)
+
Index: /tags/0.2r1/encoder_cfg/qpCfg_QP35.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/qpCfg_QP35.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/qpCfg_QP35.cfg	(revision 19)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35 42                                  # quantization parameter (view depth)
+
Index: /tags/0.2r1/encoder_cfg/qpCfg_QP40.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/qpCfg_QP40.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/qpCfg_QP40.cfg	(revision 19)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40 45                                  # quantization parameter (view depth)
+
Index: /tags/0.2r1/encoder_cfg/qpCfg_QP45.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/qpCfg_QP45.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/qpCfg_QP45.cfg	(revision 19)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45 48                                  # quantization parameter (view depth)
+
Index: /tags/0.2r1/encoder_cfg/rendering_2view_decData.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/rendering_2view_decData.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/rendering_2view_decData.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/rendering_2view_orgData.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/rendering_2view_orgData.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/rendering_2view_orgData.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/rendering_3view_decData.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/rendering_3view_decData.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/rendering_3view_decData.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/rendering_3view_orgData.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/rendering_3view_orgData.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/rendering_3view_orgData.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/seqCfg_Balloons.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/seqCfg_Balloons.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/seqCfg_Balloons.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/seqCfg_GhostTownFly.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/seqCfg_GhostTownFly.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/seqCfg_GhostTownFly.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/seqCfg_Kendo.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/seqCfg_Kendo.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/seqCfg_Kendo.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/seqCfg_Newspaper.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/seqCfg_Newspaper.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/seqCfg_Newspaper.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/seqCfg_PoznanHall2.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/seqCfg_PoznanHall2.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/seqCfg_PoznanHall2.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/seqCfg_PoznanStreet.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/seqCfg_PoznanStreet.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/seqCfg_PoznanStreet.cfg	(revision 19)
@@ -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: /tags/0.2r1/encoder_cfg/seqCfg_UndoDancer.cfg
===================================================================
--- /tags/0.2r1/encoder_cfg/seqCfg_UndoDancer.cfg	(revision 19)
+++ /tags/0.2r1/encoder_cfg/seqCfg_UndoDancer.cfg	(revision 19)
@@ -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: /tags/0.2r1/source/App/TAppCommon/TAppComCamPara.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppCommon/TAppComCamPara.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppCommon/TAppComCamPara.cpp	(revision 19)
@@ -0,0 +1,1472 @@
+/* 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 <math.h>
+#include <errno.h>
+#include <vector>
+#include <iostream>
+#include <fstream>
+#include <algorithm>
+#include <functional>
+
+
+
+
+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 config 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    iSourceViewRelNum;
+  Int    iTargetViewRelNum;
+
+  if( bByIdx )
+  {
+
+    iSourceViewNum = m_aiBaseViews[ uiSourceView ];
+    iSourceViewRelNum = m_aiBaseId2SortedId[ uiSourceView ] * ((Int) m_dViewNumPrec );
+
+    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;
+    iSourceViewRelNum = m_aiBaseId2SortedId[ xGetBaseViewId( uiSourceView) ] * ((Int) m_dViewNumPrec );
+
+    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 );
+  Double  dAbsCamPosShiftVOI01  = ( dCamPosShiftVOI01 < 0.0 ? -dCamPosShiftVOI01 : dCamPosShiftVOI01 );
+
+  //--- 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 );
+    }
+  }
+  Double  dEpsilon    = 1e-15;
+  Double  dShiftRatio = dMaxAbsCamPosShift / dAbsCamPosShiftVOI01 - dEpsilon;
+  Int     iPrecision  = 0;  for( ; (Double)( 1 << iPrecision ) < dShiftRatio; iPrecision++ );
+  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;
+
+  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;
+
+  AOF( 0 <= uiFrameId && uiFrameId <= m_uiLastFrameId - m_uiFirstFrameId );
+  if ( m_bCamParsVaryOverTime )
+  {
+    xSetShiftParametersAndLUT( m_uiFirstFrameId + uiFrameId );
+  }
+}
+
+
+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: /tags/0.2r1/source/App/TAppCommon/TAppComCamPara.h
===================================================================
--- /tags/0.2r1/source/App/TAppCommon/TAppComCamPara.h	(revision 19)
+++ /tags/0.2r1/source/App/TAppCommon/TAppComCamPara.h	(revision 19)
@@ -0,0 +1,283 @@
+/* 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 "../../Lib/TLibCommon/TComMVDRefData.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;
+
+  // 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 );
+
+  // 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: /tags/0.2r1/source/App/TAppCommon/program_options_lite.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppCommon/program_options_lite.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppCommon/program_options_lite.cpp	(revision 19)
@@ -0,0 +1,494 @@
+/* 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 <iostream>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+#include "program_options_lite.h"
+
+using namespace std;
+
+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: /tags/0.2r1/source/App/TAppCommon/program_options_lite.h
===================================================================
--- /tags/0.2r1/source/App/TAppCommon/program_options_lite.h	(revision 19)
+++ /tags/0.2r1/source/App/TAppCommon/program_options_lite.h	(revision 19)
@@ -0,0 +1,376 @@
+/* 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 <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
+
+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: /tags/0.2r1/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 19)
@@ -0,0 +1,125 @@
+/* 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     TAppDecCfg.cpp
+    \brief    Decoder configuration class
+*/
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include "TAppDecCfg.h"
+#include "../../App/TAppCommon/program_options_lite.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 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")
+#if DCM_SKIP_DECODING_FRAMES
+  ("SkipFrames,s", m_iSkipFrame, 0, "number of frames to skip before random access")
+#endif
+  ("OutputBitDepth,d", m_outputBitDepth, 0u, "bit depth of YUV output file (use 0 for native depth)")
+  ("SEIpictureDigest", m_pictureDigestEnabled, false, "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 specifed, 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: /tags/0.2r1/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- /tags/0.2r1/source/App/TAppDecoder/TAppDecCfg.h	(revision 19)
+++ /tags/0.2r1/source/App/TAppDecoder/TAppDecCfg.h	(revision 19)
@@ -0,0 +1,77 @@
+/* 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     TAppDecCfg.h
+    \brief    Decoder configuration class (header)
+*/
+
+#ifndef __TAPPDECCFG__
+#define __TAPPDECCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "../../Lib/TLibCommon/CommonDef.h"
+
+// ====================================================================================================================
+// 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
+#if DCM_SKIP_DECODING_FRAMES
+  Int           m_iSkipFrame;                         ///< counter for frames prior to the random access point to skip
+#endif
+  UInt          m_outputBitDepth;                     ///< bit depth used for writing output
+
+  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: /tags/0.2r1/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppDecoder/TAppDecTop.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppDecoder/TAppDecTop.cpp	(revision 19)
@@ -0,0 +1,540 @@
+/* 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     TAppDecTop.cpp
+    \brief    Decoder application class
+*/
+
+#include <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppDecTop.h"
+
+// ====================================================================================================================
+// Local constants
+// ====================================================================================================================
+
+/// initial bitstream buffer size
+/// should be large enough for parsing SPS
+/// resized as a function of picture size after parsing SPS
+#define BITS_BUF_SIZE 65536
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppDecTop::TAppDecTop()
+{
+  ::memset (m_abDecFlag, 0, sizeof (m_abDecFlag));
+  m_bUsingDepth = false;
+//  m_iPOCLastDisplay  = -1;
+  m_pScaleOffsetFile  = 0;
+}
+
+Void TAppDecTop::create()
+{
+  m_apcBitstream  = new TComBitstream;
+  
+  m_apcBitstream->create( BITS_BUF_SIZE );
+}
+
+Void TAppDecTop::destroy()
+{
+  if ( m_apcBitstream )
+  {
+    m_apcBitstream->destroy();
+    delete m_apcBitstream;
+    m_apcBitstream = NULL;
+  }
+  if( m_pchBitstreamFile )
+  {
+    free(m_pchBitstreamFile);
+  }
+  if( m_pchReconFile )
+  {
+    free(m_pchReconFile);
+  }
+}
+
+// ====================================================================================================================
+// 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()
+{
+  TComBitstream*      pcBitstream = m_apcBitstream;
+  UInt                uiPOC;
+  TComList<TComPic*>* pcListPic;
+  Bool bFirstSliceDecoded = true;
+
+  // create & initialize internal classes
+  xCreateDecLib();
+  xInitDecLib  ();
+#if DCM_SKIP_DECODING_FRAMES
+//  m_iPOCLastDisplay += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
+#endif
+
+  // main decoder loop
+  Bool  bEos        = false;
+  Bool resizedBitstreamBuffer = false;
+  
+  Bool bIsDepth = false;
+  Int iViewIdx = 0;
+  TComSPS cComSPS ;
+  NalUnitType eNalUnitType;
+
+  
+  while ( !bEos )
+  {
+    streampos  lLocation = m_cTVideoIOBitstreamFile.getFileLocation();
+    bEos                 = m_cTVideoIOBitstreamFile.readBits( pcBitstream );
+    if (bEos)
+    {
+      //if (!bFirstSliceDecoded) m_cTDecTop.decode( bEos, pcBitstream, uiPOC, pcListPic, eNalUnitType, cComSPS, m_iSkipFrame, m_iPOCLastDisplay);
+      if( bIsDepth )
+      {
+        if (!bFirstSliceDecoded) m_acTDecDepthTopList[iViewIdx]->decode( bEos, pcBitstream, uiPOC, pcListPic, eNalUnitType, cComSPS, m_iSkipFrame, m_aiDepthPOCLastDisplayList[iViewIdx] );
+        m_acTDecDepthTopList[iViewIdx]->executeDeblockAndAlf( bEos, pcBitstream, uiPOC, pcListPic, m_iSkipFrame, m_aiDepthPOCLastDisplayList[iViewIdx]);
+      }
+      else
+      {
+        if (!bFirstSliceDecoded) m_acTDecTopList[iViewIdx]->decode( bEos, pcBitstream, uiPOC, pcListPic, eNalUnitType, cComSPS, m_iSkipFrame, m_aiPOCLastDisplayList[iViewIdx] );
+        m_acTDecTopList[iViewIdx]->executeDeblockAndAlf( bEos, pcBitstream, uiPOC, pcListPic, m_iSkipFrame, m_aiPOCLastDisplayList[iViewIdx]);
+      }
+      if( pcListPic )
+      {
+        // write reconstuction to file
+        xWriteOutput( pcListPic );
+      }
+      break;
+    }
+    
+    // call actual decoding function
+#if DCM_SKIP_DECODING_FRAMES
+    Bool bNewPicture;
+    if( bIsDepth )
+      bNewPicture = m_acTDecDepthTopList[iViewIdx]->decode( bEos, pcBitstream, uiPOC, pcListPic, eNalUnitType, cComSPS, m_iSkipFrame, m_aiDepthPOCLastDisplayList[iViewIdx] );
+    else
+      bNewPicture = m_acTDecTopList[iViewIdx]->decode( bEos, pcBitstream, uiPOC, pcListPic, eNalUnitType, cComSPS, m_iSkipFrame, m_aiPOCLastDisplayList[iViewIdx] );
+    bFirstSliceDecoded   = true;
+
+    if( eNalUnitType == NAL_UNIT_SPS )
+    {
+      if( cComSPS.isDepth() && (m_bUsingDepth==false) )  // expected not using depth, but bitstream are using depth
+      {                                                     // know from sps
+        assert( cComSPS.getViewId() == 0 && iViewIdx == 0 && !bIsDepth );
+        startUsingDepth() ;
+      }
+      if( cComSPS.isDepth() && !bIsDepth )
+      {
+        assert( cComSPS.getViewId() == iViewIdx );
+        m_acTDecDepthTopList[iViewIdx]->setSPS(cComSPS);
+      }
+      else if( cComSPS.getViewId() >= m_acTVideoIOYuvReconFileList.size() ) // expecting iViewIdx, but got cComSPS.getViewIdx()
+      {
+        assert( cComSPS.getViewId() == m_acTVideoIOYuvReconFileList.size() );
+        assert( !cComSPS.isDepth() );
+        increaseNumberOfViews(cComSPS.getViewId()+1);
+        m_acTDecTopList[cComSPS.getViewId()]->setSPS(cComSPS);
+      }
+      bEos = m_cTVideoIOBitstreamFile.readBits( pcBitstream );
+      assert( !bEos);
+      if( cComSPS.isDepth() )
+        m_acTDecDepthTopList[cComSPS.getViewId()]->decode( bEos, pcBitstream, uiPOC, pcListPic, eNalUnitType, cComSPS, m_iSkipFrame, m_aiDepthPOCLastDisplayList[cComSPS.getViewId()]); // decode PPS
+      else
+        m_acTDecTopList[cComSPS.getViewId()]->decode( bEos, pcBitstream, uiPOC, pcListPic, eNalUnitType, cComSPS, m_iSkipFrame, m_aiPOCLastDisplayList[cComSPS.getViewId()]); // decode PPS
+      assert( eNalUnitType == NAL_UNIT_PPS );
+    }
+    assert( eNalUnitType != NAL_UNIT_SEI ); // not yet supported for MVC
+    if (bNewPicture)
+    {
+      if( bIsDepth )
+        m_acTDecDepthTopList[iViewIdx]->executeDeblockAndAlf( bEos, pcBitstream, uiPOC, pcListPic, m_iSkipFrame, m_aiDepthPOCLastDisplayList[iViewIdx]);
+      else
+        m_acTDecTopList[iViewIdx]->executeDeblockAndAlf( bEos, pcBitstream, uiPOC, pcListPic, m_iSkipFrame, m_aiPOCLastDisplayList[iViewIdx]);
+      if (!m_cTVideoIOBitstreamFile.good()) m_cTVideoIOBitstreamFile.clear();
+      m_cTVideoIOBitstreamFile.setFileLocation( lLocation );
+      bFirstSliceDecoded = false;
+
+      if( m_bUsingDepth && !bIsDepth )
+      {
+        bIsDepth = true;
+      }
+      else
+      {
+        bIsDepth = false;
+        if( iViewIdx<m_acTDecTopList.size()-1)
+        {
+          iViewIdx++ ;
+        }
+        else
+        {
+          iViewIdx = 0;
+
+          // end of access unit: delete extra pic buffers
+          Int iNumViews = (Int)m_acTVideoIOYuvReconFileList.size();
+          for( Int iVId = 0; iVId < iNumViews; iVId++ )
+          {
+            if( iVId < (Int)m_acTDecTopList.size() &&  m_acTDecTopList[iVId] )
+            {
+              m_acTDecTopList[iVId]->deleteExtraPicBuffers( (Int)uiPOC );
+            }
+            if( iVId < (Int)m_acTDecDepthTopList.size() && m_acTDecDepthTopList[iVId] )
+            {
+              m_acTDecDepthTopList[iVId]->deleteExtraPicBuffers( (Int)uiPOC );
+            }
+          }
+
+#if AMVP_BUFFERCOMPRESS
+          // compress motion for entire access unit
+          for( Int iVId = 0; iVId < iNumViews; iVId++ )
+          {
+            if( iVId < (Int)m_acTDecTopList.size() &&  m_acTDecTopList[iVId] )
+            {
+              m_acTDecTopList[iVId]->compressMotion( (Int)uiPOC );
+            }
+            if( iVId < (Int)m_acTDecDepthTopList.size() && m_acTDecDepthTopList[iVId] )
+            {
+              m_acTDecDepthTopList[iVId]->compressMotion( (Int)uiPOC );
+            }
+          }
+#endif
+        }
+      }
+    }
+#else
+#error
+    m_cTDecTop.decode( bEos, pcBitstream, uiPOC, pcListPic );
+#endif
+
+    
+    if (!resizedBitstreamBuffer)
+    {
+      TComSPS *sps = m_acTDecTopList[0]->getSPS();
+      if (sps)
+      {
+        pcBitstream->destroy();
+        pcBitstream->create(sps->getWidth() * sps->getHeight() * 2);
+        resizedBitstreamBuffer = true;
+      }
+    }
+    
+    if( pcListPic )
+    {
+      // write reconstuction to file
+      xWriteOutput( pcListPic );
+    }
+  }
+  
+  // delete buffers
+  for(Int i=0; i<m_acTDecTopList.size(); i++)
+    m_acTDecTopList[i]->deletePicBuffer();
+
+  if (m_bUsingDepth)
+  {
+    for(Int i=0; i<m_acTDecDepthTopList.size(); i++)
+      m_acTDecDepthTopList[i]->deletePicBuffer();
+  }
+  
+  // destroy internal classes
+  xDestroyDecLib();
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TAppDecTop::xCreateDecLib()
+{
+  // open bitstream file
+  m_cTVideoIOBitstreamFile.openBits( m_pchBitstreamFile, false);  // read mode
+
+  // create decoder class
+//  m_cTDecTop.create();
+  m_acTDecTopList.push_back(new TDecTop) ;// at least one decoder
+  m_acTDecTopList[0]->create() ;
+
+  m_aiPOCLastDisplayList.push_back(-1+m_iSkipFrame) ;
+
+  if( m_pchScaleOffsetFile ) 
+  { 
+    m_pScaleOffsetFile = ::fopen( m_pchScaleOffsetFile, "wt" ); 
+    AOF( m_pScaleOffsetFile ); 
+  }
+  m_cCamParsCollector.init( m_pScaleOffsetFile );
+}
+
+Void TAppDecTop::xDestroyDecLib()
+{
+  // close bitstream file
+  m_cTVideoIOBitstreamFile.closeBits();
+
+  for(Int iViewIdx=0; iViewIdx<m_acTVideoIOYuvReconFileList.size() ; iViewIdx++)
+  {
+    m_acTVideoIOYuvReconFileList[iViewIdx]->close();
+    delete m_acTVideoIOYuvReconFileList[iViewIdx]; m_acTVideoIOYuvReconFileList[iViewIdx] = NULL ;
+  }
+
+  // destroy decoder class
+//  m_cTDecTop.destroy();
+  for(Int iViewIdx=0; iViewIdx<m_acTDecTopList.size() ; iViewIdx++)
+  {
+    m_acTDecTopList[iViewIdx]->destroy() ;
+    delete m_acTDecTopList[iViewIdx] ; m_acTDecTopList[iViewIdx] = NULL ;
+  }
+
+  for(Int iViewIdx=0; iViewIdx<m_acTVideoIOYuvDepthReconFileList.size() ; iViewIdx++)
+  {
+    m_acTVideoIOYuvDepthReconFileList[iViewIdx]->close();
+    delete m_acTVideoIOYuvDepthReconFileList[iViewIdx]; m_acTVideoIOYuvDepthReconFileList[iViewIdx] = NULL ;
+  }
+
+  for(Int iViewIdx=0; iViewIdx<m_acTDecDepthTopList.size() ; iViewIdx++)
+  {
+    m_acTDecDepthTopList[iViewIdx]->destroy() ;
+    delete m_acTDecDepthTopList[iViewIdx] ; m_acTDecDepthTopList[iViewIdx] = NULL ;
+  }
+
+  m_cCamParsCollector.uninit();
+  if( m_pScaleOffsetFile ) 
+  { 
+    ::fclose( m_pScaleOffsetFile ); 
+  }
+}
+
+Void TAppDecTop::xInitDecLib()
+{
+  // initialize decoder class
+  m_acTDecTopList[0]->init( this );
+  m_acTDecTopList[0]->setViewIdx(0);
+  m_acTDecTopList[0]->setPictureDigestEnabled(m_pictureDigestEnabled);
+  m_acTDecTopList[0]->setCamParsCollector( &m_cCamParsCollector );
+}
+
+/** \param pcListPic list of pictures to be written to file
+    \param bFirst    first picture?
+    \todo            DYN_REF_FREE should be revised
+ */
+Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic )
+{
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+    Int iViewIdx = pcPic->getViewIdx();
+    Int bIsDepth = pcPic->getSlice(0)->getSPS()->isDepth() ;
+
+    if (!bIsDepth)
+    {
+      if( m_acTVideoIOYuvReconFileList.size() < iViewIdx+1 )
+            increaseNumberOfViews( iViewIdx+1 ) ;
+
+      if ( pcPic->getReconMark() && pcPic->getPOC() == (m_aiPOCLastDisplayList[iViewIdx] + 1) )
+      {
+        // write to file
+        if ( m_pchReconFile )
+        {
+          m_acTVideoIOYuvReconFileList[iViewIdx]->write( pcPic->getPicYuvRec(), pcPic->getSlice(0)->getSPS()->getPad() );
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplayList[iViewIdx] = 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
+        }
+      }
+    } /// end !bIsDepth
+    else
+    {
+      if( m_acTVideoIOYuvDepthReconFileList.size() < iViewIdx+1 )
+             increaseNumberOfViews( iViewIdx+1 ) ;
+
+      if ( pcPic->getReconMark() && pcPic->getPOC() == (m_aiDepthPOCLastDisplayList[iViewIdx] + 1) )
+      {
+        // write to file
+        if ( m_pchReconFile )
+        {
+          m_acTVideoIOYuvDepthReconFileList[iViewIdx]->write( pcPic->getPicYuvRec(), pcPic->getSlice(0)->getSPS()->getPad() );
+        }
+
+        // update POC of display order
+        m_aiDepthPOCLastDisplayList[iViewIdx] = 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
+        }
+      }
+    } // end bIsDepth
+
+    iterPic++;
+  }
+}
+
+Void TAppDecTop::startUsingDepth()
+{
+  m_bUsingDepth = true ;
+  increaseNumberOfViews( (Int)m_acTVideoIOYuvReconFileList.size() );
+}
+
+Void  TAppDecTop::increaseNumberOfViews  (Int iNewNumberOfViews)
+{
+  while( m_acTVideoIOYuvReconFileList.size() < iNewNumberOfViews)
+  {
+    m_acTVideoIOYuvReconFileList.push_back(new TVideoIOYuv);
+
+// GT FIX
+    Char cBuffer[4]  ;
+    sprintf(cBuffer,"_%i",(Int)m_acTVideoIOYuvReconFileList.size()-1 );
+    Char* pchNextFilename;
+    xAppendToFileNameEnd( m_pchReconFile, cBuffer, pchNextFilename);
+// GT FIX END
+    if ( m_outputBitDepth == 0 )
+      m_outputBitDepth = g_uiBitDepth + g_uiBitIncrement;
+    m_acTVideoIOYuvReconFileList.back()->open( pchNextFilename, true, m_outputBitDepth, g_uiBitDepth + g_uiBitIncrement );
+    free (pchNextFilename);
+  }
+
+  while( m_aiPOCLastDisplayList.size() < iNewNumberOfViews )
+    m_aiPOCLastDisplayList.push_back(-1+m_iSkipFrame) ;
+
+  while( m_acTDecTopList.size() < iNewNumberOfViews)
+  {
+    m_acTDecTopList.push_back(new TDecTop) ;// at least one decoder
+    m_acTDecTopList.back()->create() ;
+    m_acTDecTopList.back()->init( this, false );
+    m_acTDecTopList.back()->setViewIdx((Int)m_acTDecTopList.size()-1);
+    m_acTDecTopList.back()->setPictureDigestEnabled(m_pictureDigestEnabled);
+    m_acTDecTopList.back()->setCamParsCollector( &m_cCamParsCollector );
+  }
+  if( m_bUsingDepth )
+  {
+    while( m_acTVideoIOYuvDepthReconFileList.size() < iNewNumberOfViews  )
+    {
+      m_acTVideoIOYuvDepthReconFileList.push_back(new TVideoIOYuv);
+// GT FIX
+      Char* pchTempFilename = NULL;
+      xAppendToFileNameEnd( m_pchReconFile, "_depth", pchTempFilename);
+      Char cBuffer[4]  ;
+      sprintf(cBuffer,"_%i",(Int)m_acTVideoIOYuvDepthReconFileList.size()-1 );
+      Char* pchDepthFilename = NULL;
+      xAppendToFileNameEnd( pchTempFilename, cBuffer, pchDepthFilename);
+// GT FIX END
+      if ( m_outputBitDepth == 0 )
+        m_outputBitDepth = g_uiBitDepth + g_uiBitIncrement;
+      m_acTVideoIOYuvDepthReconFileList.back()->open( pchDepthFilename, true, m_outputBitDepth, g_uiBitDepth + g_uiBitIncrement );
+      free (pchTempFilename);
+      free( pchDepthFilename );
+    }
+    while( m_aiDepthPOCLastDisplayList.size() < iNewNumberOfViews )
+      m_aiDepthPOCLastDisplayList.push_back(-1+m_iSkipFrame) ;
+    while( m_acTDecDepthTopList.size() < iNewNumberOfViews)
+    {
+      m_acTDecDepthTopList.push_back(new TDecTop) ;// at least one decoder
+      m_acTDecDepthTopList.back()->create() ;
+      m_acTDecDepthTopList.back()->init( this, false );
+      m_acTDecDepthTopList.back()->setViewIdx((Int)m_acTDecTopList.size()-1);
+      m_acTDecDepthTopList.back()->setPictureDigestEnabled(m_pictureDigestEnabled);
+      m_acTDecDepthTopList.back()->setToDepth( true );
+      m_acTDecDepthTopList.back()->setCamParsCollector( &m_cCamParsCollector );
+    }
+  }
+}
+
+
+// GT FIX
+std::vector<TComPic*> TAppDecTop::getSpatialRefPics( Int iViewIdx, Int iPoc, Bool bIsDepth ) // only for mvc functionality yet
+{
+  std::vector<TComPic*> apcRefPics( iViewIdx, (TComPic*)NULL );
+  for( int iRefViewIdx = 0; iRefViewIdx < iViewIdx; iRefViewIdx++ )
+  {
+    TComPic* pcRefPic = getPicFromView( iRefViewIdx, iPoc, bIsDepth );
+    assert( pcRefPic != NULL );
+    apcRefPics[iRefViewIdx] = pcRefPic;
+  }
+  return apcRefPics;
+}
+
+TComPic* TAppDecTop::getPicFromView( Int iViewIdx, Int iPoc, bool bIsDepth )
+{
+  TComList<TComPic*>* apcListPic = (bIsDepth ? m_acTDecDepthTopList[iViewIdx] : m_acTDecTopList[iViewIdx])->getListPic();
+  TComPic* pcRefPic = NULL;
+  for( TComList<TComPic*>::iterator it=apcListPic->begin(); it!=apcListPic->end(); it++ )
+  {
+    if( (*it)->getPOC() == iPoc )
+    {
+      pcRefPic = *it;
+      break;
+    }
+  }
+  return pcRefPic;
+}
Index: /tags/0.2r1/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- /tags/0.2r1/source/App/TAppDecoder/TAppDecTop.h	(revision 19)
+++ /tags/0.2r1/source/App/TAppDecoder/TAppDecTop.h	(revision 19)
@@ -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     TAppDecTop.h
+    \brief    Decoder application class (header)
+*/
+
+#ifndef __TAPPDECTOP__
+#define __TAPPDECTOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "../../Lib/TLibVideoIO/TVideoIOYuv.h"
+#include "../../Lib/TLibVideoIO/TVideoIOBits.h"
+#include "../../Lib/TLibCommon/TComList.h"
+#include "../../Lib/TLibCommon/TComPicYuv.h"
+#include "../../Lib/TLibCommon/TComBitStream.h"
+#include "../../Lib/TLibCommon/TComDepthMapGenerator.h"
+#include "../../Lib/TLibDecoder/TDecTop.h"
+#include "TAppDecCfg.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// decoder application class
+class TAppDecTop : public TAppDecCfg
+{
+private:
+  // class interface
+  std::vector<TDecTop*>           m_acTDecTopList;
+  std::vector<TDecTop*>           m_acTDecDepthTopList;
+  TComBitstream*                  m_apcBitstream;                 ///< bitstream class
+  TVideoIOBitsStartCode           m_cTVideoIOBitstreamFile;       ///< file I/O class
+  std::vector<TVideoIOYuv*>       m_acTVideoIOYuvReconFileList;
+  std::vector<TVideoIOYuv*>       m_acTVideoIOYuvDepthReconFileList;
+
+  Bool m_bUsingDepth;
+
+  // for output control
+  Bool                            m_abDecFlag[ MAX_GOP ];         ///< decoded flag in one GOP
+//  Int                             m_iPOCLastDisplay;              ///< last POC in display order
+
+  std::vector<Bool>               m_abDecFlagList;         ///< decoded flag in one GOP
+  std::vector<Int>                m_aiPOCLastDisplayList;
+  std::vector<Int>                m_aiDepthPOCLastDisplayList;
+
+  FILE*                           m_pScaleOffsetFile;
+  CamParsCollector                m_cCamParsCollector;
+#if DEPTH_MAP_GENERATION
+  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
+  Void  increaseNumberOfViews	(Int iNewNumberOfViews);
+  Void  startUsingDepth() ;
+
+// GT FIX
+  std::vector<TComPic*> getSpatialRefPics( Int iViewIdx, Int iPoc, Bool bIsDepth );
+  TComPic* getPicFromView( Int iViewIdx, Int iPoc, bool bDepth );
+// GT FIX END
+
+#if DEPTH_MAP_GENERATION
+  TComSPSAccess*    getSPSAccess  () { return &m_cSPSAccess;   }
+  TComAUPicAccess*  getAUPicAccess() { return &m_cAUPicAccess; }
+#endif
+
+protected:
+  Void  xCreateDecLib     (); ///< create internal classes
+  Void  xDestroyDecLib    (); ///< destroy internal classes
+  Void  xInitDecLib       (); ///< initialize decoder class
+
+  Void  xWriteOutput      ( TComList<TComPic*>* pcListPic ); ///< write YUV to file
+};
+
+#endif
+
Index: /tags/0.2r1/source/App/TAppDecoder/decmain.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppDecoder/decmain.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppDecoder/decmain.cpp	(revision 19)
@@ -0,0 +1,95 @@
+/* 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     decmain.cpp
+    \brief    Decoder application main
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include "TAppDecTop.h"
+
+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, "HM %s based Multiview Video plus Depth coder: Decoder Version [%s]", HM_VERSION, NV_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: /tags/0.2r1/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 19)
@@ -0,0 +1,1041 @@
+/* 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     TAppEncCfg.cpp
+    \brief    Handle encoder configuration parameters
+*/
+
+#include <stdlib.h>
+#include <math.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+#include "TAppEncCfg.h"
+#include "../../App/TAppCommon/program_options_lite.h"
+
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+/* 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
+#define MAX_INPUT_VIEW_NUM          10
+#define MAX_ERREF_VIEW_NUM          15
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncCfg::TAppEncCfg()
+{
+  m_aidQP = NULL;
+#if HHI_VSO
+  m_aaiERViewRefLutInd.resize( MAX_INPUT_VIEW_NUM );
+#endif
+}
+
+TAppEncCfg::~TAppEncCfg()
+{
+  if ( m_aidQP )
+  {
+    delete[] m_aidQP; m_aidQP = 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_pchERRefFileList.size(); i++ )
+  {
+    if ( m_pchERRefFileList[i] != NULL )
+      free (m_pchERRefFileList[i]);
+  }
+
+  if (m_pchBitstreamFile != NULL)
+    free (m_pchBitstreamFile) ;
+
+  for(Int i = 0; i< m_pchDepthReconFileList.size(); i++ )
+  {
+    if ( m_pchDepthReconFileList[i] != NULL )
+      free (m_pchDepthReconFileList[i]);
+  }
+
+  if (m_pchCameraParameterFile != NULL)
+    free (m_pchCameraParameterFile);
+
+  if (m_pchBaseViewCameraNumbers != NULL)
+    free (m_pchBaseViewCameraNumbers);
+
+#if HHI_VSO
+  if (  m_pchVSOConfig != NULL)
+    free (  m_pchVSOConfig );
+#endif
+
+}
+
+Void TAppEncCfg::create()
+{
+}
+
+Void TAppEncCfg::destroy()
+{
+}
+
+// ====================================================================================================================
+// 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_InputFile;
+  string cfg_BitstreamFile;
+  string cfg_ReconFile;
+  string cfg_dQPFile;
+  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_INPUT_VIEW_NUM , "original Yuv input file name %d")
+  ("DepthInputFile_%d,di_%d", m_pchDepthInputFileList,  (char *) 0 , MAX_INPUT_VIEW_NUM , "original Yuv depth input file name %d")
+  ("ReconFile_%d,o_%d",       m_pchReconFileList,       (char *) 0 , MAX_INPUT_VIEW_NUM , "reconstructed Yuv output file name %d")
+  ("DepthReconFile_%d,do_%d", m_pchDepthReconFileList,  (char *) 0 , MAX_INPUT_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)" )
+
+#ifdef WEIGHT_PRED
+  ("weighted_pred_flag,-wpP",     m_bUseWeightPred, false, "weighted prediction flag (P-Slices)")
+  ("weighted_bipred_idc,-wpBidc", m_uiBiPredIdc,    0u,    "weighted bipred idc (B-Slices)")
+#endif
+  ("SourceWidth,-wdt",      m_iSourceWidth,  0, "Source picture width")
+  ("SourceHeight,-hgt",     m_iSourceHeight, 0, "Source picture height")
+  ("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")
+#if ENABLE_IBDI
+  ("BitIncrement",          m_uiBitIncrement, 0xffffffffu, "bit-depth increasement")
+#endif
+  ("InternalBitDepth",      m_uiInternalBitDepth, 0u, "Internal bit-depth (BitDepth+BitIncrement)")
+  ("HorizontalPadding,-pdx",m_aiPad[0],      0, "horizontal source padding size")
+  ("VerticalPadding,-pdy",  m_aiPad[1],      0, "vertical source padding size")
+  ("PAD",                   m_bUsePAD,   false, "automatic source padding of multiple of 16" )
+  ("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, "depricated alias of FramesToBeEncoded")
+
+  ("NumberOfViews",         m_iNumberOfViews,    0, "Number of views")
+
+
+  /* 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 */
+  ("CodedPictureStoreSize,cpss",  m_uiCodedPictureStoreSize, 16u, "Size of coded picture Buffer")
+#if DCM_DECODING_REFRESH
+  ("DecodingRefreshType,-dr",m_iDecodingRefreshType, 0, "intra refresh, (0:none 1:CDR 2:IDR)")
+#endif
+  ("GOPSize,g",      m_iGOPSize,      1, "GOP size of temporal structure")
+  ("RateGOPSize,-rg",m_iRateGOPSize, -1, "GOP size of hierarchical QP assignment (-1: implies inherit GOPSize value)")
+#if !HHI_NO_LowDelayCoding
+  ("LowDelayCoding",         m_bUseLDC,             false, "low-delay mode")
+#endif
+#if DCM_COMB_LIST
+  ("ListCombination, -lc", m_bUseLComb, true, "combined reference list for uni-prediction in B-slices")
+  ("LCModification", m_bLCMod, false, "enables signalling of combined reference list derivation")
+#endif
+
+  ("GOPFormatString,gfs", m_cInputFormatString,  string(""), "Group of pictures")
+
+  /* motion options */
+  ("FastSearch", m_iFastSearch, 1, "0:Full search  1:Diamond  2:PMVFAST")
+  ("SearchRange,-sr",m_iSearchRange, 96, "motion search range")
+  ("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")
+  ("dQPFile,m",     m_pchdQPFile , (char*) 0, "dQP file name")
+  ("RDOQ",          m_abUseRDOQ, std::vector<Bool>(1,true), "Enable RDOQ")
+  ("TemporalLayerQPOffset_L0,-tq0", m_aiTLayerQPOffset[0], 0, "QP offset of temporal layer 0")
+  ("TemporalLayerQPOffset_L1,-tq1", m_aiTLayerQPOffset[1], 0, "QP offset of temporal layer 1")
+  ("TemporalLayerQPOffset_L2,-tq2", m_aiTLayerQPOffset[2], 0, "QP offset of temporal layer 2")
+  ("TemporalLayerQPOffset_L3,-tq3", m_aiTLayerQPOffset[3], 0, "QP offset of temporal layer 3")
+  ("TemporalLayerQPOffset_L4,-tq4", m_aiTLayerQPOffset[4], 0, "QP offset of temporal layer 3")
+  ("TemporalLayerQPOffset_L5,-tq5", m_aiTLayerQPOffset[5], 0, "QP offset of temporal layer 3")
+  ("TemporalLayerQPOffset_L6,-tq6", m_aiTLayerQPOffset[6], 0, "QP offset of temporal layer 3")
+  ("TemporalLayerQPOffset_L7,-tq7", m_aiTLayerQPOffset[7], 0, "QP offset of temporal layer 3")
+  ("TemporalLayerQPOffset_L8,-tq8", m_aiTLayerQPOffset[8], 0, "QP offset of temporal layer 3")
+  ("TemporalLayerQPOffset_L9,-tq9", m_aiTLayerQPOffset[9], 0, "QP offset of temporal layer 3")
+
+  /* Entropy coding parameters */
+  ("SymbolMode,-sym", m_iSymbolMode, 1, "symbol mode (0=VLC, 1=SBAC)")
+  ("SBACRD", m_bUseSBACRD, true, "SBAC based RD estimation")
+
+  /* Deblocking filter parameters */
+  ("LoopFilterDisable", m_abLoopFilterDisable, std::vector<Bool>(1,false), "Disables LoopFilter")
+  ("LoopFilterAlphaC0Offset", m_iLoopFilterAlphaC0Offset, 0)
+  ("LoopFilterBetaOffset", m_iLoopFilterBetaOffset, 0 )
+
+  /* Camera Paremetes */
+  ("CameraParameterFile,cpf", m_pchCameraParameterFile,    (Char *) 0, "Camera Parameter File Name")
+  ("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" )
+    // GT: For development, will be removed later
+  ("VSOMode",                         m_uiVSOMode               , (UInt)   4    , "VSO Mode")
+  ("LambdaScaleVSO",                  m_dLambdaScaleVSO         , (Double) 0.5  , "Lambda Scaling for VSO")
+    ("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
+
+    ("NumberOfExternalRefs",            m_iNumberOfExternalRefs   , 0             , "Number of virtual external reference views")
+    ("ERRefFile_%d,er_%d",              m_pchERRefFileList        , (char *) 0    , MAX_ERREF_VIEW_NUM , "virtual external reference view file name %d")
+    ("VSERViewReferences_%d,evr_%d"  ,  m_aaiERViewRefInd         , vector<Int>() , MAX_INPUT_VIEW_NUM, "Numbers of external virtual reference views to be used for this view")
+    ("VSBaseViewReferences_%d,bvr_%d",  m_aaiBaseViewRefInd       , vector<Int>() , MAX_INPUT_VIEW_NUM, "Numbers of external virtual reference views to be used for this view")
+#endif
+
+  /* Coding tools */
+  ("MRG", m_bUseMRG, true, "merging of motion partitions")
+
+#if LM_CHROMA
+  ("LMChroma", m_bUseLMChroma, true, "intra chroma prediction based on recontructed luma")
+#endif
+
+  ("ALF", m_abUseALF, std::vector<Bool>(1,true), "Enables ALF")
+#if MTK_SAO
+  ("SAO", m_abUseSAO, std::vector<Bool>(1, true), "SAO")
+#endif
+
+#if MQT_ALF_NPASS
+  ("ALFEncodePassReduction", m_iALFEncodePassReduction, 0, "0:Original 16-pass, 1: 1-pass, 2: 2-pass encoding")
+#endif
+#if HHI_RMP_SWITCH
+  ("RMP", m_bUseRMP ,true, "Rectangular motion partition" )
+#endif
+#ifdef ROUNDING_CONTROL_BIPRED
+  ("RoundingControlBipred", m_useRoundingControlBipred, false, "Rounding control for bi-prediction")
+#endif
+    ("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.")
+#if MTK_NONCROSS_INLOOP_FILTER
+    ("LFCrossSliceBoundaryFlag", m_bLFCrossSliceBoundaryFlag, true)
+#endif
+#if CONSTRAINED_INTRA_PRED
+  ("ConstrainedIntraPred", m_bUseConstrainedIntraPred, false, "Constrained Intra Prediction")
+#endif
+  /* Misc. */
+  ("SEIpictureDigest", m_pictureDigestEnabled, false, "Control generation of picture_digest SEI messages\n"
+                                              "\t1: use MD5\n"
+                                              "\t0: disable")
+  ("FEN", m_bUseFastEnc, false, "fast encoder setting")
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  ("DMM", m_bUseDMM, false, "add depth modes intra")
+#endif
+#if HHI_MPI
+  ("MVI", m_bUseMVI, false, "use motion vector inheritance for depth map coding")
+#endif
+
+  /* Multiview tools */
+#if DEPTH_MAP_GENERATION
+  ("PredDepthMapGen",  m_uiPredDepthMapGeneration, (UInt)0, "generation of prediction depth maps for motion data prediction" )
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  ("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 HHI_INTER_VIEW_RESIDUAL_PRED
+  ("MultiviewResPred", m_uiMultiviewResPredMode,   (UInt)0, "usage of inter-view residual prediction" )
+#endif
+
+  ("QpChangeFrame", m_iQpChangeFrame, PicOrderCnt(0), "start frame for QP change")
+  ("QpChangeOffsetVideo", m_iQpChangeOffsetVideo, 0, "QP change offset for video")
+  ("QpChangeOffsetDepth", m_iQpChangeOffsetDepth, 0, "QP change offset for depth")
+#if HHI_INTERVIEW_SKIP
+  ("InterViewSkip",  m_uiInterViewSkip,    (UInt)0, "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")
+  ;
+
+  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());
+
+
+// GT FIX
+  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;
+      }
+    };
+  }
+// GT FIX END
+
+  if (m_iRateGOPSize == -1)
+  {
+    /* if rateGOPSize has not been specified, the default value is GOPSize */
+    m_iRateGOPSize = m_iGOPSize;
+  }
+
+  // compute source padding size
+  if ( m_bUsePAD )
+  {
+    if ( m_iSourceWidth%MAX_PAD_SIZE )
+    {
+      m_aiPad[0] = (m_iSourceWidth/MAX_PAD_SIZE+1)*MAX_PAD_SIZE - m_iSourceWidth;
+    }
+
+    if ( m_iSourceHeight%MAX_PAD_SIZE )
+    {
+      m_aiPad[1] = (m_iSourceHeight/MAX_PAD_SIZE+1)*MAX_PAD_SIZE - m_iSourceHeight;
+    }
+  }
+  m_iSourceWidth  += m_aiPad[0];
+  m_iSourceHeight += m_aiPad[1];
+
+//GT QP Depth
+  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] ) );
+  }
+//GT QP Depth end
+
+#if HHI_VSO
+  m_bUseVSO = m_bUseVSO && m_bUsingDepthMaps && (m_uiVSOMode != 0);
+#endif
+
+  xCleanUpVectors();
+
+#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 ( m_bUseVSO )
+  {
+    if ( m_iNumberOfExternalRefs != 0 )
+    {
+      xCleanUpVector( m_aaiERViewRefInd,    vector<Int>() );
+      xCleanUpVector( m_aaiBaseViewRefInd,  vector<Int>() );
+    }
+    else
+    {
+      m_aaiERViewRefInd   .clear();
+      m_aaiERViewRefInd   .resize( m_iNumberOfViews );
+      m_aaiERViewRefLutInd.clear();
+      m_aaiERViewRefLutInd.resize( m_iNumberOfViews );
+      m_aaiBaseViewRefInd .clear();
+      m_aaiBaseViewRefInd .resize( m_iNumberOfViews );
+    }
+  }
+#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
+  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
+
+
+  // check validity of input parameters
+  xCheckParameter();
+  m_cCameraData.check( false, true );
+
+  // 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
+#if ENABLE_IBDI
+  xConfirmPara( m_uiInternalBitDepth > 0 && (int)m_uiBitIncrement != -1,                    "InternalBitDepth and BitIncrement may not be specified simultaneously");
+#else
+  xConfirmPara( m_uiInputBitDepth < 8,                                                      "InputBitDepth must be at least 8" );
+#endif
+  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
+  xConfirmPara( m_iFrameToBeEncoded <= 0,                                                   "Total Number Of Frames encoded must be more than 1" );
+  xConfirmPara( m_iGOPSize < 1 ,                                                            "GOP Size must be more than 1" );
+#if DCM_DECODING_REFRESH
+  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 2,                   "Decoding Refresh Type must be equal to 0, 1 or 2" );
+#endif
+//GT QP Depth
+  xConfirmPara( m_aiQP[0] < 0 || m_aiQP[0] > 51,                                             "QP exceeds supported range (0 to 51)" );
+  if ( m_aiQP.size() >= 2 )
+  {
+    xConfirmPara( m_aiQP[1] < 0 || m_aiQP[1] > 51,                                           "QP Depth exceeds supported range (0 to 51)" );
+  }
+//GT QP Depth End
+#if MQT_ALF_NPASS
+  xConfirmPara( m_iALFEncodePassReduction < 0 || m_iALFEncodePassReduction > 2,             "ALFEncodePassReduction must be equal to 0, 1 or 2");
+#endif
+  xConfirmPara( m_iLoopFilterAlphaC0Offset < -26 || m_iLoopFilterAlphaC0Offset > 26,        "Loop Filter Alpha Offset exceeds supported range (-26 to 26)" );
+  xConfirmPara( m_iLoopFilterBetaOffset < -26 || m_iLoopFilterBetaOffset > 26,              "Loop Filter Beta Offset exceeds supported range (-26 to 26)");
+  xConfirmPara( m_iFastSearch < 0 || m_iFastSearch > 2,                                     "Fast Search Mode is not supported value (0:Full search  1:Diamond  2:PMVFAST)" );
+  xConfirmPara( m_iSearchRange < 0 ,                                                        "Search Range must be more than 0" );
+  xConfirmPara( m_bipredSearchRange < 0 ,                                                   "Search Range must be more than 0" );
+  xConfirmPara( m_iMaxDeltaQP > 7,                                                          "Absolute Delta QP exceeds supported range (0 to 7)" );
+  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,             "Frame width should be multiple of minimum CU size");
+  xConfirmPara( (m_iSourceHeight % (m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)))!=0,             "Frame height should be multiple of 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_iSliceMode < 0 || m_iSliceMode > 2, "SliceMode exceeds supported range (0 to 2)" );
+  if (m_iSliceMode!=0)
+  {
+    xConfirmPara( m_iSliceArgument < 1 ,         "SliceArgument should be larger than or equal to 1" );
+  }
+  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_iSymbolMode < 0 || m_iSymbolMode > 1,                                     "SymbolMode must be equal to 0 or 1" );
+
+  // Check MultiView stuff
+  xConfirmPara    ( m_iNumberOfViews > MAX_INPUT_VIEW_NUM ,                           "NumberOfViews must be less than or equal to MAX_INPUT_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 DEPTH_MAP_GENERATION
+  xConfirmPara    ( m_uiPredDepthMapGeneration > 3,                                   "PredDepthMapGen must be less than or equal to 3" );
+  xConfirmPara    ( m_uiPredDepthMapGeneration >= 2 && !m_bUsingDepthMaps,            "PredDepthMapGen >= 2 requires CodeDepthMaps = 1" );
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  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 HHI_INTER_VIEW_RESIDUAL_PRED
+  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 HHI_INTERVIEW_SKIP
+  xConfirmPara    ( m_uiInterViewSkip > 1,                                        "RenderingSkipMode > 1 not supported" );
+  xConfirmPara    ( m_uiInterViewSkip > 0 && !m_bUsingDepthMaps,                  "RenderingSkipMode > 0 requires CodeDepthMaps = 1" );
+#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 < 0 || m_uiVSOMode > 4 ,                             "VSO Mode must be greater than or equal to 0 and less than 5");
+      xConfirmPara( m_iNumberOfExternalRefs               > MAX_ERREF_VIEW_NUM,      "NumberOfExternalRefs must be less than of equal to TAppMVEncCfg::MAX_ERREF_VIEW_NUM" );
+      xConfirmPara( Int( m_pchERRefFileList .size() ) < m_iNumberOfExternalRefs,     "Number of ERRefFileFiles  must be greater than or equal to NumberOfExternalRefs" );
+    }
+#endif
+  }
+
+#if DCM_COMB_LIST
+#if !HHI_NO_LowDelayCoding
+  xConfirmPara( m_bUseLComb==false && m_bUseLDC==false,         "LComb can only be 0 if LowDelayCoding is 1" );
+#else
+  xConfirmPara( m_bUseLComb==false,                             "LComb can only be 0 if LowDelayCoding is 1" );
+#endif
+#endif
+
+  // 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");
+  }
+
+  // SBACRD is supported only for SBAC
+  if ( m_iSymbolMode == 0 )
+  {
+    m_bUseSBACRD = false;
+  }
+
+#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 );
+
+#if HHI_VSO
+  if ( m_bUseVSO)
+  {
+    xCleanUpVector( m_pchERRefFileList,       (char*)0 );
+  }
+#endif
+}
+
+/** \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 ENABLE_IBDI
+  if ((int)m_uiBitIncrement != -1)
+  {
+    g_uiBitDepth = m_uiInputBitDepth;
+    g_uiBitIncrement = m_uiBitIncrement;
+    m_uiInternalBitDepth = g_uiBitDepth + g_uiBitIncrement;
+  }
+  else
+  {
+    g_uiBitDepth = min(8u, m_uiInputBitDepth);
+    if (m_uiInternalBitDepth == 0) {
+      /* default increement = 2 */
+      m_uiInternalBitDepth = 2 + g_uiBitDepth;
+    }
+    g_uiBitIncrement = m_uiInternalBitDepth - g_uiBitDepth;
+  }
+#else
+#if FULL_NBIT
+  g_uiBitDepth = m_uiInternalBitDepth;
+  g_uiBitIncrement = 0;
+#else
+  g_uiBitDepth = 8;
+  g_uiBitIncrement = m_uiInternalBitDepth - g_uiBitDepth;
+#endif
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  g_dDeltaDCsQuantOffset = Double(g_uiBitIncrement) -  2.0;
+#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;
+  }
+}
+
+Void TAppEncCfg::xPrintParameter()
+{
+  printf("\n");
+  for( Int iCounter = 0; iCounter<m_iNumberOfViews; iCounter++)
+  {
+    printf("Input          File %i        : %s\n", iCounter, m_pchInputFileList[iCounter]);
+  }
+  for( Int iCounter = 0; iCounter < (Int)m_pchDepthInputFileList.size(); iCounter++)
+  {
+    printf("DepthInput     File %i        : %s\n", iCounter, m_pchDepthInputFileList[iCounter]);
+  }
+  printf("Bitstream      File          : %s\n", m_pchBitstreamFile      );
+  for( Int iCounter = 0; iCounter<m_iNumberOfViews; iCounter++)
+  {
+    printf("Reconstruction File %i        : %s\n", iCounter, m_pchReconFileList[iCounter]);
+  }
+
+  for( Int iCounter = 0; iCounter<(Int)m_pchDepthReconFileList.size(); iCounter++)
+  {
+    printf("Reconstruction Depth File %i  : %s\n", iCounter, m_pchDepthReconFileList[iCounter]);
+  }
+  printf("Real     Format              : %dx%d %dHz\n", m_iSourceWidth - m_aiPad[0], m_iSourceHeight-m_aiPad[1], 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("Motion search range          : %d\n", m_iSearchRange );
+#if DCM_DECODING_REFRESH
+  printf("Decoding refresh type        : %d\n", m_iDecodingRefreshType );
+#endif
+  printf("QP                           : %5.2f\n", m_adQP[0] );
+  printf("QP Depth                     : %5.2f\n", m_adQP[ m_adQP.size()  < 2 ? 0 : 1] );
+  printf("Coded Picture Store Size     : %d\n", m_uiCodedPictureStoreSize);
+  printf("GOP size                     : %d\n", m_iGOPSize );
+  printf("Rate GOP size                : %d\n", m_iRateGOPSize );
+  printf("Internal bit depth           : %d\n", m_uiInternalBitDepth );
+
+  if ( m_iSymbolMode == 0 )
+  {
+    printf("Entropy coder                : VLC\n");
+  }
+  else if( m_iSymbolMode == 1 )
+  {
+    printf("Entropy coder                : CABAC\n");
+  }
+  else if( m_iSymbolMode == 2 )
+  {
+    printf("Entropy coder                : PIPE\n");
+  }
+  else
+  {
+    assert(0);
+  }
+
+  printf("GOP Format String            : %s\n", m_cInputFormatString.c_str() );
+  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
+  }
+#endif
+
+
+  printf("\n");
+
+  printf("TOOL CFG GENERAL: ");
+  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("PAD:%d ", m_bUsePAD             );
+  printf("LDC:%d ", m_bUseLDC             );
+#if DCM_COMB_LIST
+  printf("LComb:%d ", m_bUseLComb         );
+  printf("LCMod:%d ", m_bLCMod         );
+#endif
+  printf("FEN:%d ", m_bUseFastEnc         );
+  printf("RQT:%d ", 1     );
+  printf("MRG:%d ", m_bUseMRG             ); // SOPH: Merge Mode
+#if LM_CHROMA
+  printf("LMC:%d ", m_bUseLMChroma        );
+#endif
+#if HHI_RMP_SWITCH
+  printf("RMP:%d ", m_bUseRMP);
+#endif
+  printf("Slice:%d ",m_iSliceMode);
+  if (m_iSliceMode!=0)
+  {
+    printf("(%d) ", m_iSliceArgument);
+  }
+  printf("EntropySlice:%d ",m_iEntropySliceMode);
+  if (m_iEntropySliceMode!=0)
+  {
+    printf("(%d) ", m_iEntropySliceArgument);
+  }
+#if CONSTRAINED_INTRA_PRED
+  printf("CIP:%d ", m_bUseConstrainedIntraPred);
+#endif
+#if MTK_SAO
+#endif
+  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) );
+  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 HHI_VSO
+  printf("VSO:%d ", m_bUseVSO             );
+#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
+  printf("\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( "                   MRG - merging of motion partitions\n"); // SOPH: Merge Mode
+
+#if LM_CHROMA
+  printf( "                   LMC - intra chroma prediction based on luma\n");
+#endif
+
+  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: /tags/0.2r1/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- /tags/0.2r1/source/App/TAppEncoder/TAppEncCfg.h	(revision 19)
+++ /tags/0.2r1/source/App/TAppEncoder/TAppEncCfg.h	(revision 19)
@@ -0,0 +1,286 @@
+/* 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     TAppEncCfg.h
+    \brief    Handle encoder configuration parameters (header)
+*/
+
+#ifndef __TAPPENCCFG__
+#define __TAPPENCCFG__
+
+#include "../../Lib/TLibCommon/CommonDef.h"
+#include "../../Lib/TLibCommon/TComMVDRefData.h"
+#include "../../App/TAppCommon/TAppComCamPara.h"
+#include "../../Lib/TLibRenderer/TRenTop.h"
+#include "../../Lib/TLibRenderer/TRenModel.h"
+#include "../../Lib/TLibRenderer/TRenModSetupStrParser.h"
+
+#include <string>
+#include <vector>
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TAppEncCfg
+{
+protected:
+  // file I/O
+  char*     m_pchBitstreamFile;                               ///< output bitstream file
+
+  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
+
+  std::vector<char*>     m_pchERRefFileList;                  ///< virtual external reference view files names
+
+  // 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_iFrameToBeEncoded;                              ///< number of encoded frames
+  Bool      m_bUsePAD;                                        ///< flag for using source padding
+  Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+
+  Int       m_iNumberOfViews;                                ///< number Views to Encode
+  Bool      m_bUsingDepthMaps ;
+
+
+  // coding structure
+#if DCM_DECODING_REFRESH
+  Int       m_iDecodingRefreshType;                           ///< random access type
+#endif
+  UInt      m_uiCodedPictureStoreSize ;
+  Int       m_iGOPSize;                                       ///< GOP size of hierarchical structure
+  Int       m_iRateGOPSize;                                   ///< GOP size for QP variance
+#if !HHI_NO_LowDelayCoding
+  Bool      m_bUseLDC;                                        ///< flag for using low-delay coding mode
+#endif
+#if DCM_COMB_LIST
+  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
+#endif
+  std::string     m_cInputFormatString ;                            // GOP string
+  // 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)
+
+  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_iMaxDeltaQP;                                    ///< max. |delta QP|
+  UInt      m_uiDeltaQpRD;                                    ///< dQP range for multi-pass slice QP optimization
+
+  // 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
+#ifdef ENABLE_IBDI
+  UInt      m_uiBitIncrement;                                 ///< bit-depth increment
+#endif
+  UInt      m_uiInternalBitDepth;                             ///< Internal bit-depth (BitDepth+BitIncrement)
+
+#if MTK_SAO
+  vector<Bool> m_abUseSAO;
+#endif
+
+  // coding tools (loop filter)
+  vector<Bool> m_abUseALF;                                    ///< flag for using adaptive loop filter [0] - video, [1] - depth
+#ifdef MQT_ALF_NPASS
+  Int       m_iALFEncodePassReduction;                        ///< ALF encoding pass, 0 = original 16-pass, 1 = 1-pass, 2 = 2-pass
+#endif
+
+  vector<Bool> m_abLoopFilterDisable;                         ///< flag for using deblocking filter filter [0] - video, [1] - depth
+  Int       m_iLoopFilterAlphaC0Offset;                       ///< alpha offset for deblocking filter
+  Int       m_iLoopFilterBetaOffset;                          ///< beta offset for deblocking filter
+
+  // coding tools (entropy coder)
+  Int       m_iSymbolMode;                                    ///< entropy coder mode, 0 = VLC, 1 = CABAC
+
+  // coding tools (inter - merge motion partitions)
+  Bool      m_bUseMRG;                                        ///< SOPH: flag for using motion partition Merge Mode
+
+#if LM_CHROMA
+  Bool      m_bUseLMChroma;                                  ///< JL: Chroma intra prediction based on luma signal
+#endif
+
+#if HHI_RMP_SWITCH
+  Bool      m_bUseRMP;
+#endif
+
+  // 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
+  Int       m_bipredSearchRange;                              ///< ME search range for bipred refinement
+  Bool      m_bUseFastEnc;                                    ///< flag for using fast encoder setting
+
+#if DEPTH_MAP_GENERATION
+  UInt      m_uiPredDepthMapGeneration;                       ///< using of (virtual) depth maps for texture coding
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  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 HHI_INTER_VIEW_RESIDUAL_PRED
+  UInt      m_uiMultiviewResPredMode;                         ///< using multiview residual prediction
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  UInt      m_uiInterViewSkip;                            ///< 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
+
+  // camera parameter
+  Char*     m_pchCameraParameterFile;                         ///< camera parameter file
+  Char*     m_pchBaseViewCameraNumbers;
+  TAppComCamPara m_cCameraData;
+
+  Int       m_iCodedCamParPrecision;                          ///< precision for coding of camera parameters
+
+#if HHI_INTERVIEW_SKIP
+  TRenTop  m_cUsedPelsRenderer;                               ///< renderer for used pels map
+#endif
+
+#if HHI_VSO
+  Char*     m_pchVSOConfig;
+  Bool      m_bUseVSO;                                    ///< flag for using View Synthesis Optimization
+
+  //// 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
+  Int       m_iNumberOfExternalRefs;                      ///< number Virtual External Reference Views
+  std::vector< std::vector<Int> > m_aaiBaseViewRefInd;    ///< View numbers of Base View References
+  std::vector< std::vector<Int> > m_aaiERViewRefInd;      ///< View numbers of External ViewReferences
+  std::vector< std::vector<Int> > m_aaiERViewRefLutInd;   ///< Indices of LUTs used for External View References
+#endif
+
+  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.
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  Bool m_bLFCrossSliceBoundaryFlag;  ///< 0: Cross-slice-boundary in-loop filtering 1: non-cross-slice-boundary in-loop filtering
+#endif
+#ifdef ROUNDING_CONTROL_BIPRED
+  Bool m_useRoundingControlBipred;
+#endif
+#if CONSTRAINED_INTRA_PRED
+  Bool      m_bUseConstrainedIntraPred;                       ///< flag for using constrained intra prediction
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool      m_bUseDMM;
+#endif
+#if HHI_MPI
+  Bool      m_bUseMVI;  ///< flag for using Motion Vector Inheritance for depth map coding
+#endif
+
+  PicOrderCnt m_iQpChangeFrame;
+  Int         m_iQpChangeOffsetVideo;
+  Int         m_iQpChangeOffsetDepth;
+
+  bool m_pictureDigestEnabled; ///< enable(1)/disable(0) md5 computation and SEI signalling
+
+  //====== Weighted Prediction ========
+#ifdef WEIGHT_PRED
+  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)
+#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
+
+  // util
+  Void  xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char* & rpchOutputFileName);
+  Bool  xConfirmParameter(Bool bflag, const char* message);
+
+
+  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: /tags/0.2r1/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppEncoder/TAppEncTop.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppEncoder/TAppEncTop.cpp	(revision 19)
@@ -0,0 +1,1309 @@
+/* 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     TAppEncTop.cpp
+    \brief    Encoder application class
+*/
+
+#include <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppEncTop.h"
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncTop::TAppEncTop()
+{
+#if HHI_VSO
+  m_iLastFramePutInERViewBuffer = -1;
+#endif
+}
+
+TAppEncTop::~TAppEncTop()
+{
+}
+
+
+Void TAppEncTop::xInitLibCfg()
+{
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+  {
+    m_iFrameRcvdVector.push_back(0) ;
+    m_acTEncTopList.push_back(new TEncTop);
+
+    m_acTVideoIOYuvInputFileList.push_back(new TVideoIOYuv);
+
+    m_acTVideoIOYuvReconFileList.push_back(new TVideoIOYuv);
+    m_cListPicYuvRecList.push_back(new TComList<TComPicYuv*>) ;
+    m_aiNextPocToDump.push_back( 0 );
+    m_cListPicYuvRecMap.push_back( std::map<PicOrderCnt,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]->setFrameToBeEncoded             ( m_iFrameToBeEncoded );
+
+  //====== Coding Structure ========
+#if DCM_DECODING_REFRESH
+    m_acTEncTopList[iViewIdx]->setDecodingRefreshType          ( m_iDecodingRefreshType );
+#endif
+    m_acTEncTopList[iViewIdx]->setCPSSize                      ( m_uiCodedPictureStoreSize );
+    m_acTEncTopList[iViewIdx]->setGOPSize                      ( m_iGOPSize );
+    m_acTEncTopList[iViewIdx]->setRateGOPSize                  ( m_iRateGOPSize );
+
+    m_acTEncTopList[iViewIdx]->setSeqStructure                              ( m_cInputFormatString );
+
+    m_acTEncTopList[iViewIdx]->setQP                           ( m_aiQP[0] );
+
+    m_acTEncTopList[iViewIdx]->setTemporalLayerQPOffset        ( m_aiTLayerQPOffset );
+    m_acTEncTopList[iViewIdx]->setPad                          ( m_aiPad );
+
+    //===== Slice ========
+
+    //====== Entropy Coding ========
+    m_acTEncTopList[iViewIdx]->setSymbolMode                   ( m_iSymbolMode );
+
+    //====== Loop/Deblock Filter ========
+    m_acTEncTopList[iViewIdx]->setLoopFilterDisable            ( m_abLoopFilterDisable[0]   );
+    m_acTEncTopList[iViewIdx]->setLoopFilterAlphaC0Offset      ( m_iLoopFilterAlphaC0Offset );
+    m_acTEncTopList[iViewIdx]->setLoopFilterBetaOffset         ( m_iLoopFilterBetaOffset    );
+
+    //====== Motion search ========
+    m_acTEncTopList[iViewIdx]->setFastSearch                   ( m_iFastSearch  );
+    m_acTEncTopList[iViewIdx]->setSearchRange                  ( m_iSearchRange );
+    m_acTEncTopList[iViewIdx]->setBipredSearchRange            ( m_bipredSearchRange );
+    m_acTEncTopList[iViewIdx]->setMaxDeltaQP                   ( m_iMaxDeltaQP  );
+
+#if HHI_VSO
+    //====== VSO =========
+    m_acTEncTopList[iViewIdx]->setForceLambdaScaleVSO          ( false );
+    m_acTEncTopList[iViewIdx]->setLambdaScaleVSO               ( 1     );
+    m_acTEncTopList[iViewIdx]->setVSOMode                      ( 0     );
+#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]  );
+#if MQT_ALF_NPASS
+    m_acTEncTopList[iViewIdx]->setALFEncodePassReduction       ( m_iALFEncodePassReduction );
+#endif
+#if DCM_COMB_LIST
+    m_acTEncTopList[iViewIdx]->setUseLComb                     ( m_bUseLComb    );
+    m_acTEncTopList[iViewIdx]->setLCMod                        ( m_bLCMod         );
+#endif
+    m_acTEncTopList[iViewIdx]->setdQPs                         ( m_aidQP        );
+    m_acTEncTopList[iViewIdx]->setUseRDOQ                      ( m_abUseRDOQ[0] );
+    m_acTEncTopList[iViewIdx]->setUseLDC                       ( m_bUseLDC      );
+    m_acTEncTopList[iViewIdx]->setUsePAD                       ( m_bUsePAD      );
+    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  );
+
+#if HHI_VSO
+    m_acTEncTopList[iViewIdx]->setUseVSO                       ( false ); //GT: might be enabled later for VSO Mode 4
+#endif
+
+    m_acTEncTopList[iViewIdx]->setViewId                       ( (UInt)iViewIdx );
+    m_acTEncTopList[iViewIdx]->setViewOrderIdx                 ( m_cCameraData.getViewOrderIndex()[ iViewIdx ] );
+    m_acTEncTopList[iViewIdx]->setIsDepth                      ( false );
+    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            () );
+#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 HHI_INTER_VIEW_MOTION_PRED
+    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 HHI_INTER_VIEW_RESIDUAL_PRED
+    m_acTEncTopList[iViewIdx]->setMultiviewResPredMode         ( m_uiMultiviewResPredMode );
+#endif
+
+
+#if HHI_INTERVIEW_SKIP
+    m_acTEncTopList[iViewIdx]->setInterViewSkip            ( iViewIdx ? m_uiInterViewSkip : 0 );
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+    m_acTEncTopList[iViewIdx]->setInterViewSkipLambdaScale ( iViewIdx ? (Int)m_dInterViewSkipLambdaScale : 1 );
+#endif
+#endif
+    m_acTEncTopList[iViewIdx]->setUseMRG                       ( m_bUseMRG      ); // SOPH:
+
+#if LM_CHROMA
+    m_acTEncTopList[iViewIdx]->setUseLMChroma                  ( m_bUseLMChroma );
+#endif
+
+#if HHI_RMP_SWITCH
+    m_acTEncTopList[iViewIdx]->setUseRMP                     ( m_bUseRMP );
+#endif
+#ifdef ROUNDING_CONTROL_BIPRED
+    m_acTEncTopList[iViewIdx]->setUseRoundingControlBipred(m_useRoundingControlBipred);
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    m_acTEncTopList[iViewIdx]->setUseDMM( false );
+#endif
+#if CONSTRAINED_INTRA_PRED
+    m_acTEncTopList[iViewIdx]->setUseConstrainedIntraPred      ( m_bUseConstrainedIntraPred );
+#endif
+#ifdef WEIGHT_PRED
+    //====== Weighted Prediction ========
+    m_acTEncTopList[iViewIdx]->setUseWP                         ( m_bUseWeightPred      );
+    m_acTEncTopList[iViewIdx]->setWPBiPredIdc                   ( m_uiBiPredIdc         );
+#endif
+    //====== 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     );
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(m_iSliceMode == 0 )
+    {
+      m_bLFCrossSliceBoundaryFlag = true;
+    }
+    m_acTEncTopList[iViewIdx]->setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+#endif
+#if MTK_SAO
+    m_acTEncTopList[iViewIdx]->setUseSAO               ( m_abUseSAO[0]     );
+#endif
+#if HHI_MPI
+    m_acTEncTopList[iViewIdx]->setUseMVI( false );
+#endif
+
+    m_acTEncTopList[iViewIdx]->setPictureDigestEnabled(m_pictureDigestEnabled);
+    m_acTEncTopList[iViewIdx]->setQpChangeFrame( m_iQpChangeFrame );
+    m_acTEncTopList[iViewIdx]->setQpChangeOffsetVideo( m_iQpChangeOffsetVideo );
+    m_acTEncTopList[iViewIdx]->setQpChangeOffsetDepth( m_iQpChangeOffsetDepth );
+  }
+  if( m_bUsingDepthMaps )
+  {
+
+#if HHI_VSO
+    for (Int iViewIdx=0; iViewIdx<m_iNumberOfExternalRefs; iViewIdx++)
+    {
+        m_acTVideoIOYuvERFileList.push_back(new TVideoIOYuv);
+    }
+#endif
+
+    for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+    {
+      m_iDepthFrameRcvdVector.push_back(0) ;
+      m_acTEncDepthTopList.push_back(new TEncTop);
+
+      m_acTVideoIOYuvDepthInputFileList.push_back(new TVideoIOYuv);
+
+      m_acTVideoIOYuvDepthReconFileList.push_back(new TVideoIOYuv);
+      m_cListPicYuvDepthRecList.push_back(new TComList<TComPicYuv*>) ;
+      m_aiNextDepthPocToDump.push_back( 0 );
+      m_cListPicYuvDepthRecMap.push_back( std::map<PicOrderCnt,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]->setFrameToBeEncoded             ( m_iFrameToBeEncoded );
+
+      //====== Coding Structure ========
+#if DCM_DECODING_REFRESH
+      m_acTEncDepthTopList[iViewIdx]->setDecodingRefreshType          ( m_iDecodingRefreshType );
+#endif
+      m_acTEncDepthTopList[iViewIdx]->setCPSSize                      ( m_uiCodedPictureStoreSize );
+      m_acTEncDepthTopList[iViewIdx]->setGOPSize                      ( m_iGOPSize );
+      m_acTEncDepthTopList[iViewIdx]->setRateGOPSize                  ( m_iRateGOPSize );
+
+      m_acTEncDepthTopList[iViewIdx]->setSeqStructure                              ( m_cInputFormatString );
+
+      m_acTEncDepthTopList[iViewIdx]->setQP                           ( m_aiQP[1] );
+
+      m_acTEncDepthTopList[iViewIdx]->setTemporalLayerQPOffset        ( m_aiTLayerQPOffset );
+      m_acTEncDepthTopList[iViewIdx]->setPad                          ( m_aiPad );
+
+      //===== Slice ========
+
+      //====== Entropy Coding ========
+      m_acTEncDepthTopList[iViewIdx]->setSymbolMode                   ( m_iSymbolMode );
+
+      //====== Loop/Deblock Filter ========
+      m_acTEncDepthTopList[iViewIdx]->setLoopFilterDisable            ( m_abLoopFilterDisable[1]   );
+      m_acTEncDepthTopList[iViewIdx]->setLoopFilterAlphaC0Offset      ( m_iLoopFilterAlphaC0Offset );
+      m_acTEncDepthTopList[iViewIdx]->setLoopFilterBetaOffset         ( m_iLoopFilterBetaOffset    );
+
+      //====== Motion search ========
+      m_acTEncDepthTopList[iViewIdx]->setFastSearch                   ( m_iFastSearch  );
+      m_acTEncDepthTopList[iViewIdx]->setSearchRange                  ( m_iSearchRange );
+      m_acTEncDepthTopList[iViewIdx]->setBipredSearchRange            ( m_bipredSearchRange );
+      m_acTEncDepthTopList[iViewIdx]->setMaxDeltaQP                   ( m_iMaxDeltaQP  );
+
+      //====== 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]  );
+#if MQT_ALF_NPASS
+      m_acTEncDepthTopList[iViewIdx]->setALFEncodePassReduction       ( m_iALFEncodePassReduction );
+#endif
+#if DCM_COMB_LIST
+      m_acTEncDepthTopList[iViewIdx]->setUseLComb                     ( m_bUseLComb    );
+      m_acTEncDepthTopList[iViewIdx]->setLCMod                        ( m_bLCMod         );
+#endif
+      m_acTEncDepthTopList[iViewIdx]->setdQPs                         ( m_aidQP        );
+      m_acTEncDepthTopList[iViewIdx]->setUseRDOQ                      ( m_abUseRDOQ[1] );
+      m_acTEncDepthTopList[iViewIdx]->setUseLDC                       ( m_bUseLDC      );
+      m_acTEncDepthTopList[iViewIdx]->setUsePAD                       ( m_bUsePAD      );
+      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  );
+
+#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 );
+#endif
+
+      m_acTEncDepthTopList[iViewIdx]->setViewId                       ( (UInt)iViewIdx );
+      m_acTEncDepthTopList[iViewIdx]->setViewOrderIdx                 ( m_cCameraData.getViewOrderIndex()[ iViewIdx ] );
+      m_acTEncDepthTopList[iViewIdx]->setIsDepth                      ( true );
+      m_acTEncDepthTopList[iViewIdx]->setCamParPrecision              ( 0 );
+      m_acTEncDepthTopList[iViewIdx]->setCamParInSliceHeader          ( false );
+      m_acTEncDepthTopList[iViewIdx]->setCodedScale                   ( 0 );
+      m_acTEncDepthTopList[iViewIdx]->setCodedOffset                  ( 0 );
+#if DEPTH_MAP_GENERATION
+      m_acTEncDepthTopList[iViewIdx]->setPredDepthMapGeneration       ( 0 );
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+      m_acTEncDepthTopList[iViewIdx]->setMultiviewMvPredMode          ( 0 );
+      m_acTEncDepthTopList[iViewIdx]->setMultiviewMvRegMode           ( 0 );
+      m_acTEncDepthTopList[iViewIdx]->setMultiviewMvRegLambdaScale    ( 0.0 );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      m_acTEncDepthTopList[iViewIdx]->setMultiviewResPredMode         ( 0 );
+#endif
+
+#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]->setUseMRG                       ( m_bUseMRG      ); // SOPH:
+
+#if LM_CHROMA
+      m_acTEncDepthTopList[iViewIdx]->setUseLMChroma                  ( m_bUseLMChroma );
+#endif
+
+#if HHI_RMP_SWITCH
+      m_acTEncDepthTopList[iViewIdx]->setUseRMP                     ( m_bUseRMP );
+#endif
+#ifdef ROUNDING_CONTROL_BIPRED
+      m_acTEncDepthTopList[iViewIdx]->setUseRoundingControlBipred(m_useRoundingControlBipred);
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      m_acTEncDepthTopList[iViewIdx]->setUseDMM( m_bUseDMM );
+#endif
+#if CONSTRAINED_INTRA_PRED
+      m_acTEncDepthTopList[iViewIdx]->setUseConstrainedIntraPred      ( m_bUseConstrainedIntraPred );
+#endif
+#ifdef WEIGHT_PRED
+    //====== Weighted Prediction ========
+      m_acTEncDepthTopList[iViewIdx]->setUseWP                         ( m_bUseWeightPred      );
+      m_acTEncDepthTopList[iViewIdx]->setWPBiPredIdc                   ( m_uiBiPredIdc         );
+#endif
+      //====== 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     );
+#if MTK_NONCROSS_INLOOP_FILTER
+      if(m_iSliceMode == 0 )
+      {
+        m_bLFCrossSliceBoundaryFlag = true;
+      }
+      m_acTEncDepthTopList[iViewIdx]->setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+#endif
+#if MTK_SAO
+      m_acTEncDepthTopList[iViewIdx]->setUseSAO               ( m_abUseSAO[1]     );
+#endif
+#if HHI_MPI
+      m_acTEncDepthTopList[iViewIdx]->setUseMVI( m_bUseMVI );
+#endif
+
+      m_acTEncDepthTopList[iViewIdx]->setPictureDigestEnabled(m_pictureDigestEnabled);
+
+      m_acTEncDepthTopList[iViewIdx]->setQpChangeFrame( m_iQpChangeFrame );
+      m_acTEncDepthTopList[iViewIdx]->setQpChangeOffsetVideo( m_iQpChangeOffsetVideo );
+      m_acTEncDepthTopList[iViewIdx]->setQpChangeOffsetDepth( m_iQpChangeOffsetDepth );
+    }
+  }
+#if HHI_INTER_VIEW_MOTION_PRED
+  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 )
+    {
+      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_iSourceHeight, LOG2_DISP_PREC_LUT, 0 );
+
+      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
+    {
+      m_cRendererTop.init(m_iSourceWidth, m_iSourceHeight,true,0,0,true, 0,0,0,0,0,0,0,1,0,0 );  //GT: simplest configuration
+    }
+  }
+#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()
+{
+  // Video I/O
+  m_cTVideoIOBitsFile.openBits( m_pchBitstreamFile, true  );  // write mode
+
+  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_iSourceHeight);
+    m_acTVideoIOYuvReconFileList[iViewIdx]->open( m_pchReconFileList[iViewIdx],     true, m_uiOutputBitDepth, m_uiInternalBitDepth);  // write mode
+
+    // Neo Decoder
+    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_iSourceHeight);
+
+      m_acTVideoIOYuvDepthReconFileList[iViewIdx]->open( m_pchDepthReconFileList[iViewIdx],     true, m_uiOutputBitDepth, m_uiInternalBitDepth);  // write mode
+
+      // Neo Decoder
+      m_acTEncDepthTopList[iViewIdx]->create();
+    }
+#if HHI_INTER_VIEW_MOTION_PRED
+    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
+  }
+
+#if HHI_VSO
+  for(Int iViewIdx=0; iViewIdx < m_iNumberOfExternalRefs; iViewIdx++)
+  {
+    m_acTVideoIOYuvERFileList[iViewIdx]->open( m_pchERRefFileList[iViewIdx], false, m_uiInputBitDepth, m_uiInternalBitDepth ); // read mode
+  }
+#endif
+}
+
+Void TAppEncTop::xDestroyLib()
+{
+
+  m_cTVideoIOBitsFile.closeBits();
+
+#if HHI_VSO
+  for ( Int iViewIdx = 0; iViewIdx < m_iNumberOfExternalRefs; iViewIdx++ )
+  {
+    m_acTVideoIOYuvERFileList[iViewIdx]->close();
+    delete m_acTVideoIOYuvERFileList[iViewIdx];
+    m_acTVideoIOYuvERFileList[iViewIdx] = 0;
+  };
+#endif
+
+  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;
+
+    delete m_cListPicYuvRecList[iViewIdx] ; m_cListPicYuvRecList[iViewIdx] = NULL;
+
+    m_acTEncTopList[iViewIdx]->destroy();
+    delete m_acTEncTopList[iViewIdx] ; m_acTEncTopList[iViewIdx] = NULL;
+
+    if( iViewIdx < Int( m_acTVideoIOYuvDepthInputFileList.size() ) && m_acTVideoIOYuvDepthInputFileList[iViewIdx] )
+    {
+      m_acTVideoIOYuvDepthInputFileList[iViewIdx]->close( );
+      delete m_acTVideoIOYuvDepthInputFileList[iViewIdx] ;
+    }
+    if( iViewIdx < Int( m_acTVideoIOYuvDepthReconFileList.size() ) && m_acTVideoIOYuvDepthReconFileList[iViewIdx] )
+    {
+      m_acTVideoIOYuvDepthReconFileList[iViewIdx]->close () ;
+      delete m_acTVideoIOYuvDepthReconFileList[iViewIdx];
+    }
+    if( iViewIdx < Int( m_acTEncDepthTopList.size() ) && m_acTEncDepthTopList[iViewIdx] )
+    {
+      m_acTEncDepthTopList[iViewIdx]->destroy();
+      delete m_acTEncDepthTopList[iViewIdx];
+    }
+    if( iViewIdx < Int( m_cListPicYuvDepthRecList.size() ) && m_cListPicYuvDepthRecList[iViewIdx] )
+    {
+      delete m_cListPicYuvDepthRecList[iViewIdx ];
+    }
+  }
+}
+
+Void TAppEncTop::xInitLib()
+{
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+  {
+    m_acTEncTopList[iViewIdx]->init( this );
+  }
+  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
+ .
+ */
+//GT PRE LOAD ENC BUFFER
+Void TAppEncTop::encode()
+{
+  TComPicYuv*       pcPicYuvOrg      = new TComPicYuv;
+  TComPicYuv*       pcDepthPicYuvOrg = new TComPicYuv;
+  TComPicYuv*       pcPdmDepthOrg    = new TComPicYuv;
+  TComPicYuv*       pcPicYuvRec      = NULL;
+  //TComPicYuv*       pcDepthPicYuvRec = NULL;
+
+  // initialize internal class & member variables
+  xInitLibCfg();
+  xCreateLib();
+  xInitLib();
+
+  // main encoder loop
+
+  //GT: setup and init Bools for Eos and Continue Reading
+  Bool  bAllEos = false;
+  Bool  bAllContinueReadingPics;
+  std::vector<Bool>  bEos ;
+  std::vector<Bool>  bContinueReadingPics ;
+
+  Bool  bAllDepthEos = false;
+  Bool  bAllContinueReadingDepthPics;
+  std::vector<Bool>  bDepthEos ;
+  std::vector<Bool>  bContinueReadingDepthPics ;
+
+  for(Int iViewIdx=0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+  {
+    bEos.push_back( false ) ;
+    bContinueReadingPics.push_back( true );
+    if( m_bUsingDepthMaps)
+    {
+      bDepthEos.push_back( false ) ;
+      bContinueReadingDepthPics.push_back( true ) ;
+    }
+  }
+  // allocate original YUV buffer
+  pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  if( m_bUsingDepthMaps)
+  {
+    pcDepthPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  }
+#if HHI_INTER_VIEW_MOTION_PRED
+  if( m_uiMultiviewMvRegMode )
+  {
+    pcPdmDepthOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  }
+#endif
+
+  TComBitstream*    pcBitstream = new TComBitstream;
+  pcBitstream->create( (m_iSourceWidth * m_iSourceHeight * 3) >> 1 ) ; //GT: is size reasonable ??
+
+  while ( !(bAllEos&& bAllContinueReadingPics) )
+  {
+    bAllContinueReadingPics = false;
+    bAllContinueReadingDepthPics = false;
+
+    //GT: Read all Buffers
+    for(Int iViewIdx=0; iViewIdx < m_iNumberOfViews; iViewIdx++ ) //GT; store frames first
+    {
+      if (!bEos[iViewIdx] && bContinueReadingPics[iViewIdx] ) //GT: read frames to buffer
+      {
+        // get buffers
+        xGetBuffer( pcPicYuvRec, iViewIdx, m_cListPicYuvRecList ); // ringbuffer of size gopsize -> m_cListPicYuvRec, m_cListBitstream
+        // read input YUV file
+        m_acTVideoIOYuvInputFileList[iViewIdx]->read( pcPicYuvOrg, m_aiPad  ) ;
+        bEos[iViewIdx] = ( m_acTVideoIOYuvInputFileList[iViewIdx]->isEof() == 1 ?   true : false  );             //GT: End of File
+        bEos[iViewIdx] = ( m_iFrameRcvdVector[iViewIdx] == (m_iFrameToBeEncoded - 1) ?    true : bEos[iViewIdx]   );   //GT: FramesToBeEncoded Reached
+        bAllEos = bAllEos|bEos[iViewIdx] ;
+
+#if HHI_INTER_VIEW_MOTION_PRED
+        if( m_uiMultiviewMvRegMode && iViewIdx )
+        {
+          m_acTVideoIOYuvDepthInputFileList[iViewIdx]->read( pcPdmDepthOrg, m_aiPad, m_bUsingDepthMaps );
+        }
+#endif
+
+        // increase number of received frames
+        m_iFrameRcvdVector[iViewIdx]++ ;
+      }
+
+#if HHI_INTER_VIEW_MOTION_PRED
+      m_acTEncTopList[iViewIdx]->receivePic( bEos[iViewIdx],  pcPicYuvOrg, m_cListPicYuvRecList[iViewIdx]->back(), ( m_uiMultiviewMvRegMode && iViewIdx ? pcPdmDepthOrg : 0 ) );
+#else
+      m_acTEncTopList[iViewIdx]->receivePic( bEos[iViewIdx],  pcPicYuvOrg, m_cListPicYuvRecList[iViewIdx]->back(), 0 );
+#endif
+
+      if( m_bUsingDepthMaps )
+      {
+        if (!bDepthEos[iViewIdx] && bContinueReadingDepthPics[iViewIdx] )
+        {
+          // get buffers
+          xGetBuffer( pcPicYuvRec, iViewIdx, m_cListPicYuvDepthRecList ); // ringbuffer of size gopsize -> m_cListPicYuvRec, m_cListBitstream
+          // read input YUV file
+          m_acTVideoIOYuvDepthInputFileList[iViewIdx]->read( pcDepthPicYuvOrg, m_aiPad  ) ;
+          bDepthEos[iViewIdx] = ( m_acTVideoIOYuvDepthInputFileList[iViewIdx]->isEof() == 1 ?   true : false  );
+          bDepthEos[iViewIdx] = ( m_iDepthFrameRcvdVector[iViewIdx] == (m_iFrameToBeEncoded - 1) ?    true : bDepthEos[iViewIdx]   );
+          bAllDepthEos = bAllDepthEos|bDepthEos[iViewIdx] ;
+          // increase number of received frames
+          m_iDepthFrameRcvdVector[iViewIdx]++ ;
+        }
+        m_acTEncDepthTopList[iViewIdx]->receivePic( bDepthEos[iViewIdx],  pcDepthPicYuvOrg, m_cListPicYuvDepthRecList[iViewIdx]->back() );
+      }
+    }
+
+    //===== store current POC =====
+    Bool  bCurrPocCoded = m_acTEncTopList[ 0 ]->currentPocWillBeCoded();
+    Int   iCurrPoc      = m_acTEncTopList[ 0 ]->getNextFrameId();
+
+    //===== update camera parameters =====
+    if( bCurrPocCoded )
+    {
+      m_cCameraData.update( (UInt)iCurrPoc );
+    }
+
+#if HHI_VSO    
+    if ( m_bUseVSO && ( m_uiVSOMode != 4) )
+    {
+      //GT: Read external reference pics or render references
+      xStoreVSORefPicsInBuffer();       //GT;
+    }
+#endif
+
+    //GT: Encode
+    for(Int iViewIdx=0; iViewIdx < m_iNumberOfViews; iViewIdx++ )     // Start encoding
+    {
+      bool bThisViewContinueReadingPics = bContinueReadingPics[iViewIdx];
+      m_acTEncTopList[iViewIdx]->encode( bEos[iViewIdx], m_cListPicYuvRecMap[iViewIdx], pcBitstream, bThisViewContinueReadingPics );
+      bContinueReadingPics[iViewIdx]=bThisViewContinueReadingPics;
+      bAllContinueReadingPics = bAllContinueReadingPics||bContinueReadingPics[iViewIdx];
+
+      if(pcBitstream->getNumberOfWrittenBits()!=0)
+      {
+        m_cTVideoIOBitsFile.writeBits( pcBitstream );
+      }
+      pcBitstream->resetBits(); //GT: also done later in ....
+      pcBitstream->rewindStreamPacket( );
+      // write bistream to file if necessary
+      xWriteOutput( iViewIdx ); //GT: Write Reconfiles (when gop is complete?)
+
+      if( m_bUsingDepthMaps )
+      {
+        bool bThisViewContinueReadingDepthPics = bContinueReadingDepthPics[iViewIdx];
+        m_acTEncDepthTopList[iViewIdx]->encode( bDepthEos[iViewIdx], m_cListPicYuvDepthRecMap[iViewIdx], pcBitstream, bThisViewContinueReadingDepthPics );
+        bContinueReadingDepthPics[iViewIdx]=bThisViewContinueReadingDepthPics;
+
+        bAllContinueReadingDepthPics = bAllContinueReadingDepthPics||bContinueReadingDepthPics[iViewIdx];
+        if(pcBitstream->getNumberOfWrittenBits()!=0)
+        {
+          m_cTVideoIOBitsFile.writeBits( pcBitstream );
+        }
+        pcBitstream->resetBits();
+        pcBitstream->rewindStreamPacket( );
+        // write bistream to file if necessary
+        xWriteOutput( iViewIdx, true );
+      }
+    }
+
+    // delete extra picture buffers
+    if( bCurrPocCoded )
+    {
+      for( Int iViewIdx = 0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+      {
+        if( iViewIdx < (Int)m_acTEncTopList.size() && m_acTEncTopList[iViewIdx] )
+        {
+          m_acTEncTopList[iViewIdx]->deleteExtraPicBuffers( iCurrPoc );
+        }
+        if( iViewIdx < (Int)m_acTEncDepthTopList.size() && m_acTEncDepthTopList[iViewIdx] )
+        {
+          m_acTEncDepthTopList[iViewIdx]->deleteExtraPicBuffers( iCurrPoc );
+        }
+      }
+    }
+
+#if AMVP_BUFFERCOMPRESS
+    // compress motion for entire access
+    if( bCurrPocCoded )
+    {
+      for( Int iViewIdx = 0; iViewIdx < m_iNumberOfViews; iViewIdx++ )
+      {
+        if( iViewIdx < (Int)m_acTEncTopList.size() && m_acTEncTopList[iViewIdx] )
+        {
+          m_acTEncTopList[iViewIdx]->compressMotion( iCurrPoc );
+        }
+        if( iViewIdx < (Int)m_acTEncDepthTopList.size() && m_acTEncDepthTopList[iViewIdx] )
+        {
+          m_acTEncDepthTopList[iViewIdx]->compressMotion( iCurrPoc );
+        }
+      }
+    }
+#endif
+  }
+
+  // write output
+  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 original YUV buffer
+  pcPicYuvOrg->destroy();
+  delete pcPicYuvOrg;
+  pcPicYuvOrg = NULL;
+
+  // valgrind
+  if( m_bUsingDepthMaps)
+  {
+    pcDepthPicYuvOrg->destroy();
+  }
+  delete pcDepthPicYuvOrg ;
+  pcDepthPicYuvOrg = NULL ;
+
+  pcBitstream->destroy();
+  delete pcBitstream;
+  pcBitstream = NULL ;
+
+
+  // delete used buffers in encoder class
+  for(Int iViewIdx =0; iViewIdx < m_iNumberOfViews; iViewIdx++)
+  {
+    m_acTEncTopList[iViewIdx]->deletePicBuffer() ;
+  }
+
+  if( m_bUsingDepthMaps)
+  {
+    for(Int iViewIdx =0; iViewIdx < m_iNumberOfViews; iViewIdx++)
+    {
+      m_acTEncDepthTopList[iViewIdx]->deletePicBuffer() ;
+    }
+  }
+
+  if ( pcPdmDepthOrg )
+  {
+    pcPdmDepthOrg->destroy();
+    delete pcPdmDepthOrg;
+    pcPdmDepthOrg = NULL;
+  }
+
+  // delete buffers & classes
+  xDeleteBuffer();
+  xDestroyLib();
+}
+
+// ====================================================================================================================
+// 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, std::vector< TComList<TComPicYuv*>*>& racBuffer )
+{
+  if ( m_uiCodedPictureStoreSize   == 0 )
+    {
+      if (racBuffer[iViewIdx]->size() == 0)
+      {
+        rpcPicYuvRec = new TComPicYuv;
+        rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+
+        racBuffer[iViewIdx]->pushBack( rpcPicYuvRec );
+      }
+      rpcPicYuvRec = racBuffer[iViewIdx]->popFront(); //GT why? only one in list ?? A: only to get rpcPicYuvRec
+      racBuffer[iViewIdx]->pushBack( rpcPicYuvRec );
+      return;
+    }
+
+    // org. buffer
+  if ( racBuffer[iViewIdx]->size() == (UInt)m_uiCodedPictureStoreSize )
+    {
+      rpcPicYuvRec = racBuffer[iViewIdx]->popFront();
+    }
+    else
+    {
+      rpcPicYuvRec = new TComPicYuv;
+      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+    }
+    racBuffer[iViewIdx]->pushBack( rpcPicYuvRec );
+}
+
+Void TAppEncTop::xDeleteBuffer( )
+{
+  TComList<TComBitstream*>::iterator iterBitstream = m_cListBitstream.begin();
+
+  Int iSize = Int( m_cListBitstream.size() );
+
+  for ( Int i = 0; i < iSize; i++ )
+  {
+    TComBitstream* pcBitstream = *(iterBitstream++);
+
+    pcBitstream->destroy();
+
+    delete pcBitstream; pcBitstream = NULL;
+  }
+
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+  {
+    TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_cListPicYuvRecList[iViewIdx]->begin();
+
+    iSize = Int( m_cListPicYuvRecList[iViewIdx]->size() );
+
+    for ( Int i = 0; i < iSize; i++ )
+    {
+        TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+        pcPicYuvRec->destroy();
+        delete pcPicYuvRec; pcPicYuvRec = NULL;
+    }
+  }
+  if( m_bUsingDepthMaps)
+  {
+    for(Int iViewIdx=0; iViewIdx<m_iNumberOfViews; iViewIdx++)
+    {
+      TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_cListPicYuvDepthRecList[iViewIdx]->begin();
+
+      iSize = Int( m_cListPicYuvDepthRecList[iViewIdx]->size() );
+
+      for ( Int i = 0; i < iSize; i++ )
+      {
+          TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+          pcPicYuvRec->destroy();
+          delete pcPicYuvRec; pcPicYuvRec = NULL;
+      }
+    }
+  }
+
+  // Delete ERFiles
+
+#if HHI_VSO
+  std::map< Int,vector<TComPicYuv*> >::iterator iterMapPicExtRefView = m_cMapPicExtRefView.begin();
+  while ( iterMapPicExtRefView != m_cMapPicExtRefView.end() )
+  {
+    for ( UInt uiViewNumber = 0; uiViewNumber < iterMapPicExtRefView->second.size(); uiViewNumber++ )
+    {
+      if ( iterMapPicExtRefView->second[uiViewNumber] )
+      {
+        iterMapPicExtRefView->second[uiViewNumber]->destroy();
+        delete iterMapPicExtRefView->second[uiViewNumber];
+      }
+    }
+    iterMapPicExtRefView++;
+  }
+#endif
+}
+
+/** \param iNumEncoded  number of encoded frames
+ */
+Void TAppEncTop::xWriteOutput( Int iViewIdx, Bool isDepth )
+{
+  std::map<PicOrderCnt, TComPicYuv*> &rcMap = ( isDepth ? m_cListPicYuvDepthRecMap          : m_cListPicYuvRecMap          )[iViewIdx];
+  PicOrderCnt  &riNextPocToDump             = ( isDepth ? m_aiNextDepthPocToDump            : m_aiNextPocToDump            )[iViewIdx];
+  TVideoIOYuv* &rpcTVideoIOYuvReconFile     = ( isDepth ? m_acTVideoIOYuvDepthReconFileList : m_acTVideoIOYuvReconFileList )[iViewIdx];
+  std::map<PicOrderCnt, TComPicYuv*>::iterator i;
+
+  while( ! rcMap.empty() && ( i = rcMap.begin() )->first == riNextPocToDump )
+  {
+    riNextPocToDump++;
+    rpcTVideoIOYuvReconFile->write( i->second, m_aiPad );
+    rcMap.erase( i );
+  }
+}
+
+// GT FIX
+std::vector<TComPic*> TAppEncTop::getSpatialRefPics( Int iViewIdx, Int iPoc, Bool bIsDepthCoder )
+{
+  std::vector<TComPic*> apcRefPics( iViewIdx, (TComPic*)NULL );
+  for( int iRefViewIdx = 0; iRefViewIdx < iViewIdx; iRefViewIdx++ )
+  {
+// GT FIX
+    TComPic* pcRefPic = xGetPicFromView(iRefViewIdx, iPoc, bIsDepthCoder);
+
+    assert( pcRefPic != NULL );
+    apcRefPics[iRefViewIdx] = pcRefPic;
+  }
+  return apcRefPics;
+}
+
+
+TComPic* TAppEncTop::xGetPicFromView( Int iViewIdx, Int iPoc, bool bDepth )
+{
+  assert( ( iViewIdx >= 0) && ( iViewIdx < m_iNumberOfViews ) );
+
+  TComPic* pcPic = 0;
+  TComList<TComPic*>* apcListPic;
+
+  apcListPic = (bDepth ?  m_acTEncDepthTopList[iViewIdx] : m_acTEncTopList[iViewIdx])->getListPic() ;
+
+  for(TComList<TComPic*>::iterator it=apcListPic->begin(); it!=apcListPic->end(); it++)
+  {
+    if( (*it)->getPOC() == iPoc )
+    {
+      pcPic = *it ;
+      break ;
+    }
+  }
+
+  return pcPic;
+};
+
+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;
+};
+
+#if HHI_VSO
+Void TAppEncTop::xSetBasePicYuv( Int iViewIdx, Int iPoc, TComMVDRefData* pcRefInfo, InterViewReference eView, bool bDepth )
+{
+
+  if ( ( iViewIdx < 0) || ( iViewIdx >= m_iNumberOfViews ) )
+    return;
+
+  if ( !m_bUsingDepthMaps && bDepth )
+    return;
+
+  TComPic* pcPic = xGetPicFromView( iViewIdx, iPoc, bDepth);
+
+  if (pcPic == 0)
+    return;
+
+  pcRefInfo->setPicYuvBaseView(eView, bDepth, pcPic->getPicYuvOrg(),  pcPic->getReconMark() ? pcPic->getPicYuvRec() : NULL );
+
+};
+
+Void TAppEncTop::setMVDPic( Int iViewIdx, Int iPoc, TComMVDRefData* pcMVDRefData )
+{
+  AOF( iViewIdx >= 0);
+  AOF( iViewIdx <  m_iNumberOfViews  );
+
+  xSetBasePicYuv(iViewIdx - 1, iPoc, pcMVDRefData, PREVVIEW, false);
+  xSetBasePicYuv(iViewIdx    , iPoc, pcMVDRefData, CURRVIEW, false );
+  xSetBasePicYuv(iViewIdx + 1, iPoc, pcMVDRefData, NEXTVIEW, false );
+
+  if ( m_bUsingDepthMaps )
+  {
+    xSetBasePicYuv(iViewIdx - 1, iPoc, pcMVDRefData, PREVVIEW, true );
+    xSetBasePicYuv(iViewIdx    , iPoc, pcMVDRefData, CURRVIEW, true );
+    xSetBasePicYuv(iViewIdx + 1, iPoc, pcMVDRefData, NEXTVIEW, true );
+  }
+
+
+  xSetBaseLUT       (iViewIdx, iViewIdx-1  , pcMVDRefData, PREVVIEW );
+  xSetBaseLUT       (iViewIdx, iViewIdx+1  , pcMVDRefData, NEXTVIEW );
+
+
+  if ( m_bUseVSO && m_uiVSOMode != 4)
+  {
+    xSetERPicYuvs               (iViewIdx, iPoc, pcMVDRefData);
+    pcMVDRefData->setShiftLUTsERView(m_cCameraData.getSynthViewShiftLUTD()[iViewIdx],  m_cCameraData.getSynthViewShiftLUTI()[iViewIdx] );
+    pcMVDRefData->setRefViewInd     (m_aaiBaseViewRefInd[iViewIdx], m_aaiERViewRefInd[iViewIdx], m_aaiERViewRefLutInd[iViewIdx]);
+  }
+};
+
+
+Void TAppEncTop::xSetBaseLUT( Int iViewIdxSource, Int iViewIdxTarget, TComMVDRefData* pcRefInfo, InterViewReference eView )
+{
+  if ( ( iViewIdxSource < 0) || ( iViewIdxSource >= m_iNumberOfViews )||( iViewIdxTarget < 0) || ( iViewIdxTarget >= m_iNumberOfViews ) )
+    return;
+  assert( abs( iViewIdxTarget - iViewIdxSource ) <= 1 );  //GT; Not supported yet
+  pcRefInfo->setShiftLUTsBaseView(eView, m_cCameraData.getBaseViewShiftLUTD()[iViewIdxSource][iViewIdxTarget],m_cCameraData.getBaseViewShiftLUTI()[iViewIdxSource][iViewIdxTarget] );
+};
+
+Void TAppEncTop::xSetERPicYuvs( Int iViewIdx, Int iPoc, TComMVDRefData* pcReferenceInfo )
+{
+  std::vector<TComPicYuv*> apcExtRefViews;
+
+  std::map< Int, vector<TComPicYuv*> >::iterator cMapIt;
+  cMapIt = m_cMapPicExtRefView.find(iPoc);
+
+  assert(  cMapIt != m_cMapPicExtRefView.end() );
+
+  pcReferenceInfo->setPicYuvERViews( cMapIt->second );
+}
+
+Void TAppEncTop::xStoreVSORefPicsInBuffer()
+{
+  // X-Check if all Encoders have received the same number of pics
+  Int iNumRcvd = m_iFrameRcvdVector[0];
+  for ( UInt uiViewNumber = 0; uiViewNumber < m_iNumberOfViews; uiViewNumber ++ )
+  {
+    assert( ( m_iFrameRcvdVector[uiViewNumber] == iNumRcvd ) && ( m_iDepthFrameRcvdVector[uiViewNumber] == iNumRcvd ) ); //GT; if assert here, the encoder instances are not synchronized any more, re-think this function and the ERView Buffer!!
+  };
+
+  Int iCurPoc = iNumRcvd - 1;
+
+  if ( iCurPoc <= m_iLastFramePutInERViewBuffer )
+  {
+    return;
+  }
+
+  std::vector<TComPicYuv*> apcExtRefViewVec;
+
+  Int iNumberOfReferenceViews = 0;
+  if (m_iNumberOfExternalRefs != 0)
+  {
+    m_aaiERViewRefLutInd = m_aaiERViewRefInd;
+    // Insert Rendered Views form File
+
+    iNumberOfReferenceViews = m_iNumberOfExternalRefs;
+
+    for ( UInt uiViewNumber = 0; uiViewNumber < iNumberOfReferenceViews; uiViewNumber++ )
+    {
+      TComPicYuv* pcPicYuvERView = new TComPicYuv;
+      pcPicYuvERView->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+
+      m_acTVideoIOYuvERFileList[uiViewNumber]->read( pcPicYuvERView, m_aiPad  ) ;
+
+      apcExtRefViewVec.push_back( pcPicYuvERView );
+    }
+  }
+  else
+  { //Render Views
+
+    for ( UInt uiViewNumber = 0; uiViewNumber < m_iNumberOfViews; uiViewNumber++ )
+    {
+      m_aaiERViewRefInd   [uiViewNumber].clear();
+      m_aaiERViewRefLutInd[uiViewNumber].clear();
+    }
+
+    iNumberOfReferenceViews = 0;
+    for ( UInt iSynthViewIdx = 0; iSynthViewIdx < m_cCameraData.getSynthViewNumbers().size(); iSynthViewIdx++ )
+    {
+      // Get Left and right view
+      Int  iLeftViewIdx  = -1;
+      Int  iRightViewIdx = -1;
+      Bool bIsBaseView;
+
+      Int iRelDistToLeft;
+      m_cCameraData.getLeftRightBaseView( iSynthViewIdx, iLeftViewIdx, iRightViewIdx, iRelDistToLeft, bIsBaseView );
+
+      if  ((iLeftViewIdx == -1) || (iRightViewIdx == -1))
+      {
+        std::cerr << "Left or right View not given." << endl;
+        exit(EXIT_FAILURE);
+      }
+
+      m_cRendererTop.setShiftLUTs(
+        m_cCameraData.getSynthViewShiftLUTD()[iLeftViewIdx] [iSynthViewIdx],
+        m_cCameraData.getSynthViewShiftLUTI()[iLeftViewIdx] [iSynthViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI ()[iLeftViewIdx] [iRightViewIdx],
+        m_cCameraData.getSynthViewShiftLUTD()[iRightViewIdx][iSynthViewIdx],
+        m_cCameraData.getSynthViewShiftLUTI()[iRightViewIdx][iSynthViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI ()[iRightViewIdx][iLeftViewIdx],
+        iRelDistToLeft
+      );
+      if ( bIsBaseView ) continue;
+
+      // Render from left
+      TComPicYuv* pcPicYuvERView = new TComPicYuv;
+      pcPicYuvERView->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+      m_cRendererTop.extrapolateView( xGetPicFromView( iLeftViewIdx, iCurPoc, false )->getPicYuvOrg(), xGetPicFromView( iLeftViewIdx, iCurPoc, true )->getPicYuvOrg(), pcPicYuvERView, true );
+
+      apcExtRefViewVec.push_back( pcPicYuvERView );
+
+      m_aaiERViewRefInd   [ iLeftViewIdx].push_back( iNumberOfReferenceViews );
+      m_aaiERViewRefLutInd[ iLeftViewIdx].push_back( iSynthViewIdx );
+      iNumberOfReferenceViews++;
+
+      //Render from right
+      pcPicYuvERView = new TComPicYuv;
+      pcPicYuvERView->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+
+      m_cRendererTop.extrapolateView( xGetPicFromView( iRightViewIdx, iCurPoc, false )->getPicYuvOrg(), xGetPicFromView( iRightViewIdx, iCurPoc, true )->getPicYuvOrg(), pcPicYuvERView, false );
+      apcExtRefViewVec.push_back( pcPicYuvERView );
+
+      m_aaiERViewRefInd   [ iRightViewIdx].push_back( iNumberOfReferenceViews );
+      m_aaiERViewRefLutInd[ iRightViewIdx].push_back( iSynthViewIdx );
+      iNumberOfReferenceViews++;
+    }
+  }
+
+  m_iLastFramePutInERViewBuffer++;
+  m_cMapPicExtRefView.insert( std::make_pair( m_iLastFramePutInERViewBuffer, apcExtRefViewVec ) );
+
+  if ( m_cMapPicExtRefView.size() >  (UInt)m_iGOPSize + 1 )
+  {
+    for ( UInt uiViewNumber = 0; uiViewNumber < (UInt) m_cMapPicExtRefView.begin()->second.size(); uiViewNumber++ )
+    {
+      if ( m_cMapPicExtRefView.begin()->second[uiViewNumber] )
+      {
+        m_cMapPicExtRefView.begin()->second[uiViewNumber]->destroy();
+        delete m_cMapPicExtRefView.begin()->second[uiViewNumber];
+      }
+    }
+    m_cMapPicExtRefView.erase ( m_cMapPicExtRefView.begin() );
+  }
+}
+#endif
+
+#if HHI_INTERVIEW_SKIP
+Void TAppEncTop::getUsedPelsMap( Int iViewIdx, Int iPoc, TComPicYuv* pcPicYuvUsedSplsMap )
+{
+  AOT( iViewIdx <= 0);
+  AOT( iViewIdx >= m_iNumberOfViews );
+  AOF( m_uiInterViewSkip != 0 );
+  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 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
+
Index: /tags/0.2r1/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- /tags/0.2r1/source/App/TAppEncoder/TAppEncTop.h	(revision 19)
+++ /tags/0.2r1/source/App/TAppEncoder/TAppEncTop.h	(revision 19)
@@ -0,0 +1,160 @@
+/* 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     TAppEncTop.h
+    \brief    Encoder application class (header)
+*/
+
+#ifndef __TAPPENCTOP__
+#define __TAPPENCTOP__
+
+#include "../../Lib/TLibEncoder/TEncTop.h"
+#include "../../Lib/TLibVideoIO/TVideoIOYuv.h"
+#include "../../Lib/TLibVideoIO/TVideoIOBits.h"
+#include "../../Lib/TLibCommon/TComBitStream.h"
+#include "../../Lib/TLibCommon/TComDepthMapGenerator.h"
+#include "TAppEncCfg.h"
+//GT VSO
+#include "../../Lib/TLibRenderer/TRenTop.h"
+//GT VSO end
+
+// ====================================================================================================================
+// 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;
+  std::vector<TVideoIOYuv*>    m_acTVideoIOYuvDepthInputFileList;
+  std::vector<TVideoIOYuv*>		 m_acTVideoIOYuvReconFileList;
+  std::vector<TVideoIOYuv*>    m_acTVideoIOYuvDepthReconFileList;
+
+  TVideoIOBitsStartCode      m_cTVideoIOBitsFile;           ///< output bitstream file
+  
+  std::vector< TComList<TComPicYuv*>* >  m_cListPicYuvRecList;              ///< list of reconstruction YUV files
+  std::vector< TComList<TComPicYuv*>* >  m_cListPicYuvDepthRecList;         ///< list of reconstruction YUV files
+  std::vector<PicOrderCnt> m_aiNextPocToDump;
+  std::vector<PicOrderCnt> m_aiNextDepthPocToDump;
+  std::vector< std::map<PicOrderCnt, TComPicYuv*> > m_cListPicYuvRecMap;
+  std::vector< std::map<PicOrderCnt, TComPicYuv*> > m_cListPicYuvDepthRecMap;
+
+  TComList<TComBitstream*>   m_cListBitstream;              ///< list of bitstreams
+  
+  std::vector<Int>           	m_iFrameRcvdVector;                  ///< number of received frames
+  std::vector<Int>            m_iDepthFrameRcvdVector;             ///< number of received frames
+
+#if DEPTH_MAP_GENERATION
+  TComSPSAccess               m_cSPSAccess;
+  TComAUPicAccess             m_cAUPicAccess;
+#endif
+  
+#if HHI_VSO
+  TRenTop                     m_cRendererTop; 
+  TRenModel                   m_cRendererModel;   
+#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,			//GT: unused?
+                           TComBitstream*& rpcBitStream );
+  
+  Void  xGetBuffer        ( TComPicYuv*& rpcPicYuvRec, Int iViewIdx, std::vector< TComList<TComPicYuv*>*>& racBuffer  );
+
+  /// delete allocated buffers
+  Void  xDeleteBuffer     ();
+  
+  // file I/O
+  Void  xWriteOutput      ( Int iViewIdx, Bool isDepth = false );              ///< write bitstream to file
+
+
+  // util  
+  TComPic*    xGetPicFromView   ( Int iViewIdx, Int iPoc, Bool bDepth );
+  TComPicYuv* xGetPicYuvFromView( Int iViewIdx, Int iPoc, Bool bDepth, Bool bRecon );
+
+
+  // Ref Data
+#if HHI_VSO
+  Void  xSetBaseLUT   ( Int iViewIdxSource, Int iViewIdxTarget, TComMVDRefData* pcRefInfo, InterViewReference eView );
+  Void  xSetBasePicYuv( Int iViewIdx, Int iPoc, TComMVDRefData* pcRefInfo, InterViewReference eView, bool bDepth ); ///< store pics from buffers in pcRefInfo
+#endif
+  
+public:
+  TAppEncTop();
+  virtual ~TAppEncTop();
+  
+  Void        encode      ();                               ///< main encoding function
+#if HHI_VSO
+  Void                  setupRenModel    ( Int iPoc, Int iEncViewIdx, Int iEncContent );
+  Void                  setMVDPic        ( Int iViewIdx, Int iPoc, TComMVDRefData* pcReferenceInfo ); // set MultiView References
+#endif
+  Void                  getUsedPelsMap   ( Int iViewIdx, Int iPoc, TComPicYuv* pcPicYuvUsedPelsMap );
+  std::vector<TComPic*> getSpatialRefPics( Int iViewIdx, Int iPoc, Bool bIsDepthCoder );              // only for mvc functionality yet 
+  TComPic*              getPicFromView   ( Int iViewIdx, Int iPoc, Bool bDepth ) { return xGetPicFromView( iViewIdx, iPoc, bDepth ); }
+
+#if HHI_VSO
+  TRenModel* getRenModel    () { return  &m_cRendererModel ; }; 
+#endif
+
+#if DEPTH_MAP_GENERATION
+  TComSPSAccess*    getSPSAccess  () { return &m_cSPSAccess;   }
+  TComAUPicAccess*  getAUPicAccess() { return &m_cAUPicAccess; }
+#endif
+
+#if HHI_VSO
+private:
+  std::vector<TVideoIOYuv*>		               m_acTVideoIOYuvERFileList;
+  std::map< Int, std::vector< TComPicYuv*> > m_cMapPicExtRefView;             /// Buffer for external Reference files
+
+  Int                                        m_iLastFramePutInERViewBuffer;   ///< Poc of last frame put to ERView Buffer
+  Void  xSetERPicYuvs(  Int iViewIdx, Int iPoc, TComMVDRefData* pcReferenceInfo );    ///< store pic from buffer in pcReferenceInfo    
+  Void  xStoreVSORefPicsInBuffer();                                                   ///< read in External Ref pic from file and store in buffer
+#endif
+  
+};// END CLASS DEFINITION TAppEncTop
+
+#endif // __TAPPENCTOP__
+
Index: /tags/0.2r1/source/App/TAppEncoder/encmain.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppEncoder/encmain.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppEncoder/encmain.cpp	(revision 19)
@@ -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-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     encmain.cpp
+    \brief    Encoder application main
+*/
+
+#include <time.h>
+#include "TAppEncTop.h"
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppEncTop  cTAppEncTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "HM %s based Multiview Video plus Depth Coder: Encoder Version [%s]", HM_VERSION, NV_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: /tags/0.2r1/source/App/TAppRenderer/RendererMain.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppRenderer/RendererMain.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppRenderer/RendererMain.cpp	(revision 19)
@@ -0,0 +1,82 @@
+/* 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[])
+	{
+  TAppRendererTop  cTAppRendererTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "Multiview Video plus Depth Renderer: 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;
+}
+
+
Index: /tags/0.2r1/source/App/TAppRenderer/TAppRendererCfg.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 19)
@@ -0,0 +1,517 @@
+/* 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 "../../App/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
+// ====================================================================================================================
+
+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",  m_pchVideoInputFileBaseName,  (Char*) 0, "Basename to generate video input file names")
+    ("DepthInputFileBaseName",  m_pchDepthInputFileBaseName,  (Char*) 0, "Basename to generate depth input file names")
+    ("SynthOutputFileBaseName", 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);
+}
Index: /tags/0.2r1/source/App/TAppRenderer/TAppRendererCfg.h
===================================================================
--- /tags/0.2r1/source/App/TAppRenderer/TAppRendererCfg.h	(revision 19)
+++ /tags/0.2r1/source/App/TAppRenderer/TAppRendererCfg.h	(revision 19)
@@ -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-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 "../TAppCommon/TAppComCamPara.h"
+#include "../../Lib/TLibCommon/CommonDef.h"
+#include "../../Lib/TLibCommon/TComMVDRefData.h"
+#include "../../Lib/TLibRenderer/TRenModel.h"
+#include "../../Lib/TLibRenderer/TRenModSetupStrParser.h"
+#include <string>
+#include <vector>
+
+// ====================================================================================================================
+// 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 // __TAppRENDERERCFG__
+
Index: /tags/0.2r1/source/App/TAppRenderer/TAppRendererTop.cpp
===================================================================
--- /tags/0.2r1/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 19)
+++ /tags/0.2r1/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 19)
@@ -0,0 +1,996 @@
+/* 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
+// ====================================================================================================================
+
+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
+
+    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 )
+  {
+
+    // 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) );
+      }
+    }
+
+    if ( iFrame < m_iFrameSkip ) // Skip Frames
+    {
+      std::cout << "Skipping Frame " << iFrame << std::endl;
+
+      iFrame++;
+      continue;
+    }
+
+    m_cCameraData.update( (UInt)iFrame );
+
+    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, aiPad );
+    }
+    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 );
+    cCurModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin );
+
+    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 )
+    {
+      // 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 )
+      {
+        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 );
+      }
+
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        m_cCameraData.update( (UInt)iFrame );
+
+        // 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, aiPad );
+        }
+      }
+      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.create( m_iNumberOfInputViews, m_iNumberOfOutputViews, m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin );
+
+  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 )
+  {
+    // 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 );
+      }
+    }
+
+    if ( iFrame < m_iFrameSkip ) // Skip Frames
+    {
+      iFrame++;
+      continue;
+    }
+
+    m_cCameraData.update( (UInt)iFrame );
+
+    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, aiPad );
+    }
+    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 )
+  {
+    // set shift LUT
+
+    // 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) );
+      }
+    }
+
+    if ( iFrame < m_iFrameSkip ) // Skip Frames
+    {
+      std::cout << "Skipping Frame " << iFrame << std::endl;
+
+      iFrame++;
+      continue;
+    }
+
+    m_cCameraData.update( (UInt)iFrame );
+
+    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, aiPad );
+
+    }
+    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();
+
+}
Index: /tags/0.2r1/source/App/TAppRenderer/TAppRendererTop.h
===================================================================
--- /tags/0.2r1/source/App/TAppRenderer/TAppRendererTop.h	(revision 19)
+++ /tags/0.2r1/source/App/TAppRenderer/TAppRendererTop.h	(revision 19)
@@ -0,0 +1,92 @@
+/* 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 "../../Lib/TLibVideoIO/TVideoIOBits.h"
+#include "../../Lib/TLibCommon/TComBitStream.h"
+#include "TAppRendererCfg.h"
+#include "TAppRendererTop.h"
+#include "../../Lib/TLibRenderer/TRenModel.h"
+
+
+// ====================================================================================================================
+// 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 // __TAppRendererTOP__
+
Index: /tags/0.2r1/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- /tags/0.2r1/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 19)
+++ /tags/0.2r1/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 19)
@@ -0,0 +1,83 @@
+
+
+#include <cstdlib>
+
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "../../App/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()) {
+    TComPicYuv *stupid = &frame;
+    input.read(stupid, pad);
+
+#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, pad);
+    num_frames_processed++;
+    if (num_frames_processed == num_frames)
+      break;
+  }
+
+  input.close();
+  output.close();
+
+  return EXIT_SUCCESS;
+}
Index: /tags/0.2r1/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/CommonDef.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/CommonDef.h	(revision 19)
@@ -0,0 +1,622 @@
+/* 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     CommonDef.h
+    \brief    Defines constants, macros and tool parameters
+*/
+
+#ifndef __COMMONDEF__
+#define __COMMONDEF__
+
+// this pragma can be used for turning off "signed and unsigned mismatch"
+#if _MSC_VER > 1000
+#pragma warning( disable : 4018 )
+#endif // _MSC_VER > 1000
+#include "TypeDef.h"
+#include "TComRom.h"
+
+#include <string>
+#include <assert.h>
+#include <stdlib.h>
+#include <vector>
+
+// ====================================================================================================================
+// Version information
+// ====================================================================================================================
+
+#define HM_VERSION        "3.0rc2"                 ///< Current software version
+#define NV_VERSION        "0.2r1"                  ///< 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_REF_PIC_NUM             64
+#define MAX_GOP                     64          ///< max. value of hierarchical GOP size
+
+#define MAX_NUM_REF                 4           ///< max. value of multiple reference frames
+#if DCM_COMB_LIST
+#define MAX_NUM_REF_LC              8           ///< max. value of combined reference frames
+#endif
+
+#define MAX_UINT                    0xFFFFFFFFU ///< max. value of unsigned 32-bit integer
+#define MAX_UINT64                  0xFFFFFFFFFFFFFFFFU
+#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
+
+#define STD_CAM_PARAMETERS_PRECISION 5        ///< quarter luma sample accuarcy for derived disparities (as default)
+
+#define MAX_INPUT_VIEW_NUM					10				///< max. number of input view for multiview coding
+
+#if HHI_VSO
+#define MAX_ERREF_VIEW_NUM					15				///< max. number of virtual external reference views
+#endif
+#define LOG2_DISP_PREC_LUT   				2		  		///< log2 of disparity precision used in integer disparity LUTs
+
+
+#if ( HHI_INTER_VIEW_MOTION_PRED || HHI_INTER_VIEW_RESIDUAL_PRED )
+#define DEPTH_MAP_GENERATION        1
+#else
+#define DEPTH_MAP_GENERATION        0
+#endif
+
+//>>>>> generation and usage of virtual prediction depth maps >>>>>
+#define PDM_DEPTH_MAP_MCP_FILTER          2         // 0: standard filter, 1:bilinear, 2:nearest neighbour
+#define PDM_ONE_DEPTH_PER_PU              1         // use only a single depth for a prediction unit (in update)
+#define PDM_NO_INTER_UPDATE               0         // no update for inter (but not inter-view) predicted blocks
+#define PDM_MERGE_POS                     0         // position of pdm in merge list (0..5)
+#define PDM_AMVP_POS                      2         // position of pdm in amvp list  (0..3)
+#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
+//<<<<< generation and usage of virtual prediction depth maps <<<<<
+
+#define OUTPUT_RESIDUAL_PICTURES          0         // output residual pictures (for debugging)
+
+#define HHI_MPI_MERGE_POS                     0         // position of mvi in merge list (0..5)
+
+
+// ====================================================================================================================
+// Macro functions
+// ====================================================================================================================
+
+#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
+
+#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);                                             \
+}
+
+
+// ====================================================================================================================
+// Coding tool configuration
+// ====================================================================================================================
+
+// modified LCEC coefficient coding
+#if QC_MOD_LCEC
+#define MAX_TR1                           4
+#endif
+
+// AMVP: advanced motion vector prediction
+#define AMVP_MAX_NUM_CANDS          6           ///< max number of final candidates
+// MERGE
+#define MRG_MAX_NUM_CANDS           6
+
+// Reference memory management
+#define DYN_REF_FREE                0           ///< dynamic free of reference memories
+
+// defines for multiview coding
+#define MAX_NUMBER_VIEWS            10
+
+// Explicit temporal layer QP offset
+#define MAX_TLAYER                  10           ///< 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 ENABLE_IBDI                 0
+
+#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]
+
+const int g_iShift8x8    = 2;
+const int g_iShift16x16  = 2;
+const int g_iShift32x32  = 2;
+const int g_iShift64x64  = 2;
+
+
+
+//RENDERER
+#define REN_LUMA_MARGIN   ( g_uiMaxCUWidth + 12 )
+#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
+
+/* End of Rounding control */
+
+enum NalRefIdc
+{
+  NAL_REF_IDC_PRIORITY_LOWEST = 0,
+  NAL_REF_IDC_PRIORITY_LOW,
+  NAL_REF_IDC_PRIORITY_HIGH,
+  NAL_REF_IDC_PRIORITY_HIGHEST
+};
+
+enum NalUnitType
+{
+  NAL_UNIT_UNSPECIFIED_0 = 0,
+  NAL_UNIT_CODED_SLICE,
+  NAL_UNIT_CODED_SLICE_DATAPART_A,
+  NAL_UNIT_CODED_SLICE_DATAPART_B,
+#if DCM_DECODING_REFRESH
+  NAL_UNIT_CODED_SLICE_CDR,
+#else
+  NAL_UNIT_CODED_SLICE_DATAPART_C,
+#endif
+  NAL_UNIT_CODED_SLICE_IDR,
+  NAL_UNIT_SEI,
+  NAL_UNIT_SPS,
+  NAL_UNIT_PPS,
+  NAL_UNIT_ACCESS_UNIT_DELIMITER,
+  NAL_UNIT_END_OF_SEQUENCE,
+  NAL_UNIT_END_OF_STREAM,
+  NAL_UNIT_FILLER_DATA,
+  NAL_UNIT_RESERVED_13,
+  NAL_UNIT_RESERVED_14,
+  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,
+  NAL_UNIT_UNSPECIFIED_25,
+  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,
+};
+
+typedef _AlfParam    ALFParam;
+#if MTK_SAO
+typedef _SaoParam    SAOParam;
+#endif
+
+
+class VideoCodecException
+{
+public:
+  VideoCodecException() : m_acFile( "unspecified" ), m_uiLine( 0 ) {}
+  VideoCodecException( const char *pcFile, UInt uiLine ) : m_acFile( pcFile ), m_uiLine( uiLine ) {}
+
+  std::string exceptionFile() const { return m_acFile; }
+  UInt        exceptionLine() const { return m_uiLine; }
+
+private:
+  std::string m_acFile;
+  UInt        m_uiLine;
+};
+
+#define RETURN_ERR_ON_EXCEPTION \
+catch( std::exception &cEx ) \
+{ \
+  std::cerr << "Abnormal program termination: " << cEx.what() << std::endl; \
+  return Err::m_nERR; \
+} \
+catch( VideoCodecException &cEx ) \
+{ \
+  std::cerr << std::endl << "VideoCodecExcteption caught at: " << std::endl; \
+  std::cerr << "File: " << cEx.exceptionFile() << std::endl; \
+  std::cerr << "Line: " << cEx.exceptionLine() << std::endl; \
+  return Err::m_nERR; \
+} \
+catch( ... ) \
+{ \
+  std::cerr << "Caught unknown exception" << std::endl; \
+  return Err::m_nERR; \
+}
+
+
+#define TOT(  exp ) { if(                exp  ) { throw VideoCodecException( __FILE__, __LINE__ ); } }
+#define TOF(  exp ) { if(              !(exp) ) { throw VideoCodecException( __FILE__, __LINE__ ); } }
+#define TNOK( exp ) { if( Err::m_nOK != (exp) ) { throw VideoCodecException( __FILE__, __LINE__ ); } }
+
+#if defined( _DEBUG )
+
+  #define TOT_DBG( exp )    TOT( exp )
+  #define TOF_DBG( exp )    TOF( exp )
+
+#else
+
+  #define TOT_DBG( exp )    ((void)0)
+  #define TOF_DBG( exp )    ((void)0)
+
+#endif
+
+typedef int            ErrVal;
+
+
+class Err
+{
+public:
+  enum
+  {
+    m_nOK               =  0,
+    m_nERR              = -1,
+    m_nEndOfFile        = -2,
+    m_nEndOfBuffer      = -3,
+    m_nInvalidParameter = -4,
+    m_nDataNotAvailable = -5,
+    m_nSizeNotAvailable = -5,
+  };
+};
+
+
+#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 );              \
+  }                           \
+}
+
+#if defined( _DEBUG )
+
+  #define AOT_DBG( exp )    AOT( exp )
+  #define AOF_DBG( exp )    AOF( exp )
+
+#else
+
+  #define AOT_DBG( exp )    ((void)0)
+  #define AOF_DBG( exp )    ((void)0)
+
+#endif
+
+#define DISABLE_DEFAULT_CPYCTOR_AND_ASOP(x) private: x( const x &r ); const x& operator=( const x &r )
+typedef Int64 PicOrderCnt;
+
+template<class T>
+class AutoDeletePtrVector
+  : public std::vector<T*>
+{
+public:
+  AutoDeletePtrVector() {}
+
+  virtual ~AutoDeletePtrVector()
+  {
+    while( !std::vector<T*>::empty() )
+    {
+      delete std::vector<T*>::back();
+      std::vector<T*>::pop_back();
+    }
+  }
+
+  DISABLE_DEFAULT_CPYCTOR_AND_ASOP( AutoDeletePtrVector );
+};
+
+  template<class T>
+  __inline T gAbs(const T& x)
+  {
+    return x < 0 ? -x : x;
+  }
+//
+
+template <typename T>
+__inline T gSign(const T& t)
+{
+    if( t == 0 )
+        return T(0);
+    else
+        return (t < 0) ? T(-1) : T(1);
+}
+
+
+
+#endif // end of #ifndef  __COMMONDEF__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/ContextModel.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/ContextModel.cpp	(revision 19)
@@ -0,0 +1,95 @@
+/* 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     ContextModel.cpp
+    \brief    context model class
+*/
+
+#include "ContextModel.h"
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - initialize context model with respect to QP and initial probability
+ .
+ \param  iQp         input QP value
+ \param  asCtxInit   initial probability table
+ */
+Void 
+ContextModel::init( Int iQp, Short asCtxInit[] )
+{
+  Int iInitState  = ( ( asCtxInit[ 0 ] * iQp ) >> 4 ) + asCtxInit[ 1 ];
+  iInitState      = Min( Max( 1, iInitState ), 126 );
+  if( iInitState >= 64 )
+  {
+    m_ucState     = Min( 62, iInitState - 64 );
+    m_ucState    += m_ucState + 1;
+  }
+  else
+  {
+    m_ucState     = Min( 62, 63 - iInitState );
+    m_ucState    += m_ucState;
+  }
+}
+
+
+const UChar 
+ContextModel::m_aucNextStateMPS[ 64 ] =
+{
+  1, 2, 3, 4, 5, 6, 7, 8,   
+  9, 10,11,12,13,14,15,16,  
+  17,18,19,20,21,22,23,24,
+  25,26,27,28,29,30,31,32,  
+  33,34,35,36,37,38,39,40,  
+  41,42,43,44,45,46,47,48,
+  49,50,51,52,53,54,55,56,  
+  57,58,59,60,61,62,62,63
+};
+
+const UChar 
+ContextModel::m_aucNextStateLPS[ 64 ] =
+{
+  0, 0, 1, 2, 2, 4, 4, 5,   
+  6, 7, 8, 9, 9, 11,11,12,  
+  13,13,15,15,16,16,18,18,
+  19,19,21,21,22,22,23,24,  
+  24,25,26,26,27,27,28,29,  
+  29,30,30,30,31,32,32,33,
+  33,33,34,34,35,35,35,36,  
+  36,36,37,37,37,38,38,63
+};
+
Index: /tags/0.2r1/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/ContextModel.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/ContextModel.h	(revision 19)
@@ -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-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     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"
+
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// context model class
+class ContextModel
+{
+public:
+  ContextModel  ()                        { m_ucState = 0;             }
+  ~ContextModel ()                        {}
+  
+  const UChar getState  ()                { return ( m_ucState >> 1 ); }                    ///< get current state
+  const UChar getMps    ()                { return ( m_ucState  & 1 ); }                    ///< get curret MPS
+  
+  Void        init      ( Int   iQp, 
+                         Short asCtxInit[] );                                              ///< initialize state with initial prob.
+  
+  Void        updateLPS ()
+  {
+    UChar ucMPS = ( m_ucState > 1    ? m_ucState  & 1 :    1   - ( m_ucState & 1 ) );
+    m_ucState   = ( m_aucNextStateLPS[ m_ucState >> 1 ] << 1 ) + ucMPS;
+  }
+  
+  Void        updateMPS ()
+  {
+    m_ucState   = ( m_aucNextStateMPS[ m_ucState >> 1 ] << 1 ) + ( m_ucState & 1 );
+  }
+  
+private:
+  UChar         m_ucState;                                                                  ///< internal state variable
+  static const  UChar m_aucNextStateMPS[ 64 ];
+  static const  UChar m_aucNextStateLPS[ 64 ];
+};
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 19)
@@ -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-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     ContextModel3DBuffer.cpp
+    \brief    context model 3D buffer class
+*/
+
+#include "ContextModel3DBuffer.h"
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+ContextModel3DBuffer::ContextModel3DBuffer( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX ) :
+m_pcContextModel( NULL ),
+m_uiSizeX( uiSizeX ),
+m_uiSizeY( uiSizeY ),
+m_uiSizeZ( uiSizeZ )
+
+{
+  // allocate 3D buffer
+  m_pcContextModel = new ContextModel[ uiSizeZ * m_uiSizeY * m_uiSizeX ];
+}
+
+ContextModel3DBuffer::~ContextModel3DBuffer()
+{
+  // delete 3D buffer
+  delete [] m_pcContextModel;
+  m_pcContextModel = NULL;
+}
+
+// ====================================================================================================================
+// 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 eSliceType, Int iQp, Short* psCtxModel )
+{
+  UInt n, z, offset = 0;
+  
+  for ( z = 0; z < m_uiSizeZ; z++ )
+  {
+    for ( n = 0; n < m_uiSizeY * m_uiSizeX; n++ )
+    {
+      m_pcContextModel[ offset + n ].init( iQp, psCtxModel + eSliceType * 2 * ( m_uiSizeZ * m_uiSizeY * m_uiSizeX ) + 2 * (n + offset) );
+    }
+    offset += n;
+  }
+  return;
+}
+
+/**
+ - copy from given 3D buffer
+ .
+ \param  pSrc          given 3D buffer
+ */
+Void ContextModel3DBuffer::copyFrom( ContextModel3DBuffer* pSrc )
+{
+  ::memcpy( this->m_pcContextModel, pSrc->m_pcContextModel, sizeof(ContextModel) * m_uiSizeZ * m_uiSizeY * m_uiSizeX );
+}
+
Index: /tags/0.2r1/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 19)
@@ -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.
+ */
+
+
+
+/** \file     ContextModel3DBuffer.h
+    \brief    context model 3D buffer class (header)
+*/
+
+#ifndef __CONTEXT_MODEL_3DBUFFER__
+#define __CONTEXT_MODEL_3DBUFFER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdio.h>
+#include <assert.h>
+#include <memory.h>
+
+#include "CommonDef.h"
+#include "ContextModel.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// context model 3D buffer class
+class ContextModel3DBuffer
+{
+protected:
+  ContextModel* m_pcContextModel;                                         ///< array of context models
+  const UInt    m_uiSizeX;                                                ///< X size of 3D buffer
+  const UInt    m_uiSizeY;                                                ///< Y size of 3D buffer
+  const UInt    m_uiSizeZ;                                                ///< Z size of 3D buffer
+  
+public:
+  ContextModel3DBuffer  ( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX );
+  ~ContextModel3DBuffer ();
+  
+  // access functions
+  ContextModel& get( UInt uiZ, UInt uiY, UInt uiX )
+  {
+    return  m_pcContextModel[ ( uiZ * m_uiSizeY + uiY ) * m_uiSizeX + uiX ];
+  }
+  ContextModel* get( UInt uiZ, UInt uiY )
+  {
+    return &m_pcContextModel[ ( uiZ * m_uiSizeY + uiY ) * m_uiSizeX       ];
+  }
+  ContextModel* get( UInt uiZ )
+  {
+    return &m_pcContextModel[ ( uiZ * m_uiSizeY       ) * m_uiSizeX       ];
+  }
+  
+  // initialization & copy functions
+  Void initBuffer( SliceType eSliceType, Int iQp, Short* psCtxModel );          ///< initialize 3D buffer by slice type & QP
+  Void copyFrom  ( ContextModel3DBuffer* pSrc                       );          ///< copy from given 3D buffer
+};
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/ContextTables.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/ContextTables.h	(revision 19)
@@ -0,0 +1,1369 @@
+/* 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     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__
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#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
+
+#define NUM_ALF_CRTL_FLAG_CTX         3       ///< number of context models for ALF ctrl flag
+
+#define NUM_MERGE_FLAG_EXT_CTX        3       ///< number of context models for merge flag of merge extended
+#define NUM_MERGE_IDX_EXT_CTX         4       ///< number of context models for merge index of merge extended
+#define NUM_MV_MERGE_IDX_EXT_CTX      5       ///< number of context models for merge index of merge extended
+#define NUM_RES_PRED_FLAG_CTX         3       ///< number of context for residual prediction flag     
+
+#define NUM_ALF_CTRL_FLAG_CTX         3       ///< number of context models for ALF control flag
+#define NUM_PART_SIZE_CTX             5       ///< number of context models for partition size
+#define NUM_PRED_MODE_CTX             2       ///< number of context models for prediction mode
+#if MTK_DCM_MPM
+#define NUM_ADI_CTX                   3       ///< number of context models for intra prediction
+#else
+#define NUM_ADI_CTX                   2
+#endif
+#if ADD_PLANAR_MODE
+#define NUM_PLANARFLAG_CTX            2       ///< number of context models for planar mode flag (intra prediction)
+#endif
+
+#define NUM_CHROMA_PRED_CTX           4       ///< 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                7       ///< number of context models for motion vector difference
+
+#define NUM_REF_NO_CTX                6       ///< 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                15      ///< number of context models for QT CBF
+#define NUM_QT_ROOT_CBF_CTX           4       ///< number of context models for QT ROOT CBF
+#define NUM_DELTA_QP_CTX              4       ///< number of context models for dQP
+#define NUM_CBF_CTX                   4       ///< number of context models for CBF
+
+#define NUM_SIG_FLAG_CTX              16      ///< number of context models for sig flag
+#if PCP_SIGMAP_SIMPLE_LAST
+#define NUM_CTX_LAST_FLAG_XY          26      ///< number of context models for PCP last flag
+#else
+#define NUM_LAST_FLAG_CTX             16      ///< number of context models for last flag
+#endif
+#define NUM_ONE_FLAG_CTX              40      ///< number of context models for greater than one
+#define NUM_ABS_FLAG_CTX              40      ///< number of context models for magnitude
+
+#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.)
+
+#if MTK_SAO
+#define NUM_AO_FLAG_CTX              1       ///< number of context models for AO flag
+#define NUM_AO_UVLC_CTX              2       ///< number of context models for AO UVLC (filter length)
+#define NUM_AO_SVLC_CTX              3       ///< number of context models for AO SVLC (filter coeff.)
+#endif
+
+#define NUM_VIEW_IDX_CTX              6
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#define NUM_DMM_CTX                   2
+#define NUM_WEDGE_CTX                 4
+#endif
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// mapping table for mapping 8x8 sigmap to 4x4 sigmap
+static const int  pos2ctx_map8x8  []  =
+{
+  0,  1,  2,  3,  4,  5,  5,  4,  4,  3,  3,  4,  4,  4,  5,  5,
+  4,  4,  4,  4,  3,  3,  6,  7,  7,  7,  8,  9, 10,  9,  8,  7,
+  7,  6, 11, 12, 13, 11,  6,  7,  8,  9, 14, 10,  9,  8,  6, 11,
+  12, 13, 11,  6,  9, 14, 10,  9, 11, 12, 13, 11 ,14, 10, 12, 14
+};
+
+// mapping table for mapping 8x8 lastbit to 4x4 lastbit
+static const int  pos2ctx_last8x8 []  =
+{
+  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
+  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
+  3,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  4,  4,  4,
+  5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8
+};
+
+// no-mapping case
+static const int  pos2ctx_nomap   []  =
+{
+  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15
+};
+
+
+// initial probability for split flag
+static const Short
+INIT_SPLIT_FLAG[3][NUM_SPLIT_FLAG_CTX][2] =
+{
+  {
+    {   -7,   68 }, {  -10,   87 }, {  -10,  105 }
+  },
+  {
+    {  -14,   71 }, {   -6,   73 }, {   -6,   91 }
+  },
+  {
+    {  -14,   71 }, {   -7,   74 }, {  -10,   92 }
+  }
+};
+
+// initial probability for skip flag
+static const Short
+INIT_SKIP_FLAG[3][NUM_SKIP_FLAG_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  }
+};
+
+// initial probability for skip flag
+static const Short
+INIT_ALF_CTRL_FLAG[3][NUM_ALF_CTRL_FLAG_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  }
+};
+
+// initial probability for merge flag
+static const Short
+INIT_MERGE_FLAG_EXT[3][NUM_MERGE_FLAG_EXT_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  }
+};
+
+static const Short
+INIT_MERGE_IDX_EXT[3][NUM_MERGE_IDX_EXT_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    1,   65 }, {    6,   42 }, {   -7,   75 }, {   -4,   72 }
+  }
+};
+
+
+static const Short
+INIT_MV_MERGE_IDX_EXT[3][NUM_MV_MERGE_IDX_EXT_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    1,   65 }, {    6,   42 }, {   -7,   75 }, {   -4,   72 }
+  }
+};
+
+
+static const Short
+INIT_RES_PRED_FLAG[3][NUM_RES_PRED_FLAG_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }
+  }
+};
+
+
+// initial probability for PU size
+static const Short
+INIT_PART_SIZE[3][NUM_PART_SIZE_CTX][2] =
+{
+  {
+    {    0,   73 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }
+  },
+  {
+    {   -1,   64 }, {   -3,   63 }, {    6,   78 }, {    0,   64 }, 
+    {    0,   64 }
+  },
+  {
+    {    6,   50 }, {   -1,   56 }, {   13,   53 }, {  -11,   76 }, 
+    {  -11,   70 }
+  }
+};
+
+// initial probability for prediction mode
+static const Short
+INIT_PRED_MODE[3][NUM_PRED_MODE_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {  -25,   89 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }
+  }
+};
+
+// initial probability for intra direction of luma
+#if MTK_DCM_MPM
+static const Short
+INIT_INTRA_PRED_MODE[3][NUM_ADI_CTX][2] =
+{
+  {
+    {    2,   54 }, {  -3,   65  }, {   -3,   65 }
+  },
+  {
+    {    0,   50 }, {  -2,   61  }, {   -2,   61 }
+  },
+  {
+    {    0,   51 }, {  1,   55   }, {    1,   55 }
+  }
+};
+#else
+static const Short
+INIT_INTRA_PRED_MODE[3][NUM_ADI_CTX][2] =
+{
+  {
+    {    2,   54 }, {   -3,   65 }
+  },
+  {
+    {    0,   50 }, {   -2,   61 }
+  },
+  {
+    {    0,   51 }, {    1,   55 }
+  }
+};
+#endif
+
+#if ADD_PLANAR_MODE
+// initial probability for planar mode flag
+static const Short
+INIT_PLANARFLAG[3][NUM_PLANARFLAG_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }
+  }
+};
+#endif
+
+// initial probability for intra direction of chroma
+static const Short
+INIT_CHROMA_PRED_MODE[3][4][2] =
+{
+#if CHROMA_CODEWORD
+  {
+    {  0,   64 }, {   0,   64 }, {  0,  64 }, {  0,  64 }
+  },
+  {
+    {  0,   64 }, {   0,   64 }, {  0,  64 }, {  0,  64 }
+  },
+  {
+    {  0,   64 }, {   0,   64 }, {  0,  64 }, {  0,  64 }
+  }
+#else
+  {
+    {  -14,   78 }, {   -5,   78 }, {  -13,  109 }, {  -13,  100 }
+  },
+  {
+    {  -26,  113 }, {  -13,   92 }, {  -23,  110 }, {  -11,  105 }
+  },
+  {
+    {  -20,  101 }, {  -25,  111 }, {  -29,  118 }, {  -24,  121 }
+  }
+#endif
+};
+
+// initial probability for temporal direction
+static const Short
+INIT_INTER_DIR[3][4][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {   -2,   58 }, {   -5,   70 }, {   -9,   85 }, {    1,   61 }
+  }
+};
+
+// initial probability for motion vector difference
+static const Short INIT_MVD[3][14][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {   -6,   80 }, {   -6,   84 }, {   -9,   90 }, {    4,   62 }, 
+    {   13,   55 }, {    2,   70 }, {    8,   74 }, {   -6,   77 }, 
+    {   -7,   84 }, {   -9,   89 }, {    5,   59 }, {   10,   62 }, 
+    {    4,   68 }, {    7,   75 }
+  },
+  {
+    {   -4,   75 }, {   -5,   82 }, {  -12,   94 }, {    7,   55 }, 
+    {   11,   59 }, {    6,   63 }, {    8,   71 }, {   -2,   71 }, 
+    {   -5,   81 }, {  -21,  111 }, {    6,   58 }, {   10,   60 }, 
+    {    5,   64 }, {   10,   67 }
+  }
+};
+
+// initial probability for reference frame index
+static const Short
+INIT_REF_PIC[3][NUM_REF_NO_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {   -6,   59 }, {  -10,   75 }, {   -8,   75 }, {  -17,   96 }, 
+    {    1,   59 }, {    0,   64 }
+  },
+  {
+    {   -9,   55 }, {   -9,   71 }, {   -9,   76 }, {  -12,   86 }, 
+    {  -18,   55 }, {    0,   64 }
+  }
+};
+
+
+static const Short
+INIT_VIEW_IDX[3][NUM_VIEW_IDX_CTX][2] =
+{
+    {
+      {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+      {    0,   64 }, {    0,   64 }
+    },
+    {
+      {   -6,   59 }, {  -10,   75 }, {   -8,   75 }, {  -17,   96 },
+      {    1,   59 }, {    0,   64 }
+    },
+    {
+      {   -9,   55 }, {   -9,   71 }, {   -9,   76 }, {  -12,   86 },
+      {  -18,   55 }, {    0,   64 }
+    }
+};
+
+// initial probability for dQP
+static const Short
+INIT_DQP[3][NUM_DELTA_QP_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }
+  }
+};
+
+static const Short
+INIT_QT_CBF[3][3*NUM_QT_CBF_CTX][2] =
+{
+  {
+    {  -22,  116 }, {   -5,   75 }, {  -16,  112 }, {  -16,  111 }, 
+    {  -32,  165 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {  -35,  116 }, 
+    {  -12,   61 }, {   -9,   73 }, {  -10,   75 }, {  -14,   96 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {  -29,  104 }, {  -12,   59 }, 
+    {   -5,   65 }, {   -6,   67 }, {  -11,   90 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }
+  },
+  {
+    {  -18,   98 }, {  -41,  120 }, {  -29,  117 }, {  -23,  108 }, 
+    {  -35,  143 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {  -46,  114 }, 
+    {  -42,  119 }, {  -11,   74 }, {  -19,   90 }, {  -42,  139 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {  -43,  107 }, {  -41,  118 }, 
+    {  -17,   86 }, {  -25,  101 }, {  -14,   91 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }
+  },
+  {
+    {  -11,   80 }, {  -32,   83 }, {  -19,   89 }, {  -16,   85 }, 
+    {  -19,  102 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {  -22,   52 }, 
+    {  -48,  123 }, {   -7,   68 }, {  -37,  121 }, {  -58,  164 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {  -19,   45 }, {  -48,  123 }, 
+    {  -21,   94 }, {   -9,   73 }, {  -42,  138 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }
+  }
+};
+
+static const Short
+INIT_QT_ROOT_CBF[3][NUM_QT_ROOT_CBF_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+  },
+  {
+    {  -22,   85 }, {  -15,   86 }, {  -13,   84 }, {  -23,  116 },
+  },
+  {
+    {  -36,  103 }, {  -21,   95 }, {  -21,   97 }, {  -24,  114 },
+  }
+};
+
+#if PCP_SIGMAP_SIMPLE_LAST
+static const Short
+INIT_LAST_X[3][2*NUM_CTX_LAST_FLAG_XY][2] =
+{
+  {
+    {   8,  31 }, {   8,  39 }, {   8,  48 }, {  12,  31 },
+    {   8,  38 }, {   6,  45 }, {   3,  46 }, {  -1,  56 },
+    {  18,  16 }, {  14,  22 }, {  15,  22 }, {  16,  17 },
+    {  16,  16 }, {  12,  24 }, {  -4,  59 }, {  33, -26 },
+    {  18,   1 }, {  20,   2 }, {  22,  -1 }, {  17,  14 },
+    {  11,  21 }, {  31, -24 }, {  38, -38 }, {  12,  11 },
+    {  -4,  47 }, { -13,  69 }, {  32,  11 }, {  25,  27 },
+    {  50,  -1 }, {  32,  20 }, {  12,  38 }, {  18,  32 },
+    {  12,  41 }, {   5,  70 }, {  40,  -6 }, {  14,  29 },
+    {  17,  26 }, {   7,  43 }, {  15,  26 }, {  15,  27 },
+    {   9,  51 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 }
+  },
+  {
+    {   9,  40 }, {   9,  44 }, {  10,  52 }, {  17,  24 },
+    {  21,  15 }, {  20,  20 }, {  14,  29 }, {   8,  46 },
+    {   7,  46 }, {  18,  18 }, {  26,   3 }, {  26,   0 },
+    {  25,   2 }, {  15,  18 }, {   9,  27 }, {  23,  20 },
+    {  19,  16 }, {  27,  -1 }, {  33, -19 }, {  38, -30 },
+    {  41, -39 }, {  40, -36 }, {  26, -12 }, {   3,  20 },
+    {  -7,  33 }, {  -4,  20 }, {  16,  42 }, {  16,  45 },
+    {  49,   7 }, {   6,  61 }, {  17,  36 }, {  24,  24 },
+    {  24,  21 }, {  61, -22 }, { -11, 101 }, {   6,  53 },
+    {  14,  40 }, {  17,  30 }, {  20,  22 }, { -10,  67 },
+    {  -6,  68 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 }
+  },
+  {
+    {   9,  40 }, {   9,  44 }, {  10,  52 }, {  17,  24 },
+    {  21,  15 }, {  20,  20 }, {  14,  29 }, {   8,  46 },
+    {   7,  46 }, {  18,  18 }, {  26,   3 }, {  26,   0 },
+    {  25,   2 }, {  15,  18 }, {   9,  27 }, {  23,  20 },
+    {  19,  16 }, {  27,  -1 }, {  33, -19 }, {  38, -30 },
+    {  41, -39 }, {  40, -36 }, {  26, -12 }, {   3,  20 },
+    {  -7,  33 }, {  -4,  20 }, {  16,  42 }, {  16,  45 },
+    {  49,   7 }, {   6,  61 }, {  17,  36 }, {  24,  24 },
+    {  24,  21 }, {  61, -22 }, { -11, 101 }, {   6,  53 },
+    {  14,  40 }, {  17,  30 }, {  20,  22 }, { -10,  67 },
+    {  -6,  68 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 }
+  }
+};
+
+static const Short
+INIT_LAST_Y[3][2*NUM_CTX_LAST_FLAG_XY][2] =
+{
+  {
+    {  19,  19 }, {  12,  36 }, {  16,  34 }, {  22,  18 },
+    {  12,  35 }, {  12,  35 }, {  12,  32 }, {   5,  46 },
+    {  16,  21 }, {  15,  20 }, {  17,  13 }, {  17,  14 },
+    {  19,  10 }, {  19,  12 }, {   4,  37 }, {  13,  22 },
+    {  22,  -4 }, {  27, -19 }, {  26, -12 }, {  18,   6 },
+    {   6,  27 }, {  12,  10 }, {  34, -33 }, {  38, -42 },
+    {  24, -15 }, {  14,   7 }, {  41,   7 }, {  45,   1 },
+    {  56,  -9 }, {  30,  22 }, {  14,  40 }, {  23,  24 },
+    {  19,  32 }, {  25,  26 }, {  29,  10 }, {  29,   4 },
+    {  19,  20 }, {  10,  37 }, {  12,  38 }, {  -2,  60 },
+    { -37, 114 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 }
+  },
+  {
+    {  15,  29 }, {  14,  36 }, {  15,  41 }, {  25,   8 },
+    {  26,   4 }, {  25,  10 }, {  21,  16 }, {  12,  34 },
+    {  18,  21 }, {  25,   1 }, {  32, -12 }, {  32, -15 },
+    {  29, -11 }, {  24,  -5 }, {  13,  12 }, {  27,   6 },
+    {  40, -32 }, {  42, -39 }, {  40, -39 }, {  45, -51 },
+    {  43, -51 }, {  45, -56 }, {  38, -46 }, {  15,  -6 },
+    {  11,  -4 }, {  11,  -4 }, {  26,  29 }, {  28,  29 },
+    {  21,  46 }, {  15,  45 }, {  27,  17 }, {  29,  12 },
+    {  23,  15 }, {  -1,  57 }, {   6,  65 }, {  22,  17 },
+    {  31,  -4 }, {  37, -25 }, {  43, -44 }, {  43, -46 },
+    {  48, -44 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 }
+  },
+  {
+    {  15,  29 }, {  14,  36 }, {  15,  41 }, {  25,   8 },
+    {  26,   4 }, {  25,  10 }, {  21,  16 }, {  12,  34 },
+    {  18,  21 }, {  25,   1 }, {  32, -12 }, {  32, -15 },
+    {  29, -11 }, {  24,  -5 }, {  13,  12 }, {  27,   6 },
+    {  40, -32 }, {  42, -39 }, {  40, -39 }, {  45, -51 },
+    {  43, -51 }, {  45, -56 }, {  38, -46 }, {  15,  -6 },
+    {  11,  -4 }, {  11,  -4 }, {  26,  29 }, {  28,  29 },
+    {  21,  46 }, {  15,  45 }, {  27,  17 }, {  29,  12 },
+    {  23,  15 }, {  -1,  57 }, {   6,  65 }, {  22,  17 },
+    {  31,  -4 }, {  37, -25 }, {  43, -44 }, {  43, -46 },
+    {  48, -44 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 },
+    {   0,  64 }, {   0,  64 }, {   0,  64 }, {   0,  64 }
+  }
+};
+#endif
+
+#if SIMPLE_CONTEXT_SIG
+static const Short
+INIT_SIG_FLAG[3][128][2] =
+{
+  {
+    {   -3,  102 }, {  -17,  114 }, {   -7,   97 }, {  -12,   96 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {   -5,   99 }, {   -9,   92 }, {   -5,   90 }, {   -7,   83 },
+    {   -3,   37 }, {   -1,   62 }, {   -5,   81 }, {   -2,   41 },
+    {    1,   64 }, {   -6,   82 }, {    0,   12 }, {    1,   43 },
+    {    0,   57 }, {   -1,   66 }, {   -4,   79 }, {    0,   64 },
+    {   23,   51 }, {    0,   69 }, {   10,   54 }, {    0,   65 },
+    {   -1,   42 }, {    4,   51 }, {   -3,   70 }, {  -12,   61 },
+    {   -4,   50 }, {   -2,   68 }, {   -18,  57 }, {    5,   38 },
+    {    1,   54 }, {   -3,   66 }, {   -9,   80 }, {    0,   64 },
+    {  -10,   91 }, {   -9,   76 }, {   -3,   61 }, {    1,   46 },
+    {  -13,   84 }, {  -13,   81 }, {   -2,   60 }, {   -5,   61 },
+    {  -11,   77 }, {  -10,   76 }, {   -3,   65 }, {   -3,   63 },
+    {   -4,   59 }, {  -14,   79 }, {    1,   61 }, {  -33,  126 },
+    {   19,   45 }, {    8,   48 }, {    2,   40 }, {   -3,   40 },
+    {    8,   46 }, {   16,   31 }, {  -10,   73 }, {  -51,  114 },
+    {    2,   52 }, {   -9,   71 }, {  -37,  118 }, {   -8,   38 },
+    {  -10,   64 }, {  -47,  113 }, { -105,  234 }, {  -32,  123 },
+    {   -4,   94 }, {   -2,   84 }, {   -4,   83 }, {   16,   39 },
+    {    0,   83 }, {   -1,   81 }, {   -4,   82 }, {  -16,   91 },
+    {   -9,   86 }, {   -8,   89 }, {   -2,   82 }, {  -14,   92 },
+    {  -16,   91 }, {   13,   44 }, {  -12,   91 }, {    0,   64 },
+    {   29,   42 }, {    1,   74 }, {   -6,   77 }, {   23,   41 },
+    {   13,   63 }, {   -6,   88 }, {   -8,   80 }, {   35,   17 },
+    {    0,   70 }, {  -17,  100 }, {  -25,  111 }, {  -39,  122 },
+    {   26,   29 }, {  -36,  114 }, {  -41,  130 }, {    0,   64 }
+  },
+  {
+    {   -7,   88 }, {    5,   52 }, {   -4,   74 }, {    5,   56 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   75 }, {    1,   59 }, {   -1,   67 }, {   -3,   67 },
+    {    6,   29 }, {    2,   57 }, {   -5,   77 }, {   -5,   44 },
+    {   -4,   64 }, {   -7,   78 }, {   -9,   34 }, {    2,   43 },
+    {    2,   53 }, {    2,   60 }, {   -8,   83 }, {    0,   64 },
+    {   19,   22 }, {   11,   48 }, {    9,   51 }, {  -24,   95 },
+    {  -27,   82 }, {  -22,   92 }, {  -20,   89 }, {  -25,   82 },
+    {  -15,   77 }, {   24,   32 }, {  -31,   76 }, {  -19,   77 },
+    {  -21,   84 }, {  -23,   95 }, {  -35,  112 }, {    0,   64 },
+    {    2,   69 }, {  -10,   82 }, {   -1,   57 }, {   -7,   59 },
+    {   -5,   71 }, {  -13,   85 }, {  -28,  107 }, {  -29,  100 },
+    {  -21,   93 }, {  -28,  108 }, {   -6,   71 }, {  -48,  136 },
+    {  -35,  111 }, {  -10,   74 }, {    4,   56 }, {    5,   56 },
+    {   -3,   84 }, {  -35,  122 }, {  -42,  111 }, {  101, -147 },
+    {  -14,   87 }, {  -70,  179 }, {    6,   30 }, {    0,   64 },
+    {    8,   32 }, {  -64,  156 }, {    0,   64 }, {    0,   64 },
+    {  -65,  144 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    6,   67 }, {   -1,   72 }, {   -9,   84 }, {  -29,  100 },
+    {    4,   65 }, {    0,   70 }, {   -7,   80 }, {  -34,  117 },
+    {  -11,   79 }, {  -14,   91 }, {  -15,   93 }, {  -34,  119 },
+    {   26,   26 }, {  -34,  111 }, {  -35,  126 }, {    0,   64 },
+    {  -15,  103 }, {   25,   19 }, {   23,   29 }, {  -65,  142 },
+    {  -21,  108 }, {   27,   19 }, {  -34,  111 }, {  -71,  174 },
+    {  -30,  104 }, {   34,   12 }, { -144,  285 }, { -168,  304 },
+    {   43,    6 }, { -125,  248 }, { -129,  252 }, {    0,   64 }
+  },
+  {
+    {   -7,   88 }, {    5,   52 }, {   -4,   74 }, {    5,   56 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    0,   75 }, {    1,   59 }, {   -1,   67 }, {   -3,   67 },
+    {    6,   29 }, {    2,   57 }, {   -5,   77 }, {   -5,   44 },
+    {   -4,   64 }, {   -7,   78 }, {   -9,   34 }, {    2,   43 },
+    {    2,   53 }, {    2,   60 }, {   -8,   83 }, {    0,   64 },
+    {   19,   22 }, {   11,   48 }, {    9,   51 }, {  -24,   95 },
+    {  -27,   82 }, {  -22,   92 }, {  -20,   89 }, {  -25,   82 },
+    {  -15,   77 }, {   24,   32 }, {  -31,   76 }, {  -19,   77 },
+    {  -21,   84 }, {  -23,   95 }, {  -35,  112 }, {    0,   64 },
+    {    2,   69 }, {  -10,   82 }, {   -1,   57 }, {   -7,   59 },
+    {   -5,   71 }, {  -13,   85 }, {  -28,  107 }, {  -29,  100 },
+    {  -21,   93 }, {  -28,  108 }, {   -6,   71 }, {  -48,  136 },
+    {  -35,  111 }, {  -10,   74 }, {    4,   56 }, {    5,   56 },
+    {   -3,   84 }, {  -35,  122 }, {  -42,  111 }, {  101, -147 },
+    {  -14,   87 }, {  -70,  179 }, {    6,   30 }, {    0,   64 },
+    {    8,   32 }, {  -64,  156 }, {    0,   64 }, {    0,   64 },
+    {  -65,  144 }, {    0,   64 }, {    0,   64 }, {    0,   64 },
+    {    6,   67 }, {   -1,   72 }, {   -9,   84 }, {  -29,  100 },
+    {    4,   65 }, {    0,   70 }, {   -7,   80 }, {  -34,  117 },
+    {  -11,   79 }, {  -14,   91 }, {  -15,   93 }, {  -34,  119 },
+    {   26,   26 }, {  -34,  111 }, {  -35,  126 }, {    0,   64 },
+    {  -15,  103 }, {   25,   19 }, {   23,   29 }, {  -65,  142 },
+    {  -21,  108 }, {   27,   19 }, {  -34,  111 }, {  -71,  174 },
+    {  -30,  104 }, {   34,   12 }, { -144,  285 }, { -168,  304 },
+    {   43,    6 }, { -125,  248 }, { -129,  252 }, {    0,   64 }
+  }
+};
+#else
+static const Short
+INIT_SIG_FLAG[3][224][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {  -24,  145 }, {  -40,  159 }, {  -38,  155 }, {  -44,  159 }, 
+    {   -1,   27 }, {   -4,   68 }, {  -12,  100 }, {  -15,   61 }, 
+    {  -14,   82 }, {  -23,  117 }, {    0,    6 }, {  -11,   54 }, 
+    {    8,   40 }, {   -1,   65 }, {  -18,  104 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {  -31,  151 }, {  -19,  114 }, {  -22,  124 }, {  -14,  100 }, 
+    {   -7,   39 }, {   -1,   61 }, {  -12,   96 }, {  -13,   55 }, 
+    {   -1,   61 }, {  -16,  101 }, {    2,    5 }, {    8,   23 }, 
+    {    6,   43 }, {    1,   62 }, {  -16,   99 }, {    0,   64 }, 
+    {  -19,  119 }, {  -12,   91 }, {  -19,  106 }, {  -25,  108 }, 
+    {   19,   -5 }, {  -24,   96 }, {   -7,   78 }, {   19,    1 }, 
+    {    1,   54 }, {  -10,   82 }, {    1,   15 }, {   -3,   51 }, 
+    {   -4,   62 }, {    1,   61 }, {   -5,   74 }, {    0,   64 }, 
+    {  -10,  107 }, {   -9,   90 }, {   -7,   89 }, {  -12,   87 }, 
+    {   -3,   32 }, {    0,   60 }, {   -3,   75 }, {   -6,   49 }, 
+    {    3,   54 }, {   -5,   78 }, {  -16,   39 }, {   -3,   43 }, 
+    {   -6,   64 }, {   -3,   67 }, {   -6,   80 }, {    0,   64 }, 
+    {  -14,  112 }, {   -6,   78 }, {   -6,   83 }, {    2,   61 }, 
+    {    9,   22 }, {   -6,   65 }, {  -26,  107 }, {    4,   33 }, 
+    {    4,   52 }, {  -27,  110 }, {    9,    4 }, {    5,   38 }, 
+    {    6,   46 }, {    6,   54 }, {   -3,   72 }, {    0,   64 }, 
+    {  -10,   91 }, {   -9,   76 }, {   -3,   61 }, {    1,   46 }, 
+    {  -13,   84 }, {  -13,   81 }, {   -2,   60 }, {   -5,   61 }, 
+    {  -11,   77 }, {  -10,   76 }, {   -3,   65 }, {   -3,   63 }, 
+    {   -4,   59 }, {  -14,   79 }, {    1,   61 }, {  -33,  126 }, 
+    {   19,   45 }, {    8,   48 }, {    2,   40 }, {   -3,   40 }, 
+    {    8,   46 }, {   16,   31 }, {  -10,   73 }, {  -51,  114 }, 
+    {    2,   52 }, {   -9,   71 }, {  -37,  118 }, {   -8,   38 }, 
+    {  -10,   64 }, {  -47,  113 }, { -105,  234 }, {  -32,  123 }, 
+    {  -11,  105 }, {   -8,   84 }, {   -5,   72 }, {   -7,   71 }, 
+    {  -13,   96 }, {   -9,   85 }, {   -4,   75 }, {   -7,   75 }, 
+    {  -10,   84 }, {   -7,   81 }, {    0,   76 }, {   -3,   78 }, 
+    {  -11,   84 }, {   -4,   75 }, {   -1,   83 }, {    0,   64 }, 
+    {   32,   35 }, {    3,   59 }, {   -1,   61 }, {  -31,  104 }, 
+    {   29,   28 }, {   11,   51 }, {   -6,   77 }, {  -41,  125 }, 
+    {    9,   53 }, {   -3,   76 }, {  -34,  130 }, {  -42,  133 }, 
+    {  -29,  109 }, {  -49,  143 }, {  -47,  144 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {  -22,  128 }, {  -14,   96 }, {  -17,   99 }, {  -26,  113 }, 
+    {    5,   31 }, {   -2,   65 }, {  -32,  125 }, {  -19,   72 }, 
+    {   -7,   69 }, {  -24,  111 }, {    0,   25 }, {   -1,   49 }, 
+    {    2,   54 }, {    0,   64 }, {  -15,   97 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   -4,   88 }, {    0,   68 }, {   -4,   75 }, {   -5,   74 }, 
+    {   17,    7 }, {    2,   56 }, {   -8,   80 }, {    1,   36 }, 
+    {    2,   52 }, {  -11,   85 }, {    6,   12 }, {    5,   41 }, 
+    {    2,   54 }, {    0,   65 }, {   -8,   82 }, {    0,   64 }, 
+    {   -8,   95 }, {   -7,   77 }, {   -7,   73 }, {   -9,   74 }, 
+    {  -18,   77 }, {   -7,   72 }, {  -11,   81 }, {  -29,   92 }, 
+    {    4,   47 }, {  -14,   83 }, {  -26,   79 }, {    2,   46 }, 
+    {    5,   50 }, {    6,   52 }, {  -22,  104 }, {    0,   64 }, 
+    {   -7,   93 }, {   -5,   79 }, {   -6,   79 }, {   -8,   79 }, 
+    {    5,   36 }, {    3,   56 }, {  -18,   99 }, {  -10,   59 }, 
+    {    0,   56 }, {  -11,   84 }, {   -3,   31 }, {    8,   35 }, 
+    {    4,   51 }, {   -1,   66 }, {   -7,   81 }, {    0,   64 }, 
+    {    1,   80 }, {  -28,  116 }, {  -26,  112 }, {    2,   56 }, 
+    {  -17,   75 }, {    3,   52 }, {  -10,   79 }, {  -26,   91 }, 
+    {   -2,   61 }, {   -3,   66 }, {  -45,  114 }, {  -21,   91 }, 
+    {    1,   59 }, {    2,   62 }, {  -10,   82 }, {    0,   64 }, 
+    {    3,   68 }, {    0,   62 }, {   -8,   69 }, {    1,   43 }, 
+    {   -6,   70 }, {   -4,   66 }, {   -2,   60 }, {   -6,   61 }, 
+    {  -13,   78 }, {   -8,   71 }, {   -6,   71 }, {   -5,   67 }, 
+    {   -7,   63 }, {    0,   56 }, {  -13,   83 }, {   -4,   77 }, 
+    {    6,   70 }, {  -19,   94 }, {  -21,   80 }, {   -7,   30 }, 
+    {  -15,   88 }, {  -19,   95 }, {  -39,  117 }, {  -10,   42 }, 
+    {  -15,   78 }, {  -30,  104 }, {    4,   36 }, {   91, -137 }, 
+    {  -45,  125 }, {    0,   42 }, {   30,    2 }, {    0,   64 }, 
+    {   -3,   84 }, {   -8,   83 }, {  -13,   86 }, {  -12,   75 }, 
+    {   -6,   81 }, {   -9,   83 }, {   -5,   77 }, {   -8,   75 }, 
+    {   -8,   79 }, {   -7,   82 }, {    0,   73 }, {   -7,   83 }, 
+    {  -13,   84 }, {   -4,   73 }, {   -3,   82 }, {    0,   64 }, 
+    {   15,   63 }, {    0,   69 }, {  -28,  110 }, {  -29,  104 }, 
+    {   -1,   74 }, {  -22,  105 }, {  -50,  150 }, {  -57,  151 }, 
+    {  -21,   96 }, {  -29,  113 }, {  -49,  151 }, {  -85,  197 }, 
+    {  -46,  133 }, {  -60,  159 }, {  -84,  198 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {  -34,  146 }, {  -20,  108 }, {  -23,  111 }, {  -38,  141 }, 
+    {    3,   34 }, {   -4,   69 }, {  -17,  103 }, {   -9,   50 }, 
+    {   -4,   66 }, {  -16,   97 }, {   -1,   24 }, {    0,   50 }, 
+    {   -1,   61 }, {  -12,   90 }, {  -14,   97 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {  -12,   99 }, {   -4,   75 }, {   -8,   81 }, {   -7,   80 }, 
+    {   15,   13 }, {    2,   57 }, {  -10,   85 }, {    4,   27 }, 
+    {  -10,   75 }, {   -9,   81 }, {   -9,   46 }, {    6,   41 }, 
+    {    3,   56 }, {   -1,   69 }, {  -14,   96 }, {    0,   64 }, 
+    {   -7,   85 }, {  -22,  102 }, {  -12,   79 }, {  -35,  121 }, 
+    {   -5,   55 }, {  -16,   88 }, {   -9,   78 }, {  -26,   73 }, 
+    {  -28,   99 }, {  -38,  123 }, {   -3,   35 }, {  -25,   97 }, 
+    {   -9,   75 }, {    6,   54 }, {  -15,   92 }, {    0,   64 }, 
+    {   -9,   94 }, {  -14,   94 }, {   -4,   74 }, {  -14,   92 }, 
+    {    7,   37 }, {    3,   57 }, {   -7,   78 }, {   -8,   54 }, 
+    {   -7,   70 }, {   -8,   78 }, {   -2,   31 }, {    4,   49 }, 
+    {    1,   60 }, {   -5,   75 }, {  -10,   87 }, {    0,   64 }, 
+    {   -3,   82 }, {  -19,  102 }, {  -14,   91 }, {  -33,  123 }, 
+    {  -46,  124 }, {  -12,   82 }, {  -43,  138 }, {  -46,  121 }, 
+    {  -38,  125 }, {  -44,  138 }, {  -32,   89 }, {   -3,   60 }, 
+    {  -22,  102 }, {  -27,  114 }, {  -37,  128 }, {    0,   64 }, 
+    {    2,   69 }, {  -10,   82 }, {   -1,   57 }, {   -7,   59 }, 
+    {   -5,   71 }, {  -13,   85 }, {  -28,  107 }, {  -29,  100 }, 
+    {  -21,   93 }, {  -28,  108 }, {   -6,   71 }, {  -48,  136 }, 
+    {  -35,  111 }, {  -10,   74 }, {    4,   56 }, {    5,   56 }, 
+    {   -3,   84 }, {  -35,  122 }, {  -42,  111 }, {  101, -147 }, 
+    {  -14,   87 }, {  -70,  179 }, {    6,   30 }, {    0,   64 }, 
+    {    8,   32 }, {  -64,  156 }, {    0,   64 }, {    0,   64 }, 
+    {  -65,  144 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    4,   67 }, {   -5,   77 }, {  -12,   85 }, {  -28,  105 }, 
+    {   -5,   77 }, {   -7,   79 }, {   -7,   79 }, {  -28,  109 }, 
+    {  -17,   94 }, {  -11,   88 }, {   -6,   81 }, {  -32,  125 }, 
+    {  -38,  128 }, {  -40,  136 }, {  -39,  142 }, {    0,   64 }, 
+    {  -35,  148 }, {  -47,  150 }, {  -22,  100 }, {  -73,  176 }, 
+    {  -12,   91 }, {  -54,  155 }, {  -86,  203 }, {  -71,  174 }, 
+    {  -66,  167 }, {  -41,  129 }, { -144,  285 }, { -168,  304 }, 
+    {  -59,  148 }, { -125,  248 }, { -129,  252 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  }
+};
+#endif
+#if !PCP_SIGMAP_SIMPLE_LAST
+static const Short
+INIT_LAST_FLAG[3][224][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   24,  -37 }, {   35,  -52 }, {    8,   -9 }, {   14,  -11 }, 
+    {   14,  -10 }, {   22,  -18 }, {   48,  -64 }, {   -1,   29 }, 
+    {   20,   13 }, {  -15,   51 }, {   77, -101 }, {   22,  -20 }, 
+    {  -34,   89 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   33,  -47 }, {   38,  -54 }, {   25,  -32 }, {   46,  -66 }, 
+    {   24,  -27 }, {   26,  -28 }, {   36,  -39 }, {   -6,   48 }, 
+    {   -2,   51 }, {   -1,   44 }, {    9,   26 }, {  -36,   93 }, 
+    {  -20,   61 }, {  -51,  130 }, {   29,   -2 }, {    0,    0 }, 
+    {   42,  -30 }, {   43,  -46 }, {   61,  -81 }, {   48,  -51 }, 
+    {   21,    5 }, {    8,   22 }, {    5,   38 }, {   23,   12 }, 
+    {  102, -138 }, {  304, -440 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   30,  -24 }, {   24,  -15 }, {   19,   -2 }, {    9,   15 }, 
+    {    9,   16 }, {    5,   27 }, {   19,    6 }, {   11,   29 }, 
+    {   -7,   62 }, {   -9,   66 }, {    7,   41 }, {  -11,   76 }, 
+    {  -42,  130 }, {  -14,   91 }, {   16,   14 }, {    0,   64 }, 
+    {   22,   14 }, {   26,   -1 }, {   13,   18 }, {    4,   37 }, 
+    {    5,   36 }, {   20,   14 }, {   12,   29 }, {   24,   17 }, 
+    {  -50,  133 }, { -165,  315 }, { -160,  301 }, { -217,  408 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   31,  -12 }, {   20,    4 }, {   16,    9 }, {   16,    9 }, 
+    {   17,    8 }, {   20,    4 }, {   23,    4 }, {   17,   18 }, 
+    {    9,   36 }, {   10,   36 }, {   10,   39 }, {    7,   52 }, 
+    {   -3,   75 }, {  -16,  103 }, {    0,   64 }, {    0,   64 }, 
+    {   14,   44 }, {   -2,   64 }, {    3,   51 }, {   18,   22 }, 
+    {   -8,   70 }, {    3,   53 }, {    7,   48 }, {   -6,   70 }, 
+    {  -48,  133 }, {  -22,   96 }, { -111,  240 }, {  -55,  156 }, 
+    {  -92,  215 }, { -347,  585 }, {    0,   64 }, {    0,   64 }, 
+    {   12,   26 }, {   11,   23 }, {   16,   15 }, {   19,   17 }, 
+    {    9,   30 }, {   14,   24 }, {   18,   21 }, {   16,   30 }, 
+    {   13,   27 }, {   12,   33 }, {   13,   37 }, {    9,   54 }, 
+    {   12,   37 }, {   12,   42 }, {   15,   49 }, {    0,   64 }, 
+    {   23,   26 }, {   17,   30 }, {    0,   60 }, {    7,   53 }, 
+    {   18,   33 }, {   15,   39 }, {   10,   48 }, {  -22,  101 }, 
+    {   19,   34 }, {   10,   51 }, {  -35,  124 }, {  -16,   93 }, 
+    {    2,   65 }, {   -9,   83 }, {  -24,  109 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   17,   18 }, {   28,  -21 }, {   40,  -50 }, {    7,   20 }, 
+    {   -9,   47 }, {  -12,   43 }, {    9,   -1 }, {   -7,   52 }, 
+    {  -29,   89 }, {   25,  -20 }, {  -36,   82 }, {  106, -178 }, 
+    {  248, -404 }, {   56,  -38 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   20,   10 }, {   25,   -8 }, {   23,   -5 }, {    2,   32 }, 
+    {    8,   15 }, {   19,   -5 }, {   15,    0 }, {    8,   27 }, 
+    {   -1,   48 }, {    1,   42 }, {    1,   41 }, {  -48,  124 }, 
+    {  -97,  213 }, {   32,  -21 }, {   61,  -47 }, { -480,  845 }, 
+    {   22,   17 }, {   26,   -6 }, {   42,  -38 }, {   33,  -15 }, 
+    {    9,   29 }, {  -19,   70 }, {  -77,  167 }, {  -80,  176 }, 
+    {  -96,  186 }, {  171, -294 }, {    5,   45 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   23,    2 }, {   30,  -12 }, {   20,    9 }, {   16,   16 }, 
+    {   19,    4 }, {    8,   24 }, {   15,   13 }, {   10,   26 }, 
+    {   12,   25 }, {  -12,   66 }, {   -7,   60 }, {   -8,   64 }, 
+    {   -2,   63 }, {   -7,   75 }, { -116,  252 }, {    0,   64 }, 
+    {   -4,   68 }, {   20,   16 }, {   17,   22 }, {   13,   31 }, 
+    {    3,   48 }, {  -21,   84 }, {  -41,  117 }, {  -43,  125 }, 
+    {    5,   40 }, {   29,    4 }, {  -24,   87 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   14,   23 }, {   24,    4 }, {   15,   23 }, {    7,   34 }, 
+    {   19,   14 }, {   19,   12 }, {   17,   18 }, {   11,   33 }, 
+    {    4,   44 }, {   -2,   55 }, {    2,   54 }, {    3,   53 }, 
+    {  -43,  137 }, {  -22,  104 }, {    0,   64 }, {    0,   64 }, 
+    {   -5,   76 }, {    7,   50 }, {    9,   43 }, {    6,   50 }, 
+    {    0,   59 }, {    1,   56 }, {    4,   51 }, {   22,   18 }, 
+    {   21,   21 }, { -105,  242 }, {  -52,  145 }, {  260, -439 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   50 }, {    5,   42 }, {    4,   43 }, {   18,   20 }, 
+    {   17,   23 }, {    0,   55 }, {   10,   39 }, {    6,   46 }, 
+    {   10,   36 }, {    9,   41 }, {   12,   42 }, {    3,   63 }, 
+    {   15,   30 }, {    9,   46 }, {    0,   73 }, {    0,   64 }, 
+    {   12,   47 }, {   11,   43 }, {    5,   50 }, {    5,   53 }, 
+    {   -2,   68 }, {  -11,   83 }, {  -18,   93 }, {  -59,  154 }, 
+    {  -22,   99 }, {  -45,  137 }, {  -63,  167 }, {  -56,  152 }, 
+    {  -34,  117 }, {  -45,  136 }, {  -74,  182 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  },
+  {
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   20,    7 }, {   38,  -44 }, {   37,  -43 }, {   -9,   48 }, 
+    {  -45,  104 }, {  -87,  174 }, {   26,  -35 }, {   51,  -63 }, 
+    {  129, -174 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    7,   38 }, {   28,  -14 }, {   25,   -7 }, {    2,   38 }, 
+    {  -13,   53 }, {   11,    2 }, {  -18,   59 }, {   23,   -4 }, 
+    {   46,  -35 }, {   -9,   59 }, {  -32,   97 }, {   -5,   57 }, 
+    {  -98,  215 }, {  -51,  141 }, {  163, -267 }, {    0,    0 }, 
+    {    2,   48 }, {   57,  -65 }, {   70,  -78 }, {   74,  -74 }, 
+    {   38,   -7 }, {   64,  -44 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   12,   24 }, {   17,   17 }, {   11,   31 }, {    6,   35 }, 
+    {    9,   25 }, {   -2,   41 }, {   11,   19 }, {   -3,   51 }, 
+    {  -30,  100 }, {   -4,   55 }, {    2,   49 }, {   38,  -17 }, 
+    {   43,  -28 }, {  -35,  117 }, {  -97,  214 }, {    0,   64 }, 
+    {    7,   41 }, {   29,   -3 }, {   17,   23 }, {    6,   45 }, 
+    {   12,   36 }, {  -22,   85 }, {    2,   54 }, {  -18,   87 }, 
+    {    0,   65 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   -5,   59 }, {   14,   25 }, {   13,   29 }, {    4,   42 }, 
+    {    8,   33 }, {    5,   37 }, {   20,   11 }, {   16,   20 }, 
+    {   15,   22 }, {  -12,   70 }, {   -9,   67 }, {   13,   35 }, 
+    {  -15,   85 }, {  -25,  101 }, {    0,   64 }, {    0,   64 }, 
+    {   -3,   65 }, {    6,   50 }, {    3,   56 }, {   21,   19 }, 
+    {   -1,   64 }, {  -73,  175 }, {  -17,   76 }, {    7,   52 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   12,   22 }, {   15,   20 }, {   18,   14 }, {   13,   28 }, 
+    {   18,   18 }, {    0,   54 }, {  -14,   77 }, {  -34,  113 }, 
+    {    4,   43 }, {    7,   43 }, {    2,   55 }, {   -2,   69 }, 
+    {  -17,   82 }, {   -2,   60 }, {   -8,   81 }, {    0,   64 }, 
+    {  -20,   92 }, {    1,   56 }, {  -35,  114 }, {  -12,   78 }, 
+    {    6,   51 }, {  -48,  141 }, {  -77,  183 }, {  -63,  157 }, 
+    {    7,   46 }, {  -56,  149 }, { -125,  254 }, { -134,  247 }, 
+    {  -49,  134 }, {  -72,  167 }, { -130,  253 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  }
+};
+#endif
+
+static const Short
+INIT_ONE_FLAG[3][80][2] =
+{
+  {
+    {  -11,   87 }, {  -20,   64 }, {  -16,   68 }, {  -13,   71 }, 
+    {  -10,   73 }, {   -5,   67 }, {   -8,   26 }, {   -8,   37 }, 
+    {   -3,   36 }, {   -9,   56 }, {    0,   63 }, {   -5,   39 }, 
+    {  -12,   56 }, {   -9,   57 }, {   -1,   52 }, {   -4,   72 }, 
+    {  -19,   73 }, {  -28,   88 }, {  -23,   85 }, {   -3,   59 }, 
+    {   -2,   72 }, {  -27,   97 }, {  -22,   89 }, {  -14,   77 }, 
+    {   -1,   58 }, {  -10,   86 }, {  -22,   74 }, {  -13,   63 }, 
+    {   -6,   57 }, {   -5,   63 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   -4,   70 }, {   16,   -2 }, {    9,   23 }, {    5,   41 }, 
+    {   -7,   67 }, {   -6,   63 }, {   13,   -5 }, {  -12,   42 }, 
+    {  -18,   53 }, {  -14,   59 }, {   -5,   65 }, {   -8,   36 }, 
+    {  -22,   67 }, {  -35,   89 }, {   -3,   47 }, {  -12,   77 }, 
+    {  -20,   66 }, {  -51,  113 }, {  -44,  109 }, {  -23,   84 }, 
+    {   -1,   64 }, {  -58,  127 }, {  -71,  143 }, {  -67,  134 }, 
+    {  -91,  187 }, {   -1,   64 }, {   20,   -3 }, {   13,   21 }, 
+    {    2,   46 }, {    5,   48 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  },
+  {
+    {   -4,   71 }, {   29,   -5 }, {    1,   45 }, {   -6,   58 }, 
+    {   -9,   67 }, {   -6,   66 }, {   23,   -7 }, {    3,   26 }, 
+    {   -5,   42 }, {    5,   31 }, {  -12,   79 }, {   -2,   45 }, 
+    {  -15,   67 }, {  -11,   62 }, {   -3,   54 }, {   -4,   70 }, 
+    {  -13,   68 }, {  -31,  100 }, {  -26,   91 }, {  -18,   84 }, 
+    {   -9,   83 }, {  -30,  103 }, {  -24,   90 }, {  -43,  122 }, 
+    {   -6,   66 }, {    4,   59 }, {   34,  -11 }, {   21,   10 }, 
+    {   14,   25 }, {    5,   44 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   -4,   69 }, {   40,  -33 }, {   19,    8 }, {  -11,   65 }, 
+    {   -6,   59 }, {  -11,   68 }, {   12,   -2 }, {   17,  -10 }, 
+    {   -6,   34 }, {   11,   14 }, {  -11,   70 }, {    1,   27 }, 
+    {  -26,   71 }, {  -28,   79 }, {   -2,   47 }, {    6,   47 }, 
+    {  -23,   67 }, {  -47,  107 }, {  -55,  117 }, {  -21,   83 }, 
+    {    1,   59 }, {  -38,   82 }, {  -34,   77 }, {  -45,   95 }, 
+    {   10,   25 }, {    9,   46 }, {   41,  -31 }, {   32,  -17 }, 
+    {   14,   19 }, {   17,   18 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  },
+  {
+    {   -2,   65 }, {   18,   22 }, {   10,   33 }, {   -2,   55 }, 
+    {   -7,   64 }, {   -6,   67 }, {   19,   11 }, {   -5,   50 }, 
+    {   -7,   53 }, {   -4,   54 }, {  -23,   99 }, {   -3,   51 }, 
+    {    2,   41 }, {  -32,  102 }, {  -16,   79 }, {   -8,   77 }, 
+    {  -21,   84 }, {  -26,   91 }, {  -33,  104 }, {   -4,   61 }, 
+    {  -31,  122 }, {  -34,  110 }, {  -25,   96 }, {  -43,  124 }, 
+    {   -6,   70 }, {    3,   60 }, {   23,   12 }, {   12,   30 }, 
+    {   11,   33 }, {    8,   40 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   -2,   66 }, {   40,  -20 }, {    0,   46 }, {   -5,   54 }, 
+    {    7,   37 }, {  -39,  116 }, {   31,  -27 }, {    1,   22 }, 
+    {  -35,   82 }, {  -32,   85 }, {  -15,   72 }, {   16,    0 }, 
+    {  -43,  102 }, {  -75,  152 }, {   -8,   55 }, {   -9,   68 }, 
+    {  -12,   54 }, {  -84,  171 }, {  -93,  186 }, {   25,   12 }, 
+    { -104,  222 }, {  -40,   92 }, {  -51,   93 }, {  110, -169 }, 
+    {    3,   52 }, {   17,   33 }, {   55,  -45 }, {   28,    1 }, 
+    {   -5,   55 }, {   29,   -4 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  }
+};
+
+static const Short
+INIT_ABS_FLAG[3][80][2] =
+{
+  {
+    {  -12,   72 }, {  -10,   79 }, {  -11,   87 }, {  -14,   94 }, 
+    {  -35,  136 }, {  -10,   58 }, {   -1,   54 }, {  -17,   86 }, 
+    {   -5,   70 }, {  -22,  105 }, {  -13,   70 }, {   -2,   59 }, 
+    {  -13,   81 }, {  -21,   96 }, {   -3,   73 }, {  -24,   90 }, 
+    {  -19,   88 }, {   -1,   63 }, {    1,   60 }, {  -17,   97 }, 
+    {   -7,   69 }, {  -20,   95 }, {  -11,   84 }, {  -27,  110 }, 
+    {  -12,   96 }, {   -9,   72 }, {   -8,   76 }, {   -4,   75 }, 
+    {   -3,   76 }, {   -9,   94 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {  -11,   65 }, {   -4,   66 }, {   -9,   82 }, {  -24,  107 }, 
+    {  -24,  111 }, {  -18,   58 }, {  -10,   61 }, {  -19,   82 }, 
+    {  -28,   97 }, {    6,   47 }, {  -12,   50 }, {  -17,   73 }, 
+    {   -8,   66 }, {  -44,  115 }, {  -17,   86 }, {  -26,   74 }, 
+    {   -4,   48 }, {  -43,  115 }, {  -58,  141 }, {  -51,  137 }, 
+    {  -51,  117 }, {  -85,  176 }, {  -47,  120 }, {  -95,  202 }, 
+    {  -65,  159 }, {   -2,   53 }, {    7,   43 }, {   -2,   67 }, 
+    {    3,   62 }, {    4,   67 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  },
+  {
+    {   -2,   49 }, {  -13,   81 }, {  -11,   82 }, {  -13,   88 }, 
+    {  -24,  112 }, {   -4,   44 }, {  -17,   77 }, {  -16,   82 }, 
+    {  -19,   89 }, {  -28,  110 }, {  -12,   64 }, {  -11,   70 }, 
+    {  -18,   88 }, {   -6,   67 }, {  -19,   97 }, {  -17,   76 }, 
+    {  -27,  100 }, {  -18,   88 }, {  -13,   84 }, {  -17,   94 }, 
+    {  -11,   73 }, {  -15,   83 }, {  -10,   77 }, {  -10,   80 }, 
+    {  -12,   91 }, {   -8,   63 }, {   -7,   71 }, {   -6,   73 }, 
+    {   -8,   80 }, {   -9,   90 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   14,   20 }, {   -7,   68 }, {   -4,   66 }, {   -8,   76 }, 
+    {  -50,  148 }, {    2,   22 }, {   11,   15 }, {   -4,   49 }, 
+    {  -41,  117 }, {  -60,  149 }, {  -12,   49 }, {   -6,   55 }, 
+    {    1,   44 }, {   -5,   58 }, {  -12,   73 }, {   13,    9 }, 
+    {    5,   26 }, {  -29,  101 }, {    0,   46 }, {  -23,   92 }, 
+    {  -12,   57 }, {    6,   30 }, {   35,   -4 }, {   42,  -24 }, 
+    {   22,   24 }, {   24,    0 }, {   11,   34 }, {    2,   61 }, 
+    {   -5,   75 }, {    4,   62 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  },
+  {
+    {    0,   43 }, {   -6,   65 }, {   -7,   71 }, {  -31,  117 }, 
+    {  -25,  109 }, {  -20,   76 }, {  -14,   73 }, {  -20,   88 }, 
+    {  -21,   92 }, {   -6,   71 }, {  -19,   73 }, {  -34,  108 }, 
+    {  -27,  101 }, {   -7,   69 }, {   -7,   75 }, {  -18,   77 }, 
+    {   -7,   64 }, {  -20,   91 }, {   -9,   75 }, {   -7,   78 }, 
+    {  -26,   98 }, {  -13,   81 }, {   -6,   69 }, {  -12,   83 }, 
+    {   -2,   70 }, {   -3,   50 }, {   -6,   66 }, {   -7,   73 }, 
+    {   -6,   75 }, {  -11,   91 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {   19,   10 }, {    2,   49 }, {    4,   52 }, {   -4,   69 }, 
+    {  -32,  114 }, {   13,   -1 }, {  -29,   85 }, {  -64,  143 }, 
+    {  -90,  186 }, {   26,    4 }, {  -24,   68 }, {    8,   30 }, 
+    {  -10,   61 }, {  -16,   78 }, {  -27,   96 }, {   31,  -16 }, 
+    {  -12,   54 }, {  -15,   70 }, {  -68,  158 }, {   31,   12 }, 
+    {   -8,   44 }, {  -32,   63 }, {  -36,   81 }, {  -53,  106 }, 
+    {   36,   12 }, {   26,   -5 }, {   19,   17 }, {  -22,  101 }, 
+    {    5,   54 }, {    8,   53 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }, {    0,   64 }, {    0,   64 } 
+  }
+};
+
+// initial probability for motion vector predictor index
+static const Short
+INIT_MVP_IDX[3][NUM_MVP_IDX_CTX][2] =
+{
+  {
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   64 }, {    0,   64 }
+  }
+};
+
+// initial probability for ALF flag
+static const Short
+INIT_ALF_FLAG[3][NUM_ALF_FLAG_CTX][2] =
+{
+  {
+    {   50,  -48 }
+  },
+  {
+    {   27,  -20 }
+  },
+  {
+    {  -12,   68 }
+  }
+};
+
+// initial probability for ALF side information (unsigned)
+static const Short
+INIT_ALF_UVLC[3][NUM_ALF_UVLC_CTX][2] =
+{
+  {
+    {    1,   66 }, {   -3,   77 }
+  },
+  {
+    {   -5,   75 }, {  -14,   94 }
+  },
+  {
+    {   -5,   72 }, {  -30,  122 }
+  }
+};
+
+// initial probability for ALF side information (signed)
+static const Short
+INIT_ALF_SVLC[3][NUM_ALF_SVLC_CTX][2] =
+{
+  {
+    {   11,   57 }, {   -1,   62 }, {    0,   64 }
+  },
+  {
+    {    6,   66 }, {   -1,   64 }, {    0,   64 }
+  },
+  {
+    {    1,   73 }, {    2,   61 }, {    0,   64 }
+  }
+};
+#if MTK_SAO
+// initial probability for ALF flag
+static const Short
+INIT_AO_FLAG[3][NUM_AO_FLAG_CTX][2] =
+{
+  {
+    {   50,  -48 }
+  },
+  {
+    {   27,  -20 }
+  },
+  {
+    {  -12,   68 }
+  }
+};
+
+// initial probability for ALF side information (unsigned)
+static const Short
+INIT_AO_UVLC[3][NUM_AO_UVLC_CTX][2] =
+{
+  {
+    {    1,   66 }, {   -3,   77 }
+  },
+  {
+    {   -5,   75 }, {  -14,   94 }
+  },
+  {
+    {   -5,   72 }, {  -30,  122 }
+  }
+};
+
+// initial probability for ALF side information (signed)
+static const Short
+INIT_AO_SVLC[3][NUM_AO_SVLC_CTX][2] =
+{
+  {
+    {   11,   57 }, {   -1,   62 }, {    0,   64 }
+  },
+  {
+    {    6,   66 }, {   -1,   64 }, {    0,   64 }
+  },
+  {
+    {    1,   73 }, {    2,   61 }, {    0,   64 }
+  }
+};
+#endif
+
+static const Short
+INIT_TRANS_SUBDIV_FLAG[3][NUM_TRANS_SUBDIV_FLAG_CTX][2] =
+{
+  {
+    {    0,    0 }, {   12,   12 }, {   22,    4 }, {   -2,   49 }, 
+    {    4,   46 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {    0,   13 }, {  -28,   89 }, {  -30,   99 }, {  -34,  106 }, 
+    {  -19,   76 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }
+  },
+  {
+    {  -11,   38 }, {  -31,   88 }, {  -42,  118 }, {  -47,  130 }, 
+    {  -21,   73 }, {    0,   64 }, {    0,   64 }, {    0,   64 }, 
+    {    0,   64 }, {    0,   64 }
+  }
+};
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+static const Short
+INIT_INTRA_DMM[3][NUM_DMM_CTX][2] =
+{
+ {
+   {   0,   64 }, {   0,   64 }
+ },
+ {
+   {   0,   64 }, {   0,   64 }
+ },
+ {
+   {   0,   64 }, {   0,   64 }
+ }
+};
+
+static const Short
+INIT_INTRA_WEDGELET[3][NUM_WEDGE_CTX][2] = 
+{
+  {
+    {   0,   64 }, {   0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {   0,   64 }, {   0,   64 }, {    0,   64 }, {    0,   64 }
+  },
+  {
+    {   0,   64 }, {   0,   64 }, {    0,   64 }, {    0,   64 }
+  }
+};
+#endif
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/SEI.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/SEI.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/SEI.h	(revision 19)
@@ -0,0 +1,110 @@
+/* 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.
+ */
+
+
+
+#pragma once
+
+/**
+ * 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: /tags/0.2r1/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComAdaptiveLoopFilter.cpp	(revision 19)
@@ -0,0 +1,3545 @@
+/* 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     TComAdaptiveLoopFilter.cpp
+    \brief    adaptive loop filter class
+*/
+
+#include "TComAdaptiveLoopFilter.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+#if TI_ALF_MAX_VSIZE_7
+Int TComAdaptiveLoopFilter::m_pattern9x9Sym[39] = 
+#else
+Int TComAdaptiveLoopFilter::m_pattern9x9Sym[41] = 
+#endif
+{
+                   0,
+               1,  2,  3,
+           4,  5,  6,  7,  8,
+       9, 10, 11, 12, 13, 14, 15,
+#if TI_ALF_MAX_VSIZE_7
+      16, 17, 18, 19, 18, 17, 16,
+#else
+  16, 17, 18, 19, 20, 19, 18, 17, 16,
+#endif
+      15, 14, 13, 12, 11, 10,  9, 
+           8,  7,  6,  5,  4,
+               3,  2,  1,
+                   0
+};
+ 
+#if TI_ALF_MAX_VSIZE_7
+Int TComAdaptiveLoopFilter::m_weights9x9Sym[21] = 
+#else
+Int TComAdaptiveLoopFilter::m_weights9x9Sym[22] = 
+#endif
+{
+#if !TI_ALF_MAX_VSIZE_7
+                   2,
+#endif
+               2,  2,  2,   
+           2,  2,  2,  2,  2, 
+       2,  2,  2,  2,  2,  2,  2,  
+   2,  2,  2,  2,  1,  1
+};
+
+#if TI_ALF_MAX_VSIZE_7
+Int TComAdaptiveLoopFilter::m_pattern9x9Sym_Quart[42] = 
+{
+   0,  0,  0,  0,  0,  0,  0,  0,  0,
+   0,  0,  0,  1,  2,  3,  0,  0,  0,
+   0,  0,  4,  5,  6,  7,  8,  0,  0,  
+   0,  9, 10, 11, 12, 13, 14, 15,  0,
+  16, 17, 18, 19, 20, 21
+};
+#else
+Int TComAdaptiveLoopFilter::m_pattern9x9Sym_Quart[42] = 
+{
+   0,  0,  0,  0,  1,  0,  0,  0,  0,
+   0,  0,  0,  2,  3,  4,  0,  0,  0,
+   0,  0,  5,  6,  7,  8,  9,  0,  0,  
+   0, 10, 11, 12, 13, 14, 15, 16,  0,
+  17, 18, 19, 20, 21, 22
+};
+#endif
+
+Int TComAdaptiveLoopFilter::m_pattern7x7Sym[25] = 
+{
+                   0,
+             1,  2,  3,
+       4,  5,  6,  7,  8,
+       9, 10, 11, 12, 11, 10, 9,
+           8,  7,  6,  5,  4,
+           3,  2,  1,
+             0
+};
+
+Int TComAdaptiveLoopFilter::m_weights7x7Sym[14] = 
+{
+                  2,  
+              2,  2,  2,   
+        2,  2,  2,  2,  2,    
+      2,  2,  2,  1,  1
+};
+
+Int TComAdaptiveLoopFilter::m_pattern7x7Sym_Quart[42] = 
+{
+   0,  0,  0,  0,  0,  0,  0,  0,  0,
+   0,  0,  0,  0,  1,  0,  0,  0,  0,
+   0,  0,  0,  2,  3,  4,  0,  0,  0,
+   0,  0,  5,  6,  7,  8,  9,  0,  0,  
+   0, 10, 11, 12, 13, 14,  
+};
+
+Int TComAdaptiveLoopFilter::m_pattern5x5Sym[13] = 
+{
+                   0,
+             1,  2,  3,
+       4,  5,  6,  5,  4,
+               3,  2,  1,
+             0
+};
+
+Int TComAdaptiveLoopFilter::m_weights5x5Sym[8] = 
+{
+           2, 
+        2, 2, 2,
+     2, 2, 1, 1
+};
+
+Int TComAdaptiveLoopFilter::m_pattern5x5Sym_Quart[45] = 
+{
+   0,  0,  0,  0,  0,  0,  0,  0,  0,
+   0,  0,  0,  0,  0,  0,  0,  0,  0,
+   0,  0,  0,  0,  1,  0,  0,  0,  0,
+   0,  0,  0,  2,  3,  4,  0,  0,  0,
+   0,  0,  5,  6,  7,  8,  0,  0,  0,  
+};
+
+#if TI_ALF_MAX_VSIZE_7
+Int TComAdaptiveLoopFilter::m_pattern9x9Sym_9[39] = 
+#else
+Int TComAdaptiveLoopFilter::m_pattern9x9Sym_9[41] = 
+#endif
+{
+#if !TI_ALF_MAX_VSIZE_7
+                   4,
+#endif
+              12, 13, 14,  
+          20, 21, 22, 23, 24, 
+      28, 29, 30, 31, 32, 33, 34,      
+  36, 37, 38, 39, 40, 39, 38, 37, 36, 
+      34, 33, 32, 31, 30, 29, 28,  
+          24, 23, 22, 21, 20, 
+              14, 13, 12,
+#if !TI_ALF_MAX_VSIZE_7
+                   4,  
+#endif
+};
+
+Int TComAdaptiveLoopFilter::m_pattern9x9Sym_7[25] = 
+{    
+               13,   
+           21, 22, 23,  
+       29, 30, 31, 32, 33,       
+   37, 38, 39, 40, 39, 38, 37,  
+       33, 32, 31, 30, 29,   
+           23, 22, 21,  
+               13  
+                     
+};
+
+Int TComAdaptiveLoopFilter::m_pattern9x9Sym_5[13] = 
+{
+          22, 
+      30, 31, 32,    
+  38, 39, 40, 39, 38, 
+      32, 31, 30, 
+          22,  
+ };
+
+Int* TComAdaptiveLoopFilter::m_patternTab_filt[NO_TEST_FILT] =
+{
+  m_pattern9x9Sym_9, m_pattern9x9Sym_7, m_pattern9x9Sym_5
+}; 
+
+Int* TComAdaptiveLoopFilter::m_patternTab[NO_TEST_FILT] =
+{
+  m_pattern9x9Sym, m_pattern7x7Sym, m_pattern5x5Sym
+}; 
+
+Int* TComAdaptiveLoopFilter::m_patternMapTab[NO_TEST_FILT] =
+{
+  m_pattern9x9Sym_Quart, m_pattern7x7Sym_Quart, m_pattern5x5Sym_Quart
+};
+
+Int* TComAdaptiveLoopFilter::m_weightsTab[NO_TEST_FILT] =
+{
+  m_weights9x9Sym, m_weights7x7Sym, m_weights5x5Sym
+};
+
+Int TComAdaptiveLoopFilter::m_flTab[NO_TEST_FILT] =
+{
+  9/2, 7/2, 5/2
+};
+
+Int TComAdaptiveLoopFilter::m_sqrFiltLengthTab[NO_TEST_FILT] =
+{
+  SQR_FILT_LENGTH_9SYM, SQR_FILT_LENGTH_7SYM, SQR_FILT_LENGTH_5SYM
+};
+
+#if TI_ALF_MAX_VSIZE_7
+Int depthInt9x9Sym[21] = 
+#else
+Int depthInt9x9Sym[22] = 
+#endif
+{
+#if !TI_ALF_MAX_VSIZE_7
+              5, 
+#endif
+           5, 6, 5, 
+        5, 6, 7, 6, 5,
+     5, 6, 7, 8, 7, 6, 5,
+  5, 6, 7, 8, 9, 9 
+};
+
+Int depthInt7x7Sym[14] = 
+{
+           4, 
+        4, 5, 4, 
+     4, 5, 6, 5, 4, 
+  4, 5, 6, 7, 7 
+};
+
+Int depthInt5x5Sym[8] = 
+{
+        3,   
+     3, 4, 3,
+  3, 4, 5, 5  
+};
+
+Int* pDepthIntTab[NO_TEST_FILT] =
+{
+  depthInt5x5Sym, depthInt7x7Sym, depthInt9x9Sym
+};
+
+// scaling factor for quantization of filter coefficients (9x9)
+const Int TComAdaptiveLoopFilter::m_aiSymmetricMag9x9[41] =
+{
+  2, 2, 2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 1
+};
+
+// scaling factor for quantization of filter coefficients (7x7)
+const Int TComAdaptiveLoopFilter::m_aiSymmetricMag7x7[25] =
+{
+  2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 1
+};
+
+// scaling factor for quantization of filter coefficients (5x5)
+const Int TComAdaptiveLoopFilter::m_aiSymmetricMag5x5[13] =
+{
+  2, 2, 2, 2, 2,
+  2, 2, 2, 2, 2,
+  2, 2, 1
+};
+
+#if TI_ALF_MAX_VSIZE_7
+const Int TComAdaptiveLoopFilter::m_aiSymmetricMag9x7[32] =
+{
+  2, 2, 2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 2, 2, 2, 2, 2,
+  2, 2, 2, 2, 1
+};
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComAdaptiveLoopFilter::TComAdaptiveLoopFilter()
+{
+  m_pcTempPicYuv = NULL;
+#if MTK_NONCROSS_INLOOP_FILTER
+  m_bUseNonCrossALF = false;
+#endif
+  m_bIsCreated = false;
+}
+
+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_imgpel(imgpel ***m2D, int d1, int d2)
+{
+  int i;
+  
+  if(!(*m2D = (imgpel **) calloc(d1, sizeof(imgpel *))))
+    FATAL_ERROR_0("initMatrix_imgpel: memory allocation problem\n", -1);
+  if(!((*m2D)[0] = (imgpel *) calloc(d1 * d2, sizeof(imgpel))))
+    FATAL_ERROR_0("initMatrix_imgpel: 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_imgpel(imgpel **m2D)
+{
+  if(m2D)
+  {
+    if(m2D[0])
+      free(m2D[0]);
+    else
+      FATAL_ERROR_0("destroyMatrix_imgpel: memory free problem\n", -1);
+    free(m2D);
+  } 
+  else
+  {
+    FATAL_ERROR_0("destroyMatrix_imgpel: memory free problem\n", -1);
+  }
+}
+
+Void TComAdaptiveLoopFilter::get_mem2Dpel(imgpel ***array2D, int rows, int columns)
+{
+  int i;
+  
+  if((*array2D      = (imgpel**)calloc(rows,        sizeof(imgpel*))) == NULL)
+    no_mem_exit("get_mem2Dpel: array2D");
+  if(((*array2D)[0] = (imgpel* )calloc(rows*columns,sizeof(imgpel ))) == NULL)
+    no_mem_exit("get_mem2Dpel: array2D");
+  
+  for(i=1 ; i<rows ; i++)
+    (*array2D)[i] =  (*array2D)[i-1] + columns  ;
+}
+
+Void TComAdaptiveLoopFilter::free_mem2Dpel(imgpel **array2D)
+{
+  if (array2D)
+  {
+    if (array2D[0])
+      free (array2D[0]);
+    else xError ("free_mem2Dpel: trying to free unused memory",100);
+    
+    free (array2D);
+  }
+  else
+  {
+    xError ("free_mem2Dpel: trying to free unused memory",100);
+  }
+}
+
+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 )
+{
+  m_bIsCreated = true;
+  if ( !m_pcTempPicYuv )
+  {
+    m_pcTempPicYuv = new TComPicYuv;
+    m_pcTempPicYuv->create( iPicWidth, iPicHeight, uiMaxCUWidth, uiMaxCUHeight, uiMaxCUDepth );
+  }
+  m_img_height = iPicHeight;
+  m_img_width = iPicWidth;
+#if !MQT_BA_RA
+  initMatrix_imgpel(&m_imgY_var, m_img_height, m_img_width); 
+#endif
+  initMatrix_int(&m_imgY_temp, m_img_height+2*VAR_SIZE+3, m_img_width+2*VAR_SIZE+3);
+#if MQT_BA_RA
+  initMatrix_int(&m_imgY_ver, m_img_height+2*VAR_SIZE+3, m_img_width+2*VAR_SIZE+3);
+  initMatrix_int(&m_imgY_hor, m_img_height+2*VAR_SIZE+3, m_img_width+2*VAR_SIZE+3);
+  for(Int i=0; i< NUM_ALF_CLASS_METHOD; i++)
+  {
+    get_mem2Dpel(&(m_varImgMethods[i]), m_img_width, m_img_width);
+  }
+#endif   
+
+  initMatrix_int(&m_filterCoeffSym, NO_VAR_BINS, MAX_SQR_FILT_LENGTH);
+  initMatrix_int(&m_filterCoeffPrevSelected, NO_VAR_BINS, MAX_SQR_FILT_LENGTH); 
+  initMatrix_int(&m_filterCoeffTmp, NO_VAR_BINS, MAX_SQR_FILT_LENGTH);      
+  initMatrix_int(&m_filterCoeffSymTmp, NO_VAR_BINS, MAX_SQR_FILT_LENGTH);   
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  m_uiNumLCUsInWidth   = m_img_width  / uiMaxCUWidth;
+  m_uiNumLCUsInHeight  = m_img_height / uiMaxCUHeight;
+
+  m_uiNumLCUsInWidth  += ( m_img_width % uiMaxCUWidth ) ? 1 : 0;
+  m_uiNumLCUsInHeight += ( m_img_height % uiMaxCUHeight ) ? 1 : 0;
+#endif
+
+#if MQT_BA_RA
+  createRegionIndexMap(m_varImgMethods[ALF_RA], m_img_width, m_img_height);
+#endif
+}
+
+Void TComAdaptiveLoopFilter::destroy()
+{
+  m_bIsCreated = false ;
+  if ( m_pcTempPicYuv )
+  {
+    m_pcTempPicYuv->destroy();
+    delete m_pcTempPicYuv;
+  }
+#if !MQT_BA_RA
+  destroyMatrix_imgpel(m_imgY_var); 
+#endif
+  destroyMatrix_int(m_imgY_temp);
+
+#if MQT_BA_RA
+  destroyMatrix_int(m_imgY_ver);
+  destroyMatrix_int(m_imgY_hor);
+  for(Int i=0; i< NUM_ALF_CLASS_METHOD; i++)
+  {
+    free_mem2Dpel(m_varImgMethods[i]);
+  }
+#endif  
+  destroyMatrix_int(m_filterCoeffSym);
+  destroyMatrix_int(m_filterCoeffPrevSelected);
+  destroyMatrix_int(m_filterCoeffTmp);
+  destroyMatrix_int(m_filterCoeffSymTmp);
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+#if TI_ALF_MAX_VSIZE_7
+Int TComAdaptiveLoopFilter::ALFTapHToTapV(Int tapH)
+{
+  return min<UInt>(tapH, 7);
+}
+
+Int TComAdaptiveLoopFilter::ALFFlHToFlV(Int flH)
+{
+  return min<UInt>(flH, 7/2);
+}
+
+Int TComAdaptiveLoopFilter::ALFTapHToNumCoeff(Int tapH)
+{
+  Int num_coeff;
+  
+  num_coeff = (Int)(tapH*tapH)/4 + 2;
+  if (tapH == 9)
+    num_coeff -= 1;
+  else
+    assert(tapH < 9);
+  
+  return num_coeff;
+}
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------
+// allocate / free / copy functions
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComAdaptiveLoopFilter::allocALFParam(ALFParam* pAlfParam)
+{
+  pAlfParam->alf_flag = 0;
+  
+  pAlfParam->coeff        = new Int[ALF_MAX_NUM_COEF];
+  pAlfParam->coeff_chroma = new Int[ALF_MAX_NUM_COEF_C];
+  
+  ::memset(pAlfParam->coeff,        0, sizeof(Int)*ALF_MAX_NUM_COEF   );
+  ::memset(pAlfParam->coeff_chroma, 0, sizeof(Int)*ALF_MAX_NUM_COEF_C );
+  pAlfParam->coeffmulti = new Int*[NO_VAR_BINS];
+  for (int i=0; i<NO_VAR_BINS; i++)
+  {
+    pAlfParam->coeffmulti[i] = new Int[ALF_MAX_NUM_COEF];
+    ::memset(pAlfParam->coeffmulti[i],        0, sizeof(Int)*ALF_MAX_NUM_COEF );
+  }
+#if TSB_ALF_HEADER
+  pAlfParam->num_cus_in_frame = m_uiNumCUsInFrame;
+  pAlfParam->num_alf_cu_flag  = 0;
+  pAlfParam->alf_cu_flag      = new UInt[(m_uiNumCUsInFrame << ((g_uiMaxCUDepth-1)*2))];
+#endif
+
+#if MQT_BA_RA
+  pAlfParam->alf_pcr_region_flag = 0;
+#endif
+}
+
+Void TComAdaptiveLoopFilter::freeALFParam(ALFParam* pAlfParam)
+{
+  assert(pAlfParam != NULL);
+  
+  if (pAlfParam->coeff != NULL)
+  {
+    delete[] pAlfParam->coeff;
+    pAlfParam->coeff = NULL;
+  }
+  
+  if (pAlfParam->coeff_chroma != NULL)
+  {
+    delete[] pAlfParam->coeff_chroma;
+    pAlfParam->coeff_chroma = NULL;
+  }
+  for (int i=0; i<NO_VAR_BINS; i++)
+  {
+    delete[] pAlfParam->coeffmulti[i];
+    pAlfParam->coeffmulti[i] = NULL;
+  }
+  delete[] pAlfParam->coeffmulti;
+  pAlfParam->coeffmulti = NULL;
+#if TSB_ALF_HEADER
+  if(pAlfParam->alf_cu_flag != NULL)
+  {
+    delete[] pAlfParam->alf_cu_flag;
+    pAlfParam->alf_cu_flag = NULL;
+  }
+#endif
+}
+
+Void TComAdaptiveLoopFilter::copyALFParam(ALFParam* pDesAlfParam, ALFParam* pSrcAlfParam)
+{
+  pDesAlfParam->alf_flag = pSrcAlfParam->alf_flag;
+  pDesAlfParam->cu_control_flag = pSrcAlfParam->cu_control_flag;
+  pDesAlfParam->chroma_idc = pSrcAlfParam->chroma_idc;
+  pDesAlfParam->tap = pSrcAlfParam->tap;
+#if TI_ALF_MAX_VSIZE_7
+  pDesAlfParam->tapV = pSrcAlfParam->tapV;
+#endif
+  pDesAlfParam->num_coeff = pSrcAlfParam->num_coeff;
+  pDesAlfParam->tap_chroma = pSrcAlfParam->tap_chroma;
+  pDesAlfParam->num_coeff_chroma = pSrcAlfParam->num_coeff_chroma;
+
+#if MQT_BA_RA
+  pDesAlfParam->alf_pcr_region_flag = pSrcAlfParam->alf_pcr_region_flag;
+#endif
+
+  ::memcpy(pDesAlfParam->coeff, pSrcAlfParam->coeff, sizeof(Int)*ALF_MAX_NUM_COEF);
+  ::memcpy(pDesAlfParam->coeff_chroma, pSrcAlfParam->coeff_chroma, sizeof(Int)*ALF_MAX_NUM_COEF_C);
+  pDesAlfParam->realfiltNo = pSrcAlfParam->realfiltNo;
+  pDesAlfParam->filtNo = pSrcAlfParam->filtNo;
+  ::memcpy(pDesAlfParam->filterPattern, pSrcAlfParam->filterPattern, sizeof(Int)*NO_VAR_BINS);
+  pDesAlfParam->startSecondFilter = pSrcAlfParam->startSecondFilter;
+  pDesAlfParam->noFilters = pSrcAlfParam->noFilters;
+  
+  //Coeff send related
+  pDesAlfParam->filters_per_group_diff = pSrcAlfParam->filters_per_group_diff; //this can be updated using codedVarBins
+  pDesAlfParam->filters_per_group = pSrcAlfParam->filters_per_group; //this can be updated using codedVarBins
+  ::memcpy(pDesAlfParam->codedVarBins, pSrcAlfParam->codedVarBins, sizeof(Int)*NO_VAR_BINS);
+  pDesAlfParam->forceCoeff0 = pSrcAlfParam->forceCoeff0;
+  pDesAlfParam->predMethod = pSrcAlfParam->predMethod;
+  for (int i=0; i<NO_VAR_BINS; i++)
+  {
+    ::memcpy(pDesAlfParam->coeffmulti[i], pSrcAlfParam->coeffmulti[i], sizeof(Int)*ALF_MAX_NUM_COEF);
+  }
+  
+#if TSB_ALF_HEADER
+  pDesAlfParam->num_alf_cu_flag = pSrcAlfParam->num_alf_cu_flag;
+  ::memcpy(pDesAlfParam->alf_cu_flag, pSrcAlfParam->alf_cu_flag, sizeof(UInt)*pSrcAlfParam->num_alf_cu_flag);
+#endif
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// prediction of filter coefficients
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComAdaptiveLoopFilter::predictALFCoeff( ALFParam* pAlfParam)
+{
+  Int i, sum, pred, tap, N;
+  const Int* pFiltMag = NULL;
+  
+  tap = pAlfParam->tap;
+#if TI_ALF_MAX_VSIZE_7
+  Int tapV = pAlfParam->tapV;
+#endif
+  
+  switch(tap)
+  {
+    case 5:
+      pFiltMag = m_aiSymmetricMag5x5;
+      break;
+    case 7:
+      pFiltMag = m_aiSymmetricMag7x7;
+      break;
+    case 9:
+#if TI_ALF_MAX_VSIZE_7
+      pFiltMag = m_aiSymmetricMag9x7;
+#else
+      pFiltMag = m_aiSymmetricMag9x9;
+#endif
+      break;
+    default:
+      assert(0);
+      break;
+  }
+#if TI_ALF_MAX_VSIZE_7
+  N = (tap * tapV + 1) >> 1;
+#else
+  N = (tap * tap + 1) >> 1;
+#endif
+  sum=0;
+  for(i=0; i<N-1;i++)
+  {
+    sum+=pFiltMag[i]*pAlfParam->coeff[i];
+  }
+  pred=(1<<ALF_NUM_BIT_SHIFT)-sum;
+  pAlfParam->coeff[N-1]=pred-pAlfParam->coeff[N-1];
+}
+
+Void TComAdaptiveLoopFilter::predictALFCoeffChroma( ALFParam* pAlfParam )
+{
+  Int i, sum, pred, tap, N;
+  const Int* pFiltMag = NULL;
+  
+  tap = pAlfParam->tap_chroma;
+  switch(tap)
+  {
+    case 5:
+      pFiltMag = m_aiSymmetricMag5x5;
+      break;
+    case 7:
+      pFiltMag = m_aiSymmetricMag7x7;
+      break;
+    case 9:
+      pFiltMag = m_aiSymmetricMag9x9;
+      break;
+    default:
+      assert(0);
+      break;
+  }
+  N = (tap*tap+1)>>1;
+  sum=0;
+  for(i=0; i<N;i++)
+  {
+    sum+=pFiltMag[i]*pAlfParam->coeff_chroma[i];
+  }
+  pred=(1<<ALF_NUM_BIT_SHIFT)-(sum-pAlfParam->coeff_chroma[N-1]);
+  pAlfParam->coeff_chroma[N-1]=pred-pAlfParam->coeff_chroma[N-1];
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// interface function for actual ALF process
+// --------------------------------------------------------------------------------------------------------------------
+
+/**
+ \param pcPic         picture (TComPic) class (input/output)
+ \param pcAlfParam    ALF parameter
+ \todo   for temporal buffer, it uses residual picture buffer, which may not be safe. Make it be safer.
+ */
+Void TComAdaptiveLoopFilter::ALFProcess(TComPic* pcPic, ALFParam* pcAlfParam)
+{
+  if(!pcAlfParam->alf_flag)
+  {
+    return;
+  }
+  
+  TComPicYuv* pcPicYuvRec    = pcPic->getPicYuvRec();
+  TComPicYuv* pcPicYuvExtRec = m_pcTempPicYuv;
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(!m_bUseNonCrossALF)
+  {
+#endif     
+  pcPicYuvRec   ->copyToPic          ( pcPicYuvExtRec );
+  pcPicYuvExtRec->setBorderExtension ( false );
+  pcPicYuvExtRec->extendPicBorder    ();
+#if MTK_NONCROSS_INLOOP_FILTER
+  }
+#endif
+
+#if TSB_ALF_HEADER
+  if(pcAlfParam->cu_control_flag)
+  {
+    UInt idx = 0;
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(!m_bUseNonCrossALF)
+    {
+#endif
+    for(UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++)
+    {
+      TComDataCU *pcCU = pcPic->getCU(uiCUAddr);
+      setAlfCtrlFlags(pcAlfParam, pcCU, 0, 0, idx);
+    }
+#if MTK_NONCROSS_INLOOP_FILTER
+    }
+    else
+    {
+      setAlfCtrlFlagsforSlices(pcAlfParam, idx);
+    }
+#endif
+
+  }
+#endif
+  xALFLuma_qc(pcPic, pcAlfParam, pcPicYuvExtRec, pcPicYuvRec);
+  
+  if(pcAlfParam->chroma_idc)
+  {
+    predictALFCoeffChroma(pcAlfParam);
+    xALFChroma( pcAlfParam, pcPicYuvExtRec, pcPicYuvRec);
+  }
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// ALF for luma
+// --------------------------------------------------------------------------------------------------------------------
+Void TComAdaptiveLoopFilter::xALFLuma_qc(TComPic* pcPic, ALFParam* pcAlfParam, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest)
+{
+  Int    LumaStride = pcPicDec->getStride();
+  imgpel* pDec = (imgpel*)pcPicDec->getLumaAddr();
+  imgpel* pRest = (imgpel*)pcPicRest->getLumaAddr();
+  
+  //Decode and reconst filter coefficients
+  DecFilter_qc(pDec,pcAlfParam,LumaStride);
+  //set maskImg using cu adaptive one.
+
+#if MQT_BA_RA
+  m_uiVarGenMethod = pcAlfParam->alf_pcr_region_flag;
+  m_imgY_var       = m_varImgMethods[m_uiVarGenMethod];
+#endif
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  memset(m_imgY_temp[0],0,sizeof(int)*(m_img_height+2*VAR_SIZE)*(m_img_width+2*VAR_SIZE));
+  if(!m_bUseNonCrossALF)
+  {
+    calcVar(0, 0, m_imgY_var, pDec, FILTER_LENGTH/2, VAR_SIZE, m_img_height, m_img_width, LumaStride);
+#endif
+
+
+  if(pcAlfParam->cu_control_flag)
+  {
+    xCUAdaptive_qc(pcPic, pcAlfParam, pRest, pDec, LumaStride);
+  }  
+  else
+  {
+    //then do whole frame filtering
+    filterFrame(pRest, pDec, pcAlfParam->realfiltNo, LumaStride);
+  }
+#if MTK_NONCROSS_INLOOP_FILTER
+  }
+  else
+  {
+    for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+    {
+      CAlfSlice* pSlice = &(m_pSlice[s]);
+
+      pSlice->copySliceLuma((Pel*)pDec, (Pel*)pRest, LumaStride);
+      pSlice->extendSliceBorderLuma((Pel*)pDec, LumaStride, (UInt)EXTEND_NUM_PEL);
+
+#if MQT_BA_RA
+      if(m_uiVarGenMethod != ALF_RA)
+      {
+#endif
+        calcVarforOneSlice(pSlice, m_imgY_var, pDec, FILTER_LENGTH/2, VAR_SIZE, LumaStride);
+#if MQT_BA_RA
+      }
+#endif
+      xFilterOneSlice(pSlice, pDec, pRest, LumaStride, pcAlfParam);
+
+    }
+  }
+#endif
+
+}
+
+
+Void TComAdaptiveLoopFilter::DecFilter_qc(imgpel* imgY_rec,ALFParam* pcAlfParam, int Stride)
+{
+  int i;
+  int numBits = NUM_BITS; 
+#if !MTK_NONCROSS_INLOOP_FILTER
+  int fl=FILTER_LENGTH/2;
+#endif
+  int **pfilterCoeffSym;
+  pfilterCoeffSym= m_filterCoeffSym;
+  
+  if(pcAlfParam->filtNo>=0)
+  {
+    //// Reconstruct filter coefficients
+    reconstructFilterCoeffs( pcAlfParam, pfilterCoeffSym, numBits);
+  }
+  else
+  {
+    for(i = 0; i < NO_VAR_BINS; i++)
+    {
+      pcAlfParam->varIndTab[i]=0;
+      memset(pfilterCoeffSym[i],0,sizeof(int)*MAX_SQR_FILT_LENGTH);
+    }
+  }
+  getCurrentFilter(pfilterCoeffSym,pcAlfParam);
+#if !MTK_NONCROSS_INLOOP_FILTER
+  memset(m_imgY_temp[0],0,sizeof(int)*(m_img_height+2*VAR_SIZE)*(m_img_width+2*VAR_SIZE));
+  
+  calcVar(m_imgY_var, imgY_rec, fl, VAR_SIZE, m_img_height, m_img_width, Stride);
+#endif
+}
+
+Void TComAdaptiveLoopFilter::getCurrentFilter(int **filterCoeffSym,ALFParam* pcAlfParam)
+{ 
+  int i,  k, varInd;
+  int *patternMap;
+  int *patternMapTab[3]={m_pattern9x9Sym_Quart, m_pattern7x7Sym_Quart, m_pattern5x5Sym_Quart};
+  {
+    for(varInd=0; varInd<NO_VAR_BINS; ++varInd)
+    {
+      memset(m_filterCoeffPrevSelected[varInd],0,sizeof(int)*MAX_SQR_FILT_LENGTH);
+    }
+    patternMap=patternMapTab[pcAlfParam->realfiltNo];
+    for(varInd=0; varInd<NO_VAR_BINS; ++varInd)
+    {
+      k=0;
+      for(i = 0; i < MAX_SQR_FILT_LENGTH; i++)
+      {
+        if (patternMap[i]>0)
+        {
+          m_filterCoeffPrevSelected[varInd][i]=filterCoeffSym[pcAlfParam->varIndTab[varInd]][k];
+          k++;
+        }
+        else
+        {
+          m_filterCoeffPrevSelected[varInd][i]=0;
+        }
+      }
+    }
+  }
+}
+
+Void TComAdaptiveLoopFilter::reconstructFilterCoeffs(ALFParam* pcAlfParam,int **pfilterCoeffSym, int bit_depth)
+{
+  int i, src, ind;
+  
+  // Copy non zero filters in filterCoeffTmp
+  for(ind = 0; ind < pcAlfParam->filters_per_group_diff; ++ind)
+  {
+    for(i = 0; i < pcAlfParam->num_coeff; i++)
+      m_filterCoeffTmp[ind][i] = pcAlfParam->coeffmulti[ind][i];
+  }
+  // Undo prediction
+  for(ind = 0; ind < pcAlfParam->filters_per_group_diff; ++ind)
+  {
+    if((!pcAlfParam->predMethod) || (ind == 0)) 
+    {
+      memcpy(m_filterCoeffSymTmp[ind],m_filterCoeffTmp[ind],sizeof(int)*pcAlfParam->num_coeff);
+    }
+    else
+    {
+      // Prediction
+      for(i = 0; i < pcAlfParam->num_coeff; ++i)
+        m_filterCoeffSymTmp[ind][i] = (int)(m_filterCoeffTmp[ind][i] + m_filterCoeffSymTmp[ind - 1][i]);
+    }
+  }
+  
+  // Inverse quantization
+  // Add filters forced to zero
+  if(pcAlfParam->forceCoeff0)
+  {
+    assert(pcAlfParam->filters_per_group_diff < pcAlfParam->filters_per_group);
+    src = 0;
+    for(ind = 0; ind < pcAlfParam->filters_per_group; ++ind)
+    {
+      if(pcAlfParam->codedVarBins[ind])
+      {
+        memcpy(pfilterCoeffSym[ind],m_filterCoeffSymTmp[src],sizeof(int)*pcAlfParam->num_coeff);
+        ++src;
+      }
+      else
+      {
+        memset(pfilterCoeffSym[ind],0,sizeof(int)*pcAlfParam->num_coeff);
+      }
+    }
+    assert(src == pcAlfParam->filters_per_group_diff);
+  }
+  else
+  {
+    assert(pcAlfParam->filters_per_group_diff == pcAlfParam->filters_per_group);
+    for(ind = 0; ind < pcAlfParam->filters_per_group; ++ind)
+      memcpy(pfilterCoeffSym[ind],m_filterCoeffSymTmp[ind],sizeof(int)*pcAlfParam->num_coeff);
+  }
+}
+
+
+static imgpel Clip_post(int high, int val)
+{
+  return (imgpel)(((val > high)? high: val));
+}
+#if MTK_NONCROSS_INLOOP_FILTER
+Void TComAdaptiveLoopFilter::calcVar(int ypos, int xpos, imgpel **imgY_var, imgpel *imgY_pad, int pad_size, int fl, int img_height, int img_width, int img_stride)
+#else
+Void TComAdaptiveLoopFilter::calcVar(imgpel **imgY_var, imgpel *imgY_pad, int pad_size, int fl, int img_height, int img_width, int img_stride)
+#endif
+{
+
+#if MQT_BA_RA
+  if(m_uiVarGenMethod == ALF_RA)
+  {
+    return;
+  }
+
+  static Int shift_h     = (Int)(log((double)VAR_SIZE_H)/log(2.0));
+  static Int shift_w     = (Int)(log((double)VAR_SIZE_W)/log(2.0));
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  Int start_height = ypos;
+  Int start_width  = xpos;
+  Int end_height   = ypos + img_height;
+  Int end_width    = xpos + img_width;
+#else
+  Int start_height = 0;
+  Int start_width = 0;
+  Int end_height = img_height;
+  Int end_width = img_width;
+#endif
+  Int i, j;
+  Int *p_imgY_temp;
+#if FULL_NBIT
+  Int shift= (11+ g_uiBitIncrement + g_uiBitDepth - 8);
+#else
+  Int shift= (11+ g_uiBitIncrement);
+#endif
+  Int fl2plusOne= (VAR_SIZE<<1)+1; //3
+  Int pad_offset = pad_size-fl-1;
+  Int var_max= NO_VAR_BINS-1;
+  Int mult_fact_int_tab[4]= {1,114,41,21};
+  Int mult_fact_int = mult_fact_int_tab[VAR_SIZE];
+  Int avg_var;
+  Int vertical, horizontal;
+  Int direction;
+  Int step1 = NO_VAR_BINS/3 - 1;
+  Int th[NO_VAR_BINS] = {0, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4}; 
+
+  for(i = 1+start_height; i < end_height + fl2plusOne; i++)
+  {
+    Int yoffset = (pad_offset+i-pad_size) * img_stride + pad_offset-pad_size;
+    imgpel *p_imgY_pad = &imgY_pad[yoffset];
+    imgpel *p_imgY_pad_up   = &imgY_pad[yoffset + img_stride];
+    imgpel *p_imgY_pad_down = &imgY_pad[yoffset - img_stride];
+    p_imgY_temp = (Int*)&m_imgY_temp[i-1][start_width];
+    for(j = 1+start_width; j < end_width +fl2plusOne; j++)  
+    {
+      vertical = abs((p_imgY_pad[j]<<1) - p_imgY_pad_down[j] - p_imgY_pad_up[j]);
+      horizontal = abs((p_imgY_pad[j]<<1) - p_imgY_pad[j+1] - p_imgY_pad[j-1]);
+      m_imgY_ver[i-1][j-1] = vertical;
+      m_imgY_hor[i-1][j-1] = horizontal;
+      *(p_imgY_temp++) = vertical + horizontal;
+    }
+
+    for(j = 1+start_width; j < end_width + fl2plusOne; j=j+4)  
+    {
+      m_imgY_temp [i-1][j] =  (m_imgY_temp [i-1][j-1] + m_imgY_temp [i-1][j+4])
+        + ((m_imgY_temp [i-1][j] + m_imgY_temp [i-1][j+3]) << 1)
+        + ((m_imgY_temp [i-1][j+1] + m_imgY_temp [i-1][j+2]) * 3);
+      m_imgY_ver[i-1][j] = m_imgY_ver[i-1][j] + m_imgY_ver[i-1][j+1] + m_imgY_ver[i-1][j+2] + m_imgY_ver[i-1][j+3];      
+      m_imgY_hor[i-1][j] = m_imgY_hor[i-1][j] + m_imgY_hor[i-1][j+1] + m_imgY_hor[i-1][j+2] + m_imgY_hor[i-1][j+3];    
+    }
+  }
+
+  for(i = 1+start_height; i < end_height + 1; i=i+4)
+  {
+    for(j = 1+start_width; j < end_width + 1; j=j+4)  
+    {
+      m_imgY_temp [i-1][j-1] =  (m_imgY_temp [i-1][j]+m_imgY_temp [i+4][j])
+        + ((m_imgY_temp [i][j]+m_imgY_temp [i+3][j]) << 1)
+        + ((m_imgY_temp [i+1][j]+m_imgY_temp [i+2][j]) * 3);
+
+      m_imgY_ver[i-1][j-1] = m_imgY_ver[i][j] + m_imgY_ver[i+1][j] + m_imgY_ver[i+2][j] + m_imgY_ver[i+3][j];  
+      m_imgY_hor[i-1][j-1] = m_imgY_hor[i][j] + m_imgY_hor[i+1][j] + m_imgY_hor[i+2][j] + m_imgY_hor[i+3][j];    
+      avg_var = m_imgY_temp [i-1][j-1]>>(shift_h + shift_w);
+      avg_var = (imgpel) Clip_post(var_max, (avg_var * mult_fact_int)>>shift);
+      avg_var = th[avg_var];
+
+      direction = 0;
+      if (m_imgY_ver[i-1][j-1] > 2*m_imgY_hor[i-1][j-1]) direction = 1; //vertical
+      if (m_imgY_hor[i-1][j-1] > 2*m_imgY_ver[i-1][j-1]) direction = 2; //horizontal
+
+      avg_var = Clip_post(step1, (Int) avg_var ) + (step1+1)*direction; 
+      imgY_var[(i - 1)>>shift_h][(j - 1)>>shift_w] = avg_var;   
+    }
+  }
+
+#else
+
+  int i, j, ii, jj;
+  int sum;
+  int *p_imgY_temp;
+#if FULL_NBIT
+  int shift= (11+ g_uiBitIncrement + g_uiBitDepth - 8);
+#else
+  int shift= (11+ g_uiBitIncrement);
+#endif
+  int fl2plusOne= (VAR_SIZE<<1)+1;
+  int pad_offset = pad_size-fl-1;
+  int var_max= NO_VAR_BINS-1;
+  int mult_fact_int_tab[4]= {1,114,41,21};
+  int mult_fact_int = mult_fact_int_tab[VAR_SIZE];
+  
+  if (VAR_SIZE ==0)
+  {
+    imgpel *p_imgY_var;
+#if FULL_NBIT
+    shift = g_uiBitIncrement + g_uiBitDepth - 8;
+#else
+    shift = g_uiBitIncrement;
+#endif
+    //current
+    for(i = 1; i < img_height + fl2plusOne; i++)
+    {
+      imgpel *p_imgY_pad = &imgY_pad[(pad_offset+i-pad_size) * img_stride + pad_offset-pad_size];
+      imgpel *p_imgY_pad_up   = &imgY_pad[(pad_offset+i+1-pad_size) * img_stride + pad_offset-pad_size];
+      imgpel *p_imgY_pad_down = &imgY_pad[(pad_offset+i-1-pad_size) * img_stride + pad_offset-pad_size];
+      p_imgY_temp = (int*)&m_imgY_temp[i-1][0];
+#if MTK_NONCROSS_INLOOP_FILTER
+      p_imgY_var  = &imgY_var [ypos+ i-1][xpos];
+#else
+      p_imgY_var  = &imgY_var [i-1][0];
+#endif
+      for(j = 1; j < img_width +fl2plusOne; j++)
+      {
+        *(p_imgY_temp) = abs((p_imgY_pad[j]<<1) - p_imgY_pad[j+1] - p_imgY_pad[j-1])+
+        abs((p_imgY_pad[j]<<1) - p_imgY_pad_down[j] - p_imgY_pad_up[j]);
+        *(p_imgY_var++) =(imgpel) Clip_post(var_max, (int) ((*(p_imgY_temp++))>>shift));
+      }
+    }
+    return;
+  }
+  
+  //current
+  for(i = 1; i < img_height + fl2plusOne; i++)
+  {
+    imgpel *p_imgY_pad = &imgY_pad[(pad_offset+i-pad_size) * img_stride + pad_offset-pad_size];
+    imgpel *p_imgY_pad_up   = &imgY_pad[(pad_offset+i+1-pad_size) * img_stride + pad_offset-pad_size];
+    imgpel *p_imgY_pad_down = &imgY_pad[(pad_offset+i-1-pad_size) * img_stride + pad_offset-pad_size];
+    p_imgY_temp = (int*)&m_imgY_temp[i-1][0];
+    for(j = 1; j < img_width +fl2plusOne; j++)
+    {
+      *(p_imgY_temp++) = abs((p_imgY_pad[j]<<1) - p_imgY_pad[j+1] - p_imgY_pad[j-1])+
+        abs((p_imgY_pad[j]<<1) - p_imgY_pad_down[j] - p_imgY_pad_up[j]);
+    }
+  }
+  {
+    //int temp;
+    int sum_0=0;
+    int y=img_height+((VAR_SIZE+1)<<1);
+
+    int *p_imgY_temp_sum;
+    i = fl;
+    j = fl;
+
+    memset(m_imgY_temp[y],0,sizeof(int)*(img_width+((VAR_SIZE+1)<<1)));
+    //--------------------------------------------------------------------------------------------
+
+    for(ii = i - fl; ii <= i + fl; ii++)
+    {
+      p_imgY_temp= (int*)&m_imgY_temp[ii][j - fl];
+      p_imgY_temp_sum=(int*)&m_imgY_temp[y][j - fl];
+      for(jj = j - fl; jj <= j + fl; jj++)
+      {
+        *(p_imgY_temp_sum++) += *(p_imgY_temp++);
+      }
+    }
+    p_imgY_temp_sum=(int*)&m_imgY_temp[y][j - fl];
+    for(jj = j - fl; jj <= j + fl; jj++)
+      sum_0+=*(p_imgY_temp_sum++);
+#if MTK_NONCROSS_INLOOP_FILTER
+    imgY_var[ypos+ i - fl][xpos+ j - fl] 
+#else
+    imgY_var[i - fl][j - fl] 
+#endif
+    = (imgpel) Clip_post(var_max, (int) ((sum_0 * mult_fact_int)>>shift));
+    //--------------------------------------------------------------------------------------------
+    sum = sum_0;
+    for(j = fl+1; j < img_width + fl; ++j)
+    {
+      int k=j+fl;
+      for(ii = i - fl; ii <= i + fl; ii++)
+        m_imgY_temp[y][k] += (m_imgY_temp[ii][k]);
+
+      sum += (m_imgY_temp[y][k]-m_imgY_temp[y][j - fl-1]);
+#if MTK_NONCROSS_INLOOP_FILTER
+      imgY_var[ypos+ i - fl][xpos+ j - fl] 
+#else
+      imgY_var[i - fl][j - fl] 
+#endif
+      = (imgpel) Clip_post(var_max, (int) ((sum * mult_fact_int)>>shift));
+
+    }
+    //--------------------------------------------------------------------------------------------
+
+    for(i = fl+1; i < img_height + fl; ++i)
+    {
+#if MTK_NONCROSS_INLOOP_FILTER
+      imgpel  *pimgY_var= &imgY_var[ypos+ i-fl][xpos];
+#else
+      imgpel  *pimgY_var= &imgY_var[i-fl][0];
+#endif
+      int *p_imgY_temp1;
+      int *p_imgY_temp2;
+      sum = sum_0;
+      j= fl;
+      p_imgY_temp1= (int*)&m_imgY_temp[i+fl  ][j - fl];
+      p_imgY_temp2= (int*)&m_imgY_temp[i-fl-1][j - fl];
+      p_imgY_temp_sum=(int*)&m_imgY_temp[y][j - fl];
+      for(jj = j - fl; jj <= j + fl; jj++)
+      {
+        int diff = *(p_imgY_temp1++)-*(p_imgY_temp2++);
+        *(p_imgY_temp_sum++) += diff;
+        sum += diff;
+      }
+      sum_0=sum;
+
+      *(pimgY_var++) = (imgpel) Clip_post(var_max, (int) ((sum * mult_fact_int)>>shift));
+      //--------------------------------------------------------------------------------------------
+      p_imgY_temp_sum=(int*)m_imgY_temp[y];
+      for(j = fl+1; j < img_width + fl; ++j)
+      {
+        int k = j+fl;
+        p_imgY_temp_sum[k] += (m_imgY_temp[i + fl][k]-m_imgY_temp[i-fl-1][k]);
+        sum += (p_imgY_temp_sum[k]-p_imgY_temp_sum[j-fl-1]);
+        *(pimgY_var++) = (imgpel) Clip_post(var_max, (int) ((sum * mult_fact_int)>>shift));
+      }
+    }
+  }
+#endif
+}
+
+
+#if MQT_BA_RA
+
+Void TComAdaptiveLoopFilter::createRegionIndexMap(imgpel **imgYVar, Int imgWidth, Int imgHeight)
+{
+  int varStepSizeWidth = VAR_SIZE_W;
+  int varStepSizeHeight = VAR_SIZE_H;
+  int shiftHeight = (int)(log((double)varStepSizeHeight)/log(2.0));
+  int shiftWidth = (int)(log((double)varStepSizeWidth)/log(2.0));
+
+  int i, j;
+  int regionTable[NO_VAR_BINS] = {0, 1, 4, 5, 15, 2, 3, 6, 14, 11, 10, 7, 13, 12,  9,  8}; 
+  int xInterval;
+  int yInterval;
+  int yIndex;
+  int yIndexOffset;
+  int yStartLine;
+  int yEndLine;
+
+  xInterval = ((( (imgWidth+63)/64) + 1) / 4 * 64)>>shiftWidth;  
+  yInterval = ((((imgHeight+63)/64) + 1) / 4 * 64)>>shiftHeight;
+
+  for (yIndex = 0; yIndex < 4 ; yIndex++)
+  {
+    yIndexOffset = yIndex * 4;
+    yStartLine = yIndex * yInterval;
+    yEndLine   = (yIndex == 3) ? imgHeight>>shiftHeight : (yStartLine+yInterval);
+
+    for(i = yStartLine; i < yEndLine ; i++)
+    {
+      for(j = 0; j < xInterval ; j++)
+      {
+        imgYVar[i][j] = regionTable[yIndexOffset+0];     
+      }
+
+      for(j = xInterval; j < xInterval*2 ; j++)
+      {
+        imgYVar[i][j] = regionTable[yIndexOffset+1];     
+      }
+
+      for(j = xInterval*2; j < xInterval*3 ; j++)
+      {
+        imgYVar[i][j] = regionTable[yIndexOffset+2];     
+      }
+
+      for(j = xInterval*3; j < imgWidth>>shiftWidth ; j++)
+      {
+        imgYVar[i][j] = regionTable[yIndexOffset+3];     
+      }
+    }
+  }
+
+}
+
+Void TComAdaptiveLoopFilter::filterFrame(imgpel *imgYRecPost, imgpel *imgYRec, int filtNo, int stride)
+{
+  Int varStepSizeWidth = VAR_SIZE_W;
+  Int varStepSizeHeight = VAR_SIZE_H;
+  Int shiftHeight = (Int)(log((double)varStepSizeHeight)/log(2.0));
+
+  Int i, j, pixelInt;
+  imgpel *pImgYVar,*pImgYPad;
+  Int maxVal=g_uiIBDI_MAX;
+  imgpel *pImgYPad1,*pImgYPad2,*pImgYPad3,*pImgYPad4,*pImgYPad5,*pImgYPad6;
+  Int lastCoef= MAX_SQR_FILT_LENGTH-1;
+  Int *coef = m_filterCoeffPrevSelected[0];
+  Int numBitsMinus1= NUM_BITS-1;
+  Int offset = (1<<(NUM_BITS-2));
+
+  switch(filtNo)
+  {
+  case 2:
+    for (i = 0; i < m_img_height; i++)
+    {
+      pImgYVar = m_imgY_var[i>>shiftHeight];
+      pImgYPad = imgYRec + i*stride;
+      {
+        pImgYPad1 = imgYRec + (i+1)*stride;
+        pImgYPad2 = imgYRec + (i-1)*stride;
+        pImgYPad3 = imgYRec + (i+2)*stride;
+        pImgYPad4 = imgYRec + (i-2)*stride;
+        pImgYPad5 = imgYRec + (i+3)*stride;
+        pImgYPad6 = imgYRec + (i-3)*stride;
+      }
+
+      for (j = 0; j < m_img_width; j++)
+      {
+        if (j%varStepSizeWidth==0) coef = m_filterCoeffPrevSelected[*(pImgYVar++)];
+        pixelInt=coef[lastCoef];
+
+        pixelInt += coef[22]* (pImgYPad3[j]+pImgYPad4[j]);
+
+        pixelInt += coef[30]* (pImgYPad1[j+1]+pImgYPad2[j-1]);
+        pixelInt += coef[31]* (pImgYPad1[j]  +pImgYPad2[j]);
+        pixelInt += coef[32]* (pImgYPad1[j-1]+pImgYPad2[j+1]);
+
+        pixelInt += coef[38]* (pImgYPad[j-2]+pImgYPad[j+2]);
+        pixelInt += coef[39]* (pImgYPad[j-1]+pImgYPad[j+1]);
+        pixelInt += coef[40]* (pImgYPad[j]);
+
+        pixelInt=(Int)((pixelInt+offset) >> (numBitsMinus1));
+        imgYRecPost[i*stride + j]=max(0, min(pixelInt,maxVal));
+      }
+    }
+    break;
+
+  case 1:
+    for (i = 0; i < m_img_height; i++)
+    {
+      pImgYVar = m_imgY_var[i>>shiftHeight];
+      pImgYPad = imgYRec + i*stride;
+      {
+        pImgYPad1 = imgYRec + (i+1)*stride;
+        pImgYPad2 = imgYRec + (i-1)*stride;
+        pImgYPad3 = imgYRec + (i+2)*stride;
+        pImgYPad4 = imgYRec + (i-2)*stride;
+        pImgYPad5 = imgYRec + (i+3)*stride;
+        pImgYPad6 = imgYRec + (i-3)*stride;
+      }
+
+      for (j = 0; j < m_img_width; j++)
+      {
+        if (j%varStepSizeWidth==0) coef = m_filterCoeffPrevSelected[*(pImgYVar++)];
+        pixelInt=coef[lastCoef];
+
+        pixelInt += coef[13]* (imgYRec[(i+3)*stride + j]+imgYRec[(i-3)*stride + j]);
+
+        pixelInt += coef[21]* (pImgYPad3[j+1]+pImgYPad4[j-1]);
+        pixelInt += coef[22]* (pImgYPad3[j]+pImgYPad4[j]);
+        pixelInt += coef[23]* (pImgYPad3[j-1]+pImgYPad4[j+1]);
+
+        pixelInt += coef[29]* (pImgYPad1[j+2]+pImgYPad2[j-2]);
+        pixelInt += coef[30]* (pImgYPad1[j+1]+pImgYPad2[j-1]);
+        pixelInt += coef[31]* (pImgYPad1[j]+pImgYPad2[j]);
+        pixelInt += coef[32]* (pImgYPad1[j-1]+pImgYPad2[j+1]);
+        pixelInt += coef[33]* (pImgYPad1[j-2]+pImgYPad2[j+2]);
+
+        pixelInt += coef[37]* (pImgYPad[j+3]+pImgYPad[j-3]);
+        pixelInt += coef[38]* (pImgYPad[j+2]+pImgYPad[j-2]);
+        pixelInt += coef[39]* (pImgYPad[j+1]+pImgYPad[j-1]);
+        pixelInt += coef[40]* (pImgYPad[j]);
+
+        pixelInt=(Int)((pixelInt+offset) >> (numBitsMinus1));
+        imgYRecPost[i*stride + j]=max(0, min(pixelInt,maxVal));
+      }
+    }
+    break;
+
+  case 0:
+    for (i = 0; i < m_img_height; i++)
+    {
+      pImgYVar = m_imgY_var[i>>shiftHeight];
+      pImgYPad = imgYRec + i*stride;
+      {
+        pImgYPad1 = imgYRec + (i+1)*stride;
+        pImgYPad2 = imgYRec + (i-1)*stride;
+        pImgYPad3 = imgYRec + (i+2)*stride;
+        pImgYPad4 = imgYRec + (i-2)*stride;
+        pImgYPad5 = imgYRec + (i+3)*stride;
+        pImgYPad6 = imgYRec + (i-3)*stride;
+      }
+
+      for (j = 0; j < m_img_width; j++)
+      {
+        if (j%varStepSizeWidth==0) coef = m_filterCoeffPrevSelected[*(pImgYVar++)];
+        pixelInt=coef[lastCoef];
+
+#if !TI_ALF_MAX_VSIZE_7
+        pixelInt += coef[4]* (imgYRec[(i+4)*stride + j]+imgYRec[(i-4)*stride + j]);
+#endif        
+        pixelInt += coef[12]* (pImgYPad5[j+1]+pImgYPad6[j-1]);
+        pixelInt += coef[13]* (pImgYPad5[j]+pImgYPad6[j]);
+        pixelInt += coef[14]* (pImgYPad5[j-1]+pImgYPad6[j+1]);
+
+        pixelInt += coef[20]* (pImgYPad3[j+2]+pImgYPad4[j-2]);
+        pixelInt += coef[21]* (pImgYPad3[j+1]+pImgYPad4[j-1]);
+        pixelInt += coef[22]* (pImgYPad3[j]+pImgYPad4[j]);
+        pixelInt += coef[23]* (pImgYPad3[j-1]+pImgYPad4[j+1]);
+        pixelInt += coef[24]* (pImgYPad3[j-2]+pImgYPad4[j+2]);
+
+        pixelInt += coef[28]* (pImgYPad1[j+3]+pImgYPad2[j-3]);
+        pixelInt += coef[29]* (pImgYPad1[j+2]+pImgYPad2[j-2]);
+        pixelInt += coef[30]* (pImgYPad1[j+1]+pImgYPad2[j-1]);
+        pixelInt += coef[31]* (pImgYPad1[j]+pImgYPad2[j]);
+        pixelInt += coef[32]* (pImgYPad1[j-1]+pImgYPad2[j+1]);
+        pixelInt += coef[33]* (pImgYPad1[j-2]+pImgYPad2[j+2]);
+        pixelInt += coef[34]* (pImgYPad1[j-3]+pImgYPad2[j+3]);
+
+        pixelInt += coef[36]* (pImgYPad[j+4]+pImgYPad[j-4]);
+        pixelInt += coef[37]* (pImgYPad[j+3]+pImgYPad[j-3]);
+        pixelInt += coef[38]* (pImgYPad[j+2]+pImgYPad[j-2]);
+        pixelInt += coef[39]* (pImgYPad[j+1]+pImgYPad[j-1]);
+        pixelInt += coef[40]* (pImgYPad[j]);
+
+        pixelInt=(Int)((pixelInt+offset) >> (numBitsMinus1));
+        imgYRecPost[i*stride + j]=max(0, min(pixelInt,maxVal));
+      }
+    }
+    break;
+  }
+}
+
+Void TComAdaptiveLoopFilter::subfilterFrame(imgpel *imgYRecPost, imgpel *imgYRec, int filtNo, int startHeight, int endHeight, int startWidth, int endWidth, int stride)
+{
+  Int varStepSizeWidth = VAR_SIZE_W;
+  Int varStepSizeHeight = VAR_SIZE_H;
+  Int shiftHeight = (Int)(log((double)varStepSizeHeight)/log(2.0));
+  Int shiftWidth = (Int)(log((double)varStepSizeWidth)/log(2.0));
+  Int i, j, pixelInt;
+  imgpel *pImgYVar,*pImgYPad;
+  imgpel *pImgYPad1,*pImgYPad2,*pImgYPad3,*pImgYPad4,*pImgYPad5,*pImgYPad6;
+  Int maxVal=g_uiIBDI_MAX;
+  Int lastCoef= MAX_SQR_FILT_LENGTH-1;
+  Int *coef = m_filterCoeffPrevSelected[0];
+  Int numBitsMinus1= NUM_BITS-1;
+  Int offset = (1<<(NUM_BITS-2));
+
+  switch(filtNo)
+  {
+  case 2:
+    for (i =  startHeight; i < endHeight; i++)
+    {
+      pImgYVar = m_imgY_var[i>>shiftHeight] + (startWidth>>shiftWidth);
+      pImgYPad = imgYRec + i*stride;
+      {
+        pImgYPad1 = imgYRec + (i+1)*stride;
+        pImgYPad2 = imgYRec + (i-1)*stride;
+        pImgYPad3 = imgYRec + (i+2)*stride;
+        pImgYPad4 = imgYRec + (i-2)*stride;
+        pImgYPad5 = imgYRec + (i+3)*stride;
+        pImgYPad6 = imgYRec + (i-3)*stride;
+      }
+
+      for (j = startWidth; j < endWidth; j++)
+      {
+        if (j%varStepSizeWidth==0) coef = m_filterCoeffPrevSelected[*(pImgYVar++)];
+        pixelInt=coef[lastCoef];
+
+        pixelInt += coef[22]* (pImgYPad3[j]+pImgYPad4[j]);
+
+        pixelInt += coef[30]* (pImgYPad1[j+1]+pImgYPad2[j-1]);
+        pixelInt += coef[31]* (pImgYPad1[j]  +pImgYPad2[j]);
+        pixelInt += coef[32]* (pImgYPad1[j-1]+pImgYPad2[j+1]);
+
+        pixelInt += coef[38]* (pImgYPad[j-2]+pImgYPad[j+2]);
+        pixelInt += coef[39]* (pImgYPad[j-1]+pImgYPad[j+1]);
+        pixelInt += coef[40]* (pImgYPad[j]);
+
+        pixelInt=(Int)((pixelInt+offset) >> (numBitsMinus1));
+        imgYRecPost[i*stride + j]=max(0, min(pixelInt,maxVal));
+      }
+    }
+    break;
+
+  case 1:
+    for (i =  startHeight; i < endHeight; i++)
+    {
+      pImgYVar = m_imgY_var[i>>shiftHeight] + (startWidth>>shiftWidth);
+      pImgYPad = imgYRec + i*stride;
+      {
+        pImgYPad1 = imgYRec + (i+1)*stride;
+        pImgYPad2 = imgYRec + (i-1)*stride;
+        pImgYPad3 = imgYRec + (i+2)*stride;
+        pImgYPad4 = imgYRec + (i-2)*stride;
+        pImgYPad5 = imgYRec + (i+3)*stride;
+        pImgYPad6 = imgYRec + (i-3)*stride;
+      }
+
+      for (j = startWidth; j < endWidth; j++)
+      {
+        if (j%varStepSizeWidth==0) coef = m_filterCoeffPrevSelected[*(pImgYVar++)];
+        pixelInt=coef[lastCoef];
+
+        pixelInt += coef[13]* (imgYRec[(i+3)*stride + j]+imgYRec[(i-3)*stride + j]);
+
+        pixelInt += coef[21]* (pImgYPad3[j+1]+pImgYPad4[j-1]);
+        pixelInt += coef[22]* (pImgYPad3[j]+pImgYPad4[j]);
+        pixelInt += coef[23]* (pImgYPad3[j-1]+pImgYPad4[j+1]);
+
+        pixelInt += coef[29]* (pImgYPad1[j+2]+pImgYPad2[j-2]);
+        pixelInt += coef[30]* (pImgYPad1[j+1]+pImgYPad2[j-1]);
+        pixelInt += coef[31]* (pImgYPad1[j]+pImgYPad2[j]);
+        pixelInt += coef[32]* (pImgYPad1[j-1]+pImgYPad2[j+1]);
+        pixelInt += coef[33]* (pImgYPad1[j-2]+pImgYPad2[j+2]);
+
+        pixelInt += coef[37]* (pImgYPad[j+3]+pImgYPad[j-3]);
+        pixelInt += coef[38]* (pImgYPad[j+2]+pImgYPad[j-2]);
+        pixelInt += coef[39]* (pImgYPad[j+1]+pImgYPad[j-1]);
+        pixelInt += coef[40]* (pImgYPad[j]);
+
+        pixelInt=(Int)((pixelInt+offset) >> (numBitsMinus1));
+        imgYRecPost[i*stride + j]=max(0, min(pixelInt,maxVal));
+      }
+    }
+    break;
+
+  case 0:
+    for (i =  startHeight; i < endHeight; i++)
+    {
+      pImgYVar = m_imgY_var[i>>shiftHeight] + (startWidth>>shiftWidth);
+      pImgYPad = imgYRec + i*stride;
+      {
+        pImgYPad1 = imgYRec + (i+1)*stride;
+        pImgYPad2 = imgYRec + (i-1)*stride;
+        pImgYPad3 = imgYRec + (i+2)*stride;
+        pImgYPad4 = imgYRec + (i-2)*stride;
+        pImgYPad5 = imgYRec + (i+3)*stride;
+        pImgYPad6 = imgYRec + (i-3)*stride;
+      }
+
+      for (j = startWidth; j < endWidth; j++)
+      {
+        if (j%varStepSizeWidth==0) coef = m_filterCoeffPrevSelected[*(pImgYVar++)];
+        pixelInt=coef[lastCoef];
+
+#if !TI_ALF_MAX_VSIZE_7
+        pixelInt += coef[4]* (imgYRec[(i+4)*stride + j]+imgYRec[(i-4)*stride + j]);
+#endif        
+        pixelInt += coef[12]* (pImgYPad5[j+1]+pImgYPad6[j-1]);
+        pixelInt += coef[13]* (pImgYPad5[j]+pImgYPad6[j]);
+        pixelInt += coef[14]* (pImgYPad5[j-1]+pImgYPad6[j+1]);
+
+        pixelInt += coef[20]* (pImgYPad3[j+2]+pImgYPad4[j-2]);
+        pixelInt += coef[21]* (pImgYPad3[j+1]+pImgYPad4[j-1]);
+        pixelInt += coef[22]* (pImgYPad3[j]+pImgYPad4[j]);
+        pixelInt += coef[23]* (pImgYPad3[j-1]+pImgYPad4[j+1]);
+        pixelInt += coef[24]* (pImgYPad3[j-2]+pImgYPad4[j+2]);
+
+        pixelInt += coef[28]* (pImgYPad1[j+3]+pImgYPad2[j-3]);
+        pixelInt += coef[29]* (pImgYPad1[j+2]+pImgYPad2[j-2]);
+        pixelInt += coef[30]* (pImgYPad1[j+1]+pImgYPad2[j-1]);
+        pixelInt += coef[31]* (pImgYPad1[j]+pImgYPad2[j]);
+        pixelInt += coef[32]* (pImgYPad1[j-1]+pImgYPad2[j+1]);
+        pixelInt += coef[33]* (pImgYPad1[j-2]+pImgYPad2[j+2]);
+        pixelInt += coef[34]* (pImgYPad1[j-3]+pImgYPad2[j+3]);
+
+        pixelInt += coef[36]* (pImgYPad[j+4]+pImgYPad[j-4]);
+        pixelInt += coef[37]* (pImgYPad[j+3]+pImgYPad[j-3]);
+        pixelInt += coef[38]* (pImgYPad[j+2]+pImgYPad[j-2]);
+        pixelInt += coef[39]* (pImgYPad[j+1]+pImgYPad[j-1]);
+        pixelInt += coef[40]* (pImgYPad[j]);
+
+        pixelInt=(Int)((pixelInt+offset) >> (numBitsMinus1));
+        imgYRecPost[i*stride + j]=max(0, min(pixelInt,maxVal));
+      }
+    }
+    break;
+  }
+}
+#else
+
+Void TComAdaptiveLoopFilter::filterFrame(imgpel *imgY_rec_post, imgpel *imgY_rec, int filtNo, int Stride)
+{
+  int i, j, ii, jj, pixelInt,m=0;
+  imgpel *p_imgY_var,*p_imgY_pad;
+  int max_val=g_uiIBDI_MAX;
+  int fl=FILTER_LENGTH/2;
+  int *pattern=m_pattern9x9Sym;
+  int fl_temp;
+  int last_coef= MAX_SQR_FILT_LENGTH-1;
+  imgpel *im1,*im2;
+  int *coef;
+  int num_bits_minus_1= NUM_BITS-1;
+  int offset = (1<<(NUM_BITS-2));
+  int *pattern_fix=m_patternTab_filt[filtNo];
+  fl_temp=m_flTab[filtNo];
+#if TI_ALF_MAX_VSIZE_7
+  Int fl_tempV = ALFFlHToFlV(fl_temp);
+#endif
+  
+  // Filter
+  for (i = fl; i < m_img_height+fl; i++)
+  {
+    p_imgY_var = m_imgY_var[i-fl];
+    p_imgY_pad = imgY_rec + (i-fl)*Stride;
+    for (j = fl; j < m_img_width+fl; j++)
+    {
+      coef = m_filterCoeffPrevSelected[*(p_imgY_var++)];
+      pixelInt=coef[last_coef];
+      pattern=pattern_fix;
+
+#if TI_ALF_MAX_VSIZE_7
+      for (ii = -fl_tempV, m = fl_temp - fl_tempV; ii < 0; ii++, m++)
+#else
+      for (ii = -fl_temp, m = 0; ii < 0; ii++, m++)
+#endif
+      {
+        im1= &(imgY_rec[(i-fl+ii)*Stride + j-fl-m]);
+        im2= &(imgY_rec[(i-fl-ii)*Stride + j-fl+m]);
+        for (jj=-m; jj<=m; jj++)
+          pixelInt+=((*(im1++)+ *(im2--))*coef[*(pattern++)]);
+      }
+
+      im1= &(p_imgY_pad[(j-fl)-fl_temp]);
+      im2= &(p_imgY_pad[(j-fl)+fl_temp]);
+      for (jj=0; jj<fl_temp; jj++)
+        pixelInt+=((*(im1++)+ *(im2--))*coef[*(pattern++)]);
+
+      pixelInt+=(p_imgY_pad[j-fl]*coef[*(pattern++)]);
+      pixelInt=(int)((pixelInt+offset) >> (num_bits_minus_1));
+      imgY_rec_post[(i-fl)*Stride + j-fl]=max(0, min(pixelInt,max_val));
+    }
+  }
+}
+
+Void TComAdaptiveLoopFilter::subfilterFrame(imgpel *imgY_rec_post, imgpel *imgY_rec, int filtNo, int start_height, int end_height, int start_width, int end_width, int Stride)
+{
+  int i, j, ii, jj, pixelInt,m=0;
+  imgpel *p_imgY_var,*p_imgY_pad;
+  int max_val=g_uiIBDI_MAX;
+  int fl=FILTER_LENGTH/2;
+  int *pattern=m_pattern9x9Sym;
+  int fl_temp;
+  int last_coef= MAX_SQR_FILT_LENGTH-1;
+  imgpel *im1,*im2;
+  int *coef;
+  int num_bits_minus_1= NUM_BITS-1;
+  int offset = (1<<(NUM_BITS-2));
+  int *pattern_fix=m_patternTab_filt[filtNo];
+  fl_temp=m_flTab[filtNo];
+#if TI_ALF_MAX_VSIZE_7
+  Int fl_tempV = ALFFlHToFlV(fl_temp);
+#endif
+  
+  // Filter
+  for (i = fl + start_height; i < end_height+fl; i++)
+  {
+    p_imgY_var = m_imgY_var[i-fl] + start_width;
+    p_imgY_pad = imgY_rec + (i-fl)*Stride;
+    for (j = fl + start_width; j < end_width+fl; j++)
+    {
+      coef = m_filterCoeffPrevSelected[*(p_imgY_var++)];
+      pixelInt=coef[last_coef];
+      pattern=pattern_fix;
+
+#if TI_ALF_MAX_VSIZE_7
+      for (ii = -fl_tempV, m = fl_temp - fl_tempV; ii < 0; ii++, m++)
+#else
+      for (ii = -fl_temp, m = 0; ii < 0; ii++, m++)
+#endif
+      {
+        im1= &(imgY_rec[(i-fl+ii)*Stride + j-fl-m]);
+        im2= &(imgY_rec[(i-fl-ii)*Stride + j-fl+m]);
+        for (jj=-m; jj<=m; jj++)
+          pixelInt+=((*(im1++)+ *(im2--))*coef[*(pattern++)]);
+      }
+
+      im1= &(p_imgY_pad[(j-fl)-fl_temp]);
+      im2= &(p_imgY_pad[(j-fl)+fl_temp]);
+      for (jj=0; jj<fl_temp; jj++)
+        pixelInt+=((*(im1++)+ *(im2--))*coef[*(pattern++)]);
+
+      pixelInt+=(p_imgY_pad[j-fl]*coef[*(pattern++)]);
+      pixelInt=(int)((pixelInt+offset) >> (num_bits_minus_1));
+      imgY_rec_post[(i-fl)*Stride + j-fl]=max(0, min(pixelInt,max_val));
+    }
+  }
+}
+
+#endif
+
+
+Void TComAdaptiveLoopFilter::xCUAdaptive_qc(TComPic* pcPic, ALFParam* pcAlfParam, imgpel *imgY_rec_post, imgpel *imgY_rec, Int Stride)
+{
+  // for every CU, call CU-adaptive ALF process
+  for( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+    xSubCUAdaptive_qc(pcCU, pcAlfParam, imgY_rec_post, imgY_rec, 0, 0, Stride);
+  }
+}
+
+Void TComAdaptiveLoopFilter::xSubCUAdaptive_qc(TComDataCU* pcCU, ALFParam* pcAlfParam, imgpel *imgY_rec_post, imgpel *imgY_rec, UInt uiAbsPartIdx, UInt uiDepth, Int Stride)
+{
+  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;
+  
+  // check picture boundary
+  if ( ( uiRPelX >= pcCU->getSlice()->getSPS()->getWidth() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() ) )
+  {
+    bBoundary = true;
+  }
+  
+  // go to sub-CU?
+  if ( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( 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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+        xSubCUAdaptive_qc(pcCU, pcAlfParam, imgY_rec_post, imgY_rec, uiAbsPartIdx, uiDepth+1, Stride);
+    }
+    return;
+  }
+  
+  // check maskImagedec
+  if ( pcCU->getAlfCtrlFlag(uiAbsPartIdx) )
+  {
+    subfilterFrame(imgY_rec_post, imgY_rec, pcAlfParam->realfiltNo, uiTPelY, min(uiBPelY+1,(unsigned int)(m_img_height)), uiLPelX, min(uiRPelX+1,(unsigned int)(m_img_width)), Stride);
+  }
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// ALF for chroma
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComAdaptiveLoopFilter::xALFChroma(ALFParam* pcAlfParam, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest)
+{
+  if((pcAlfParam->chroma_idc>>1)&0x01)
+  {
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(!m_bUseNonCrossALF)
+      xFrameChroma(0, 0, (m_img_height>>1), (m_img_width>>1), pcPicDec, pcPicRest, pcAlfParam->coeff_chroma, pcAlfParam->tap_chroma, 0);
+    else
+    {
+      Int iStride   = pcPicRest->getCStride();
+      Pel* pDec     = pcPicDec->getCbAddr();
+      Pel* pRest    = pcPicRest->getCbAddr();
+
+      for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+      {
+        CAlfSlice* pSlice = &(m_pSlice[s]);
+        pSlice->copySliceChroma(pDec, pRest, iStride);
+        pSlice->extendSliceBorderChroma(pDec, iStride, (UInt)EXTEND_NUM_PEL_C);
+        xFrameChromaforOneSlice(pSlice, ALF_Cb, pcPicDec, pcPicRest, pcAlfParam->coeff_chroma, pcAlfParam->tap_chroma);
+      }
+    }
+#else
+    xFrameChroma(pcPicDec, pcPicRest, pcAlfParam->coeff_chroma, pcAlfParam->tap_chroma, 0);
+#endif
+  }
+  
+  if(pcAlfParam->chroma_idc&0x01)
+  {
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(!m_bUseNonCrossALF)
+      xFrameChroma(0, 0, (m_img_height>>1), (m_img_width>>1), pcPicDec, pcPicRest, pcAlfParam->coeff_chroma, pcAlfParam->tap_chroma, 1);
+    else
+    {
+      Int iStride   = pcPicRest->getCStride();
+      Pel* pDec     = pcPicDec->getCrAddr();
+      Pel* pRest    = pcPicRest->getCrAddr();
+      for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+      {
+        CAlfSlice* pSlice = &(m_pSlice[s]);
+        pSlice->copySliceChroma(pDec, pRest, iStride);
+        pSlice->extendSliceBorderChroma(pDec, iStride, (UInt)EXTEND_NUM_PEL_C);
+        xFrameChromaforOneSlice(pSlice, ALF_Cr, pcPicDec, pcPicRest, pcAlfParam->coeff_chroma, pcAlfParam->tap_chroma);
+      }
+    }
+#else
+    xFrameChroma(pcPicDec, pcPicRest, pcAlfParam->coeff_chroma, pcAlfParam->tap_chroma, 1);
+#endif
+  }
+}
+
+/** 
+ \param pcPicDec    picture before ALF
+ \param pcPicRest   picture after  ALF
+ \param qh          filter coefficient
+ \param iTap        filter tap
+ \param iColor      0 for Cb and 1 for Cr
+ */
+#if MTK_NONCROSS_INLOOP_FILTER
+Void TComAdaptiveLoopFilter::xFrameChroma(Int ypos, Int xpos, Int iHeight, Int iWidth, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Int *qh, Int iTap, Int iColor )
+#else
+Void TComAdaptiveLoopFilter::xFrameChroma( TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Int *qh, Int iTap, Int iColor )
+#endif
+{
+  Int i, x, y, value, N, offset;
+  //  Pel PixSum[ALF_MAX_NUM_COEF_C];// th
+  Pel PixSum[ALF_MAX_NUM_COEF]; 
+  
+  N      = (iTap*iTap+1)>>1;
+  offset = iTap>>1;
+#if !MTK_NONCROSS_INLOOP_FILTER
+  Int iHeight = pcPicRest->getHeight() >> 1;
+  Int iWidth = pcPicRest->getWidth() >> 1;
+#endif  
+  Pel* pDec;
+  Int iDecStride = pcPicDec->getCStride();
+  
+  Pel* pRest;
+  Int iRestStride = pcPicRest->getCStride();
+  
+  Int iShift = g_uiBitDepth + g_uiBitIncrement - 8;
+  
+  if (iColor)
+  {
+    pDec = pcPicDec->getCrAddr();
+    pRest = pcPicRest->getCrAddr();
+  }
+  else
+  {
+    pDec = pcPicDec->getCbAddr();
+    pRest = pcPicRest->getCbAddr();
+  }
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(m_bUseNonCrossALF)
+  {
+    pDec  += ( ypos*iDecStride  + xpos);
+    pRest += ( ypos*iRestStride + xpos);
+  }
+  else
+  {
+    assert(ypos ==0 && xpos ==0);
+    assert(iHeight == pcPicRest->getHeight() >> 1);
+    assert(iWidth  == pcPicRest->getWidth()  >> 1);
+  }
+#endif
+
+  Pel* pTmpDec1, *pTmpDec2;
+  Pel* pTmpPixSum;
+  
+  switch(iTap)
+  {
+    case 5:
+    {
+      Int iJump = iDecStride - 4;
+      pDec -= iDecStride*2;
+      for (y = 0; y < iHeight; y++)
+      {
+        for (x = 0; x < iWidth; x++)
+        {
+          pTmpDec1 = pDec+x-2;
+          pTmpDec2 = pTmpDec1+4+(4*iDecStride);
+          pTmpPixSum = PixSum;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++;
+          *pTmpPixSum = (*pTmpDec1);
+          
+          value = 0;
+          for(i=0; i<N; i++)
+          {
+            value += qh[i]*PixSum[i];
+          }
+          // DC offset
+          value += qh[N] << iShift;
+          value = (value + ALF_ROUND_OFFSET)>>ALF_NUM_BIT_SHIFT;
+          
+          pRest[x] = (Pel) Clip(value);
+        }
+        pRest += iRestStride;
+        pDec += iDecStride;
+      }
+    }
+      break;
+    case 7:
+    {
+      Int iJump = iDecStride - 6;
+      pDec -= iDecStride*3;
+      for (y = 0; y < iHeight; y++)
+      {
+        for (x = 0; x < iWidth; x++)
+        {
+          pTmpDec1 = pDec+x-3;
+          pTmpDec2 = pTmpDec1+6+(6*iDecStride);
+          pTmpPixSum = PixSum;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++;
+          *pTmpPixSum = (*pTmpDec1);
+          
+          value = 0;
+          for(i=0; i<N; i++)
+          {
+            value += qh[i]*PixSum[i];
+          }
+          // DC offset
+          value += qh[N] << iShift;
+          value = (value + ALF_ROUND_OFFSET)>>ALF_NUM_BIT_SHIFT;
+          
+          pRest[x] = (Pel) Clip(value);
+        }
+        pRest += iRestStride;
+        pDec += iDecStride;
+      }
+    }
+      break;
+    case 9:
+    {
+      Int iJump = iDecStride - 8;
+      pDec -= iDecStride*4;
+      for (y = 0; y < iHeight; y++)
+      {
+        for (x = 0; x < iWidth; x++)
+        {
+          pTmpDec1 = pDec+x-4;
+          pTmpDec2 = pTmpDec1+8+(8*iDecStride);
+          pTmpPixSum = PixSum;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1 += iJump; pTmpDec2 -= iJump;
+          
+          
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++; pTmpDec2--;
+          *pTmpPixSum = ((*pTmpDec1) + (*pTmpDec2));
+          pTmpPixSum++; pTmpDec1++;
+          *pTmpPixSum =(*pTmpDec1);
+          
+          value = 0;
+          for(i=0; i<N; i++)
+          {
+            value += qh[i]*PixSum[i];
+          }
+          // DC offset
+          value += qh[N] << iShift;
+          value = (value + ALF_ROUND_OFFSET)>>ALF_NUM_BIT_SHIFT;
+          
+          pRest[x] = (Pel) Clip(value);
+        }
+        pRest += iRestStride;
+        pDec += iDecStride;
+      }
+    }
+      break;
+    default:
+      assert(0);
+      break;
+  }
+}
+
+#if TSB_ALF_HEADER
+Void TComAdaptiveLoopFilter::setNumCUsInFrame(TComPic *pcPic)
+{
+  m_uiNumCUsInFrame = pcPic->getNumCUsInFrame();
+}
+
+Void TComAdaptiveLoopFilter::setAlfCtrlFlags(ALFParam *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()->getWidth() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() ) )
+  {
+    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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+      {
+        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++;
+  }
+}
+#endif
+
+#if MTK_NONCROSS_INLOOP_FILTER
+
+
+Void TComAdaptiveLoopFilter::createSlice()
+{
+  m_pSlice = new CAlfSlice[m_uiNumSlicesInPic];
+
+  for(Int i=0; i< m_uiNumSlicesInPic; i++)
+  {
+    m_pSlice[i].init(m_uiNumLCUsInWidth, m_uiNumLCUsInHeight);
+  }
+
+}
+Void TComAdaptiveLoopFilter::destroySlice()
+{
+  delete[] m_pSlice;
+}
+
+
+
+Void TComAdaptiveLoopFilter::setAlfCtrlFlagsforSlices(ALFParam *pcAlfParam, UInt &idx)
+{
+
+  for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    CAlfSlice* pSlice = &(m_pSlice[s]);
+    setAlfCtrlFlagsforOneSlice(pSlice, pcAlfParam, idx);
+  }
+}
+
+Void TComAdaptiveLoopFilter::setAlfCtrlFlagsforOneSlice(CAlfSlice* pSlice, ALFParam *pcAlfParam, UInt &idx)
+{
+
+  for(Int i=0; i< pSlice->getNumLCUs(); i++)
+  { 
+    CAlfCU*     pAlfCU = &((*pSlice)[i]);
+    TComDataCU* pcCU = pAlfCU->getCU();
+
+    setAlfCtrlFlags(pcAlfParam, pcCU, 0, 0, idx);
+  }
+
+}
+
+
+
+
+Void TComAdaptiveLoopFilter::calcVarforOneSlice(CAlfSlice* pSlice, imgpel **imgY_var, imgpel *imgY_pad, Int pad_size, Int fl, Int img_stride)
+{  
+  Int iHeight, iWidth;
+#if !MQT_BA_RA
+  Int iPelPosOffset;
+#endif
+  Int ypos, xpos;
+
+  for(Int i=0; i< pSlice->getNumLCUs(); i++)
+  { 
+    CAlfCU* pAlfCU = &((*pSlice)[i]);
+
+    ypos    = pAlfCU->getCU()->getCUPelY();
+    xpos    = pAlfCU->getCU()->getCUPelX();
+    iHeight = pAlfCU->getHeight();
+    iWidth  = pAlfCU->getWidth();
+
+#if MQT_BA_RA
+    calcVar(ypos, xpos, imgY_var, imgY_pad, pad_size, fl, iHeight, iWidth, img_stride);
+#else
+    iPelPosOffset = (ypos * img_stride) + xpos;
+
+    calcVar(ypos, xpos, imgY_var, imgY_pad+ iPelPosOffset, pad_size, fl, iHeight, iWidth, img_stride);
+#endif
+  }
+}
+
+
+Void TComAdaptiveLoopFilter::xFrameChromaforOneSlice(CAlfSlice* pSlice, Int ComponentID, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Int *qh, Int iTap)
+{
+  Int iColor = (ComponentID == ALF_Cb)?(0):(1);
+
+  Int iHeight, iWidth;
+  Int ypos, xpos;
+
+  for(Int i=0; i< pSlice->getNumLCUs(); i++)
+  { 
+    CAlfCU* pAlfCU = &((*pSlice)[i]);
+
+    ypos    = (pAlfCU->getCU()->getCUPelY() >> 1);
+    xpos    = (pAlfCU->getCU()->getCUPelX() >> 1);
+    iHeight = (pAlfCU->getHeight() >> 1);
+    iWidth  = (pAlfCU->getWidth() >> 1);
+
+    xFrameChroma(ypos, xpos, iHeight, iWidth, pcPicDec, pcPicRest, qh, iTap, iColor );
+  }
+
+}
+
+
+//-------------- CAlfCU ---------------------//
+Void CAlfCU::init(TComPic* pcPic, UInt uiCUAddr, UInt uiStartCU, UInt uiEndCU, UInt uiNumCUWidth, UInt uiNumCUHeight)
+{
+  m_uiCUAddr = uiCUAddr;
+  m_pcCU = pcPic->getCU(m_uiCUAddr);
+
+  UInt uiPicWidth = m_pcCU->getSlice()->getSPS()->getWidth();
+  UInt uiPicHeight= m_pcCU->getSlice()->getSPS()->getHeight();
+  UInt uiLPelX    = m_pcCU->getCUPelX();
+  UInt uiTPelY    = m_pcCU->getCUPelY();
+  UInt uiRPelX    = uiLPelX + g_uiMaxCUWidth  - 1;
+  UInt uiBPelY    = uiTPelY + g_uiMaxCUHeight - 1;
+
+  m_uiWidth      = (uiRPelX >= uiPicWidth)? (uiPicWidth - uiLPelX):(uiRPelX - uiLPelX +1);
+  m_uiHeight     = (uiBPelY >= uiPicHeight)?(uiPicHeight- uiTPelY):(uiBPelY - uiTPelY +1);
+
+  //check CU border status
+  assignBorderStatus(uiStartCU, uiEndCU, uiNumCUWidth, uiNumCUHeight);
+
+}
+
+
+Void CAlfCU::assignBorderStatus(UInt uiStartCU, UInt uiEndCU, UInt uiNumCUWidth, UInt uiNumCUHeight)
+{
+
+  memset(m_aiCUBorderFlag, 0, NUM_PADDING_REGION*sizeof(Int));
+
+  for(UInt pos = 0; pos < NUM_PADDING_REGION; pos++)
+  {
+    Int& riVal = m_aiCUBorderFlag[pos];
+
+    switch(pos)
+    {
+    case PRP_L:
+      {
+        riVal = (m_uiCUAddr % uiNumCUWidth ==0)?(true):
+          (
+          (m_uiCUAddr-1 < uiStartCU)?(true):(false)
+          );
+      }
+      break;
+    case PRP_R:
+      {
+        riVal = ( (m_uiCUAddr+1) % uiNumCUWidth  == 0)?(true):
+          (
+          (m_uiCUAddr+1 > uiEndCU)?(true):(false)
+          );
+      }
+      break;
+    case PRP_T:
+      {
+        riVal = ( m_uiCUAddr< uiNumCUWidth )?(true):
+          (
+          ( m_uiCUAddr - uiNumCUWidth < uiStartCU)?(true):(false)
+          );
+      }
+      break;
+    case PRP_B:
+      {
+        riVal = ( m_uiCUAddr >= (uiNumCUWidth* (uiNumCUHeight-1)) )?(true):
+          (
+          ( m_uiCUAddr + uiNumCUWidth > uiEndCU)?(true):(false)
+          );
+      }
+      break;
+    case PRP_LT:
+      riVal = ( m_aiCUBorderFlag[PRP_L]==1 && m_aiCUBorderFlag[PRP_T]==1 )?(1):(0);
+      break;
+    case PRP_RT:
+      riVal = ( m_aiCUBorderFlag[PRP_R]==1 && m_aiCUBorderFlag[PRP_T]==1 )?(1):(0);
+      if(riVal)
+      {
+        if( !( (m_uiCUAddr+1) % uiNumCUWidth  == 0) && !( m_uiCUAddr< uiNumCUWidth )) 
+        {
+          Int iAddr = (Int)m_uiCUAddr - (Int)uiNumCUWidth +1;
+          if( iAddr >= (Int)uiStartCU && iAddr <= (Int)uiEndCU)
+            riVal = 0;
+        }
+
+      }
+      break;
+    case PRP_LB:
+      riVal = ( m_aiCUBorderFlag[PRP_L]==1 && m_aiCUBorderFlag[PRP_B]==1 )?(1):(0);
+      if(riVal)
+      {
+        if( !(m_uiCUAddr % uiNumCUWidth ==0)  && !( m_uiCUAddr >= (uiNumCUWidth* (uiNumCUHeight-1)) )) 
+        {
+          Int iAddr = (Int)m_uiCUAddr + (Int)uiNumCUWidth -1;
+          if( iAddr >= (Int)uiStartCU && iAddr <= (Int)uiEndCU)
+            riVal = 0;
+
+        }
+      }
+
+      break;
+    case PRP_RB:
+      riVal = ( m_aiCUBorderFlag[PRP_R]==1 && m_aiCUBorderFlag[PRP_B]==1 )?(1):(0);
+      break;
+    default:
+      assert(0);
+      exit(-1);
+    }
+
+
+  }
+
+}
+
+
+Void CAlfCU::extendCUBorder(Pel* pCUPel, UInt uiCUWidth, UInt uiCUHeight, Int iStride, UInt uiExtSize)
+{
+  Int* piExtFlag  = m_aiCUBorderFlag;
+
+  Pel* pPelDst;
+  Pel* pPelSrc;
+  UInt i, j, pos;
+
+
+  for(pos =0; pos < NUM_PADDING_REGION; pos++)
+  {
+    if(piExtFlag[pos] ==0)
+      continue;
+
+    switch(pos)
+    {
+    case PRP_L:
+      {
+        pPelDst = pCUPel - uiExtSize;
+        pPelSrc = pCUPel;
+
+        for(j=0; j< uiCUHeight; j++)
+        {
+          for(i=0; i< uiExtSize; i++)
+            pPelDst[i] = *pPelSrc;
+
+          pPelDst += iStride;
+          pPelSrc += iStride;
+
+        }
+
+      }
+      break;
+    case PRP_R:
+      {
+        pPelDst = pCUPel + uiCUWidth;
+        pPelSrc = pPelDst -1;
+
+
+        for(j=0; j< uiCUHeight; j++)
+        {
+          for(i=0; i< uiExtSize; i++)
+            pPelDst[i] = *pPelSrc;
+
+          pPelDst += iStride;
+          pPelSrc += iStride;
+        }
+
+      }
+      break;
+    case PRP_T:
+      {
+        pPelSrc = pCUPel;
+        pPelDst = pCUPel - iStride;
+
+        for(j=0; j< uiExtSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*uiCUWidth);
+          pPelDst -= iStride;
+        }
+
+      }
+      break;
+    case PRP_B:
+      {
+        pPelDst = pCUPel + uiCUHeight*iStride;
+        pPelSrc = pPelDst - iStride;
+
+        for(j=0; j< uiExtSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*uiCUWidth);
+          pPelDst += iStride;
+        }
+
+      }
+      break;
+    case PRP_LT:
+      {
+
+        pPelSrc = pCUPel  - uiExtSize;
+        pPelDst = pPelSrc - iStride;
+
+        for(j=0; j< uiExtSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*uiExtSize);
+          pPelDst -= iStride;
+        }
+
+      }
+      break;
+    case PRP_RT:
+      {
+        pPelSrc = pCUPel + uiCUWidth;
+        pPelDst = pPelSrc - iStride;
+
+        for(j=0; j< uiExtSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*uiExtSize);
+          pPelDst -= iStride;
+        }
+
+      }
+      break;
+    case PRP_LB:
+      {
+        pPelDst = pCUPel + uiCUHeight*iStride; pPelDst-= uiExtSize;
+        pPelSrc = pPelDst - iStride;
+
+        for(j=0; j< uiExtSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*uiExtSize);
+          pPelDst += iStride;
+        }
+
+      }
+      break;
+    case PRP_RB:
+      {
+        pPelDst = pCUPel + uiCUHeight*iStride; pPelDst += uiCUWidth;
+        pPelSrc = pPelDst - iStride;
+
+        for(j=0; j< uiExtSize; j++)
+        {
+          ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*uiExtSize);
+          pPelDst += iStride;
+        }
+
+      }
+      break;
+    default:
+      {
+        assert(0);
+        exit(-1);
+      }
+
+    }
+  }
+
+
+
+}
+
+
+//-------------- CAlfSlice -----------------//
+
+Void CAlfSlice::init(UInt uiNumLCUsInPicWidth, UInt uiNumLCUsInPicHeight)
+{
+  m_uiNumLCUsInPicWidth = uiNumLCUsInPicWidth;
+  m_uiNumLCUsInPicHeight= uiNumLCUsInPicHeight;
+}
+Void CAlfSlice::create(TComPic* pcPic, Int iSliceID, UInt uiStartLCU, UInt uiEndLCU)
+{
+  m_iSliceID    = iSliceID;
+  m_uiStartLCU  = uiStartLCU;
+  m_uiEndLCU    = uiEndLCU;
+
+  m_uiNumLCUs= uiEndLCU - uiStartLCU +1;
+
+  m_pcAlfCU = new CAlfCU[m_uiNumLCUs];
+
+  for(UInt uiAddr= m_uiStartLCU; uiAddr <=  m_uiEndLCU; uiAddr++)
+  {
+    m_pcAlfCU[uiAddr - m_uiStartLCU].init(pcPic, uiAddr, m_uiStartLCU, m_uiEndLCU, m_uiNumLCUsInPicWidth, m_uiNumLCUsInPicHeight);
+  }
+
+}
+
+Void CAlfSlice::destroy()
+{
+  if(m_pcAlfCU != NULL)
+  {
+    delete[] m_pcAlfCU;
+    m_pcAlfCU = NULL;
+  }
+}
+
+
+
+Void CAlfSlice::extendSliceBorderLuma(Pel* pPelSrc, Int iStride, UInt uiExtSize)
+{
+  UInt idx;  
+  Pel* pPelTmp;
+  CAlfCU* pcAlfCU;
+  UInt uiTPelY, uiLPelX;
+  UInt uiWidth, uiHeight;
+
+
+  for(idx = 0; idx < m_uiNumLCUs; idx++)
+  {
+    pcAlfCU = &(m_pcAlfCU[idx]);
+
+    uiTPelY = pcAlfCU->getCU()->getCUPelY();
+    uiLPelX = pcAlfCU->getCU()->getCUPelX();
+    uiWidth = pcAlfCU->getWidth();
+    uiHeight= pcAlfCU->getHeight();
+
+    pPelTmp   = pPelSrc + (uiTPelY*iStride)+ uiLPelX;
+
+    pcAlfCU->extendCUBorder(pPelTmp, uiWidth, uiHeight, iStride, uiExtSize);
+  }
+}
+
+
+Void CAlfSlice::extendSliceBorderChroma(Pel* pPelSrc, Int iStride, UInt uiExtSize)
+{
+  UInt idx;  
+  Pel* pPelTmp;
+  CAlfCU* pcAlfCU;
+  UInt uiTPelY, uiLPelX;
+  UInt uiWidth, uiHeight;
+
+
+  for(idx = 0; idx < m_uiNumLCUs; idx++)
+  {
+    pcAlfCU = &(m_pcAlfCU[idx]);
+
+    uiTPelY = (pcAlfCU->getCU()->getCUPelY() >> 1);
+    uiLPelX = (pcAlfCU->getCU()->getCUPelX() >> 1);
+    uiWidth = (pcAlfCU->getWidth() >> 1);
+    uiHeight= (pcAlfCU->getHeight() >> 1);
+
+    pPelTmp   = pPelSrc + (uiTPelY*iStride)+ uiLPelX;
+
+    pcAlfCU->extendCUBorder(pPelTmp, uiWidth, uiHeight, iStride, uiExtSize);
+  }
+}
+
+
+
+Void CAlfSlice::copySliceLuma(Pel* pPicDst, Pel* pPicSrc, Int iStride )
+{
+  UInt uiLPelX, uiTPelY;
+  UInt uiPelOffset;
+  Int  iWidth, iHeight;
+  Pel* pPelDst;
+  Pel* pPelSrc;
+  CAlfCU* pcAlfCU;
+
+  for(UInt i=0; i< m_uiNumLCUs; i++)
+  {
+    pcAlfCU = &(m_pcAlfCU[i]);
+
+    uiLPelX = pcAlfCU->getCU()->getCUPelX();
+    uiTPelY = pcAlfCU->getCU()->getCUPelY();
+    iWidth  = (Int)pcAlfCU->getWidth();
+    iHeight = (Int)pcAlfCU->getHeight();
+
+    uiPelOffset = uiTPelY* iStride + uiLPelX;
+
+    pPelDst = pPicDst + uiPelOffset;
+    pPelSrc = pPicSrc + uiPelOffset;
+
+    for(Int j=0; j< iHeight; j++)
+    {
+      ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*iWidth);
+      pPelDst += iStride;
+      pPelSrc += iStride;
+    }
+
+
+
+  }
+
+}
+
+
+Void CAlfSlice::copySliceChroma(Pel* pPicDst, Pel* pPicSrc, Int iStride )
+{
+  UInt uiLPelX, uiTPelY;
+  UInt uiPelOffset;
+  Int  iWidth, iHeight;
+  Pel* pPelDst;
+  Pel* pPelSrc;
+  CAlfCU* pcAlfCU;
+
+  for(UInt i=0; i< m_uiNumLCUs; i++)
+  {
+    pcAlfCU = &(m_pcAlfCU[i]);
+
+    uiLPelX = (pcAlfCU->getCU()->getCUPelX())>>1;
+    uiTPelY = (pcAlfCU->getCU()->getCUPelY())>>1;
+    iWidth  = (Int)(pcAlfCU->getWidth()>>1 );
+    iHeight = (Int)(pcAlfCU->getHeight()>>1);
+
+    uiPelOffset = uiTPelY* iStride + uiLPelX;
+
+    pPelDst = pPicDst + uiPelOffset;
+    pPelSrc = pPicSrc + uiPelOffset;
+
+    for(Int j=0; j< iHeight; j++)
+    {
+      ::memcpy(pPelDst, pPelSrc, sizeof(Pel)*iWidth);
+      pPelDst += iStride;
+      pPelSrc += iStride;
+    }
+
+
+
+  }
+
+}
+
+
+
+
+Void TComAdaptiveLoopFilter::xFilterOneSlice(CAlfSlice* pSlice, imgpel* pDec, imgpel* pRest, Int iStride, ALFParam* pcAlfParam)
+{
+
+
+  //set maskImg using cu adaptive one.
+  if(pcAlfParam->cu_control_flag)
+  {
+    UInt uiNumLCU = pSlice->getNumLCUs();
+    for(UInt i=0; i< uiNumLCU; i++)
+    {
+      CAlfCU*     pAlfCU = &((*pSlice)[i]);
+      TComDataCU* pcCU   = pAlfCU->getCU();
+      xSubCUAdaptive_qc(pcCU, pcAlfParam, pRest, pDec, 0, 0, iStride);
+    }
+
+  }  
+  else
+  {
+    //then do whole frame filtering
+    UInt uiNumLCU = pSlice->getNumLCUs();
+    Int  iTPelY,  iLPelX;
+    Int  iWidth, iHeight;
+
+
+    for(UInt i=0; i< uiNumLCU; i++)
+    {
+      CAlfCU*     pAlfCU = &((*pSlice)[i]);
+      TComDataCU* pcCU   = pAlfCU->getCU();
+
+      iTPelY = (Int)pcCU->getCUPelY();
+      iLPelX = (Int)pcCU->getCUPelX();
+      iHeight= pAlfCU->getHeight();
+      iWidth = pAlfCU->getWidth();
+
+      subfilterFrame(pRest, pDec, pcAlfParam->realfiltNo, iTPelY, iTPelY+ iHeight, iLPelX, iLPelX+ iWidth, iStride);
+
+    }
+
+
+
+
+  }
+
+
+}
+
+#endif
+
+#if MTK_SAO
+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_iWeightAO[MAX_NUM_SAO_TYPE] =
+{
+  2,
+  2,
+  2,
+  2,
+  1,
+  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,
+  SAO_BO_LEN
+};
+
+UInt TComSampleAdaptiveOffset::m_uiMaxDepth = AO_MAX_DEPTH;
+
+/** Create SampleAdaptiveOffset memory.
+ * \param uiSourceWidth, uiSourceHeight, uiMaxCUWidth, uiMaxCUHeight, uiMaxCUDepth
+ */
+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_uiMaxCUWidth   = 16;
+  //  m_uiMaxCUHeight  = 16;
+
+  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;
+
+  xCreateQAOParts();
+
+
+  UInt auiTable[2][LUMA_GROUP_NUM] = 
+  {{0, 0, 0, 0, 0, 0, 0, 0,
+  1, 2, 3, 4, 5, 6, 7, 8,
+  9,10,11,12,13,14,15,16,
+  0, 0, 0, 0, 0, 0, 0, 0},
+
+  {1, 2, 3, 4, 5, 6, 7, 8,
+  0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0,
+  9,10,11,12,13,14,15,16}};
+
+
+  UInt uiInternalBitDepth = g_uiBitDepth+g_uiBitIncrement;
+  UInt uiPixelRange = 1<<uiInternalBitDepth;
+  UInt uiBoRangeShift = uiInternalBitDepth - MTK_QAO_BO_BITS;
+
+  m_ppLumaTableBo0 = new Pel [uiPixelRange];
+  m_ppLumaTableBo1 = new Pel [uiPixelRange];
+  for (Int k2=0; k2<uiPixelRange; k2++)
+  {
+    m_ppLumaTableBo0[k2] = auiTable[0][k2>>uiBoRangeShift];
+    m_ppLumaTableBo1[k2] = auiTable[1][k2>>uiBoRangeShift];
+  }
+
+
+  m_iUpBuff1 = new Int[m_iPicWidth+2];
+  m_iUpBuff2 = new Int[m_iPicWidth+2];
+  m_iUpBufft = new Int[m_iPicWidth+2];
+
+  Pel i;
+
+
+  UInt uiMaxY  = 255   << g_uiBitIncrement;
+  UInt uiMinY  = 0   << g_uiBitIncrement;
+
+
+  Int iCcTableRange = CRANGE >> (4-g_uiBitIncrement);
+
+  for(i=0;i<iCcTableRange;i++)
+  {
+    m_pClipTableBase[i+CRANGE_EXT] = i;
+  }
+
+  for(i=0;i<uiMinY+CRANGE_EXT;i++)
+  {
+    m_pClipTableBase[i] = uiMinY;
+  }
+  for(i=uiMaxY+CRANGE_EXT;i<CRANGE_ALL;i++)
+  {
+    m_pClipTableBase[i] = uiMaxY;
+  }
+
+  m_pClipTable = &(m_pClipTableBase[CRANGE_EXT]);
+
+
+}
+
+
+/** destroy SampleAdaptiveOffset memory.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::destroy()
+{
+
+  if (m_ppLumaTableBo0)
+  {
+    delete[] m_ppLumaTableBo0; m_ppLumaTableBo0 = NULL;
+  }
+  if (m_ppLumaTableBo1)
+  {
+    delete[] m_ppLumaTableBo1; m_ppLumaTableBo1 = NULL;
+  }
+
+  xDestroyQAOParts();
+  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;
+  }
+
+}
+
+
+
+/** Initialize SampleAdaptiveOffset data.
+ * \param SAOParam
+ */
+Void TComSampleAdaptiveOffset::InitSao(SAOParam* pSaoParam)
+{
+  pSaoParam->psSaoPart      = m_psQAOPart;
+  pSaoParam->iMaxSplitLevel = m_uiMaxSplitLevel;
+
+  resetQTPart();
+
+
+}
+
+/** Create QAO Parts.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::xCreateQAOParts()
+{
+  Int iMaxSplitLevelHeight    = (Int)(logf((float)m_iNumCuInHeight)/logf(2.0));
+  Int iMaxSplitLevelWidth     = (Int)(logf((float)m_iNumCuInWidth )/logf(2.0));
+
+  //find the max split level of IMQALF
+  m_uiMaxSplitLevel= (iMaxSplitLevelHeight < iMaxSplitLevelWidth)?(iMaxSplitLevelHeight):(iMaxSplitLevelWidth);
+  m_uiMaxSplitLevel= (m_uiMaxSplitLevel< m_uiMaxDepth)?(m_uiMaxSplitLevel):(m_uiMaxDepth);
+
+  m_psQAOPart= new SAOQTPart[ m_aiNumCulPartsLevel[m_uiMaxSplitLevel] ];
+
+  xInitALfOnePart(0, 0, 0, 
+    -1, 
+    0, m_iNumCuInWidth-1, 
+    0, m_iNumCuInHeight-1);
+
+  //add subpart list
+  Int i;
+  Int NumSubPart;
+  Int part_level;
+  Int part_row;
+  Int part_col;
+  for(i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
+  {
+    Idx2LevelRowCol(i, &part_level, &part_row, &part_col);
+
+    NumSubPart = m_aiNumPartsLevel[m_uiMaxSplitLevel - part_level];
+
+    m_psQAOPart[i].pSubPartList       = new Int[NumSubPart];
+    m_psQAOPart[i].iLengthSubPartList = 0;
+
+    xMakeSubPartList(part_level, part_row, part_col, 
+      m_psQAOPart[i].pSubPartList, 
+      m_psQAOPart[i].iLengthSubPartList, 
+      1);
+
+  }
+  xSetQTPartCUInfo();
+
+  m_iNumTotalParts = m_aiNumCulPartsLevel[m_uiMaxSplitLevel];
+
+}
+
+/** Set QT Part CU Info.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::xSetQTPartCUInfo()
+{
+
+  Int         i, j;
+  SAOQTPart*  pAlfPart;
+
+
+  for(i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
+  {
+
+    pAlfPart              = &(m_psQAOPart[i]);
+    pAlfPart->bEnableFlag =  0;
+    pAlfPart->iBestType   = -1;
+    pAlfPart->iLength     =  0;
+    for (j=0;j<MAX_NUM_QAO_CLASS;j++)
+    {
+      pAlfPart->iOffset[j] = 0;
+    }
+
+    pAlfPart->part_xs = pAlfPart->StartCUX * (Int)(m_uiMaxCUWidth);
+    pAlfPart->part_ys = pAlfPart->StartCUY * (Int)(m_uiMaxCUHeight);
+
+    //part_xe, part_ye
+    pAlfPart->part_xe = pAlfPart->part_xs + 
+      ( (Int)(m_uiMaxCUWidth) * (pAlfPart->EndCUX- pAlfPart->StartCUX + 1) ) -1;
+    pAlfPart->part_ye = pAlfPart->part_ys + 
+      ( (Int)(m_uiMaxCUHeight)* (pAlfPart->EndCUY- pAlfPart->StartCUY + 1)) -1;
+
+    if(pAlfPart->part_xe > m_iPicWidth-1)
+      pAlfPart->part_xe = m_iPicWidth -1;
+
+    if(pAlfPart->part_ye > m_iPicHeight-1)
+      pAlfPart->part_ye = m_iPicHeight-1;
+
+
+    pAlfPart->part_width = pAlfPart->part_xe - pAlfPart->part_xs +1;
+    pAlfPart->part_height= pAlfPart->part_ye - pAlfPart->part_ys +1;
+
+  }
+
+
+
+}
+
+/** Destroy QAO Parts.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::xDestroyQAOParts()
+{
+
+  int i;
+  for(i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
+  {
+    //        freeALFParam( &(m_psAlfPart[i].sAlfParam) );
+
+    if (m_psQAOPart[i].pSubPartList)
+    {
+      delete[] m_psQAOPart[i].pSubPartList;    m_psQAOPart[i].pSubPartList = NULL;
+
+    }
+
+  }
+
+  if (m_psQAOPart)
+  {
+    delete[] m_psQAOPart; m_psQAOPart = NULL;
+  }
+}
+
+
+/** Initialize ALf One Part.
+ * \param iPartLevel, iPartRow, iPartCol, iParentPartIdx, StartCUX, EndCUX, StartCUY, EndCUX, StartCUY, EndCUY
+ */
+Void TComSampleAdaptiveOffset::xInitALfOnePart(Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY)
+{
+  Int             part_idx    = LevelRowCol2Idx(iPartLevel, iPartRow, iPartCol);
+  SAOQTPart*      pAlfPart       = &(m_psQAOPart[part_idx]);
+
+  //    allocALFParam( &(pAlfPart->sAlfParam) );
+
+  pAlfPart->PartIdx   = part_idx;
+  pAlfPart->PartLevel = iPartLevel;
+  pAlfPart->PartRow   = iPartRow;
+  pAlfPart->PartCol   = iPartCol;
+
+  pAlfPart->StartCUX  = StartCUX;
+  pAlfPart->EndCUX    = EndCUX;
+  pAlfPart->StartCUY  = StartCUY;
+  pAlfPart->EndCUY    = EndCUY;
+
+  pAlfPart->UpPartIdx = iParentPartIdx;
+
+
+  if(pAlfPart->PartLevel != m_uiMaxSplitLevel)
+  {
+    pAlfPart->bBottomLevel = false;
+
+    Int DownLevel   = iPartLevel+1;
+    Int DownRowStart= (iPartRow << 1);
+    Int DownColStart= (iPartCol << 1);
+
+    Int DownRow_Idx, DownCol_Idx;
+    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);
+
+    //part 00
+    DownStartCUX=   StartCUX;
+    DownEndCUX=     DownStartCUX + NumCULeft -1;
+    DownStartCUY=   StartCUY;
+    DownEndCUY=     DownStartCUY + NumCUTop -1;
+
+    DownRow_Idx= DownRowStart + 0;
+    DownCol_Idx= DownColStart + 0;
+
+    pAlfPart->DownPartsIdx[0]= LevelRowCol2Idx(DownLevel, DownRow_Idx, DownCol_Idx);
+
+    xInitALfOnePart(DownLevel, DownRow_Idx, DownCol_Idx, 
+      part_idx, 
+      DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY);
+
+
+    //part 01
+    DownStartCUX=   StartCUX + NumCULeft;
+    DownEndCUX=     EndCUX;
+    DownStartCUY=   StartCUY;
+    DownEndCUY=     DownStartCUY + NumCUTop -1;
+
+    DownRow_Idx= DownRowStart + 0;
+    DownCol_Idx= DownColStart + 1;
+
+    pAlfPart->DownPartsIdx[1]= LevelRowCol2Idx(DownLevel, DownRow_Idx, DownCol_Idx);
+
+    xInitALfOnePart(DownLevel, DownRow_Idx, DownCol_Idx, 
+      part_idx, 
+      DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY);
+
+
+
+    //part 10
+    DownStartCUX=   StartCUX;
+    DownEndCUX=     DownStartCUX + NumCULeft -1;
+    DownStartCUY=   StartCUY + NumCUTop;
+    DownEndCUY=     EndCUY;
+
+    DownRow_Idx= DownRowStart + 1;
+    DownCol_Idx= DownColStart + 0;
+
+    pAlfPart->DownPartsIdx[2]= LevelRowCol2Idx(DownLevel, DownRow_Idx, DownCol_Idx);
+
+    xInitALfOnePart(DownLevel, DownRow_Idx, DownCol_Idx, 
+      part_idx, 
+      DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY);
+
+
+
+    //part 11
+    DownStartCUX=   StartCUX+ NumCULeft;
+    DownEndCUX=     EndCUX;
+    DownStartCUY=   StartCUY + NumCUTop;
+    DownEndCUY=     EndCUY;
+
+    DownRow_Idx= DownRowStart + 1;
+    DownCol_Idx= DownColStart + 1;
+
+    pAlfPart->DownPartsIdx[3]= LevelRowCol2Idx(DownLevel, DownRow_Idx, DownCol_Idx);
+
+    xInitALfOnePart(DownLevel, DownRow_Idx, DownCol_Idx, 
+      part_idx, 
+      DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY);
+
+
+
+  }
+  else
+  {
+    pAlfPart->bBottomLevel = true;
+    pAlfPart->DownPartsIdx[0]=pAlfPart->DownPartsIdx[1]= pAlfPart->DownPartsIdx[2]= pAlfPart->DownPartsIdx[3]= -1; 
+  }
+
+}
+
+
+/** Make Sub Part List.
+ * \param  iPartLevel,  iPartRow,  iPartCol,  pList,  rListLength, NumPartInRow
+ */
+Void TComSampleAdaptiveOffset::xMakeSubPartList(Int iPartLevel, Int iPartRow, Int iPartCol, Int* pList, Int& rListLength, Int NumPartInRow)
+{
+
+  if(iPartLevel != m_uiMaxSplitLevel)
+  {
+    xMakeSubPartList(iPartLevel+1, iPartRow*2, iPartCol*2, 
+      pList, rListLength,
+      NumPartInRow*2);
+
+  }
+  else  //bottom level
+  {
+
+    Int part_idx;
+    Int i,j;
+
+    for(j= iPartRow; j< iPartRow + NumPartInRow; j++)
+    {
+      for(i= iPartCol; i< iPartCol + NumPartInRow; i++)
+      {
+        part_idx= LevelRowCol2Idx(iPartLevel, j, i);
+        pList[rListLength]= part_idx;
+        rListLength++;
+      }
+    }
+
+  }
+
+}
+
+
+inline int xSign(int x)
+{
+  return ((x >> 31) | ((int)( (((unsigned int) -x)) >> 31)));
+}
+
+/** Adaptive offset process for Cu
+ * \param  iAddr, iPartIdx
+ */
+Void TComSampleAdaptiveOffset::AoProcessCu(Int iAddr, Int iPartIdx)
+{
+  Int x,y;
+  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
+  Pel* pRec       = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+  Int  iStride    = m_pcPic->getStride();
+  Int  iLcuWidth  = m_uiMaxCUWidth;
+  Int  iLcuHeight = m_uiMaxCUHeight;
+  UInt uiLPelX    = pTmpCu->getCUPelX();
+  UInt uiRPelX    = uiLPelX + iLcuWidth;
+  UInt uiTPelY    = pTmpCu->getCUPelY();
+  UInt uiBPelY    = uiTPelY + iLcuHeight;
+  Int  iAoType    = m_psQAOPart[iPartIdx].iBestType;
+  Int  iSignLeft;
+  Int  iSignRight;
+  Int  iSignDown;
+  Int  iSignDown1;
+  Int  iSignDown2;
+  UInt uiEdgeType;
+
+  uiRPelX    = uiRPelX > m_iPicWidth ? m_iPicWidth : uiRPelX;
+  uiBPelY    = uiBPelY > m_iPicHeight? m_iPicHeight: uiBPelY;
+  iLcuWidth  = uiRPelX - uiLPelX;
+  iLcuHeight = uiBPelY - uiTPelY;
+
+  switch (iAoType)
+  {
+  case SAO_EO_0:
+    {
+      for (y=0; y<iLcuHeight; y++)
+      {
+        iSignLeft  = xSign(pRec[1] - pRec[0]);
+        for (x=1; x<iLcuWidth-1; 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:
+    {
+      pRec += iStride;
+      for (x=0; x< iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride]);
+      }
+      for (y=1; y<iLcuHeight-1; 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:
+    {
+      pRec += iStride;
+      for (x=1; x<iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride-1]);
+      }
+      for (y=1; y<iLcuHeight-1; y++)
+      {
+        iSignDown2 = xSign(pRec[iStride] - pRec[0]);
+
+        for (x=1; x<iLcuWidth-1; 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[1] = iSignDown2;
+
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pRec += iStride;
+      }
+      break;
+    } 
+  case SAO_EO_3:
+    {
+      pRec += iStride;
+      for (x=0; x<iLcuWidth-1; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride+1]);
+      }
+      for (y=1; y<iLcuHeight-1; y++)
+      {
+        for (x=1; x<iLcuWidth-1; 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[iLcuWidth-2] = xSign(pRec[iLcuWidth-2 + iStride] - pRec[iLcuWidth-1]);
+
+        pRec += iStride;
+      } 
+      break;
+    }   
+  case SAO_BO_0:
+  case SAO_BO_1:
+    {
+      for (y=0; y<iLcuHeight; y++)
+      {
+        for (x=0; x<iLcuWidth; x++)
+        {
+          pRec[x] = m_iOffsetBo[pRec[x]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  default: break;
+
+  }
+}
+
+
+/** run adaptive offset One Part
+ * \param  uiPartIdx, pcPicYuvDst, pcPicYuvSrc
+ */
+Void TComSampleAdaptiveOffset::xAoOnePart(UInt uiPartIdx, TComPicYuv* pcPicYuvDst, TComPicYuv* pcPicYuvSrc)
+{
+  int  i;
+  UInt uiEdgeType, uiTypeIdx;
+  Pel* ppLumaTable = NULL;
+
+  static Int iOffset[LUMA_GROUP_NUM];
+  Int LcuIdxX;
+  Int LcuIdxY;
+  Int iAddr;
+  Int iFrameWidthInCU = m_pcPic->getFrameWidthInCU();
+
+  if(m_psQAOPart[uiPartIdx].bEnableFlag)
+  {
+    uiTypeIdx = m_psQAOPart[uiPartIdx].iBestType;
+    if (uiTypeIdx == SAO_BO_0 || uiTypeIdx == SAO_BO_1)
+    {
+      for (i=0;i<m_psQAOPart[uiPartIdx].iLength;i++)
+        iOffset[i+1] = m_psQAOPart[uiPartIdx].iOffset[i] << (g_uiBitIncrement-m_uiAoBitDepth);
+
+      if (uiTypeIdx == SAO_BO_0 )
+      {
+        ppLumaTable = m_ppLumaTableBo0;
+      }
+      if (uiTypeIdx == SAO_BO_1 )
+      {
+        ppLumaTable = m_ppLumaTableBo1;
+      }
+
+      for (i=0;i<(1<<(g_uiBitIncrement+8));i++)
+      {
+        m_iOffsetBo[i] = m_pClipTable[i + iOffset[ppLumaTable[i]]];
+      }
+
+    }
+    if (uiTypeIdx == SAO_EO_0 || uiTypeIdx == SAO_EO_1 || uiTypeIdx == SAO_EO_2 || uiTypeIdx == SAO_EO_3)
+    {
+      for (i=0;i<m_psQAOPart[uiPartIdx].iLength;i++)
+      {
+        iOffset[i+1] = m_psQAOPart[uiPartIdx].iOffset[i] << (g_uiBitIncrement-m_uiAoBitDepth);
+      }
+      for (uiEdgeType=0;uiEdgeType<6;uiEdgeType++)
+      {
+        m_iOffsetEo[uiEdgeType]= iOffset[m_auiEoTable[uiEdgeType]];
+      }
+    }
+    for (LcuIdxY = m_psQAOPart[uiPartIdx].StartCUY; LcuIdxY<= m_psQAOPart[uiPartIdx].EndCUY; LcuIdxY++)
+    {
+      for (LcuIdxX = m_psQAOPart[uiPartIdx].StartCUX; LcuIdxX<= m_psQAOPart[uiPartIdx].EndCUX; LcuIdxX++)
+      {
+        iAddr = LcuIdxY * iFrameWidthInCU + LcuIdxX;
+        AoProcessCu(iAddr, uiPartIdx);
+      }
+    }
+  }
+}
+
+
+/** Process QuadTree adaptive offset
+ * \param  uiPartIdx, pcPicYuvRec, pcPicYuvExt
+ */
+Void TComSampleAdaptiveOffset::xProcessQuadTreeAo(UInt uiPartIdx, TComPicYuv* pcPicYuvRec, TComPicYuv* pcPicYuvExt)
+{
+
+  SAOQTPart*  pQAOPart= &(m_psQAOPart[uiPartIdx]);
+
+  if (!pQAOPart->bSplit)
+  {
+    if (pQAOPart->bEnableFlag)
+    {
+      xAoOnePart(uiPartIdx, pcPicYuvRec, pcPicYuvExt);
+    }
+    else
+    {
+    }
+    return;
+  }
+
+  if (pQAOPart->PartLevel < m_uiMaxSplitLevel)
+  {
+    xProcessQuadTreeAo(pQAOPart->DownPartsIdx[0], pcPicYuvRec, pcPicYuvExt);
+    xProcessQuadTreeAo(pQAOPart->DownPartsIdx[1], pcPicYuvRec, pcPicYuvExt);
+    xProcessQuadTreeAo(pQAOPart->DownPartsIdx[2], pcPicYuvRec, pcPicYuvExt);
+    xProcessQuadTreeAo(pQAOPart->DownPartsIdx[3], pcPicYuvRec, pcPicYuvExt);
+  }
+}
+
+
+/** reset QT Part
+ * \param  
+ */
+Void TComSampleAdaptiveOffset::resetQTPart()
+{
+  Int iPartIdx, i;
+  for (iPartIdx=0; iPartIdx<m_iNumTotalParts; iPartIdx++)
+  {
+    m_psQAOPart[iPartIdx].bEnableFlag = 0;
+    m_psQAOPart[iPartIdx].bSplit = 0;
+    m_psQAOPart[iPartIdx].iBestType = -1;
+    m_psQAOPart[iPartIdx].iLength = 0;
+    for (i=0;i<MAX_NUM_QAO_CLASS;i++)
+    {
+      m_psQAOPart[iPartIdx].iOffset[i] = 0;
+    }
+  }
+
+}
+
+
+/** copy Qao Data
+ * \param SAOParam* pcQaoParam  
+ */
+Void TComSampleAdaptiveOffset::copyQaoData(SAOParam* pcQaoParam )
+{
+  pcQaoParam->bSaoFlag  = m_bSaoFlag;
+  pcQaoParam->psSaoPart = m_psQAOPart;
+  pcQaoParam->iMaxSplitLevel = (Int) m_uiMaxSplitLevel;
+
+  for(Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+  {
+    pcQaoParam->iNumClass[j] = m_iNumClass[j];
+  }
+
+}
+/** Sample adaptive offset Process
+ * \param pcPic, pcQaoParam  
+ */
+Void TComSampleAdaptiveOffset::SAOProcess(TComPic* pcPic, SAOParam* pcQaoParam)
+{
+
+  if (pcQaoParam->bSaoFlag)
+  {
+    if (g_uiBitIncrement>1)
+    {
+      m_uiAoBitDepth = 1;
+    }
+    else
+    {
+      m_uiAoBitDepth = 0;
+    }
+    m_pcPic = pcPic;
+    TComPicYuv* pcPicYuvRec = m_pcPic->getPicYuvRec();
+    TComPicYuv* pcPicYuvExt = NULL;
+
+
+    {
+      xProcessQuadTreeAo( 0, pcPicYuvRec,  pcPicYuvExt);
+    }
+
+    m_pcPic = NULL;
+  }
+
+
+
+}
+
+
+
+
+#endif // MTK_SAO
Index: /tags/0.2r1/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComAdaptiveLoopFilter.h	(revision 19)
@@ -0,0 +1,483 @@
+/* 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     TComAdaptiveLoopFilter.h
+    \brief    adaptive loop filter class (header)
+*/
+
+#ifndef __TCOMADAPTIVELOOPFILTER__
+#define __TCOMADAPTIVELOOPFILTER__
+
+#include "TComPic.h"
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define ALF_MAX_NUM_TAP       9                                       ///< maximum number of filter taps (9x9)
+#define ALF_MIN_NUM_TAP       5                                       ///< minimum number of filter taps (5x5)
+#define ALF_MAX_NUM_TAP_C     5                                       ///< number of filter taps for chroma (5x5)
+#define ALF_MAX_NUM_COEF      42                                      ///< maximum number of filter coefficients
+#define ALF_MIN_NUM_COEF      14                                      ///< minimum number of filter coefficients
+#define ALF_MAX_NUM_COEF_C    14                                      ///< number of filter taps for chroma
+#define ALF_NUM_BIT_SHIFT     8                                       ///< bit shift parameter for quantization of ALF param.
+#define ALF_ROUND_OFFSET      ( 1 << ( ALF_NUM_BIT_SHIFT - 1 ) )      ///< rounding offset for ALF quantization
+
+#include "../TLibCommon/CommonDef.h"
+
+#define NUM_BITS               9
+#define NO_TEST_FILT           3       // Filter supports (5/7/9)
+#define NO_VAR_BINS           16 
+#define NO_FILTERS            16
+
+#if MQT_BA_RA 
+#define VAR_SIZE               1 // JCTVC-E323+E046
+#else
+#define VAR_SIZE               3
+#endif
+
+#define FILTER_LENGTH          9
+
+#define MAX_SQR_FILT_LENGTH   ((FILTER_LENGTH*FILTER_LENGTH) / 2 + 2)
+#if TI_ALF_MAX_VSIZE_7
+#define SQR_FILT_LENGTH_9SYM  ((9*9) / 4 + 2 - 1) 
+#else
+#define SQR_FILT_LENGTH_9SYM  ((9*9) / 4 + 2) 
+#endif
+#define SQR_FILT_LENGTH_7SYM  ((7*7) / 4 + 2) 
+#define SQR_FILT_LENGTH_5SYM  ((5*5) / 4 + 2) 
+#define MAX_SCAN_VAL    11
+#define MAX_EXP_GOLOMB  16
+
+#define min(a, b) (((a) < (b)) ? (a) : (b))
+#define max(a, b) (((a) > (b)) ? (a) : (b))
+#define imgpel  unsigned short
+
+#if TI_ALF_MAX_VSIZE_7
+extern Int depthInt9x9Sym[21];
+#else
+extern Int depthInt9x9Sym[22];
+#endif
+extern Int depthInt7x7Sym[14];
+extern Int depthInt5x5Sym[8];
+extern Int *pDepthIntTab[NO_TEST_FILT];
+void destroyMatrix_int(int **m2D);
+void initMatrix_int(int ***m2D, int d1, int d2);
+
+#if MTK_NONCROSS_INLOOP_FILTER
+#define EXTEND_NUM_PEL    (UInt)(ALF_MAX_NUM_TAP/2)
+#define EXTEND_NUM_PEL_C  (UInt)(ALF_MAX_NUM_TAP_C/2)
+enum PaddingRegionPosition
+{
+  PRP_L = 0,
+  PRP_R,
+  PRP_T,
+  PRP_B,
+  NUM_PADDING_TILE,
+  PRP_LT = NUM_PADDING_TILE,
+  PRP_RT,
+  PRP_LB,
+  PRP_RB,
+  NUM_PADDING_REGION
+};
+enum AlfChromaID
+{
+  ALF_Cb = 0,
+  ALF_Cr = 1
+};
+#endif
+
+#if MQT_BA_RA
+enum ALFClassficationMethod
+{
+  ALF_BA =0,
+  ALF_RA,
+  NUM_ALF_CLASS_METHOD
+};
+#endif
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+#if MTK_SAO
+
+#define CRANGE_EXT                     512
+#define CRANGE                         4096
+#define CRANGE_ALL                     (CRANGE + (CRANGE_EXT*2))  
+#define AO_MAX_DEPTH                   4
+#define MAX_NUM_QAO_PART               341
+#define MTK_QAO_BO_BITS                5
+#define LUMA_GROUP_NUM                 (1<<MTK_QAO_BO_BITS)
+#define MAX_NUM_QAO_CLASS              32
+#define SAO_RDCO 0
+
+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_iWeightAO[MAX_NUM_SAO_TYPE];
+  Int m_iOffsetBo[4096];
+  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];
+
+  Bool m_bSaoFlag;
+  SAOQTPart *m_psQAOPart;
+
+  SliceType  m_eSliceType;
+  Int        m_iPicNalReferenceIdc;
+
+  UInt m_uiAoBitDepth;
+  UInt m_uiQP;
+
+  Bool  m_bBcEnable;
+  Int   m_iMinY;
+  Int   m_iMaxY;
+  Int   m_iMinCb;
+  Int   m_iMaxCb;
+  Int   m_iMinCr;
+  Int   m_iMaxCr;
+  Pel   *m_pClipTable;
+  Pel   m_pClipTableBase[CRANGE_ALL];
+  Pel   *m_ppLumaTableBo0;
+  Pel   *m_ppLumaTableBo1;
+
+  Int   *m_iUpBuff1;
+  Int   *m_iUpBuff2;
+  Int   *m_iUpBufft;
+  Int  *ipSwap;
+
+public:
+  Void create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
+  Void destroy ();
+  Void xCreateQAOParts();
+  Void xDestroyQAOParts();
+  Void xInitALfOnePart(Int part_level, Int part_row, Int part_col, Int parent_part_idx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY);
+  Void xMakeSubPartList(Int part_level, Int part_row, Int part_col, Int* pList, Int& rListLength, Int NumPartInRow);
+  Void xSetQTPartCUInfo();
+
+  Bool getQAOFlag      () {return m_bSaoFlag;}
+  Int  getMaxSplitLevel() {return (Int)m_uiMaxSplitLevel;}
+  SAOQTPart * getQTPart() {return m_psQAOPart;}
+
+  Void SAOProcess(TComPic* pcPic, SAOParam* pcQaoParam);
+  Void resetQTPart();
+  Void xAoOnePart(UInt uiPartIdx, TComPicYuv* pcPicYuvRec, TComPicYuv* pcPicYuvExt);
+  Void xProcessQuadTreeAo(UInt uiPartIdx, TComPicYuv* pcPicYuvRec, TComPicYuv* pcPicYuvExt);
+  Void copyQaoData(SAOParam* pcQaoParam);
+
+  Void InitSao(SAOParam* pSaoParam);
+  Void AoProcessCu(Int iAddr, Int iPartIdx);
+};
+#endif
+
+
+#if MTK_NONCROSS_INLOOP_FILTER
+
+class CAlfCU
+{
+public:
+  CAlfCU() {}
+  ~CAlfCU() {}
+public:
+  //  Void        init(TComDataCU* pcCU, UInt uiCUAddr, UInt uiStartCU, UInt uiEndCU, UInt uiNumCUWidth, UInt uiNumCUHeight);
+  Void        init(TComPic* pcPic, UInt uiCUAddr, UInt uiStartCU, UInt uiEndCU, UInt uiNumCUWidth, UInt uiNumCUHeight);
+  TComDataCU* getCU()           {return m_pcCU;}
+  UInt        getWidth()        {return m_uiWidth;}
+  UInt        getHeight()       {return m_uiHeight;}
+  Int*        getCUBorderFlag() {return m_aiCUBorderFlag;}
+  Void        extendCUBorder(Pel* pCUPel, UInt uiCUWidth, UInt uiCUHeight, Int iStride, UInt uiExtSize);
+private:
+  Void assignBorderStatus(UInt uiStartCU, UInt uiEndCU, UInt uiNumCUWidth, UInt uiNumCUHeight);
+
+private:
+  TComDataCU* m_pcCU;
+
+  UInt        m_uiCUAddr;
+  Int         m_aiCUBorderFlag[NUM_PADDING_REGION];
+  UInt        m_uiWidth;
+  UInt        m_uiHeight;
+};
+
+class CAlfSlice
+{
+public:
+  CAlfSlice()
+  {
+    m_pcAlfCU= NULL;
+  }
+  ~CAlfSlice()
+  {
+    destroy(); 
+  }
+public:  //operator to access CAlfCU
+  CAlfCU& operator[] (Int idx)
+  {
+    assert(idx < m_uiNumLCUs);
+    return m_pcAlfCU[idx];
+  }
+
+public:
+  Void init(UInt uiNumLCUsInPicWidth, UInt uiNumLCUsInPicHeight);
+  Void create(TComPic* pcPic, Int iSliceID, UInt uiStartLCU, UInt uiEndLCU);
+  Void destroy();
+
+  UInt getNumLCUs     ()         {return m_uiNumLCUs;}
+
+  Void extendSliceBorderLuma(Pel* pPelSrc, Int iStride, UInt uiExtSize);
+  Void extendSliceBorderChroma(Pel* pPelSrc, Int iStride, UInt uiExtSize);
+  Void copySliceLuma(Pel* pPicDst, Pel* pPicSrc, Int iStride);
+  Void copySliceChroma(Pel* pPicDst, Pel* pPicSrc, Int iStride );
+
+private: 
+
+  Int    m_iSliceID;
+  UInt   m_uiStartLCU;
+  UInt   m_uiEndLCU;
+  UInt   m_uiNumLCUs;
+
+  CAlfCU* m_pcAlfCU;
+
+  //----------------------------------------//
+  UInt   m_uiNumLCUsInPicWidth;
+  UInt   m_uiNumLCUsInPicHeight;
+};
+
+#endif 
+
+
+/// adaptive loop filter class
+class TComAdaptiveLoopFilter
+{
+protected:
+  // quantized filter coefficients
+  static const  Int m_aiSymmetricMag9x9[41];             ///< quantization scaling factor for 9x9 filter
+  static const  Int m_aiSymmetricMag7x7[25];             ///< quantization scaling factor for 7x7 filter
+  static const  Int m_aiSymmetricMag5x5[13];             ///< quantization scaling factor for 5x5 filter
+#if TI_ALF_MAX_VSIZE_7
+  static const  Int m_aiSymmetricMag9x7[32];             ///< quantization scaling factor for 9x7 filter
+#endif
+  
+  // temporary picture buffer
+  TComPicYuv*   m_pcTempPicYuv;                          ///< temporary picture buffer for ALF processing
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // For luma component
+  // ------------------------------------------------------------------------------------------------------------------
+#if TI_ALF_MAX_VSIZE_7
+  static Int m_pattern9x9Sym[39];
+  static Int m_weights9x9Sym[21];
+#else
+  static Int m_pattern9x9Sym[41];
+  static Int m_weights9x9Sym[22];
+#endif
+  static Int m_pattern9x9Sym_Quart[42];
+  static Int m_pattern7x7Sym[25];
+  static Int m_weights7x7Sym[14];
+  static Int m_pattern7x7Sym_Quart[42];
+  static Int m_pattern5x5Sym[13];
+  static Int m_weights5x5Sym[8];
+  static Int m_pattern5x5Sym_Quart[45];
+#if TI_ALF_MAX_VSIZE_7
+  static Int m_pattern9x9Sym_9[39];
+#else
+  static Int m_pattern9x9Sym_9[41];
+#endif
+  static Int m_pattern9x9Sym_7[25];
+  static Int m_pattern9x9Sym_5[13];
+  
+  static Int *m_patternTab_filt[NO_TEST_FILT];
+  static Int m_flTab[NO_TEST_FILT];
+  static Int *m_patternTab[NO_TEST_FILT]; 
+  static Int *m_patternMapTab[NO_TEST_FILT];
+  static Int *m_weightsTab[NO_TEST_FILT];
+  static Int m_sqrFiltLengthTab[NO_TEST_FILT];
+  
+  Int m_img_height,m_img_width;
+  
+  imgpel **m_imgY_pad;
+  imgpel **m_imgY_var;
+  Int    **m_imgY_temp;
+  
+#if MQT_BA_RA
+  Int**    m_imgY_ver;
+  Int**    m_imgY_hor;
+  UInt     m_uiVarGenMethod;
+  imgpel** m_varImgMethods[NUM_ALF_CLASS_METHOD];
+#endif 
+
+  Int **m_filterCoeffSym;
+  Int **m_filterCoeffPrevSelected;
+  Int **m_filterCoeffTmp;
+  Int **m_filterCoeffSymTmp;
+  
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  Bool        m_bUseNonCrossALF;
+  UInt        m_uiNumLCUsInWidth;
+  UInt        m_uiNumLCUsInHeight;
+  UInt        m_uiNumSlicesInPic;
+  CAlfSlice*  m_pSlice;
+  Bool        m_bIsFirstDecodedSlice;
+
+  Bool        m_bIsCreated;
+  Void xFilterOneSlice            (CAlfSlice* pSlice, imgpel* pDec, imgpel* pRest, Int iStride, ALFParam* pcAlfParam);
+  Void calcVarforOneSlice         (CAlfSlice* pSlice, imgpel **imgY_var, imgpel *imgY_pad, Int pad_size, Int fl, Int img_stride);
+  Void xFrameChromaforOneSlice    (CAlfSlice* pSlice, Int ComponentID, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Int *qh, Int iTap);
+  //for decoder CU on/off control
+  Void setAlfCtrlFlagsforSlices   (ALFParam *pcAlfParam, UInt &idx);
+  Void setAlfCtrlFlagsforOneSlice (CAlfSlice* pSlice, ALFParam *pcAlfParam, UInt &idx);
+#endif
+
+#if MQT_BA_RA
+  Void createRegionIndexMap(imgpel **imgY_var, Int img_width, Int img_height);
+#endif
+
+  /// ALF for luma component
+  Void xALFLuma_qc( TComPic* pcPic, ALFParam* pcAlfParam, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest );
+  
+  Void reconstructFilterCoeffs(ALFParam* pcAlfParam,int **pfilterCoeffSym, int bit_depth);
+  Void getCurrentFilter(int **filterCoeffSym,ALFParam* pcAlfParam);
+  // memory allocation
+  Void destroyMatrix_imgpel(imgpel **m2D);
+  Void destroyMatrix_int(int **m2D);
+  Void initMatrix_int(int ***m2D, int d1, int d2);
+  Void initMatrix_imgpel(imgpel ***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 free_mem2Dpel(imgpel **array2D);
+  Void get_mem2Dpel(imgpel ***array2D, int rows, int columns);
+  Void no_mem_exit(const char *where);
+  Void xError(const char *text, int code);
+#if MTK_NONCROSS_INLOOP_FILTER
+  Void calcVar(int ypos, int xpos, imgpel **imgY_var, imgpel *imgY_pad, int pad_size, int fl, int img_height, int img_width, int img_stride);
+#else
+  Void calcVar(imgpel **imgY_var, imgpel *imgY_pad, int pad_size, int fl, int img_height, int img_width, int img_stride);
+#endif
+  Void DecFilter_qc(imgpel* imgY_rec,ALFParam* pcAlfParam, int Stride);
+  Void xSubCUAdaptive_qc(TComDataCU* pcCU, ALFParam* pcAlfParam, imgpel *imgY_rec_post, imgpel *imgY_rec, UInt uiAbsPartIdx, UInt uiDepth, Int Stride);
+  Void xCUAdaptive_qc(TComPic* pcPic, ALFParam* pcAlfParam, imgpel *imgY_rec_post, imgpel *imgY_rec, Int Stride);
+  Void subfilterFrame(imgpel *imgY_rec_post, imgpel *imgY_rec, int filtNo, int start_height, int end_height, int start_width, int end_width, int Stride);
+  Void filterFrame(imgpel *imgY_rec_post, imgpel *imgY_rec, int filtNo, int Stride);
+#if TSB_ALF_HEADER
+  UInt  m_uiNumCUsInFrame;
+  Void  setAlfCtrlFlags (ALFParam *pAlfParam, TComDataCU *pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt &idx);
+#endif
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // For chroma component
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  /// ALF for chroma component
+  Void xALFChroma   ( ALFParam* pcAlfParam, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest );
+  
+  /// sub function: non-adaptive ALF process for chroma
+#if MTK_NONCROSS_INLOOP_FILTER
+  Void xFrameChroma ( Int ypos, Int xpos, Int iHeight, Int iWidth, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Int *qh, Int iTap, Int iColor );
+#else
+  Void xFrameChroma ( TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Int *qh, Int iTap, Int iColor );
+#endif
+
+public:
+  TComAdaptiveLoopFilter();
+  virtual ~TComAdaptiveLoopFilter() {}
+  
+  // initialize & destory temporary buffer
+  Void create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
+  Void destroy ();
+  
+  Bool isCreated() { return m_bIsCreated;}
+  // alloc & free & set functions
+  Void allocALFParam  ( ALFParam* pAlfParam );
+  Void freeALFParam   ( ALFParam* pAlfParam );
+  Void copyALFParam   ( ALFParam* pDesAlfParam, ALFParam* pSrcAlfParam );
+#if TSB_ALF_HEADER
+  Void  setNumCUsInFrame        (TComPic *pcPic);
+#endif
+  
+  // predict filter coefficients
+  Void predictALFCoeff        ( ALFParam* pAlfParam );                  ///< prediction of luma ALF coefficients
+  Void predictALFCoeffChroma  ( ALFParam* pAlfParam );                  ///< prediction of chroma ALF coefficients
+  
+  // interface function
+  Void ALFProcess             ( TComPic* pcPic, ALFParam* pcAlfParam ); ///< interface function for ALF process
+  
+#if TI_ALF_MAX_VSIZE_7
+  static Int ALFTapHToTapV(Int tapH);
+  static Int ALFTapHToNumCoeff(Int tapH);
+  static Int ALFFlHToFlV(Int flH);
+#endif
+
+
+#if MTK_NONCROSS_INLOOP_FILTER
+public:
+  Void setNumSlicesInPic(UInt uiNum) {m_uiNumSlicesInPic = uiNum;}
+  UInt getNumSlicesInPic()           {return m_uiNumSlicesInPic;}
+  Void setUseNonCrossAlf(Bool bVal)  {m_bUseNonCrossALF = bVal;}
+  Bool getUseNonCrossAlf()           {return m_bUseNonCrossALF;}
+  Void createSlice      ();
+  Void destroySlice     ();
+
+public: //operator to access Alf slice
+  CAlfSlice& operator[] (UInt i)
+  {
+    assert(i < m_uiNumSlicesInPic);
+    return m_pSlice[i];
+  }
+#endif
+
+
+};
+#endif
Index: /tags/0.2r1/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComBitCounter.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComBitCounter.h	(revision 19)
@@ -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-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     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"
+
+// ====================================================================================================================
+// 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: /tags/0.2r1/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComBitStream.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComBitStream.cpp	(revision 19)
@@ -0,0 +1,465 @@
+/* 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     TComBitStream.cpp
+    \brief    class for handling bitstream
+*/
+
+#include "TComBitStream.h"
+#include <string.h>
+#include <memory.h>
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+Void TComBitstream::create( UInt uiSizeInBytes )
+{
+  UInt uiSize = uiSizeInBytes / sizeof(UInt);
+  
+  m_apulStreamPacketBegin = new UInt[uiSize];
+  m_uiBufSize       = uiSize;
+  m_uiBitSize       = 0;
+  m_iValidBits      = 32;
+  
+  m_ulCurrentBits   = 0;
+  m_uiBitsWritten   = 0;
+  
+  m_pulStreamPacket = m_apulStreamPacketBegin;
+  m_auiSliceByteLocation = NULL;
+  m_uiSliceCount         = 0;
+}
+
+Void TComBitstream::destroy()
+{
+  delete [] m_apulStreamPacketBegin;     m_apulStreamPacketBegin = NULL;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TComBitstream::write   ( UInt uiBits, UInt uiNumberOfBits )
+{
+  assert( m_uiBufSize > 0 );
+  assert( uiNumberOfBits <= 32 );
+  assert( ! ( (uiBits >> 1) >> (uiNumberOfBits - 1)) ); // because shift with 32 has no effect
+  
+  m_uiBitsWritten += uiNumberOfBits;
+  
+  if( (Int)uiNumberOfBits < m_iValidBits)  // one word
+  {
+    m_iValidBits -= uiNumberOfBits;
+    
+    m_ulCurrentBits |= uiBits << m_iValidBits;
+    
+    return;
+  }
+  
+  UInt uiShift = uiNumberOfBits - m_iValidBits;
+  
+  // add the last bits
+  m_ulCurrentBits |= uiBits >> uiShift;
+  
+  *m_pulStreamPacket++ = xSwap( m_ulCurrentBits );
+  
+  
+  // note: there is a problem with left shift with 32
+  m_iValidBits = 32 - uiShift;
+  
+  m_ulCurrentBits = uiBits << m_iValidBits;
+  
+  if( 0 == uiShift )
+  {
+    m_ulCurrentBits = 0;
+  }
+}
+
+Void TComBitstream::writeAlignOne()
+{
+  write( ( 1 << (m_iValidBits & 0x7) ) - 1, m_iValidBits & 0x7 );
+  return;
+}
+
+Void TComBitstream::writeAlignZero()
+{
+  write( 0, m_iValidBits & 0x7 );
+  return;
+}
+
+Void  TComBitstream::flushBuffer()
+{
+  if (m_iValidBits == 0)
+    return;
+  
+  *m_pulStreamPacket = xSwap( m_ulCurrentBits );
+  
+  m_uiBitsWritten = (m_uiBitsWritten+7)/8;
+  
+  m_uiBitsWritten *= 8;
+}
+
+Void TComBitstream::initParsing ( UInt uiNumBytes )
+{
+  m_ulCurrentBits     = 0xdeaddead;
+  m_uiNextBits        = 0xdeaddead;
+  m_uiBitsLeft        = 0;
+  m_iValidBits        = 0;
+  m_uiDWordsLeft      = 0;
+  
+  m_uiBitsLeft        = uiNumBytes << 3;
+  
+  m_uiDWordsLeft      = m_uiBitsLeft >> 5;
+  m_iValidBits        = -32;
+  
+  xReadNextWord();
+  xReadNextWord();
+}
+
+#if LCEC_INTRA_MODE || QC_LCEC_INTER_MODE
+Void TComBitstream::pseudoRead ( UInt uiNumberOfBits, UInt& ruiBits )
+{
+  UInt ui_right_shift;
+
+  // check the number_of_bits parameter matches the range
+  assert( uiNumberOfBits <= 32 );
+
+  if( uiNumberOfBits > m_uiBitsLeft )
+  {
+    //assert (0);
+  }
+
+  Int  iValidBits = m_iValidBits - uiNumberOfBits;
+  UInt ulCurrentBits=m_ulCurrentBits;
+  UInt uiNextBits= m_uiNextBits;
+  if( 0 <= iValidBits )
+  {
+    // calculate the number of bits to extract the desired number of bits
+    ui_right_shift = 32 - uiNumberOfBits ;
+    // mask out the value
+    ruiBits  = ulCurrentBits >> ui_right_shift;
+    //prepare for next access
+    ulCurrentBits = ulCurrentBits << uiNumberOfBits;
+  }
+  else
+  {
+    // mask out the value in the current word
+    ruiBits = ulCurrentBits;
+    // calculate the number of bits to extract the desired number of bits
+    ui_right_shift = iValidBits + uiNumberOfBits ;
+    // mask out the value in the next word
+    ruiBits |= uiNextBits >> ui_right_shift;
+    ruiBits >>= 32 - uiNumberOfBits;
+    uiNextBits <<=  -iValidBits;
+  }
+
+  // check the current word for being empty
+  //-- baekeun.lee@samsung.com
+  if ( 0 < m_iValidBits)
+  {
+    return ;
+  }
+}
+#endif
+
+
+Void TComBitstream::read (UInt uiNumberOfBits, UInt& ruiBits)
+{
+  UInt ui_right_shift;
+  
+  // check the number_of_bits parameter matches the range
+  assert( uiNumberOfBits <= 32 );
+  
+  if( uiNumberOfBits > m_uiBitsLeft )
+  {
+    assert (0);
+  }
+  
+  m_uiBitsLeft -= uiNumberOfBits;
+  m_iValidBits -= uiNumberOfBits;
+  
+  if( 0 <= m_iValidBits )
+  {
+    // calculate the number of bits to extract the desired number of bits
+    ui_right_shift = 32 - uiNumberOfBits ;
+    
+    // mask out the value
+    ruiBits  = m_ulCurrentBits >> ui_right_shift;
+    
+    //prepare for next access
+    m_ulCurrentBits = m_ulCurrentBits << uiNumberOfBits;
+  }
+  else
+  {
+    // mask out the value in the current word
+    ruiBits = m_ulCurrentBits;
+    
+    // calculate the number of bits to extract the desired number of bits
+    ui_right_shift = m_iValidBits + uiNumberOfBits ;
+    
+    // mask out the value in the next word
+    ruiBits |= m_uiNextBits >> ui_right_shift;
+    
+    ruiBits >>= 32 - uiNumberOfBits;
+    
+    m_uiNextBits <<=  -m_iValidBits;
+  }
+  
+  // check the current word for being empty
+  //-- baekeun.lee@samsung.com
+  if ( 0 < m_iValidBits)
+  {
+    return ;
+  }
+  xReadNextWord();
+}
+
+Void TComBitstream::readAlignOne()
+{
+  UInt uiNumberOfBits = getBitsUntilByteAligned();
+  
+  // check the number_of_bits parameter matches the range
+  assert (uiNumberOfBits <= 32);
+  assert (uiNumberOfBits <= m_uiBitsLeft);
+  
+  // sub the desired number of bits
+  m_uiBitsLeft -= uiNumberOfBits;
+  m_iValidBits -= uiNumberOfBits;
+  
+  assert (m_uiBitsLeft%8 == 0);
+  assert (m_iValidBits%8 == 0);
+  
+  // check the current word for beeing still valid
+  if( 0 < m_iValidBits )
+  {
+    m_ulCurrentBits <<= uiNumberOfBits;
+    return;
+  }
+  
+  xReadNextWord();
+  
+  // shift to the right position
+  m_ulCurrentBits <<= 32 - m_iValidBits;
+  
+  return;
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+__inline Void TComBitstream::xReadNextWord()
+{
+  m_ulCurrentBits = m_uiNextBits;
+  m_iValidBits += 32;
+  
+  // chech if there are bytes left in the packet
+  if( m_uiDWordsLeft )
+  {
+    // read 32 bit from the packet
+    m_uiNextBits = xSwap( *m_pulStreamPacket++ );
+    m_uiDWordsLeft--;
+  }
+  else
+  {
+    Int iBytesLeft  = ((Int)m_uiBitsLeft - m_iValidBits+7) >> 3;
+    UChar* puc      = (UChar*) m_pulStreamPacket;
+    m_uiNextBits  = 0;
+    
+    if( iBytesLeft > 0)
+    {
+      for( Int iByte = 0; iByte < iBytesLeft; iByte++ )
+      {
+        m_uiNextBits <<= 8;
+        m_uiNextBits += puc[iByte];
+      }
+      m_uiNextBits <<= (4-iBytesLeft)<<3;
+    }
+  }
+}
+
+Void TComBitstream::initParsingConvertPayloadToRBSP( const UInt uiBytesRead )
+{
+  UInt uiZeroCount    = 0;
+  UInt uiReadOffset   = 0;
+  UInt uiWriteOffset  = 0;
+  const UChar* pucRead = reinterpret_cast<UChar*> (getBuffer());
+  UChar* pucWrite      = reinterpret_cast<UChar*> (getBuffer());
+  
+  for( ; uiReadOffset < uiBytesRead; uiReadOffset++ )
+  {
+    if( 2 == uiZeroCount && 0x03 == pucRead[uiReadOffset] )
+    {
+      uiReadOffset++;
+      uiZeroCount = 0;
+      if (uiReadOffset>=uiBytesRead)
+      {
+        break;
+      }
+    }
+    
+    pucWrite[uiWriteOffset++] = pucRead[uiReadOffset];
+    
+    if( 0x00 == pucRead[uiReadOffset] )
+    {
+      uiZeroCount++;
+    }
+    else
+    {
+      uiZeroCount = 0;
+    }
+  }
+  
+  // th just clear the remaining bits in the buffer
+  for( UInt ui = uiWriteOffset; ui < uiBytesRead; ui++)
+  {
+    pucWrite[ui] = 0;
+  }
+  
+  initParsing( uiWriteOffset );
+}
+
+Void TComBitstream::convertRBSPToPayload( UInt uiStartPos )
+{
+  UInt uiZeroCount    = 0;
+  
+  //make sure the buffer is flushed
+  assert( 0 == getBitsUntilByteAligned() );
+  
+  const UInt uiBytesInBuffer = getNumberOfWrittenBits()>>3;
+  //make sure there's something in the buffer
+  assert( 0 != uiBytesInBuffer );
+  
+  //make sure start pos is inside the buffer
+  //  assert( uiStartPos > uiBytesInBuffer );
+  
+  UChar* pucRead = new UChar[ uiBytesInBuffer ];
+  //th this is not nice but ...
+  memcpy( pucRead, getStartStream(), uiBytesInBuffer );
+  
+  UChar* pucWrite      =  reinterpret_cast<UChar*> (getStartStream());
+  
+  UInt uiWriteOffset  = uiStartPos;
+  UInt uiReadOffset = uiStartPos;
+  UInt uiSliceIdx   = 0;
+  while ( uiReadOffset < uiBytesInBuffer )
+  {
+    if (uiSliceIdx < m_uiSliceCount && uiReadOffset == m_auiSliceByteLocation[uiSliceIdx]) // skip over start codes introduced before slice headers
+    {
+      assert(pucRead[uiReadOffset] == 0); pucWrite[uiWriteOffset++] =  pucRead[uiReadOffset++];
+      assert(pucRead[uiReadOffset] == 0); pucWrite[uiWriteOffset++] =  pucRead[uiReadOffset++];
+      assert(pucRead[uiReadOffset] == 0); pucWrite[uiWriteOffset++] =  pucRead[uiReadOffset++];
+      assert(pucRead[uiReadOffset] == 1); pucWrite[uiWriteOffset++] =  pucRead[uiReadOffset++];
+
+      uiSliceIdx++;
+    }
+    if( 2 == uiZeroCount && 0 == (pucRead[uiReadOffset] & 0xfc) )
+    {
+      pucWrite[uiWriteOffset++] = 0x03;
+      uiZeroCount = 0;
+    }
+    
+    pucWrite[uiWriteOffset++] = pucRead[uiReadOffset];
+    
+    if( 0 == pucRead[uiReadOffset] )
+    {
+      uiZeroCount++;
+    }
+    else
+    {
+      uiZeroCount = 0;
+    }
+    uiReadOffset++;
+  }
+  
+  delete [] pucRead;
+  m_uiBitsWritten = uiWriteOffset << 3;
+}
+
+Void TComBitstream::allocateMemoryForSliceLocations ( UInt uiMaxNumOfSlices )
+{
+  m_auiSliceByteLocation     = new UInt[ uiMaxNumOfSlices ];
+  m_uiSliceCount             = 0;
+}
+
+Void TComBitstream::freeMemoryAllocatedForSliceLocations ()
+{
+  if (m_auiSliceByteLocation!=NULL)
+  {
+    delete [] m_auiSliceByteLocation;
+    m_auiSliceByteLocation   = NULL;
+  }
+  m_uiSliceCount             = 0;
+}
+
+/**
+ * insert the contents of the bytealigned (and flushed) bitstream @src
+ * into @this at byte position @pos.
+ *
+ * NB, there is currently a restriction that src_bytes must be a
+ * multiple of sizeof(UInt) if @this->write(...) is going to be called
+ * again.  This restriction will be removed when TComBitstream is refactored
+ * to work on bytes.
+ */
+void TComBitstream::insertAt(const TComBitstream& src, unsigned pos)
+{
+  unsigned src_bits = src.getNumberOfWrittenBits();
+  assert(0 == src_bits % 8);
+  unsigned src_bytes = src_bits/8;
+
+  /* check that there is enough space in the current buffer to accommodate @src */
+  unsigned this_buf_size = m_uiBufSize * sizeof(UInt);
+  unsigned this_bytes = this->getNumberOfWrittenBits()/8;
+  assert(this_buf_size - this_bytes > src_bytes);
+
+  /* make space */
+  unsigned char *this_dest = pos + src_bytes + (unsigned char*) this->getStartStream();
+  unsigned char *this_src = pos + (unsigned char*) this->getStartStream();
+  memmove(this_dest, this_src, this_bytes - pos);
+
+  /* splice src */
+  memcpy(this_src, src.getStartStream(), src_bytes);
+
+  /* update state */
+  this->m_uiBitsWritten += src_bits;
+  this->m_pulStreamPacket += src_bytes / sizeof(UInt);
+  /* XXX: this will go horribly wrong if data being inserted isn't a
+   * multiple of UInt. To work correctly, some data would have to be
+   * pulled back from the fifo into currentBits. */
+  /* Since davidf has rewritten this to work in bytes, i'm not going
+   * to make this work for UInt words.  This will be fine as long as
+   * no further data is pushed after this splice.
+   */
+}
Index: /tags/0.2r1/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComBitStream.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComBitStream.h	(revision 19)
@@ -0,0 +1,169 @@
+/* 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     TComBitStream.h
+    \brief    class for handling bitstream (header)
+*/
+
+#ifndef __COMBITSTREAM__
+#define __COMBITSTREAM__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdio.h>
+#include <assert.h>
+#include "CommonDef.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// pure virtual class for basic bit handling
+class TComBitIf
+{
+public:
+  virtual Void        writeAlignOne         () {};
+  virtual Void        write                 ( UInt uiBits, UInt uiNumberOfBits )  = 0;
+  virtual Void        resetBits             ()                                    = 0;
+  virtual UInt getNumberOfWrittenBits() const = 0;
+  virtual ~TComBitIf() {}
+};
+
+/// class for handling bitstream
+class TComBitstream : public TComBitIf
+{
+protected:
+  UInt*       m_apulStreamPacketBegin;
+  UInt*       m_pulStreamPacket;
+  UInt        m_uiBufSize;
+  
+  UInt        m_uiBitSize;
+  Int         m_iValidBits;
+  
+  UInt        m_ulCurrentBits;
+  UInt        m_uiBitsWritten;
+  
+  UInt        m_uiDWordsLeft;
+  UInt        m_uiBitsLeft;
+  UInt        m_uiNextBits;
+  
+  UInt        *m_auiSliceByteLocation, m_uiSliceCount;  // used to skip over slice start codes in initParsingConvertPayloadToRBSP()
+  UInt        m_uiSliceProcessed;
+
+  UInt xSwap ( UInt ui )
+  {
+    // heiko.schwarz@hhi.fhg.de: support for BSD systems as proposed by Steffen Kamp [kamp@ient.rwth-aachen.de]
+#ifdef MSYS_BIG_ENDIAN
+    return ui;
+#else
+    UInt ul2;
+    
+    ul2  = ui>>24;
+    ul2 |= (ui>>8) & 0x0000ff00;
+    ul2 |= (ui<<8) & 0x00ff0000;
+    ul2 |= ui<<24;
+    
+    return ul2;
+#endif
+  }
+  
+  // read one word
+  __inline Void xReadNextWord ();
+  
+public:
+  TComBitstream()             {}
+  virtual ~TComBitstream()    {}
+  
+  // create / destroy
+  Void        create          ( UInt uiSizeInBytes );
+  Void        destroy         ();
+  
+  // interface for encoding
+  Void        write           ( UInt uiBits, UInt uiNumberOfBits );
+  Void        writeAlignOne   ();
+  Void        writeAlignZero  ();
+  Void        convertRBSPToPayload( UInt uiStartPos = 0);
+  // interface for decoding
+  Void        initParsingConvertPayloadToRBSP( const UInt uiBytesRead );
+  Void        initParsing     ( UInt uiNumBytes );
+#if LCEC_INTRA_MODE || QC_LCEC_INTER_MODE
+  Void        pseudoRead      ( UInt uiNumberOfBits, UInt& ruiBits );
+#endif
+  Void        read            ( UInt uiNumberOfBits, UInt& ruiBits );
+  Void        readAlignOne    ();
+  UInt        getSliceProcessed                ()       { return m_uiSliceProcessed;                }
+  Void        setSliceProcessed                (UInt u) { m_uiSliceProcessed                = u;    }
+  
+  // interface for slice start-code positioning at encoder
+  UInt        getSliceCount                    ()                            { return m_uiSliceCount;                     }
+  UInt        getSliceByteLocation             ( UInt uiIdx )                { return m_auiSliceByteLocation[ uiIdx ];    }
+  Void        setSliceCount                    ( UInt uiCount )              { m_uiSliceCount = uiCount;                  }
+  Void        setSliceByteLocation             ( UInt uiIdx, UInt uiCount )  { m_auiSliceByteLocation[ uiIdx ] = uiCount; }
+
+  // memory allocation / deallocation interface for "slice location" bookkeeping
+  Void        allocateMemoryForSliceLocations       ( UInt uiMaxNumOfSlices );
+  Void        freeMemoryAllocatedForSliceLocations  ();
+
+  // 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) { return( m_ulCurrentBits >> (32 - uiBits));  }
+
+  // reset internal status
+  Void        resetBits       ()
+  {
+    m_uiBitSize = 0;
+    m_iValidBits = 32;
+    m_ulCurrentBits = 0;
+    m_uiBitsWritten = 0;
+  }
+  
+  // utility functions
+  unsigned read(unsigned numberOfBits) { UInt tmp; read(numberOfBits, tmp); return tmp; }
+  UInt* getStartStream() const { return m_apulStreamPacketBegin; }
+  UInt*       getBuffer()               { return  m_pulStreamPacket;                    }
+  Int         getBitsUntilByteAligned() { return m_iValidBits & (0x7);                  }
+  Void        setModeSbac()             { m_uiBitsLeft = 8*((m_uiBitsLeft+7)/8);        } // stop bit + trailing stuffing bits
+  Bool        isWordAligned()           { return  (0 == (m_iValidBits & (0x1f)));       }
+  UInt getNumberOfWrittenBits() const { return  m_uiBitsWritten; }
+  Void        flushBuffer();
+  Void        rewindStreamPacket()      { m_pulStreamPacket = m_apulStreamPacketBegin;  }
+  UInt        getBitsLeft()             { return  m_uiBitsLeft;                         }
+
+  void insertAt(const TComBitstream& src, unsigned pos);
+};
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 19)
@@ -0,0 +1,109 @@
+/* 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     TComCABACTables.cpp
+ *  \brief    static class for CABAC tables
+ */
+
+#include "TComCABACTables.h"
+
+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}
+};
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComCABACTables.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComCABACTables.h	(revision 19)
@@ -0,0 +1,57 @@
+/* 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     TComCABACTables.h
+    \brief    static class for CABAC tables
+*/
+
+#ifndef __TCOM_CABAC_TABLES__
+#define __TCOM_CABAC_TABLES__
+
+#include "../TLibCommon/CommonDef.h"
+
+/**
+ * \brief static class for CABAC tables
+ */
+
+class TComCABACTables
+{
+public:
+  const static UChar  sm_aucLPSTable[64][4];
+};
+
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComDataCU.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComDataCU.cpp	(revision 19)
@@ -0,0 +1,4792 @@
+/* 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     TComDataCU.cpp
+    \brief    CU data structure
+    \todo     not all entities are documented
+*/
+
+#include "TComDataCU.h"
+#include "TComPic.h"
+#include "TComDepthMapGenerator.h"
+#include "TComResidualGenerator.h"
+
+// ====================================================================================================================
+// 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;
+  m_pePredMode         = NULL;
+  m_puiAlfCtrlFlag     = NULL;
+  m_puiTmpAlfCtrlFlag  = NULL;
+  m_puhWidth           = NULL;
+  m_puhHeight          = NULL;
+  m_phQP               = NULL;
+  m_pbMergeFlag        = NULL;
+  m_puhMergeIndex      = NULL;
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_pbResPredAvailable = NULL;
+  m_pbResPredFlag      = NULL;
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    m_apuhNeighbourCandIdx[ui] = NULL;
+  }
+  m_puhLumaIntraDir    = NULL;
+  m_puhChromaIntraDir  = NULL;
+  m_puhInterDir        = NULL;
+  m_puhTrIdx           = NULL;
+  m_puhCbf[0]          = NULL;
+  m_puhCbf[1]          = NULL;
+  m_puhCbf[2]          = NULL;
+  m_pcTrCoeffY         = NULL;
+  m_pcTrCoeffCb        = NULL;
+  m_pcTrCoeffCr        = 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 SNY_DQP 
+  m_bdQP               = false;               
+#endif//SNY_DQP
+
+#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;
+  m_piWedgePredTexDeltaDC1    = NULL;
+  m_piWedgePredTexDeltaDC2    = NULL;
+
+  m_piContourPredTexDeltaDC1  = NULL;
+  m_piContourPredTexDeltaDC2  = NULL;
+#endif
+}
+
+TComDataCU::~TComDataCU()
+{
+}
+
+Void TComDataCU::create(UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu)
+{
+  m_bDecSubCu = bDecSubCu;
+  
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  m_uiNumPartition     = uiNumPartition;
+  
+  if ( !bDecSubCu )
+  {
+    m_phQP               = (UChar*    )xMalloc(UChar,    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         = (PartSize* )xMalloc(PartSize, uiNumPartition);
+    m_pePredMode         = (PredMode* )xMalloc(PredMode, uiNumPartition);
+    
+    m_puiAlfCtrlFlag     = (UInt*  )xMalloc(UInt,   uiNumPartition);
+    
+    m_pbMergeFlag        = (Bool*  )xMalloc(Bool,   uiNumPartition);
+    m_puhMergeIndex      = (UChar* )xMalloc(UChar,  uiNumPartition);
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    m_pbResPredAvailable = (Bool*  )xMalloc(Bool,   uiNumPartition);
+    m_pbResPredFlag      = (Bool*  )xMalloc(Bool,   uiNumPartition);
+#endif
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+    {
+      m_apuhNeighbourCandIdx[ ui ] = (UChar* )xMalloc(UChar, uiNumPartition);
+    }
+    
+    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_puhCbf[0]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhCbf[1]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhCbf[2]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    
+    m_apiMVPIdx[0]       = (Int*   )xMalloc(Int,  uiNumPartition);
+    m_apiMVPIdx[1]       = (Int*   )xMalloc(Int,  uiNumPartition);
+    m_apiMVPNum[0]       = (Int*   )xMalloc(Int,  uiNumPartition);
+    m_apiMVPNum[1]       = (Int*   )xMalloc(Int,  uiNumPartition);
+    
+    m_pcTrCoeffY         = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight);
+    m_pcTrCoeffCb        = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight/4);
+    m_pcTrCoeffCr        = (TCoeff*)xMalloc(TCoeff, 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);
+    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
+  }
+  else
+  {
+    m_acCUMvField[0].setNumPartition(uiNumPartition );
+    m_acCUMvField[1].setNumPartition(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         ) { xFree(m_pePartSize);          m_pePartSize        = NULL; }
+    if ( m_pePredMode         ) { xFree(m_pePredMode);          m_pePredMode        = NULL; }
+    if ( m_puhCbf[0]          ) { xFree(m_puhCbf[0]);           m_puhCbf[0]         = NULL; }
+    if ( m_puhCbf[1]          ) { xFree(m_puhCbf[1]);           m_puhCbf[1]         = NULL; }
+    if ( m_puhCbf[2]          ) { xFree(m_puhCbf[2]);           m_puhCbf[2]         = NULL; }
+    if ( m_puiAlfCtrlFlag     ) { xFree(m_puiAlfCtrlFlag);      m_puiAlfCtrlFlag    = NULL; }
+    if ( m_puhInterDir        ) { xFree(m_puhInterDir);         m_puhInterDir       = NULL; }
+    if ( m_pbMergeFlag        ) { xFree(m_pbMergeFlag);         m_pbMergeFlag       = NULL; }
+    if ( m_puhMergeIndex      ) { xFree(m_puhMergeIndex);       m_puhMergeIndex     = NULL; }
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    if ( m_pbResPredAvailable ) { xFree(m_pbResPredAvailable);  m_pbResPredAvailable= NULL; }
+    if ( m_pbResPredFlag      ) { xFree(m_pbResPredFlag);       m_pbResPredFlag     = NULL; }
+#endif
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+    {
+      if( m_apuhNeighbourCandIdx[ ui ] ) { xFree(m_apuhNeighbourCandIdx[ ui ]); m_apuhNeighbourCandIdx[ ui ] = NULL; }
+    }
+    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_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 ( m_apiMVPIdx[0]       ) { xFree(m_apiMVPIdx[0]);        m_apiMVPIdx[0]      = NULL; }
+    if ( m_apiMVPIdx[1]       ) { xFree(m_apiMVPIdx[1]);        m_apiMVPIdx[1]      = NULL; }
+    if ( m_apiMVPNum[0]       ) { xFree(m_apiMVPNum[0]);        m_apiMVPNum[0]      = NULL; }
+    if ( m_apiMVPNum[1]       ) { xFree(m_apiMVPNum[1]);        m_apiMVPNum[1]      = NULL; }
+    
+    m_acCUMvField[0].destroy();
+    m_acCUMvField[1].destroy();
+    
+#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 ( 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    
+  }
+  
+  m_pcCUAboveLeft       = NULL;
+  m_pcCUAboveRight      = NULL;
+  m_pcCUAbove           = NULL;
+  m_pcCULeft            = NULL;
+  
+  m_apcCUColocated[0]   = NULL;
+  m_apcCUColocated[1]   = NULL;
+}
+
+// ====================================================================================================================
+// 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 )
+{
+  TComSlice* pcSlice   = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  m_pcSlice            = pcSlice;
+  m_uiSliceStartCU     = pcSlice->getSliceCurStartCUAddr();
+  m_uiEntropySliceStartCU  = pcSlice->getEntropySliceCurStartCUAddr();
+  m_pcPic              = pcPic;
+  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_uiNumPartition     = pcPic->getNumPartInCU();
+  
+  Int iSizeInUchar = sizeof( UChar ) * m_uiNumPartition;
+  Int iSizeInUInt  = sizeof( UInt  ) * m_uiNumPartition;
+  Int iSizeInBool  = sizeof( Bool  ) * m_uiNumPartition;
+
+  Int iSizeInInt   = sizeof( Int   ) * m_uiNumPartition;
+  
+  memset( m_phQP,               pcSlice->getSliceQp(), iSizeInUchar );
+  memset( m_puiAlfCtrlFlag,     0, iSizeInUInt  );
+  memset( m_pbMergeFlag,        0, iSizeInBool  );
+  memset( m_puhMergeIndex,      0, iSizeInUchar );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  memset( m_pbResPredAvailable, 0, iSizeInBool  );
+  memset( m_pbResPredFlag,      0, iSizeInBool  );
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    memset( m_apuhNeighbourCandIdx[ ui ], 0, iSizeInUchar );
+  }
+  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,           0, iSizeInUchar );
+#if HHI_MPI
+  memset( m_piTextureModeDepth,-1, iSizeInInt );
+#endif
+  
+  UChar uhWidth  = g_uiMaxCUWidth;
+  UChar uhHeight = g_uiMaxCUHeight;
+  memset( m_puhWidth,          uhWidth,  iSizeInUchar );
+  memset( m_puhHeight,         uhHeight, iSizeInUchar );
+  
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    m_pePartSize[ui] = SIZE_NONE;
+    m_pePredMode[ui] = MODE_NONE;
+    
+    m_apiMVPIdx[0][ui] = -1;
+    m_apiMVPIdx[1][ui] = -1;
+    m_apiMVPNum[0][ui] = -1;
+    m_apiMVPNum[1][ui] = -1;
+  }
+  
+  m_acCUMvField[0].clearMvField();
+  m_acCUMvField[1].clearMvField();
+  
+  UInt uiTmp = m_puhWidth[0]*m_puhHeight[0];
+  memset( m_pcTrCoeffY , 0, sizeof( TCoeff ) * uiTmp );
+  
+  uiTmp  >>= 2;
+  memset( m_pcTrCoeffCb, 0, sizeof( TCoeff ) * uiTmp );
+  memset( m_pcTrCoeffCr, 0, sizeof( TCoeff ) * uiTmp );
+  
+  // 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 ( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+  {
+    m_apcCUColocated[0] = pcSlice->getRefPic( REF_PIC_LIST_0, 0)->getCU( m_uiCUAddr );
+  }
+
+  if ( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+  {
+    m_apcCUColocated[1] = pcSlice->getRefPic( REF_PIC_LIST_1, 0)->getCU( m_uiCUAddr );
+  }
+
+#if HHI_DMM_WEDGE_INTRA
+  memset( m_puiWedgeFullTabIdx,  0, iSizeInUInt   );
+  memset( m_piWedgeFullDeltaDC1,       0, iSizeInInt  );
+  memset( m_piWedgeFullDeltaDC2,       0, iSizeInInt  );
+
+  memset( m_puiWedgePredDirTabIdx,    0, iSizeInUInt );
+  memset( m_piWedgePredDirDeltaDC1,   0, iSizeInInt  );
+  memset( m_piWedgePredDirDeltaDC2,   0, iSizeInInt  );
+  memset( m_piWedgePredDirDeltaEnd,   0, iSizeInInt  );
+#endif
+#if HHI_DMM_PRED_TEX
+  memset( m_puiWedgePredTexTabIdx,     0, iSizeInUInt );
+  memset( m_piWedgePredTexDeltaDC1,    0, iSizeInInt  );
+  memset( m_piWedgePredTexDeltaDC2,    0, iSizeInInt  );
+
+  memset( m_piContourPredTexDeltaDC1,  0, iSizeInInt  );
+  memset( m_piContourPredTexDeltaDC2,  0, iSizeInInt  );
+#endif    
+}
+
+// initialize prediction data
+Void TComDataCU::initEstData()
+{
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  
+  Int iSizeInUchar = sizeof( UChar  ) * m_uiNumPartition;
+  Int iSizeInUInt  = sizeof( UInt   ) * m_uiNumPartition;
+  Int iSizeInBool  = sizeof( Bool   ) * m_uiNumPartition;
+  Int iSizeInInt   = sizeof( Int   ) * m_uiNumPartition;
+  memset( m_phQP,              getSlice()->getSliceQp(), iSizeInUchar );
+  memset( m_puiAlfCtrlFlag,     0, iSizeInUInt );
+  memset( m_pbMergeFlag,        0, iSizeInBool  );
+  memset( m_puhMergeIndex,      0, iSizeInUchar );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  memset( m_pbResPredAvailable, 0, iSizeInBool  );
+  memset( m_pbResPredFlag,      0, iSizeInBool  );
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    memset( m_apuhNeighbourCandIdx[ ui ], 0, iSizeInUchar );
+  }
+  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 );
+  
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    m_pePartSize[ui] = SIZE_NONE;
+    m_pePredMode[ui] = MODE_NONE;
+    
+    m_apiMVPIdx[0][ui] = -1;
+    m_apiMVPIdx[1][ui] = -1;
+    m_apiMVPNum[0][ui] = -1;
+    m_apiMVPNum[1][ui] = -1;
+  }
+  
+  UInt uiTmp = m_puhWidth[0]*m_puhHeight[0];
+  memset( m_pcTrCoeffY , 0, sizeof(TCoeff)*uiTmp );
+  
+  uiTmp >>= 2;
+  memset( m_pcTrCoeffCb, 0, sizeof(TCoeff)*uiTmp );
+  memset( m_pcTrCoeffCr, 0, sizeof(TCoeff)*uiTmp );
+  
+  m_acCUMvField[0].clearMvField();
+  m_acCUMvField[1].clearMvField();
+
+#if HHI_DMM_WEDGE_INTRA
+  memset( m_puiWedgeFullTabIdx,  0, iSizeInUInt   );
+  memset( m_piWedgeFullDeltaDC1,       0, iSizeInInt  );
+  memset( m_piWedgeFullDeltaDC2,       0, iSizeInInt  );
+
+  memset( m_puiWedgePredDirTabIdx,    0, iSizeInUInt );
+  memset( m_piWedgePredDirDeltaDC1,   0, iSizeInInt  );
+  memset( m_piWedgePredDirDeltaDC2,   0, iSizeInInt  );
+  memset( m_piWedgePredDirDeltaEnd,   0, iSizeInInt  );
+#endif
+#if HHI_DMM_PRED_TEX
+  memset( m_puiWedgePredTexTabIdx,     0, iSizeInUInt );
+  memset( m_piWedgePredTexDeltaDC1,    0, iSizeInInt  );
+  memset( m_piWedgePredTexDeltaDC2,    0, iSizeInInt  );
+
+  memset( m_piContourPredTexDeltaDC1,  0, iSizeInInt  );
+  memset( m_piContourPredTexDeltaDC2,  0, iSizeInInt  );
+#endif    
+
+#if HHI_MPI
+  memset( m_piTextureModeDepth, -1, iSizeInInt );
+#endif
+}
+
+// initialize Sub partition
+Void TComDataCU::initSubCU( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth )
+{
+  assert( uiPartUnitIdx<4 );
+  
+  UInt uiPartOffset = ( pcCU->getTotalNumPart()>>2 )*uiPartUnitIdx;
+  
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = pcCU->getSlice();
+  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_uiNumPartition     = pcCU->getTotalNumPart() >> 2;
+  
+  Int iSizeInUchar = sizeof( UChar  ) * m_uiNumPartition;
+  Int iSizeInUInt  = sizeof( UInt   ) * m_uiNumPartition;
+  Int iSizeInBool  = sizeof( Bool   ) * m_uiNumPartition;
+  Int iSizeInInt   = sizeof( Int   ) * m_uiNumPartition;
+  
+  memset( m_phQP,              getSlice()->getSliceQp(), iSizeInUchar );
+  memset( m_puiAlfCtrlFlag,     0, iSizeInUInt );
+  memset( m_pbMergeFlag,        0, iSizeInBool  );
+  memset( m_puhMergeIndex,      0, iSizeInUchar );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  memset( m_pbResPredAvailable, 0, iSizeInBool  );
+  memset( m_pbResPredFlag,      0, iSizeInBool  );
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    memset( m_apuhNeighbourCandIdx[ ui ], 0, iSizeInUchar );
+  }
+  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, iSizeInInt );
+#endif
+  
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  memset( m_puhWidth,          uhWidth,  iSizeInUchar );
+  memset( m_puhHeight,         uhHeight, iSizeInUchar );
+  
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    m_pePartSize[ui] = SIZE_NONE;
+    m_pePredMode[ui] = MODE_NONE;
+    
+    m_apiMVPIdx[0][ui] = -1;
+    m_apiMVPIdx[1][ui] = -1;
+    m_apiMVPNum[0][ui] = -1;
+    m_apiMVPNum[1][ui] = -1;
+  }
+  
+  UInt uiTmp = m_puhWidth[0]*m_puhHeight[0];
+  memset( m_pcTrCoeffY , 0, sizeof(TCoeff)*uiTmp );
+  
+  uiTmp >>= 2;
+  memset( m_pcTrCoeffCb, 0, sizeof(TCoeff)*uiTmp );
+  memset( m_pcTrCoeffCr, 0, sizeof(TCoeff)*uiTmp );
+  
+  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);
+  
+  m_acCUMvField[0].clearMvField();
+  m_acCUMvField[1].clearMvField();
+  m_uiSliceStartCU          = pcCU->getSliceStartCU();
+  m_uiEntropySliceStartCU   = pcCU->getEntropySliceStartCU();
+
+#if HHI_DMM_WEDGE_INTRA
+  memset( m_puiWedgeFullTabIdx,  0, iSizeInUInt   );
+  memset( m_piWedgeFullDeltaDC1,       0, iSizeInInt  );
+  memset( m_piWedgeFullDeltaDC2,       0, iSizeInInt  );
+
+  memset( m_puiWedgePredDirTabIdx,    0, iSizeInUInt );
+  memset( m_piWedgePredDirDeltaDC1,   0, iSizeInInt  );
+  memset( m_piWedgePredDirDeltaDC2,   0, iSizeInInt  );
+  memset( m_piWedgePredDirDeltaEnd,   0, iSizeInInt  );
+#endif
+#if HHI_DMM_PRED_TEX
+  memset( m_puiWedgePredTexTabIdx,     0, iSizeInUInt );
+  memset( m_piWedgePredTexDeltaDC1,    0, iSizeInInt  );
+  memset( m_piWedgePredTexDeltaDC2,    0, iSizeInInt  );
+
+  memset( m_piContourPredTexDeltaDC1,  0, iSizeInInt  );
+  memset( m_piContourPredTexDeltaDC2,  0, iSizeInInt  );
+#endif
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// 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;
+  m_pePredMode=pcCU->getPredictionMode()  + uiPart;
+  
+  m_pbMergeFlag         = pcCU->getMergeFlag()        + uiPart;
+  m_puhMergeIndex       = pcCU->getMergeIndex()       + uiPart;
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_pbResPredAvailable  = pcCU->getResPredAvail()     + uiPart;
+  m_pbResPredFlag       = pcCU->getResPredFlag ()     + uiPart;
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    m_apuhNeighbourCandIdx[ ui ] = pcCU->getNeighbourCandIdx( ui ) + uiPart;
+  }
+
+  m_puhLumaIntraDir     = pcCU->getLumaIntraDir()     + uiPart;
+  m_puhChromaIntraDir   = pcCU->getChromaIntraDir()   + uiPart;
+  m_puhInterDir         = pcCU->getInterDir()         + uiPart;
+  m_puhTrIdx            = pcCU->getTransformIdx()     + 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_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;
+  
+  uiTmp >>= 2;
+  uiCoffOffset >>=2;
+  m_pcTrCoeffCb=pcCU->getCoeffCb() + uiCoffOffset;
+  m_pcTrCoeffCr=pcCU->getCoeffCr() + uiCoffOffset;
+  
+  m_acCUMvField[0].setMvPtr(pcCU->getCUMvField(REF_PIC_LIST_0)->getMv()     + uiPart);
+  m_acCUMvField[0].setMvdPtr(pcCU->getCUMvField(REF_PIC_LIST_0)->getMvd()    + uiPart);
+  m_acCUMvField[0].setRefIdxPtr(pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx() + uiPart);
+  m_acCUMvField[1].setMvPtr(pcCU->getCUMvField(REF_PIC_LIST_1)->getMv()     + uiPart);
+  m_acCUMvField[1].setMvdPtr(pcCU->getCUMvField(REF_PIC_LIST_1)->getMvd()    + uiPart);
+  m_acCUMvField[1].setRefIdxPtr(pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx() + uiPart);
+  m_uiSliceStartCU        = pcCU->getSliceStartCU();
+  m_uiEntropySliceStartCU = pcCU->getEntropySliceStartCU();
+
+#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;   
+  m_piWedgePredTexDeltaDC1    = pcCU->getWedgePredTexDeltaDC1()   + uiPart;   
+  m_piWedgePredTexDeltaDC2    = pcCU->getWedgePredTexDeltaDC2()   + uiPart;   
+
+  m_piContourPredTexDeltaDC1  = pcCU->getContourPredTexDeltaDC1() + uiPart;   
+  m_piContourPredTexDeltaDC2  = pcCU->getContourPredTexDeltaDC2() + 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;
+  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;
+  m_puhMergeIndex      = pcCU->getMergeIndex()            + uiAbsPartIdx;
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_pbResPredAvailable = pcCU->getResPredAvail()          + uiAbsPartIdx;
+  m_pbResPredFlag      = pcCU->getResPredFlag ()          + uiAbsPartIdx;
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui ++ )
+  {
+    m_apuhNeighbourCandIdx[ui] = pcCU->getNeighbourCandIdx( ui ) + uiAbsPartIdx;
+  }
+
+  m_apiMVPIdx[eRefPicList] = pcCU->getMVPIdx(eRefPicList) + uiAbsPartIdx;
+  m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;
+  
+  m_acCUMvField[eRefPicList].setMvPtr(pcCU->getCUMvField(eRefPicList)->getMv()     + uiAbsPartIdx);
+  m_acCUMvField[eRefPicList].setMvdPtr(pcCU->getCUMvField(eRefPicList)->getMvd()    + uiAbsPartIdx);
+  m_acCUMvField[eRefPicList].setRefIdxPtr(pcCU->getCUMvField(eRefPicList)->getRefIdx() + uiAbsPartIdx);
+#if HHI_MPI
+  m_piTextureModeDepth = pcCU->getTextureModeDepth() + uiAbsPartIdx;
+#endif
+
+  m_uiSliceStartCU        = pcCU->getSliceStartCU();
+  m_uiEntropySliceStartCU = pcCU->getEntropySliceStartCU();
+}
+
+// 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 iSizeInUInt   = sizeof( UInt  ) * uiNumPartition;
+  Int iSizeInInt    = sizeof( Int   ) * uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * uiNumPartition;
+  
+  memcpy( m_phQP       + uiOffset, pcCU->getQP(),             iSizeInUchar                        );
+  memcpy( m_pePartSize + uiOffset, pcCU->getPartitionSize(),  sizeof( PartSize ) * uiNumPartition );
+  memcpy( m_pePredMode + uiOffset, pcCU->getPredictionMode(), sizeof( PredMode ) * uiNumPartition );
+  
+  memcpy( m_puiAlfCtrlFlag      + uiOffset, pcCU->getAlfCtrlFlag(),       iSizeInUInt  );
+  memcpy( m_pbMergeFlag         + uiOffset, pcCU->getMergeFlag(),         iSizeInBool  );
+  memcpy( m_puhMergeIndex       + uiOffset, pcCU->getMergeIndex(),        iSizeInUchar );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  memcpy( m_pbResPredAvailable  + uiOffset, pcCU->getResPredAvail(),      iSizeInBool  );
+  memcpy( m_pbResPredFlag       + uiOffset, pcCU->getResPredFlag(),       iSizeInBool  );
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    memcpy( m_apuhNeighbourCandIdx[ ui ] + uiOffset, pcCU->getNeighbourCandIdx( ui ), iSizeInUchar );
+  }
+  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_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), iSizeInInt );
+  memcpy( m_apiMVPIdx[1] + uiOffset, pcCU->getMVPIdx(REF_PIC_LIST_1), iSizeInInt );
+  memcpy( m_apiMVPNum[0] + uiOffset, pcCU->getMVPNum(REF_PIC_LIST_0), iSizeInInt );
+  memcpy( m_apiMVPNum[1] + uiOffset, pcCU->getMVPNum(REF_PIC_LIST_1), iSizeInInt );
+  
+  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 );
+  
+  uiTmp >>= 2; uiTmp2>>= 2;
+  memcpy( m_pcTrCoeffCb + uiTmp2, pcCU->getCoeffCb(), sizeof(TCoeff)*uiTmp );
+  memcpy( m_pcTrCoeffCr + uiTmp2, pcCU->getCoeffCr(), sizeof(TCoeff)*uiTmp );
+  m_uiSliceStartCU        = pcCU->getSliceStartCU();
+  m_uiEntropySliceStartCU = pcCU->getEntropySliceStartCU();
+
+#if HHI_DMM_WEDGE_INTRA
+  memcpy( m_puiWedgeFullTabIdx   + uiOffset, pcCU->getWedgeFullTabIdx(),    iSizeInUInt    );
+  memcpy( m_piWedgeFullDeltaDC1       + uiOffset, pcCU->getWedgeFullDeltaDC1(),      iSizeInInt  );
+  memcpy( m_piWedgeFullDeltaDC2       + uiOffset, pcCU->getWedgeFullDeltaDC2(),      iSizeInInt  );
+
+  memcpy( m_puiWedgePredDirTabIdx    + uiOffset, pcCU->getWedgePredDirTabIdx(),     iSizeInUInt );
+  memcpy( m_piWedgePredDirDeltaDC1   + uiOffset, pcCU->getWedgePredDirDeltaDC1(),   iSizeInInt  );
+  memcpy( m_piWedgePredDirDeltaDC2   + uiOffset, pcCU->getWedgePredDirDeltaDC2(),   iSizeInInt  );
+  memcpy( m_piWedgePredDirDeltaEnd   + uiOffset, pcCU->getWedgePredDirDeltaEnd(),   iSizeInInt  );
+#endif
+#if HHI_DMM_PRED_TEX
+  memcpy( m_puiWedgePredTexTabIdx     + uiOffset, pcCU->getWedgePredTexTabIdx(),     iSizeInUInt );
+  memcpy( m_piWedgePredTexDeltaDC1    + uiOffset, pcCU->getWedgePredTexDeltaDC1(),   iSizeInInt  );
+  memcpy( m_piWedgePredTexDeltaDC2    + uiOffset, pcCU->getWedgePredTexDeltaDC2(),   iSizeInInt  );
+
+  memcpy( m_piContourPredTexDeltaDC1  + uiOffset, pcCU->getContourPredTexDeltaDC1(), iSizeInInt  );
+  memcpy( m_piContourPredTexDeltaDC2  + uiOffset, pcCU->getContourPredTexDeltaDC2(), iSizeInInt  );
+#endif
+
+#if HHI_MPI
+  memcpy( m_piTextureModeDepth + uiOffset, pcCU->getTextureModeDepth(), iSizeInInt );
+#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 iSizeInUInt   = sizeof( UInt  ) * m_uiNumPartition;
+  Int iSizeInInt    = sizeof( Int   ) * m_uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * m_uiNumPartition;
+  
+  memcpy( rpcCU->getQP() + m_uiAbsIdxInLCU, m_phQP, iSizeInUchar );
+  
+  memcpy( rpcCU->getPartitionSize()  + m_uiAbsIdxInLCU, m_pePartSize, sizeof( PartSize ) * m_uiNumPartition );
+  memcpy( rpcCU->getPredictionMode() + m_uiAbsIdxInLCU, m_pePredMode, sizeof( PredMode ) * m_uiNumPartition );
+  
+  memcpy( rpcCU->getAlfCtrlFlag()    + m_uiAbsIdxInLCU, m_puiAlfCtrlFlag,    iSizeInUInt  );
+  
+  memcpy( rpcCU->getMergeFlag()         + m_uiAbsIdxInLCU, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( rpcCU->getMergeIndex()        + m_uiAbsIdxInLCU, m_puhMergeIndex,       iSizeInUchar );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  memcpy( rpcCU->getResPredAvail()      + m_uiAbsIdxInLCU, m_pbResPredAvailable,  iSizeInBool  );
+  memcpy( rpcCU->getResPredFlag()       + m_uiAbsIdxInLCU, m_pbResPredFlag,       iSizeInBool  );
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    memcpy( rpcCU->getNeighbourCandIdx( ui ) + m_uiAbsIdxInLCU, m_apuhNeighbourCandIdx[ui], iSizeInUchar );
+  }
+  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->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], iSizeInInt );
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_1) + m_uiAbsIdxInLCU, m_apiMVPIdx[1], iSizeInInt );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_0) + m_uiAbsIdxInLCU, m_apiMVPNum[0], iSizeInInt );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_1) + m_uiAbsIdxInLCU, m_apiMVPNum[1], iSizeInInt );
+  
+  m_acCUMvField[0].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_0 ), m_uiAbsIdxInLCU );
+  m_acCUMvField[1].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_1 ), m_uiAbsIdxInLCU );
+  
+  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  );
+  
+  uiTmp >>= 2; uiTmp2 >>= 2;
+  memcpy( rpcCU->getCoeffCb() + uiTmp2, m_pcTrCoeffCb, sizeof(TCoeff)*uiTmp  );
+  memcpy( rpcCU->getCoeffCr() + uiTmp2, m_pcTrCoeffCr, sizeof(TCoeff)*uiTmp  );
+  rpcCU->setSliceStartCU( m_uiSliceStartCU );
+  rpcCU->setEntropySliceStartCU( m_uiEntropySliceStartCU );
+
+#if HHI_DMM_WEDGE_INTRA
+  memcpy( rpcCU->getWedgeFullTabIdx()  + m_uiAbsIdxInLCU, m_puiWedgeFullTabIdx,  iSizeInUInt   );
+  memcpy( rpcCU->getWedgeFullDeltaDC1()      + m_uiAbsIdxInLCU, m_piWedgeFullDeltaDC1,       iSizeInInt  );
+  memcpy( rpcCU->getWedgeFullDeltaDC2()      + m_uiAbsIdxInLCU, m_piWedgeFullDeltaDC2,       iSizeInInt  );
+
+  memcpy( rpcCU->getWedgePredDirTabIdx()     + m_uiAbsIdxInLCU, m_puiWedgePredDirTabIdx,    iSizeInUInt );
+  memcpy( rpcCU->getWedgePredDirDeltaDC1()   + m_uiAbsIdxInLCU, m_piWedgePredDirDeltaDC1,   iSizeInInt  );
+  memcpy( rpcCU->getWedgePredDirDeltaDC2()   + m_uiAbsIdxInLCU, m_piWedgePredDirDeltaDC2,   iSizeInInt  );
+  memcpy( rpcCU->getWedgePredDirDeltaEnd()   + m_uiAbsIdxInLCU, m_piWedgePredDirDeltaEnd,   iSizeInInt  );
+#endif
+#if HHI_DMM_PRED_TEX
+  memcpy( rpcCU->getWedgePredTexTabIdx()     + m_uiAbsIdxInLCU, m_puiWedgePredTexTabIdx,     iSizeInUInt );
+  memcpy( rpcCU->getWedgePredTexDeltaDC1()   + m_uiAbsIdxInLCU, m_piWedgePredTexDeltaDC1,    iSizeInInt  );
+  memcpy( rpcCU->getWedgePredTexDeltaDC2()   + m_uiAbsIdxInLCU, m_piWedgePredTexDeltaDC2,    iSizeInInt  );
+
+  memcpy( rpcCU->getContourPredTexDeltaDC1() + m_uiAbsIdxInLCU, m_piContourPredTexDeltaDC1,  iSizeInInt  );
+  memcpy( rpcCU->getContourPredTexDeltaDC2() + m_uiAbsIdxInLCU, m_piContourPredTexDeltaDC2,  iSizeInInt  );
+#endif
+
+#if HHI_MPI
+  memcpy( rpcCU->getTextureModeDepth() + m_uiAbsIdxInLCU, m_piTextureModeDepth, iSizeInInt );
+#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 iSizeInUInt   = sizeof( UInt   ) * uiQNumPart;
+  Int iSizeInInt    = sizeof( Int    ) * uiQNumPart;
+  Int iSizeInBool   = sizeof( Bool   ) * uiQNumPart;
+  
+  memcpy( rpcCU->getQP() + uiPartOffset, m_phQP, iSizeInUchar );
+  
+  memcpy( rpcCU->getPartitionSize()  + uiPartOffset, m_pePartSize, sizeof( PartSize ) * uiQNumPart );
+  memcpy( rpcCU->getPredictionMode() + uiPartOffset, m_pePredMode, sizeof( PredMode ) * uiQNumPart );
+  
+  memcpy( rpcCU->getAlfCtrlFlag()       + uiPartOffset, m_puiAlfCtrlFlag,      iSizeInUInt  );
+  memcpy( rpcCU->getMergeFlag()         + uiPartOffset, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( rpcCU->getMergeIndex()        + uiPartOffset, m_puhMergeIndex,       iSizeInUchar );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  memcpy( rpcCU->getResPredAvail()      + uiPartOffset, m_pbResPredAvailable,  iSizeInBool  );
+  memcpy( rpcCU->getResPredFlag()       + uiPartOffset, m_pbResPredFlag,       iSizeInBool  );
+#endif
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    memcpy( rpcCU->getNeighbourCandIdx( ui ) + uiPartOffset, m_apuhNeighbourCandIdx[ui], iSizeInUchar );
+  }
+  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->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], iSizeInInt );
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_1) + uiPartOffset, m_apiMVPIdx[1], iSizeInInt );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_0) + uiPartOffset, m_apiMVPNum[0], iSizeInInt );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_1) + uiPartOffset, m_apiMVPNum[1], iSizeInInt );
+  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 );
+  
+  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  );
+  
+  uiTmp >>= 2; uiTmp2 >>= 2;
+  memcpy( rpcCU->getCoeffCb() + uiTmp2, m_pcTrCoeffCb, sizeof(TCoeff)*uiTmp  );
+  memcpy( rpcCU->getCoeffCr() + uiTmp2, m_pcTrCoeffCr, sizeof(TCoeff)*uiTmp  );
+  rpcCU->setSliceStartCU( m_uiSliceStartCU );
+  rpcCU->setEntropySliceStartCU( m_uiEntropySliceStartCU );
+
+#if HHI_DMM_WEDGE_INTRA
+  memcpy( rpcCU->getWedgeFullTabIdx()  + uiPartOffset, m_puiWedgeFullTabIdx,  iSizeInUInt   );
+  memcpy( rpcCU->getWedgeFullDeltaDC1()      + uiPartOffset, m_piWedgeFullDeltaDC1,       iSizeInInt  );
+  memcpy( rpcCU->getWedgeFullDeltaDC2()      + uiPartOffset, m_piWedgeFullDeltaDC2,       iSizeInInt  );
+
+  memcpy( rpcCU->getWedgePredDirTabIdx()     + uiPartOffset, m_puiWedgePredDirTabIdx,    iSizeInUInt );
+  memcpy( rpcCU->getWedgePredDirDeltaDC1()   + uiPartOffset, m_piWedgePredDirDeltaDC1,   iSizeInInt  );
+  memcpy( rpcCU->getWedgePredDirDeltaDC2()   + uiPartOffset, m_piWedgePredDirDeltaDC2,   iSizeInInt  );
+  memcpy( rpcCU->getWedgePredDirDeltaEnd()   + uiPartOffset, m_piWedgePredDirDeltaEnd,   iSizeInInt  );
+#endif
+#if HHI_DMM_PRED_TEX
+  memcpy( rpcCU->getWedgePredTexTabIdx()     + uiPartOffset, m_puiWedgePredTexTabIdx,     iSizeInUInt );
+  memcpy( rpcCU->getWedgePredTexDeltaDC1()   + uiPartOffset, m_piWedgePredTexDeltaDC1,    iSizeInInt  );
+  memcpy( rpcCU->getWedgePredTexDeltaDC2()   + uiPartOffset, m_piWedgePredTexDeltaDC2,    iSizeInInt  );
+
+  memcpy( rpcCU->getContourPredTexDeltaDC1() + uiPartOffset, m_piContourPredTexDeltaDC1,  iSizeInInt  );
+  memcpy( rpcCU->getContourPredTexDeltaDC2() + uiPartOffset, m_piContourPredTexDeltaDC2,  iSizeInInt  );
+#endif
+
+#if HHI_MPI
+  memcpy( rpcCU->getTextureModeDepth() + uiPartOffset, m_piTextureModeDepth, iSizeInInt );
+#endif
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Other public functions
+// --------------------------------------------------------------------------------------------------------------------
+
+TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( uiAbsPartIdx % uiNumPartInCUWidth )
+  {
+    uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( uiAbsPartIdx % uiNumPartInCUWidth == uiAbsZorderCUIdx % uiNumPartInCUWidth )
+    {
+      return m_pcPic->getCU( getAddr() );
+    }
+    else
+    {
+      uiLPartUnitIdx -= m_uiAbsIdxInLCU;
+      return this;
+    }
+  }
+  
+  uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + uiNumPartInCUWidth - 1 ];
+  if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getAddr() < m_uiSliceStartCU)) ||
+       (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getAddr() < m_uiEntropySliceStartCU)) )
+  {
+    return NULL;
+  }
+  return m_pcCULeft;
+}
+
+TComDataCU* TComDataCU::getPUAbove( UInt& uiAPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( uiAbsPartIdx / uiNumPartInCUWidth )
+  {
+    uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - uiNumPartInCUWidth ];
+    if ( uiAbsPartIdx / uiNumPartInCUWidth == uiAbsZorderCUIdx / uiNumPartInCUWidth )
+    {
+      return m_pcPic->getCU( getAddr() );
+    }
+    else
+    {
+      uiAPartUnitIdx -= m_uiAbsIdxInLCU;
+      return this;
+    }
+  }
+  
+  uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+  if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getAddr() < m_uiSliceStartCU)) ||
+       (bEnforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getAddr() < m_uiEntropySliceStartCU)) )
+  {
+    return NULL;
+  }
+  return m_pcCUAbove;
+}
+
+TComDataCU* TComDataCU::getPUAboveLeft( UInt& uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( uiAbsPartIdx % uiNumPartInCUWidth )
+  {
+    if( uiAbsPartIdx / uiNumPartInCUWidth )
+    {
+      uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - uiNumPartInCUWidth - 1 ];
+      if ( ( uiAbsPartIdx % uiNumPartInCUWidth == uiAbsZorderCUIdx % uiNumPartInCUWidth ) || ( uiAbsPartIdx / uiNumPartInCUWidth == uiAbsZorderCUIdx / uiNumPartInCUWidth ) )
+      {
+        return m_pcPic->getCU( getAddr() );
+      }
+      else
+      {
+        uiALPartUnitIdx -= m_uiAbsIdxInLCU;
+        return this;
+      }
+    }
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + getPic()->getNumPartInCU() - uiNumPartInCUWidth - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getAddr() < m_uiSliceStartCU)) ||
+         (bEnforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getAddr() < m_uiEntropySliceStartCU)) )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if( uiAbsPartIdx / uiNumPartInCUWidth )
+  {
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getAddr() < m_uiSliceStartCU)) ||
+         (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getAddr() < m_uiEntropySliceStartCU)) )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiALPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - 1 ];
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveLeft==NULL || m_pcCUAboveLeft->getSlice()==NULL || m_pcCUAboveLeft->getAddr() < m_uiSliceStartCU)) ||
+       (bEnforceEntropySliceRestriction && (m_pcCUAboveLeft==NULL || m_pcCUAboveLeft->getSlice()==NULL|| m_pcCUAboveLeft->getAddr() < m_uiEntropySliceStartCU)) )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveLeft;
+}
+
+TComDataCU* TComDataCU::getPUAboveRight( UInt& uiARPartUnitIdx, UInt uiCurrPartUnitIdx, 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->getMinCUWidth() ) >= m_pcSlice->getSPS()->getWidth() )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( uiAbsPartIdxRT % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )
+  {
+    if ( uiAbsPartIdxRT / uiNumPartInCUWidth )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ] )
+      {
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ];
+        if ( ( uiAbsPartIdxRT % uiNumPartInCUWidth == uiAbsZorderCUIdx % uiNumPartInCUWidth ) || ( uiAbsPartIdxRT / uiNumPartInCUWidth == uiAbsZorderCUIdx / uiNumPartInCUWidth ) )
+        {
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getAddr() < m_uiSliceStartCU)) ||
+         (bEnforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getAddr() < m_uiEntropySliceStartCU)) )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( uiAbsPartIdxRT / uiNumPartInCUWidth )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL || m_pcCUAboveRight->getAddr() < m_uiSliceStartCU)) ||
+       (bEnforceEntropySliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL || m_pcCUAboveRight->getAddr() < m_uiEntropySliceStartCU)) )
+  {
+    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()->getHeight() )
+  {
+    uiBLPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( uiAbsPartIdxLB / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 )
+  {
+    if ( uiAbsPartIdxLB % uiNumPartInCUWidth )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ] )
+      {
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ];
+        if ( ( (uiAbsPartIdxLB % uiNumPartInCUWidth) == (uiAbsZorderCUIdxLB % uiNumPartInCUWidth) ) || ( (uiAbsPartIdxLB / uiNumPartInCUWidth) == (uiAbsZorderCUIdxLB / uiNumPartInCUWidth) ) )
+        {
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+          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->getAddr() < m_uiSliceStartCU)) ||
+         (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getAddr() < m_uiEntropySliceStartCU)) )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiBLPartUnitIdx = MAX_UINT;
+  return NULL;
+}
+
+#if CONSTRAINED_INTRA_PRED
+TComDataCU* TComDataCU::getPUBelowLeftAdi(UInt& uiBLPartUnitIdx, UInt uiPuHeight,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+#else //CONSTRAINED_INTRA_PRED
+TComDataCU* TComDataCU::getPUBelowLeftAdi(UInt& uiBLPartUnitIdx, UInt uiPuHeight,  UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+#endif //CONSTRAINED_INTRA_PRED
+{
+  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] + uiPuHeight ) >= m_pcSlice->getSPS()->getHeight() )
+  {
+    uiBLPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+#if CONSTRAINED_INTRA_PRED
+  if ( uiAbsPartIdxLB / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - uiPartUnitOffset )
+#else
+  if ( uiAbsPartIdxLB / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 )
+#endif
+  {
+    if ( uiAbsPartIdxLB % uiNumPartInCUWidth )
+    {
+#if CONSTRAINED_INTRA_PRED
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * uiNumPartInCUWidth - 1 ] )
+#else
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ] )
+#endif
+      {
+#if CONSTRAINED_INTRA_PRED
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * uiNumPartInCUWidth - 1 ];
+#else
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ];
+#endif
+        if ( ( (uiAbsPartIdxLB % uiNumPartInCUWidth) == (uiAbsZorderCUIdxLB % uiNumPartInCUWidth) ) || ( (uiAbsPartIdxLB / uiNumPartInCUWidth) == (uiAbsZorderCUIdxLB / uiNumPartInCUWidth) ) )
+        {
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+          return this;
+        }
+      }
+      uiBLPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+#if CONSTRAINED_INTRA_PRED
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + (1+uiPartUnitOffset) * uiNumPartInCUWidth - 1 ];
+#else
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth*2 - 1 ];
+#endif
+    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getAddr() < m_uiSliceStartCU)) ||
+         (bEnforceEntropySliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getAddr() < m_uiEntropySliceStartCU)) )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiBLPartUnitIdx = MAX_UINT;
+  return NULL;
+}
+
+#if CONSTRAINED_INTRA_PRED
+TComDataCU* TComDataCU::getPUAboveRightAdi(UInt&  uiARPartUnitIdx, UInt uiPuWidth, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+#else //CONSTRAINED_INTRA_PRED
+TComDataCU* TComDataCU::getPUAboveRightAdi(UInt&  uiARPartUnitIdx, UInt uiPuWidth, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction, Bool bEnforceEntropySliceRestriction )
+#endif //CONSTRAINED_INTRA_PRED
+{
+  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] + uiPuWidth ) >= m_pcSlice->getSPS()->getWidth() )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+#if CONSTRAINED_INTRA_PRED
+  if ( uiAbsPartIdxRT % uiNumPartInCUWidth < uiNumPartInCUWidth - uiPartUnitOffset )
+#else
+  if ( uiAbsPartIdxRT % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )
+#endif
+  {
+    if ( uiAbsPartIdxRT / uiNumPartInCUWidth )
+    {
+#if CONSTRAINED_INTRA_PRED
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + uiPartUnitOffset ] )
+#else
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ] )
+#endif
+      {
+#if CONSTRAINED_INTRA_PRED
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + uiPartUnitOffset ];
+#else
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ];
+#endif
+        if ( ( uiAbsPartIdxRT % uiNumPartInCUWidth == uiAbsZorderCUIdx % uiNumPartInCUWidth ) || ( uiAbsPartIdxRT / uiNumPartInCUWidth == uiAbsZorderCUIdx / uiNumPartInCUWidth ) )
+        {
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+#if CONSTRAINED_INTRA_PRED
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + uiPartUnitOffset ];
+#else
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + 1 ];
+#endif
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getAddr() < m_uiSliceStartCU)) ||
+         (bEnforceEntropySliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getAddr() < m_uiEntropySliceStartCU)) )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( uiAbsPartIdxRT / uiNumPartInCUWidth )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+#if CONSTRAINED_INTRA_PRED
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + uiPartUnitOffset-1 ];
+#else
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+#endif
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL || m_pcCUAboveRight->getAddr() < m_uiSliceStartCU)) ||
+       (bEnforceEntropySliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL || m_pcCUAboveRight->getAddr() < m_uiEntropySliceStartCU)) )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveRight;
+}
+
+#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;
+  }
+}
+
+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_INTER_VIEW_MOTION_PRED
+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 );
+}
+
+
+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 HHI_INTER_VIEW_RESIDUAL_PRED
+Bool
+TComDataCU::getResidualSamples( UInt uiPartIdx, TComYuv* pcYuv )
+{
+  TComResidualGenerator*  pcResidualGenerator = m_pcSlice->getSPS()->getResidualGenerator();
+  ROFRS( pcResidualGenerator, false );
+  return pcResidualGenerator->getResidualSamples( this, uiPartIdx, pcYuv );
+}
+#endif
+
+
+Int TComDataCU::getMostProbableIntraDirLuma( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  Int         iLeftIntraDir, iAboveIntraDir, iMostProbable;
+  
+  // Get intra direction of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, false );
+  iLeftIntraDir  = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : 2 ) : NOT_VALID;
+#if ADD_PLANAR_MODE
+  mapPlanartoDC( iLeftIntraDir );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  mapDMMtoDC( iLeftIntraDir );
+#endif
+  
+  // Get intra direction of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, false );
+  iAboveIntraDir = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : 2 ) : NOT_VALID;
+#if ADD_PLANAR_MODE
+  mapPlanartoDC( iAboveIntraDir );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  mapDMMtoDC( iAboveIntraDir );
+#endif
+  
+  iMostProbable  = Min( iLeftIntraDir, iAboveIntraDir );
+  
+  // Mode conversion process for blocks with different number of available prediction directions
+  Int iIdx  = getIntraSizeIdx(uiAbsPartIdx);
+  
+  if ( iMostProbable >= g_aucIntraModeNumAng[iIdx] )
+  {
+    if ( g_aucIntraModeNumAng[iIdx] == 5 )
+      iMostProbable = g_aucAngModeMapping[0][g_aucAngIntraModeOrder[iMostProbable]];
+    if ( g_aucIntraModeNumAng[iIdx] == 3 )
+      iMostProbable = g_aucAngModeMapping[3][g_aucAngIntraModeOrder[iMostProbable]];
+    else
+      iMostProbable = g_aucAngModeMapping[1][g_aucAngIntraModeOrder[iMostProbable]]; 
+  } 
+  
+  return ( NOT_VALID == iMostProbable ) ? 2 : iMostProbable;
+}
+#if MTK_DCM_MPM
+Int TComDataCU::getIntraDirLumaPredictor( UInt uiAbsPartIdx, Int uiIntraDirPred[] )
+{
+  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 ) : 2 ) : 2;
+#if ADD_PLANAR_MODE
+  mapPlanartoDC( iLeftIntraDir );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  mapDMMtoDC( iLeftIntraDir );
+#endif
+
+  // Get intra direction of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  iAboveIntraDir = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : 2 ) : 2;
+#if ADD_PLANAR_MODE
+  mapPlanartoDC( iAboveIntraDir );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  mapDMMtoDC( iAboveIntraDir );
+#endif
+
+  Int iIdx  = getIntraSizeIdx(uiAbsPartIdx);
+
+  if ( iLeftIntraDir >= g_aucIntraModeNumAng[iIdx] ) 
+  {
+   if ( g_aucIntraModeNumAng[iIdx] == 5 )
+   {
+      iLeftIntraDir = g_aucAngModeMapping[0][g_aucAngIntraModeOrder[iLeftIntraDir]];
+   }
+   if ( g_aucIntraModeNumAng[iIdx] == 3 )
+   {
+      iLeftIntraDir = g_aucAngModeMapping[3][g_aucAngIntraModeOrder[iLeftIntraDir]];
+   }
+   else
+   {
+      iLeftIntraDir = g_aucAngModeMapping[1][g_aucAngIntraModeOrder[iLeftIntraDir]]; 
+   }
+  }
+   
+   
+ if ( iAboveIntraDir >= g_aucIntraModeNumAng[iIdx] ) 
+ {
+   if ( g_aucIntraModeNumAng[iIdx] == 5 )
+   {
+      iAboveIntraDir = g_aucAngModeMapping[0][g_aucAngIntraModeOrder[iAboveIntraDir]];
+   }
+   if ( g_aucIntraModeNumAng[iIdx] == 3 )
+   {
+      iAboveIntraDir = g_aucAngModeMapping[3][g_aucAngIntraModeOrder[iAboveIntraDir]];
+   }
+   else
+   {
+      iAboveIntraDir = g_aucAngModeMapping[1][g_aucAngIntraModeOrder[iAboveIntraDir]]; 
+   }
+ }
+   
+ if(iLeftIntraDir == iAboveIntraDir)
+ {
+   uiPredNum = 1;
+   uiIntraDirPred[0] = iLeftIntraDir ;
+ }
+ else
+ {
+   uiPredNum = 2;
+   uiIntraDirPred[0] = Min(iLeftIntraDir, iAboveIntraDir);
+   uiIntraDirPred[1] = Max(iLeftIntraDir, iAboveIntraDir);
+ }
+
+
+  return uiPredNum;
+}
+#endif
+#if LCEC_INTRA_MODE
+Int TComDataCU::getLeftIntraDirLuma( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  Int         iLeftIntraDir;
+
+  // Get intra direction of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  iLeftIntraDir  = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : 2 ) : NOT_VALID;
+#if ADD_PLANAR_MODE
+  mapPlanartoDC( iLeftIntraDir );
+#endif
+
+  return iLeftIntraDir;
+}
+
+Int TComDataCU::getAboveIntraDirLuma( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  Int         iAboveIntraDir;
+
+  // Get intra direction of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  iAboveIntraDir = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : 2 ) : NOT_VALID;
+#if ADD_PLANAR_MODE
+  mapPlanartoDC( iAboveIntraDir );
+#endif
+
+  return iAboveIntraDir;
+}
+#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::getCtxIntraDirChroma( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx;
+  
+  // Get intra direction of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#if CHROMA_CODEWORD
+  uiCtx  = ( pcTempCU ) ? ( ( pcTempCU->isIntra( uiTempPartIdx ) && pcTempCU->getChromaIntraDir( uiTempPartIdx ) == 4 ) ? 1 : 0 ) : 0;
+#else
+  uiCtx  = ( pcTempCU ) ? ( ( pcTempCU->isIntra( uiTempPartIdx ) && pcTempCU->getChromaIntraDir( uiTempPartIdx ) > 0 ) ? 1 : 0 ) : 0;
+#endif
+  
+  // Get intra direction of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+#if CHROMA_CODEWORD
+  uiCtx += ( pcTempCU ) ? ( ( pcTempCU->isIntra( uiTempPartIdx ) && pcTempCU->getChromaIntraDir( uiTempPartIdx ) == 4 ) ? 1 : 0 ) : 0;
+#else
+  uiCtx += ( pcTempCU ) ? ( ( pcTempCU->isIntra( uiTempPartIdx ) && pcTempCU->getChromaIntraDir( uiTempPartIdx ) > 0 ) ? 1 : 0 ) : 0;
+#endif
+  
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxCbf( UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx, uiTempTrDepth;
+  UInt        uiErrRet = !isIntra(uiAbsPartIdx) ? 0 : 1;
+  UInt        uiCtx = 0;
+  
+  // Get Cbf of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  if ( pcTempCU )
+  {
+    uiTempTrDepth = pcTempCU->getTransformIdx( uiTempPartIdx );
+    uiCtx = pcTempCU->getCbf( uiTempPartIdx, eType, uiTempTrDepth < uiTrDepth ? uiTempTrDepth : uiTrDepth );
+  }
+  else
+  {
+    uiCtx = uiErrRet;
+  }
+  
+  // Get Cbf of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  if ( pcTempCU )
+  {
+    uiTempTrDepth = pcTempCU->getTransformIdx( uiTempPartIdx );
+    uiCtx += pcTempCU->getCbf( uiTempPartIdx, eType, uiTempTrDepth < uiTrDepth ? uiTempTrDepth : uiTrDepth ) << 1;
+  }
+  else
+  {
+    uiCtx += uiErrRet << 1;
+  }
+  
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxQtCbf( UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  if( getPredictionMode( uiAbsPartIdx ) != MODE_INTRA && eType != TEXT_LUMA )
+  {
+    return uiTrDepth;
+  }
+  UInt uiCtx = 0;
+  const UInt uiDepth = getDepth( uiAbsPartIdx );
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth - uiTrDepth;
+  
+  if( uiTrDepth == 0 || uiLog2TrafoSize == getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    TComDataCU* pcTempCU;
+    UInt        uiTempPartIdx, uiTempTrDepth;
+    
+    // Get Cbf of left PU
+    pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+    if ( pcTempCU )
+    {
+      uiTempTrDepth = pcTempCU->getTransformIdx( uiTempPartIdx );
+      uiCtx = pcTempCU->getCbf( uiTempPartIdx, eType, uiTempTrDepth );
+    }
+    
+    // Get Cbf of above PU
+    pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+    if ( pcTempCU )
+    {
+      uiTempTrDepth = pcTempCU->getTransformIdx( uiTempPartIdx );
+      uiCtx += pcTempCU->getCbf( uiTempPartIdx, eType, uiTempTrDepth ) << 1;
+    }
+    uiCtx++;
+  }
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxQtRootCbf( UInt uiAbsPartIdx )
+{
+  UInt uiCtx = 0;
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  
+  // Get RootCbf of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  if ( pcTempCU )
+  {
+    uiCtx = pcTempCU->getQtRootCbf( uiTempPartIdx );
+  }
+  
+  // Get RootCbf of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  if ( pcTempCU )
+  {
+    uiCtx += pcTempCU->getQtRootCbf( uiTempPartIdx ) << 1;
+  }
+  
+  return uiCtx;
+}
+
+UInt TComDataCU::getQuadtreeTULog2MinSizeInCU( UInt uiIdx )
+{
+#if HHI_RQT_DISABLE_SUB
+  return getQuadtreeTULog2RootSizeInCU(uiIdx);
+#else
+#if HHI_RQT_FORCE_SPLIT_ACC2_PU
+  UInt uiLog2MinTUSizeInCU = getQuadtreeTULog2RootSizeInCU(uiIdx);
+#else
+  UInt uiLog2MinTUSizeInCU = g_aucConvertToBit[getWidth( uiIdx )] + 2;
+  
+  if ( getPredictionMode( uiIdx ) == MODE_INTRA && getPartitionSize( uiIdx ) == SIZE_NxN )
+  {
+    uiLog2MinTUSizeInCU--;
+  }
+#endif  
+  
+  UInt uiQuadtreeTUMaxDepth = getPredictionMode( uiIdx ) == MODE_INTRA ? m_pcSlice->getSPS()->getQuadtreeTUMaxDepthIntra() : m_pcSlice->getSPS()->getQuadtreeTUMaxDepthInter();
+  if (uiLog2MinTUSizeInCU < m_pcSlice->getSPS()->getQuadtreeTULog2MinSize() + uiQuadtreeTUMaxDepth - 1)
+  {
+    uiLog2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MinSize();  
+  }
+  else
+  {
+    uiLog2MinTUSizeInCU -= uiQuadtreeTUMaxDepth - 1;  
+  }
+  
+  if ( uiLog2MinTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize())
+  {
+    uiLog2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize();
+  }  
+  return uiLog2MinTUSizeInCU;
+#endif
+}
+
+#if HHI_RQT_FORCE_SPLIT_ACC2_PU || HHI_RQT_DISABLE_SUB
+UInt TComDataCU::getQuadtreeTULog2RootSizeInCU( UInt uiIdx )
+{
+  UInt uiLog2RootTUSizeInCU = g_aucConvertToBit[getWidth( uiIdx )] +2;
+  
+#if !HHI_RQT_FORCE_SPLIT_NxN && !HHI_RQT_DISABLE_SUB
+  if ( getPredictionMode( uiIdx ) == MODE_INTRA && getPartitionSize( uiIdx ) == SIZE_NxN )
+  {
+    uiLog2RootTUSizeInCU--;
+    return (uiLog2RootTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() ? m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() : uiLog2RootTUSizeInCU);
+  }
+#endif
+  
+  if (m_pePartSize[ uiIdx ] == SIZE_2Nx2N)
+  {
+    return (uiLog2RootTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() ? m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() : uiLog2RootTUSizeInCU);
+  }
+  else if (m_pePartSize[ uiIdx ] >= SIZE_2NxN && m_pePartSize[ uiIdx ] <= SIZE_Nx2N)  
+  {
+#if HHI_RQT_FORCE_SPLIT_RECT || HHI_RQT_DISABLE_SUB
+    uiLog2RootTUSizeInCU--;
+#endif
+    return (uiLog2RootTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() ? m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() : uiLog2RootTUSizeInCU);
+  }
+  else if (m_pePartSize[ uiIdx ] == SIZE_NxN)  
+  {
+#if HHI_RQT_FORCE_SPLIT_NxN || HHI_RQT_DISABLE_SUB
+    uiLog2RootTUSizeInCU--;
+#endif
+    return (uiLog2RootTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() ? m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() : uiLog2RootTUSizeInCU);
+  }
+  
+  return (uiLog2RootTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() ? m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize() : uiLog2RootTUSizeInCU);
+}
+#endif
+
+UInt TComDataCU::getCtxAlfCtrlFlag( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  // Get BCBP of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx    = ( pcTempCU ) ? pcTempCU->getAlfCtrlFlag( uiTempPartIdx ) : 0;
+  
+  // Get BCBP of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx   += ( pcTempCU ) ? pcTempCU->getAlfCtrlFlag( uiTempPartIdx ) : 0;
+  
+  return uiCtx;
+}
+
+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;
+}
+
+/** CABAC context derivation for merge flag
+ * \param uiAbsPartIdx
+ * \returns context offset
+ */
+UInt TComDataCU::getCtxMergeFlag( UInt uiAbsPartIdx )
+{
+  UInt uiCtx = 0;
+#if CHANGE_MERGE_CONTEXT
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+
+  // Get BCBP of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx    = ( pcTempCU ) ? pcTempCU->getMergeFlag( uiTempPartIdx ) : 0;
+
+  // Get BCBP of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx   += ( pcTempCU ) ? pcTempCU->getMergeFlag( uiTempPartIdx ) : 0;
+#endif
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxInterDir( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  // Get BCBP of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx += ( pcTempCU ) ? ( ( pcTempCU->getInterDir( uiTempPartIdx ) % 3 ) ? 0 : 1 ) : 0;
+  
+  // Get BCBP of Above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx += ( pcTempCU ) ? ( ( pcTempCU->getInterDir( uiTempPartIdx ) % 3 ) ? 0 : 1 ) : 0;
+  
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxRefIdx( UInt uiAbsPartIdx, RefPicList eRefPicList )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  TComMvField cMvFieldTemp;
+  UInt        uiCtx = 0;
+  
+  // Get BCBP of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  getMvField( pcTempCU, uiTempPartIdx, eRefPicList, cMvFieldTemp );
+  uiCtx += cMvFieldTemp.getRefIdx() > 0 ? 1 : 0;
+  
+  // Get BCBP of Above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  getMvField( pcTempCU, uiTempPartIdx, eRefPicList, cMvFieldTemp );
+  uiCtx += cMvFieldTemp.getRefIdx() > 0 ? 2 : 0;
+  
+  return uiCtx;
+}
+
+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 );
+}
+
+#if HHI_MRG_SKIP
+/** 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 )
+{
+  setSubPartUChar( uiCbf, m_puhCbf[g_aucConvertTxtTypeToIdx[eTType]], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+#endif
+
+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         ( UInt uiFlag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  for (UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_puiAlfCtrlFlag[uiAbsPartIdx + ui] = uiFlag;
+  }
+}
+
+Void TComDataCU::createTmpAlfCtrlFlag()
+{
+  m_puiTmpAlfCtrlFlag = (UInt* )xMalloc(UInt, m_uiNumPartition);
+}
+
+Void TComDataCU::destroyTmpAlfCtrlFlag()
+{
+  if(m_puiTmpAlfCtrlFlag)
+  {
+    xFree(m_puiTmpAlfCtrlFlag);        m_puiTmpAlfCtrlFlag = NULL;
+  }
+}
+
+Void TComDataCU::copyAlfCtrlFlagToTmp()
+{
+  memcpy( m_puiTmpAlfCtrlFlag, m_puiAlfCtrlFlag, sizeof(UInt)*m_uiNumPartition );
+}
+
+Void TComDataCU::copyAlfCtrlFlagFromTmp()
+{
+  memcpy( m_puiAlfCtrlFlag, m_puiTmpAlfCtrlFlag, sizeof(UInt)*m_uiNumPartition );
+}
+
+Void TComDataCU::setPartSizeSubParts( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  for (UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_pePartSize[uiAbsPartIdx + ui] = eMode;
+  }
+}
+
+Void TComDataCU::setPredModeSubParts( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  for (UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_pePredMode[uiAbsPartIdx + ui] = eMode;
+  }
+}
+
+Void TComDataCU::setQPSubParts( UInt uiQP, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_phQP + uiAbsPartIdx, uiQP, sizeof(Char)*uiCurrPartNumb );
+}
+
+Void TComDataCU::setLumaIntraDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhLumaIntraDir + uiAbsPartIdx, uiDir, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Void TComDataCU::setSubPartUChar( UInt uiParameter, UChar* puhBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx )
+{
+  UInt uiCurrPartNumQ = (m_pcPic->getNumPartInCU() >> (uiCUDepth << 1)) >> 2;
+  switch ( m_pePartSize[ uiCUAddr ] )
+  {
+  case SIZE_2Nx2N:
+    memset( puhBaseLCU + uiCUAddr, uiParameter, sizeof(UChar)*uiCurrPartNumQ << 2 );                      break;
+  case SIZE_2NxN:
+    memset( puhBaseLCU + uiCUAddr, uiParameter, sizeof(UChar)*uiCurrPartNumQ << 1 );                      break;
+  case SIZE_Nx2N:
+    memset( puhBaseLCU + uiCUAddr, uiParameter, sizeof(UChar)*uiCurrPartNumQ );
+    memset( puhBaseLCU + uiCUAddr + ( uiCurrPartNumQ << 1 ), uiParameter, sizeof(UChar)*uiCurrPartNumQ ); break;
+  case SIZE_NxN:
+    memset( puhBaseLCU + uiCUAddr, uiParameter, sizeof(UChar)*uiCurrPartNumQ );                           break;
+  default:
+    assert( 0 );
+  }
+}
+
+Void TComDataCU::setSubPartBool( Bool bParameter, Bool* pbBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx )
+{
+  UInt uiQuaterCUPartNum = (m_pcPic->getNumPartInCU() >> (uiCUDepth << 1)) >> 2;
+  switch ( m_pePartSize[ uiCUAddr ] )
+  {
+  case SIZE_2Nx2N:
+    memset( pbBaseLCU + uiCUAddr, bParameter, sizeof(Bool)*uiQuaterCUPartNum << 2 );                      break;
+  case SIZE_2NxN:
+    memset( pbBaseLCU + uiCUAddr, bParameter, sizeof(Bool)*uiQuaterCUPartNum << 1 );                      break;
+  case SIZE_Nx2N:
+    memset( pbBaseLCU + uiCUAddr, bParameter, sizeof(Bool)*uiQuaterCUPartNum );
+    memset( pbBaseLCU + uiCUAddr + ( uiQuaterCUPartNum << 1 ), bParameter, sizeof(Bool)*uiQuaterCUPartNum ); break;
+  case SIZE_NxN:
+    memset( pbBaseLCU + uiCUAddr, bParameter, sizeof(Bool)*uiQuaterCUPartNum );                           break;
+  default:
+    assert( 0 );
+  }
+}
+
+Void TComDataCU::setMergeFlagSubParts ( Bool bMergeFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPartBool( bMergeFlag, m_pbMergeFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPartUChar( uiMergeIndex, m_puhMergeIndex, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+Void TComDataCU::setResPredAvailSubParts( Bool bResPredAvailable, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPartBool( bResPredAvailable, m_pbResPredAvailable, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setResPredFlagSubParts( Bool bResPredFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPartBool( 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 )
+{
+  setSubPartUChar( uiDir, m_puhInterDir, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setMVPIdxSubParts( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumQ = m_pcPic->getNumPartInCU() >> (uiDepth << 1) >> 2;
+  UInt i;
+  Int* pi;
+  switch ( m_pePartSize[ uiAbsPartIdx ] )
+  {
+    case SIZE_2Nx2N:
+    {
+      pi = m_apiMVPIdx[eRefPicList] + uiAbsPartIdx;
+      for (i = 0; i < (uiCurrPartNumQ << 2); i++)
+      {
+        pi[i] = iMVPIdx;
+      }
+    }
+      break;
+    case SIZE_2NxN:
+    {
+      pi = m_apiMVPIdx[eRefPicList] + uiAbsPartIdx;
+      for (i = 0; i < (uiCurrPartNumQ << 1); i++)
+      {
+        pi[i] = iMVPIdx;
+      }
+    }
+      break;
+    case SIZE_Nx2N:
+    {
+      Int* pi2 = m_apiMVPIdx[eRefPicList] + uiAbsPartIdx + ( uiCurrPartNumQ << 1 );
+      pi = m_apiMVPIdx[eRefPicList] + uiAbsPartIdx;
+      for (i = 0; i < uiCurrPartNumQ; i++)
+      {
+        pi [i] = iMVPIdx;
+        pi2[i] = iMVPIdx;
+      }
+      break;
+    }
+    case SIZE_NxN:
+    {
+      pi = m_apiMVPIdx[eRefPicList] + uiAbsPartIdx;
+      for (i = 0; i < uiCurrPartNumQ; i++)
+      {
+        pi[i] = iMVPIdx;
+      }
+      break;
+    }
+    default:
+      assert( 0 );
+  }
+}
+
+Void TComDataCU::setMVPNumSubParts( Int iMVPNum, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumQ = m_pcPic->getNumPartInCU() >> (uiDepth << 1) >> 2;
+  UInt i;
+  Int* pi;
+  switch ( m_pePartSize[ uiAbsPartIdx ] )
+  {
+    case SIZE_2Nx2N:
+    {
+      pi = m_apiMVPNum[eRefPicList] + uiAbsPartIdx;
+      for (i = 0; i < (uiCurrPartNumQ << 2); i++)
+      {
+        pi[i] = iMVPNum;
+      }
+    }
+      break;
+    case SIZE_2NxN:
+    {
+      pi = m_apiMVPNum[eRefPicList] + uiAbsPartIdx;
+      for (i = 0; i < (uiCurrPartNumQ << 1); i++)
+      {
+        pi[i] = iMVPNum;
+      }
+    }
+      break;
+    case SIZE_Nx2N:
+    {
+      pi = m_apiMVPNum[eRefPicList] + uiAbsPartIdx;
+      for (i = 0; i < uiCurrPartNumQ; i++)
+      {
+        pi[i] = iMVPNum;
+      }
+      pi = m_apiMVPNum[eRefPicList] + uiAbsPartIdx + ( uiCurrPartNumQ << 1 );
+      for (i = 0; i < uiCurrPartNumQ; i++)
+      {
+        pi[i] = iMVPNum;
+      }
+    }
+      break;
+    case SIZE_NxN:
+    {
+      pi = m_apiMVPNum[eRefPicList] + uiAbsPartIdx;
+      for (i = 0; i < uiCurrPartNumQ; i++)
+      {
+        pi[i] = iMVPNum;
+      }
+    }
+      break;
+    default:
+      assert( 0 );
+  }
+}
+
+
+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::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;
+    default:            assert (0);   break;
+  }
+  
+  return  iNumPart;
+}
+
+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;
+    default:
+      assert ( m_pePartSize[0] == SIZE_2Nx2N );
+      riWidth = getWidth(0);      riHeight = getHeight(0);      ruiPartAddr = 0;
+      break;
+  }
+}
+
+
+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;
+    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;
+    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;
+    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;
+    default:
+      assert (0);
+      break;
+  }
+}
+
+#if MTK_TMVP_H_MRG || MTK_TMVP_H_AMVP
+/** Derives the partition index of neighbouring bottom right block
+ * \param in eCUMode
+ * \param in uiPartIdx 
+ * \param out ruiPartIdx 
+ * \returns Void
+ */
+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;
+    default:
+      assert (0);
+      break;
+  }
+}
+#endif
+
+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, UInt uiCandInterDir, Int* paiCandRefIdx, TComMv* pacCandMv )
+{
+  AOT  ( getInterDir( uiAbsPartIdx ) == 0 );
+  ROTRS( getInterDir( uiAbsPartIdx ) == uiCandInterDir, false );
+  for  ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+  {
+    if ( getInterDir( uiAbsPartIdx ) & ( 1 << uiRefListIdx ) )
+    {
+      if ( getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiAbsPartIdx ) != paiCandRefIdx[ uiRefListIdx ] ||
+           getCUMvField( RefPicList( uiRefListIdx ) )->getMv    ( uiAbsPartIdx ) != pacCandMv    [ uiRefListIdx ]    )
+      {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+Bool TComDataCU::hasEqualMotion( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx )
+{
+  assert( getInterDir( uiAbsPartIdx ) != 0 );
+
+  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;
+}
+
+Bool TComDataCU::avoidMergeCandidate( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, UInt uiCandInterDir, Int* paiCandRefIdx, TComMv* pacCandMv )
+{
+  // uiAbsPartIdx has to be the first index of the current PU
+  PartSize ePartSize = getPartitionSize( uiAbsPartIdx );
+
+  if ( ePartSize != SIZE_NxN && ePartSize != SIZE_2Nx2N )
+  {
+    // we have exactly 2 PUs. Avoid imitating 2Nx2N.
+    if ( uiPUIdx == 1 )
+    {
+      // we would merge the second PU
+      UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+      UInt uiAbsPartIdxOfFirstPU = uiAbsPartIdx - uiPUOffset;
+      if ( hasEqualMotion( uiAbsPartIdxOfFirstPU, uiCandInterDir, paiCandRefIdx, pacCandMv ) )
+      {
+        // don't merge
+        return true;
+      }
+    }
+  }
+  if ( ePartSize == SIZE_NxN )
+  {
+    if ( uiPUIdx == 3 )
+    {
+      UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+      UInt uiPUOffsetIdx0 = uiAbsPartIdx - 3*uiPUOffset;
+      UInt uiPUOffsetIdx1 = uiAbsPartIdx - 2*uiPUOffset;
+      UInt uiPUOffsetIdx2 = uiAbsPartIdx -   uiPUOffset;
+
+      // avoid imitating 2Nx2N and Nx2N partitioning.
+      if ( hasEqualMotion( uiPUOffsetIdx0, this, uiPUOffsetIdx2 ) &&
+           hasEqualMotion( uiPUOffsetIdx1, uiCandInterDir, paiCandRefIdx, pacCandMv ) )
+      {
+        // don't merge
+        return true;
+      }
+
+      // avoid imitating 2NxN partitioning.
+      if ( hasEqualMotion( uiPUOffsetIdx0, this, uiPUOffsetIdx1 ) &&
+           hasEqualMotion( uiPUOffsetIdx2, uiCandInterDir, paiCandRefIdx, pacCandMv ) )
+      {
+        // don't merge
+        return true;
+      }
+    }
+  }
+  return false;
+}
+
+Bool TComDataCU::avoidMergeCandidate( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx )
+{
+  // uiAbsPartIdx has to be the first index of the current PU
+
+  if ( !pcCandCU )
+  {
+    return true;
+  }
+
+  PartSize ePartSize = getPartitionSize( uiAbsPartIdx );
+
+  if ( ePartSize != SIZE_NxN && ePartSize != SIZE_2Nx2N )
+  {
+    // we have exactly 2 PUs. Avoid imitating 2Nx2N.
+    if ( uiPUIdx == 1 )
+    {
+      // we would merge the second PU
+      UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+      UInt uiAbsPartIdxOfFirstPU = uiAbsPartIdx - uiPUOffset;
+      if ( hasEqualMotion( uiAbsPartIdxOfFirstPU, pcCandCU, uiCandAbsPartIdx ) )
+      {
+        // don't merge
+        return true;
+      }
+    }
+  }
+  if ( ePartSize == SIZE_NxN )
+  {
+    if ( uiPUIdx == 3 )
+    {
+      UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+      UInt uiPUOffsetIdx0 = uiAbsPartIdx - 3*uiPUOffset;
+      UInt uiPUOffsetIdx1 = uiAbsPartIdx - 2*uiPUOffset;
+      UInt uiPUOffsetIdx2 = uiAbsPartIdx -   uiPUOffset;
+
+      // avoid imitating 2Nx2N and Nx2N partitioning.
+      if ( hasEqualMotion( uiPUOffsetIdx0, this, uiPUOffsetIdx2 ) &&
+           hasEqualMotion( uiPUOffsetIdx1, pcCandCU, uiCandAbsPartIdx ) )
+      {
+        // don't merge
+        return true;
+      }
+
+      // avoid imitating 2NxN partitioning.
+      if ( hasEqualMotion( uiPUOffsetIdx0, this, uiPUOffsetIdx1 ) &&
+           hasEqualMotion( uiPUOffsetIdx2, pcCandCU, uiCandAbsPartIdx ) )
+      {
+        // don't merge
+        return true;
+      }
+    }
+  }
+  return false;
+}
+
+/** Constructs a list of merging candidates
+ * \param uiAbsPartIdx
+ * \param uiPUIdx 
+ * \param uiDepth
+ * \param pcMvFieldNeighbours
+ * \param puhInterDirNeighbours
+ * \param puiNeighbourCandIdx
+ * \returns Void
+ */
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, UInt* puiNeighbourCandIdx )
+{
+  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiAbsPartIdx;
+#if HHI_INTER_VIEW_MOTION_PRED
+  Bool bNoPdmMerge   = ( m_pcSlice->getSPS()->getViewId() == 0 || ( m_pcSlice->getSPS()->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) != PDM_USE_FOR_MERGE );
+  UInt uiPdmMergePos = ( bNoPdmMerge ? 5 : PDM_MERGE_POS );
+  UInt uiLeftAddr    = ( uiPdmMergePos < 1 ? 1 : 0 );
+  UInt uiAboveAddr   = ( uiPdmMergePos < 2 ? 2 : 1 );
+  UInt uiColocAddr   = ( uiPdmMergePos < 3 ? 3 : 2 );
+  UInt uiCorRTAddr   = ( uiPdmMergePos < 4 ? 4 : 3 );
+  UInt uiCorBLAddr   = ( uiPdmMergePos < 5 ? 5 : 4 );
+  UInt uiPdmAddr     =   uiPdmMergePos;
+#else
+  UInt uiLeftAddr    = 0;
+  UInt uiAboveAddr   = 1;
+  UInt uiColocAddr   = 2;
+  UInt uiCorRTAddr   = 3;
+  UInt uiCorBLAddr   = 4;
+#endif
+  
+  bool abCandIsInter[ MRG_MAX_NUM_CANDS ];
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+  {
+    abCandIsInter[ui] = false;
+  }
+  
+  //===== left =====
+  UInt uiLeftPartIdx = 0;
+  TComDataCU* pcCULeft = 0;
+  pcCULeft  = getPULeft( uiLeftPartIdx, uiAbsPartAddr );
+  if( avoidMergeCandidate( uiAbsPartIdx, uiPUIdx, uiDepth, pcCULeft, uiLeftPartIdx ) )
+  {
+    pcCULeft = NULL;
+  }
+  if( pcCULeft && !pcCULeft->isIntra( uiLeftPartIdx ) )
+  {
+    abCandIsInter[uiLeftAddr] = true;
+    puiNeighbourCandIdx[uiLeftAddr] = uiLeftAddr+1;
+  }
+  if( abCandIsInter[uiLeftAddr] )
+  {
+    // get Inter Dir
+    puhInterDirNeighbours[uiLeftAddr] = pcCULeft->getInterDir( uiLeftPartIdx );
+    // get Mv from Left
+    pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[uiLeftAddr<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(uiLeftAddr<<1)+1] );
+    }
+  }
+
+
+  //===== top =====
+  UInt uiAbovePartIdx = 0;
+  TComDataCU* pcCUAbove = 0;
+  pcCUAbove = getPUAbove( uiAbovePartIdx, uiAbsPartAddr );
+  if( avoidMergeCandidate( uiAbsPartIdx, uiPUIdx, uiDepth, pcCUAbove, uiAbovePartIdx ) )
+  {
+    pcCUAbove = NULL;
+  }
+  if ( pcCUAbove && !pcCUAbove->isIntra( uiAbovePartIdx ) )
+  {
+    abCandIsInter[uiAboveAddr] = true;
+    puiNeighbourCandIdx[uiAboveAddr] = uiAboveAddr+1;
+  }
+  if ( abCandIsInter[uiAboveAddr] )
+  {
+    // get Inter Dir
+    puhInterDirNeighbours[uiAboveAddr] = pcCUAbove->getInterDir( uiAbovePartIdx );
+    // get Mv from Above
+    pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[uiAboveAddr<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(uiAboveAddr<<1)+1] );
+    }
+  }
+
+
+  //===== colocated =====
+#if MRG_NEIGH_COL
+#if PANASONIC_MRG_TMVP_REFIDX
+  Int iRefIdxSkip[2] = {-1, -1};
+  TComDataCU* pcTmpCU = NULL;
+  UInt uiIdxblk;
+  Int iRefIdxLeft[2] = {-1, -1};
+  Int iRefIdxAbove[2] = {-1, -1};
+  Int iRefIdxCor[2] = {-1, -1};
+
+  UInt uiPUIdxLT = 0;
+  UInt uiPUIdxRT  = 0;
+  UInt uiPUIdxLB = 0;
+  PartSize cCurPS = m_pePartSize[uiAbsPartIdx];
+  deriveLeftRightTopIdxGeneral( cCurPS, uiAbsPartIdx, uiPUIdx, uiPUIdxLT, uiPUIdxRT );
+  deriveLeftBottomIdxGeneral( cCurPS, uiAbsPartIdx, uiPUIdx, uiPUIdxLB );
+
+  for (int i=0; i<2; i++) 
+  {
+    RefPicList  eRefPicList = ( i==1 ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+  
+    pcTmpCU = getPULeft(uiIdxblk, uiPUIdxLT);
+    iRefIdxLeft[i] = (pcTmpCU != NULL) ? pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdxblk) : -1;
+    pcTmpCU = getPUAbove(uiIdxblk, uiPUIdxLT);
+    iRefIdxAbove[i] = (pcTmpCU != NULL) ? pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdxblk) : -1;
+    pcTmpCU = getPUAboveRight( uiIdxblk, uiPUIdxRT );
+    if (pcTmpCU == NULL) 
+    {
+      pcTmpCU = getPUBelowLeft( uiIdxblk, uiPUIdxLB );
+    }
+    if (pcTmpCU == NULL) 
+    {
+      pcTmpCU = getPUAboveLeft( uiIdxblk, uiPUIdxLT );
+    }
+    iRefIdxCor[i] = (pcTmpCU != NULL) ? pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdxblk) : -1;
+
+    if (iRefIdxLeft[i] == iRefIdxAbove[i] && iRefIdxAbove[i] == iRefIdxCor[i])
+    {
+      iRefIdxSkip[i] = (iRefIdxLeft[i] == -1) ? 0 : iRefIdxLeft[i];
+    }
+    else if (iRefIdxLeft[i] == iRefIdxAbove[i])
+    {
+      iRefIdxSkip[i] = (iRefIdxLeft[i] == -1) ? iRefIdxCor[i] : iRefIdxLeft[i];
+    }
+    else if (iRefIdxAbove[i] == iRefIdxCor[i])
+    {
+      iRefIdxSkip[i] = (iRefIdxAbove[i] == -1) ? iRefIdxLeft[i] : iRefIdxAbove[i];
+    }
+    else if (iRefIdxLeft[i] == iRefIdxCor[i])
+    {
+      iRefIdxSkip[i] = (iRefIdxLeft[i] == -1) ? iRefIdxAbove[i] : iRefIdxLeft[i];
+    }
+    else if (iRefIdxLeft[i] == -1)
+    {
+      iRefIdxSkip[i] = min(iRefIdxAbove[i], iRefIdxCor[i]);
+    }
+    else if (iRefIdxAbove[i] == -1)
+    {
+      iRefIdxSkip[i] = min(iRefIdxLeft[i], iRefIdxCor[i]);
+    }
+    else if (iRefIdxCor[i] == -1)
+    {
+      iRefIdxSkip[i] = min(iRefIdxLeft[i], iRefIdxAbove[i]);
+    }
+    else
+    {
+      iRefIdxSkip[i] = min( min(iRefIdxLeft[i], iRefIdxAbove[i]), iRefIdxCor[i]);
+    }
+  }
+#endif
+#if MTK_TMVP_H_MRG
+  //>> MTK colocated-RightBottom
+  UInt uiPartIdxRB;
+  Int uiLCUIdx = getAddr();
+  PartSize eCUMode = m_pePartSize[0];
+
+  deriveRightBottomIdx( eCUMode, uiPUIdx, uiPartIdxRB );  
+
+  UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+  TComMv cColMv;
+  Int iRefIdx;
+
+  if      ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getWidth() )  // image boundary check
+  {
+    uiLCUIdx = -1;
+  }
+  else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getHeight() )
+  {
+    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 = getAddr() + 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
+    {
+      uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+      uiLCUIdx = getAddr() + 1;
+    }
+    else //is the right bottom corner of LCU                       
+    {
+      uiAbsPartAddr = 0;
+      uiLCUIdx = getAddr() + m_pcPic->getFrameWidthInCU() + 1;
+    }
+  }
+#if PANASONIC_MRG_TMVP_REFIDX
+  iRefIdx = iRefIdxSkip[0];
+#else
+  iRefIdx = 0; // scaled to 1st ref pic for List0/List1
+#endif
+  
+#if FT_TCTR_MRG
+  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( bExistMV == false )
+  {
+    bExistMV = xGetColMVP( REF_PIC_LIST_0, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx );
+  }
+  if( bExistMV )
+#else
+  if (uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_0, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx ) )
+#endif
+  {
+    abCandIsInter[uiColocAddr] = true;
+#if PANASONIC_MRG_TMVP_REFIDX
+    pcMvFieldNeighbours[uiColocAddr << 1].setMvField( cColMv, iRefIdx );
+#else
+    pcMvFieldNeighbours[uiColocAddr << 1].setMvField( cColMv, 0 );
+#endif
+    puiNeighbourCandIdx[uiColocAddr] = uiColocAddr+1;
+
+    if ( getSlice()->isInterB() )
+    {       
+#if PANASONIC_MRG_TMVP_REFIDX
+      iRefIdx = iRefIdxSkip[1];
+#endif
+#if FT_TCTR_MRG
+      bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_1, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx);
+      if( bExistMV == false )
+      {
+        bExistMV = xGetColMVP( REF_PIC_LIST_1, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx );
+      }
+      if( bExistMV )
+#else
+      if (xGetColMVP( REF_PIC_LIST_1, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx) )
+#endif
+  {
+#if PANASONIC_MRG_TMVP_REFIDX
+        pcMvFieldNeighbours[ ( uiColocAddr << 1 ) + 1 ].setMvField( cColMv, iRefIdx );
+#else
+        pcMvFieldNeighbours[ ( uiColocAddr << 1 ) + 1 ].setMvField( cColMv, 0 );
+#endif
+        puhInterDirNeighbours[uiColocAddr] = 3;
+      }
+      else
+      {
+        puhInterDirNeighbours[uiColocAddr] = 1;
+      }
+    }
+    else
+    {
+      puhInterDirNeighbours[uiColocAddr] = 1;
+    }
+  }
+#else //MTK_TMVP_H_MRG
+#if FT_TCTR_MRG
+    TComMv cMvTCenter[2];
+#if PANASONIC_MRG_TMVP_REFIDX
+  Int iRefIdx = iRefIdxSkip[0];
+  if (xGetCenterCol( uiPUIdx, REF_PIC_LIST_0, iRefIdx, &cMvTCenter[0] ))
+#else
+    if (xGetCenterCol( uiPUIdx, REF_PIC_LIST_0, 0, &cMvTCenter[0] ))
+#endif
+    {
+      abCandIsInter[uiColocAddr] = true;
+#if PANASONIC_MRG_TMVP_REFIDX
+    pcMvFieldNeighbours[uiColocAddr << 1].setMvField( cMvTCenter[0], iRefIdx );
+#else
+      pcMvFieldNeighbours[uiColocAddr << 1].setMvField( cMvTCenter[0], 0 );
+#endif
+      puiNeighbourCandIdx[uiColocAddr] = uiIdx;
+
+      if ( getSlice()->isInterB() )
+      {       
+#if PANASONIC_MRG_TMVP_REFIDX
+      if ( xGetCenterCol( uiPUIdx, REF_PIC_LIST_1, iRefIdx, &cMvTCenter[1] ) )
+#else
+        if ( xGetCenterCol( uiPUIdx, REF_PIC_LIST_1, 0, &cMvTCenter[1] ) )
+#endif
+        {
+#if PANASONIC_MRG_TMVP_REFIDX
+        pcMvFieldNeighbours[ ( uiColocAddr << 1 ) + 1 ].setMvField( cMvTCenter[1], iRefIdx );
+#else
+          pcMvFieldNeighbours[ ( uiColocAddr << 1 ) + 1 ].setMvField( cMvTCenter[1], 0 );
+#endif
+          puhInterDirNeighbours[uiColocAddr] = 3;
+        }
+        else
+        {
+          puhInterDirNeighbours[uiColocAddr] = 1;
+        }
+      }
+      else
+      {
+        puhInterDirNeighbours[uiColocAddr] = 1;
+      }
+    }
+#else //FT_TCTR_MRG
+  UInt uiColDir = ( m_pcSlice->isInterB()? m_pcSlice->getColDir() : 0 );
+  TComDataCU* pcCUColocated = getCUColocated( RefPicList( uiColDir ) );
+  RefPicList eColRefPicList = ( m_pcSlice->isInterB()? RefPicList( 1-uiColDir ) : REF_PIC_LIST_0 );
+#if PANASONIC_MERGETEMPORALEXT
+  RefPicList eColRefPicList2 = (m_pcSlice->isInterB()? RefPicList(uiColDir) : REF_PIC_LIST_0);
+#endif
+  if( pcCUColocated && !pcCUColocated->isIntra( uiAbsPartAddr ) &&
+    pcCUColocated->getCUMvField( eColRefPicList )->getRefIdx( uiAbsPartAddr ) >= 0 )
+  {
+    Int iColPOC = pcCUColocated->getSlice()->getPOC();
+    Int iColRefPOC = pcCUColocated->getSlice()->getRefPOC( eColRefPicList, pcCUColocated->getCUMvField( eColRefPicList )->getRefIdx( uiAbsPartAddr ) );
+    TComMv cColMv = pcCUColocated->getCUMvField( eColRefPicList )->getMv( uiAbsPartAddr );
+
+    Int iCurrPOC = m_pcSlice->getPOC();
+    Int iCurrRefPOC = m_pcSlice->getRefPic( REF_PIC_LIST_0, 0 )->getPOC();
+
+    TComMv cMv;
+    Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC );
+
+    if( iScale == 1024 )
+    {
+      cMv = cColMv;
+    }
+    else
+    {
+      cMv = cColMv.scaleMv( iScale );
+    }
+    clipMv( cMv );
+    abCandIsInter[uiColocAddr] = true;
+    pcMvFieldNeighbours[uiColocAddr << 1].setMvField( cMv, 0 );
+    puiNeighbourCandIdx[uiColocAddr] = uiIdx;
+    if ( getSlice()->isInterB() )
+    {
+      iCurrRefPOC = m_pcSlice->getRefPic( REF_PIC_LIST_1, 0 )->getPOC();
+      TComMv cMvB;
+      iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC );
+      if( iScale == 1024 )
+      {
+        cMvB = cColMv;
+      }
+      else
+      {
+        cMvB = cColMv.scaleMv( iScale );
+      }
+      clipMv( cMvB );
+      pcMvFieldNeighbours[ ( uiColocAddr << 1 ) + 1 ].setMvField( cMvB, 0 );
+      puhInterDirNeighbours[uiColocAddr] = 3;
+    }
+    else
+    {
+      puhInterDirNeighbours[uiColocAddr] = 1;
+    }
+  }
+#if PANASONIC_MERGETEMPORALEXT
+  else if( pcCUColocated && !pcCUColocated->isIntra( uiAbsPartAddr ) &&
+          pcCUColocated->getCUMvField( eColRefPicList2 )->getRefIdx( uiAbsPartAddr ) >= 0 )
+  {
+    Int iColPOC = pcCUColocated->getSlice()->getPOC();
+    Int iColRefPOC = pcCUColocated->getSlice()->getRefPOC( eColRefPicList2, pcCUColocated->getCUMvField( eColRefPicList2 )->getRefIdx( uiAbsPartAddr ) );
+    TComMv cColMv = pcCUColocated->getCUMvField( eColRefPicList2 )->getMv( uiAbsPartAddr );
+    
+    Int iCurrPOC = m_pcSlice->getPOC();
+    Int iCurrRefPOC = m_pcSlice->getRefPic( REF_PIC_LIST_0, 0 )->getPOC();
+    
+    TComMv cMv;
+    Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC );
+    
+    if( iScale == 1024 )
+    {
+      cMv = cColMv;
+    }
+    else
+    {
+      cMv = cColMv.scaleMv( iScale );
+    }
+    clipMv( cMv );
+    abCandIsInter[uiColocAddr] = true;
+    pcMvFieldNeighbours[uiColocAddr << 1].setMvField( cMv, 0 );
+    puiNeighbourCandIdx[uiColocAddr] = uiIdx;
+    if ( getSlice()->isInterB() )
+    {
+      iCurrRefPOC = m_pcSlice->getRefPic( REF_PIC_LIST_1, 0 )->getPOC();
+      TComMv cMvB;
+      iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC );
+      if( iScale == 1024 )
+      {
+        cMvB = cColMv;
+      }
+      else
+      {
+        cMvB = cColMv.scaleMv( iScale );
+      }
+      clipMv( cMvB );
+      pcMvFieldNeighbours[ ( uiColocAddr << 1 ) + 1 ].setMvField( cMvB, 0 );
+      puhInterDirNeighbours[uiColocAddr] = 3;
+    }
+    else
+    {
+      puhInterDirNeighbours[uiColocAddr] = 1;
+    }
+  }
+#endif // PANASONIC_MERGETEMPORALEXT
+#endif // FT_TCTR_MRG
+#endif // MTK_TMVP_H_MRG 
+#endif // MRG_NEIGH_COL
+
+  
+  //===== corners =====
+#if MRG_NEIGH_COL && PANASONIC_MRG_TMVP_REFIDX
+  uiPUIdxLT = 0;
+  uiPUIdxRT  = 0;
+  uiPUIdxLB = 0;
+  cCurPS = m_pePartSize[uiAbsPartIdx];
+#else
+  UInt uiPUIdxLT = 0;
+  UInt uiPUIdxRT  = 0;
+  UInt uiPUIdxLB = 0;
+  PartSize cCurPS = m_pePartSize[uiAbsPartIdx];
+#endif
+
+  deriveLeftRightTopIdxGeneral( cCurPS, uiAbsPartIdx, uiPUIdx, uiPUIdxLT, uiPUIdxRT );
+  deriveLeftBottomIdxGeneral( cCurPS, uiAbsPartIdx, uiPUIdx, uiPUIdxLB );
+  
+  TComDataCU* pcCorner = 0;
+  UInt uiCornerIdx = 0;
+
+  Bool bRTCornerCand = false;
+  Bool bLBCornerCand = false;
+  for( UInt uiIter = 0; uiIter < 2; uiIter++ )
+  {
+    if( !bRTCornerCand )
+    {
+      pcCorner = getPUAboveRight( uiCornerIdx, uiPUIdxRT );
+      xCheckCornerCand( pcCorner, uiCornerIdx, uiIter, bRTCornerCand );
+      if( avoidMergeCandidate( uiAbsPartIdx, uiPUIdx, uiDepth, pcCorner, uiCornerIdx ) )
+      {
+        bRTCornerCand = false;
+      }
+      if( bRTCornerCand )
+      {
+        abCandIsInter[uiCorRTAddr] = true;
+        puiNeighbourCandIdx[uiCorRTAddr] = uiCorRTAddr+1;
+        // get Inter Dir
+        puhInterDirNeighbours[uiCorRTAddr] = pcCorner->getInterDir( uiCornerIdx );
+        // get Mv from Left
+        pcCorner->getMvField( pcCorner, uiCornerIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[uiCorRTAddr << 1] );
+        if ( getSlice()->isInterB() )
+        {
+          pcCorner->getMvField( pcCorner, uiCornerIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[( uiCorRTAddr << 1 ) + 1] );
+        }
+      }
+    }
+    if( !bLBCornerCand )
+    {
+      pcCorner = getPUBelowLeft( uiCornerIdx, uiPUIdxLB );
+      xCheckCornerCand( pcCorner, uiCornerIdx, uiIter, bLBCornerCand );
+      if( avoidMergeCandidate( uiAbsPartIdx, uiPUIdx, uiDepth, pcCorner, uiCornerIdx ) )
+      {
+        bLBCornerCand = false;
+      }
+      if( bLBCornerCand )
+      {
+        uiCorBLAddr = 4;
+        abCandIsInter[uiCorBLAddr] = true;
+        puiNeighbourCandIdx[uiCorBLAddr] = uiCorBLAddr+1;
+        // get Inter Dir
+        puhInterDirNeighbours[uiCorBLAddr] = pcCorner->getInterDir( uiCornerIdx );
+        // get Mv from Left
+        pcCorner->getMvField( pcCorner, uiCornerIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[uiCorBLAddr << 1] );
+        if ( getSlice()->isInterB() )
+        {
+          pcCorner->getMvField( pcCorner, uiCornerIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[( uiCorBLAddr << 1 ) + 1] );
+        }
+      }
+    }
+  }
+
+
+#if HHI_INTER_VIEW_MOTION_PRED
+  //===== add merge with predicted depth maps =====
+  TComMv  acPdmMv       [2];
+  Int     aiPdmRefIdx   [2] = {-1,-1};
+  Int     iPdmInterDir      = getPdmMergeCandidate( uiPUIdx, aiPdmRefIdx, acPdmMv );
+  if( iPdmInterDir )
+  {
+    if( avoidMergeCandidate( uiAbsPartIdx, uiPUIdx, uiDepth, iPdmInterDir, aiPdmRefIdx, acPdmMv ) )
+    {
+      iPdmInterDir = 0;
+    }
+  }
+  if( iPdmInterDir )
+  {
+    abCandIsInter        [ uiPdmAddr ] = true;
+    puiNeighbourCandIdx  [ uiPdmAddr ] = uiPdmAddr + 1;
+    puhInterDirNeighbours[ uiPdmAddr ] = iPdmInterDir;
+    if( ( iPdmInterDir & 1 ) == 1 )
+    {
+      pcMvFieldNeighbours[ uiPdmAddr<<1    ].setMvField( acPdmMv[ 0 ], aiPdmRefIdx[ 0 ] );
+    }
+    if( ( iPdmInterDir & 2 ) == 2 )
+    {
+      pcMvFieldNeighbours[(uiPdmAddr<<1)+1 ].setMvField( acPdmMv[ 1 ], aiPdmRefIdx[ 1 ] );
+    }
+  }
+#endif
+
+
+  //===== remove duplicates =====
+  for( UInt uiOuter = 0; uiOuter < MRG_MAX_NUM_CANDS; uiOuter++ )
+  {
+    if( abCandIsInter[ uiOuter ] && ( puiNeighbourCandIdx[uiOuter] == uiOuter + 1 ) )
+    {
+      for( UInt uiIter = uiOuter + 1; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+      {
+        if( abCandIsInter[ uiIter ] )
+        {
+          UInt uiMvFieldNeighIdxCurr = uiOuter << 1;
+          UInt uiMvFieldNeighIdxComp = uiIter << 1;
+          if( getSlice()->isInterB() )
+          {
+            if( puhInterDirNeighbours[ uiOuter ] == 3 )
+            {
+              if( pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getRefIdx() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getRefIdx() && pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr + 1 ].getRefIdx() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp + 1 ].getRefIdx() &&
+                pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getMv() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getMv() && pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr + 1 ].getMv() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp + 1 ].getMv() &&
+                puhInterDirNeighbours[ uiOuter ] == puhInterDirNeighbours[ uiIter ] )
+              {
+                puiNeighbourCandIdx[ uiIter ] = puiNeighbourCandIdx[ uiOuter ];
+                abCandIsInter[ uiIter ] = false;
+              }
+            }
+            else if( puhInterDirNeighbours[ uiOuter ] == 2 )
+            {
+              if( pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr + 1 ].getRefIdx() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp + 1 ].getRefIdx() &&
+                pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr + 1 ].getMv() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp + 1 ].getMv() &&
+                puhInterDirNeighbours[ uiOuter ] == puhInterDirNeighbours[ uiIter ] )
+              {
+                puiNeighbourCandIdx[ uiIter ] = puiNeighbourCandIdx[ uiOuter ];
+                abCandIsInter[ uiIter ] = false;
+              }
+            }
+            else
+            {
+              if( pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getRefIdx() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getRefIdx() &&
+                pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getMv() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getMv() &&
+                puhInterDirNeighbours[ uiOuter ] == puhInterDirNeighbours[ uiIter ] )
+              {
+                puiNeighbourCandIdx[ uiIter ] = puiNeighbourCandIdx[ uiOuter ];
+                abCandIsInter[ uiIter ] = false;
+              }
+            }
+          }
+          else
+          {
+            if( pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getRefIdx() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getRefIdx() && 
+                pcMvFieldNeighbours[ uiMvFieldNeighIdxCurr ].getMv() == pcMvFieldNeighbours[ uiMvFieldNeighIdxComp ].getMv() )
+            {
+              assert( puhInterDirNeighbours[ uiOuter ] == puhInterDirNeighbours[ uiIter ] );
+              puiNeighbourCandIdx[ uiIter ] = puiNeighbourCandIdx[ uiOuter ];
+              abCandIsInter[ uiIter ] = false;
+            }
+          }
+        }
+      }
+    }
+  }
+#if AVOID_ZERO_MERGE_CANDIDATE
+  // if all merge candidate
+  int i;
+  for ( i=0; i<MRG_MAX_NUM_CANDS; i++ )
+  {
+    if ( abCandIsInter[i] )
+    {
+      break;
+    }
+  }
+  if ( i==MRG_MAX_NUM_CANDS ) // no merge candidate
+  {
+    abCandIsInter[0] = true;
+    puiNeighbourCandIdx[0] = 1;
+    puhInterDirNeighbours[0] = 1;
+    pcMvFieldNeighbours[0].setMvField( TComMv(0, 0), 0 );
+    if ( getSlice()->isInterB() )
+    {
+      puhInterDirNeighbours[0] = 3;
+      pcMvFieldNeighbours[1].setMvField( TComMv(0, 0), 0 );
+    }
+  }
+#endif
+}
+
+Void TComDataCU::xCheckCornerCand( TComDataCU* pcCorner, UInt uiCornerPUIdx, UInt uiIter, Bool& rbValidCand )
+{
+  if( uiIter == 0 )
+  {
+    if( pcCorner && !pcCorner->isIntra( uiCornerPUIdx ) )
+    {
+      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 ) )
+    {
+      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;
+      }
+    }
+  }
+}
+
+Void TComDataCU::setNeighbourCandIdxSubParts( UInt uiCandIdx, UChar uhNumCands, UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth )
+{
+  setSubPartUChar( uhNumCands, m_apuhNeighbourCandIdx[uiCandIdx], uiAbsPartIdx, uiDepth, uiPUIdx );
+}
+
+AMVP_MODE TComDataCU::getAMVPMode(UInt uiIdx)
+{
+  return m_pcSlice->getSPS()->getAMVPMode(m_puhDepth[uiIdx]);
+}
+
+/** Constructs a list of candidates for AMVP
+ * \param uiPartIdx
+ * \param uiPartAddr 
+ * \param eRefPicList
+ * \param iRefIdx
+ * \param pInfo
+ * \param puiNeighbourCandIdx
+ * \returns Void
+ */
+Void TComDataCU::fillMvpCand ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo )
+{
+  PartSize eCUMode = m_pePartSize[0];
+  
+  TComMv cMvPred;
+  
+  pInfo->iN = 0;
+#if !DCM_SIMPLIFIED_MVP
+  UInt uiIdx;
+#endif
+  
+  if (iRefIdx < 0)
+  {
+    return;
+  }
+
+  Int iLeftIdx = -1;
+
+#if HHI_INTER_VIEW_MOTION_PRED
+#if ( PDM_AMVP_POS == 0 )
+  // get inter-view mv predictor (at position 0)
+  TComMv  cPdmMvPred;
+  if( getPdmMvPred( uiPartIdx, eRefPicList, iRefIdx, cPdmMvPred ) )
+  {
+    clipMv( cPdmMvPred );
+    pInfo->m_acMvCand[ pInfo->iN++ ] = cPdmMvPred;
+  }
+#endif
+#endif
+
+#if !DCM_SIMPLIFIED_MVP
+  pInfo->m_acMvCand[pInfo->iN++] = cMvPred;   //dummy mv
+#endif
+  
+  //-- Get Spatial MV
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+#if (DCM_SIMPLIFIED_MVP && !TI_AMVP_SMVP_SIMPLIFIED) || (!DCM_SIMPLIFIED_MVP) || MTK_TMVP_H_AMVP
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+#endif
+  Bool bAdded = false;
+#if !DCM_SIMPLIFIED_MVP
+  Int iLeftMvIdx = -1;
+  Int iAboveMvIdx = -1;
+  Int iCornerMvIdx = -1;
+#endif
+  
+  deriveLeftRightTopIdx( eCUMode, uiPartIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdx( eCUMode, uiPartIdx, uiPartIdxLB );
+  
+#if DCM_SIMPLIFIED_MVP
+  // Left predictor search
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+#if TI_AMVP_SMVP_SIMPLIFIED
+  if (!bAdded) 
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+  }
+#else
+  for ( Int idx = (Int)g_auiZscanToRaster[uiPartIdxLB]; !bAdded && idx >= (Int)g_auiZscanToRaster[uiPartIdxLT]; idx-= uiNumPartInCUWidth )
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, g_auiRasterToZscan[idx], MD_LEFT );
+  }
+#endif
+  
+#if MTK_AMVP_SMVP_DERIVATION
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+#if TI_AMVP_SMVP_SIMPLIFIED
+    if (!bAdded) 
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+    }
+#else
+    for ( Int idx = (Int)g_auiZscanToRaster[uiPartIdxLB]; !bAdded && idx >= (Int)g_auiZscanToRaster[uiPartIdxLT]; idx-= uiNumPartInCUWidth )
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, g_auiRasterToZscan[idx], MD_LEFT );
+    }
+#endif
+  }
+#endif
+  if( bAdded )
+  {
+    iLeftIdx = pInfo->iN - 1;
+  }
+  
+
+
+#if HHI_INTER_VIEW_MOTION_PRED
+#if ( PDM_AMVP_POS == 1 )
+  // get inter-view mv predictor (at position 1)
+  TComMv  cPdmMvPred;
+  if( getPdmMvPred( uiPartIdx, eRefPicList, iRefIdx, cPdmMvPred ) )
+  {
+    clipMv( cPdmMvPred );
+    pInfo->m_acMvCand[ pInfo->iN++ ] = cPdmMvPred;
+  }
+#endif
+#endif
+
+  
+  // Above predictor search
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+  if (bAdded && iLeftIdx >= 0 && pInfo->m_acMvCand[iLeftIdx] == pInfo->m_acMvCand[pInfo->iN-1])
+  {
+    pInfo->iN--; //remove duplicate entries
+    bAdded = false;
+  }
+#if TI_AMVP_SMVP_SIMPLIFIED
+  if (!bAdded) 
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+  }
+  if (bAdded && iLeftIdx >= 0 && pInfo->m_acMvCand[iLeftIdx] == pInfo->m_acMvCand[pInfo->iN-1])
+  {
+    pInfo->iN--; //remove duplicate entries
+    bAdded = false;
+  }
+#else  
+  for ( Int idx = (Int)g_auiZscanToRaster[uiPartIdxRT]; !bAdded && idx >= (Int)g_auiZscanToRaster[uiPartIdxLT]; idx-- )
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, g_auiRasterToZscan[idx], MD_ABOVE);
+    if (bAdded && iLeftIdx >= 0 && pInfo->m_acMvCand[iLeftIdx] == pInfo->m_acMvCand[pInfo->iN-1])
+    {
+      pInfo->iN--; //remove duplicate entries
+      bAdded = false;
+    }
+  }
+#endif
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+    if (bAdded && iLeftIdx >= 0 && pInfo->m_acMvCand[iLeftIdx] == pInfo->m_acMvCand[pInfo->iN-1])
+    {
+      pInfo->iN--; //remove duplicate entries
+    }
+  }
+#if MTK_AMVP_SMVP_DERIVATION
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+    if (bAdded && iLeftIdx >= 0 && pInfo->m_acMvCand[iLeftIdx] == pInfo->m_acMvCand[pInfo->iN-1])
+    {
+      pInfo->iN--; //remove duplicate entries
+      bAdded = false;
+    }
+#if TI_AMVP_SMVP_SIMPLIFIED
+    if (!bAdded) 
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+    }
+    if (bAdded && iLeftIdx >= 0 && pInfo->m_acMvCand[iLeftIdx] == pInfo->m_acMvCand[pInfo->iN-1])
+    {
+      pInfo->iN--; //remove duplicate entries
+      bAdded = false;
+    }
+#else
+    for ( Int idx = (Int)g_auiZscanToRaster[uiPartIdxRT]; !bAdded && idx >= (Int)g_auiZscanToRaster[uiPartIdxLT]; idx-- )
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, g_auiRasterToZscan[idx], MD_ABOVE);
+      if (bAdded && iLeftIdx >= 0 && pInfo->m_acMvCand[iLeftIdx] == pInfo->m_acMvCand[pInfo->iN-1])
+      {
+        pInfo->iN--; //remove duplicate entries
+        bAdded = false;
+      }
+    }
+#endif
+    if(!bAdded)
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+      if (bAdded && iLeftIdx >= 0 && pInfo->m_acMvCand[iLeftIdx] == pInfo->m_acMvCand[pInfo->iN-1])
+      {
+        pInfo->iN--; //remove duplicate entries
+      }
+    }
+  }
+#endif
+#else  
+  //Left
+  for ( uiIdx = g_auiZscanToRaster[uiPartIdxLT]; uiIdx <= g_auiZscanToRaster[uiPartIdxLB]; uiIdx+= uiNumPartInCUWidth )
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, g_auiRasterToZscan[uiIdx], MD_LEFT );
+    if (bAdded && iLeftMvIdx < 0)
+    {
+      iLeftMvIdx = pInfo->iN-1;
+    }
+    if (bAdded) break;
+  }
+  
+  bAdded = false;
+  //Above
+  for ( uiIdx = g_auiZscanToRaster[uiPartIdxLT]; uiIdx <= g_auiZscanToRaster[uiPartIdxRT]; uiIdx++ )
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, g_auiRasterToZscan[uiIdx], MD_ABOVE);
+    if (bAdded && iAboveMvIdx < 0)
+    {
+      iAboveMvIdx = pInfo->iN-1;
+    }
+    if (bAdded) break;
+  }
+  
+  bAdded = false;
+  //Above Right
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+  if (bAdded && iCornerMvIdx < 0)
+  {
+    iCornerMvIdx = pInfo->iN-1;
+  }
+  
+  //Below Left
+  if (!bAdded)
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+  }
+  if (bAdded && iCornerMvIdx < 0)
+  {
+    iCornerMvIdx = pInfo->iN-1;
+  }
+  
+  //Above Left
+  if (!bAdded)
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+  }
+  
+  if (bAdded && iCornerMvIdx < 0)
+  {
+    iCornerMvIdx = pInfo->iN-1;
+  }
+  
+  assert(iLeftMvIdx!=0 && iAboveMvIdx!=0 && iCornerMvIdx!=0);
+  
+  if (iLeftMvIdx < 0 && iAboveMvIdx < 0 && iCornerMvIdx < 0)
+  {
+    //done --> already zero Mv
+  }
+  else if ( (iLeftMvIdx > 0 && iAboveMvIdx > 0 && iCornerMvIdx > 0) || iLeftMvIdx*iAboveMvIdx*iCornerMvIdx < 0)
+  {
+    TComMv cLeftMv, cAboveMv, cCornerMv;
+    
+    if (iLeftMvIdx > 0)
+    {
+      cLeftMv = pInfo->m_acMvCand[iLeftMvIdx];
+    }
+    if (iAboveMvIdx > 0)
+    {
+      cAboveMv = pInfo->m_acMvCand[iAboveMvIdx];
+    }
+    if (iCornerMvIdx > 0)
+    {
+      cCornerMv = pInfo->m_acMvCand[iCornerMvIdx];
+    }
+    pInfo->m_acMvCand[0].setHor ( Median (cLeftMv.getHor(), cAboveMv.getHor(), cCornerMv.getHor()) );
+    pInfo->m_acMvCand[0].setVer ( Median (cLeftMv.getVer(), cAboveMv.getVer(), cCornerMv.getVer()) );
+  }
+  else //only one is available among three candidates
+  {
+    if (iLeftMvIdx > 0)
+    {
+      pInfo->m_acMvCand[0] = pInfo->m_acMvCand[iLeftMvIdx];
+    }
+    else if (iAboveMvIdx > 0)
+    {
+      pInfo->m_acMvCand[0] = pInfo->m_acMvCand[iAboveMvIdx];
+    }
+    else if (iCornerMvIdx > 0)
+    {
+      pInfo->m_acMvCand[0] = pInfo->m_acMvCand[iCornerMvIdx];
+    }
+    else
+    {
+      assert(0);
+    }
+  }
+  
+  clipMv(pInfo->m_acMvCand[0]);
+  TComMv cTempMv;
+  if ( ( ( ((eCUMode == SIZE_2NxN)) && uiPartIdx == 1 ) ||
+        ( ((eCUMode == SIZE_Nx2N)) && uiPartIdx == 0 ) )
+      && iLeftMvIdx > 0 )
+  {
+    cTempMv = pInfo->m_acMvCand[0];
+    pInfo->m_acMvCand[0] = pInfo->m_acMvCand[iLeftMvIdx];
+    pInfo->m_acMvCand[iLeftMvIdx] = cTempMv;
+  }
+#endif
+  
+  if (getAMVPMode(uiPartAddr) == AM_NONE)  //Should be optimized later for special cases
+  {
+    assert(pInfo->iN > 0);
+    pInfo->iN = 1;
+    return;
+  }
+
+
+
+#if HHI_INTER_VIEW_MOTION_PRED
+#if ( PDM_AMVP_POS == 2 )
+  // get inter-view mv predictor (at position 2)
+  TComMv  cPdmMvPred;
+  if( getPdmMvPred( uiPartIdx, eRefPicList, iRefIdx, cPdmMvPred ) )
+  {
+    clipMv( cPdmMvPred );
+    pInfo->m_acMvCand[ pInfo->iN++ ] = cPdmMvPred;
+  }
+#endif
+#endif
+
+  // Get Temporal Motion Predictor
+#if AMVP_NEIGH_COL
+#if MTK_TMVP_H_AMVP
+  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()->getWidth() )  // image boundary check
+  {
+    uiLCUIdx = -1;
+  }
+  else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getHeight() )
+  {
+    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 = getAddr() + m_pcPic->getFrameWidthInCU();
+    }
+    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 = getAddr() + m_pcPic->getFrameWidthInCU() + 1;
+    }
+  }
+  if ( uiLCUIdx >= 0 && xGetColMVP( eRefPicList, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx_Col ) )
+  {
+    pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+  }
+#if FT_TCTR_AMVP
+  else 
+  {
+    UInt uiPartIdxCenter;
+    UInt uiCurLCUIdx = getAddr();
+    xDeriveCenterIdx( eCUMode, uiPartIdx, uiPartIdxCenter );
+    if (xGetColMVP( eRefPicList, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx_Col ))
+  {
+      pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+    }
+  }
+#endif
+  //----  co-located RightBottom Temporal Predictor  ---//
+
+#else //MTK_TMVP_H_AMVP
+#if FT_TCTR_AMVP
+    TComMv cMvTCenter;
+    if (xGetCenterCol( uiPartIdx, eRefPicList, iRefIdx, &cMvTCenter ))
+    {
+      for (int i = pInfo->iN-1; i >= 0; i--)
+      {
+        pInfo->m_acMvCand[i+1] = pInfo->m_acMvCand[i];
+      }
+      pInfo->m_acMvCand[0] = cMvTCenter;
+      pInfo->iN++;
+    }
+#else //FT_TCTR_AMVP
+  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiPartAddr;
+  
+  UInt uiColDir = (m_pcSlice->isInterB()? m_pcSlice->getColDir() : 0);
+  
+  TComDataCU* pcCUColocated = getCUColocated(RefPicList(uiColDir));
+  
+  RefPicList eColRefPicList = (m_pcSlice->isInterB()? RefPicList(1-uiColDir) : REF_PIC_LIST_0);
+#if PANASONIC_AMVPTEMPORALEXT
+  RefPicList eColRefPicList2 = (m_pcSlice->isInterB()? RefPicList(uiColDir) : REF_PIC_LIST_0);
+#endif
+  
+  if ( pcCUColocated && !pcCUColocated->isIntra(uiAbsPartAddr) &&
+      pcCUColocated->getCUMvField(eColRefPicList)->getRefIdx(uiAbsPartAddr) >= 0 )
+  {
+    Int iColPOC = pcCUColocated->getSlice()->getPOC();
+    Int iColRefPOC = pcCUColocated->getSlice()->getRefPOC(eColRefPicList, pcCUColocated->getCUMvField(eColRefPicList)->getRefIdx(uiAbsPartAddr));
+    TComMv cColMv = pcCUColocated->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+    
+    Int iCurrPOC = m_pcSlice->getPOC();
+    Int iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, iRefIdx)->getPOC();
+    
+    TComMv cMv;
+    Int iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
+    
+    if (iScale == 1024)
+    {
+      cMv = cColMv;
+    }
+    else
+    {
+      cMv = cColMv.scaleMv( iScale );
+    }
+    
+    clipMv(cMv);
+    
+    pInfo->m_acMvCand[pInfo->iN++] = cMv ;
+  }
+#if PANASONIC_AMVPTEMPORALEXT
+  else if ( pcCUColocated && !pcCUColocated->isIntra(uiAbsPartAddr) &&
+           pcCUColocated->getCUMvField(eColRefPicList2)->getRefIdx(uiAbsPartAddr) >= 0 )
+  {
+    Int iColPOC = pcCUColocated->getSlice()->getPOC();
+    Int iColRefPOC = pcCUColocated->getSlice()->getRefPOC(eColRefPicList2, pcCUColocated->getCUMvField(eColRefPicList2)->getRefIdx(uiAbsPartAddr));
+    TComMv cColMv = pcCUColocated->getCUMvField(eColRefPicList2)->getMv(uiAbsPartAddr);
+    
+    Int iCurrPOC = m_pcSlice->getPOC();
+    Int iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, iRefIdx)->getPOC();
+    
+    TComMv cMv;
+    Int iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
+    
+    if (iScale == 1024)
+    {
+      cMv = cColMv;
+    }
+    else
+    {
+      cMv = cColMv.scaleMv( iScale );
+    }
+    
+    clipMv(cMv);
+    
+    pInfo->m_acMvCand[pInfo->iN++] = cMv ;
+  }
+#endif // PANASONIC_AMVPTEMPORALEXT
+#endif // FT_TCTR_AMVP
+#endif // MTK_TMVP_H_AMVP
+#endif // AMVP_NEIGH_COL
+
+
+#if HHI_INTER_VIEW_MOTION_PRED
+#if ( PDM_AMVP_POS == 3 )
+  // get inter-view mv predictor (at position 3)
+  TComMv  cPdmMvPred;
+  if( getPdmMvPred( uiPartIdx, eRefPicList, iRefIdx, cPdmMvPred ) )
+  {
+    clipMv( cPdmMvPred );
+    pInfo->m_acMvCand[ pInfo->iN++ ] = cPdmMvPred;
+  }
+#endif
+#endif
+
+  // Check No MV Candidate
+  xUniqueMVPCand( pInfo );
+  return ;
+}
+
+#if DCM_SIMPLIFIED_MVP==0
+Bool TComDataCU::clearMVPCand( TComMv cMvd, AMVPInfo* pInfo )
+{
+  // only works for multiple candidates
+  if (pInfo->iN <= 1)
+  {
+    return false;
+  }
+  
+  // only works for non-zero mvd case
+  if (cMvd.getHor() == 0 && cMvd.getVer() == 0)
+  {
+    return false;
+  }
+  
+  TComMv  acMv[ AMVP_MAX_NUM_CANDS ];
+  Int aiValid [ AMVP_MAX_NUM_CANDS ];
+  
+  Int iNTmp, i, j;
+  
+  for ( i=0; i<pInfo->iN; i++ )
+  {
+    aiValid[i] = 1;
+  }
+  
+  for ( i=0; i<pInfo->iN; i++ )
+  {
+    TComMv cMvCand = pInfo->m_acMvCand[i] + cMvd;
+    
+    UInt uiBestBits = xGetMvdBits(cMvd);
+    for ( j=0; j<pInfo->iN; j++ )
+    {
+      if (aiValid[j] && i!=j && xGetMvdBits(cMvCand-pInfo->m_acMvCand[j]) < uiBestBits)
+      {
+        aiValid[i] = 0;
+      }
+    }
+  }
+  
+  iNTmp = 0;
+  for ( i=0; i<pInfo->iN; i++ )
+  {
+    if (aiValid[i])
+      iNTmp++;
+  }
+  
+  if (iNTmp == pInfo->iN)
+  {
+    return false;
+  }
+  
+  assert(iNTmp > 0);
+  
+  iNTmp = 0;
+  for ( i=0; i<pInfo->iN; i++ )
+  {
+    if (aiValid[i])
+    {
+      acMv[iNTmp++] = pInfo->m_acMvCand[i];
+    }
+  }
+  
+  for ( i=0; i<iNTmp; i++ ) pInfo->m_acMvCand[i] = acMv[i];
+  pInfo->iN = iNTmp;
+  
+  return true;
+}
+#endif
+
+Int TComDataCU::searchMVPIdx(TComMv cMv, AMVPInfo* pInfo)
+{
+  for ( Int i=0; i<pInfo->iN; i++ )
+  {
+    if (cMv == pInfo->m_acMvCand[i])
+      return i;
+  }
+  
+  assert(0);
+  return -1;
+}
+
+Void TComDataCU::clipMv    (TComMv&  rcMv)
+{
+  Int  iMvShift = 2;
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( getSlice()->getSPS()->isDepth() )
+    iMvShift = 0;
+#endif
+  Int iHorMax = (m_pcSlice->getSPS()->getWidth() - m_uiCUPelX - 1 )<<iMvShift;
+  Int iHorMin = (      -(Int)g_uiMaxCUWidth - (Int)m_uiCUPelX + 1 )<<iMvShift;
+  
+  Int iVerMax = (m_pcSlice->getSPS()->getHeight() - m_uiCUPelY - 1 )<<iMvShift;
+  Int iVerMin = (      -(Int)g_uiMaxCUHeight - (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);
+}
+
+/** Test if the current block is skipped or not
+ * \param uiPartIdx
+ * \returns Bool
+ */
+Bool TComDataCU::isSkipped( UInt uiPartIdx )
+{
+  if ( m_pcSlice->isIntra () )
+  {
+    return false;
+  }
+#if HHI_MRG_SKIP
+  return ( m_pePredMode[ uiPartIdx ] == MODE_SKIP && getMergeFlag( uiPartIdx ) && !getQtRootCbf( uiPartIdx ) );
+#else
+  if ( m_pcSlice->isInterP() )
+  {
+    return ( ( m_pePredMode[ uiPartIdx ] == MODE_SKIP ) && ( ( m_puhCbf[0][uiPartIdx] & 0x1 ) + ( m_puhCbf[1][uiPartIdx] & 0x1 ) + ( m_puhCbf[2][uiPartIdx] & 0x1 ) == 0) );
+  }
+  else //if ( m_pcSlice->isInterB()  )
+  {
+    return ( ( m_pePredMode[ uiPartIdx ] == MODE_SKIP ) && ( ( m_puhCbf[0][uiPartIdx] & 0x1 ) + ( m_puhCbf[1][uiPartIdx] & 0x1 ) + ( m_puhCbf[2][uiPartIdx] & 0x1 ) == 0) && (m_puhInterDir[uiPartIdx] == 3) );
+  }
+#endif
+}
+
+// ====================================================================================================================
+// 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);
+      break;
+    }
+    case MD_ABOVE:
+    {
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx);
+      break;
+    }
+    case MD_ABOVE_RIGHT:
+    {
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx);
+      break;
+    }
+    case MD_BELOW_LEFT:
+    {
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+    case MD_ABOVE_LEFT:
+    {
+      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+    default:
+    {
+      break;
+    }
+  }
+ 
+  if ( pcTmpCU != NULL && m_pcSlice->isEqualRef(eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx), iRefIdx) )
+  {
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+    clipMv(cMvPred);
+    
+    pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
+    return true;
+  }
+  return false;
+}
+
+Void TComDataCU::xUniqueMVPCand(AMVPInfo* pInfo)
+{
+  if ( pInfo->iN == 0 )
+  {
+    pInfo->m_acMvCand[ pInfo->iN++ ].setZero();
+    return;
+  }
+  
+  TComMv  acMv[ AMVP_MAX_NUM_CANDS ];
+  Int iNTmp, i, j;
+  
+  // make it be unique
+  iNTmp = 0;
+  acMv[ iNTmp++ ] = pInfo->m_acMvCand[0];
+  for ( i=1; i<pInfo->iN; i++ )
+  {
+    // BugFix for 1603
+    for ( j=iNTmp - 1; j>=0; j-- )
+    {
+      if ( pInfo->m_acMvCand[i] == acMv[j] ) break;
+    }
+    if ( j<0 )
+    {
+      acMv[ iNTmp++ ] = pInfo->m_acMvCand[i];
+    }
+  }
+  for ( i=0; i<iNTmp; i++ ) pInfo->m_acMvCand[i] = acMv[i];
+  pInfo->iN = iNTmp;
+  
+  return ;
+}
+
+#if MTK_AMVP_SMVP_DERIVATION
+/** 
+ * \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);
+      break;
+    }
+  case MD_ABOVE:
+    {
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  case MD_ABOVE_RIGHT:
+    {
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  case MD_BELOW_LEFT:
+    {
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  case MD_ABOVE_LEFT:
+    {
+      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  default:
+    {
+      break;
+    }
+  }
+
+  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 iCurrPOC = m_pcSlice->getPOC();
+  Int iCurrRefPOC = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
+  Int iNeibPOC = iCurrPOC;
+  Int iNeibRefPOC;
+
+
+  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0 )
+  {
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
+    if( pcTmpCU->getSlice()->getRefViewIdx( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) ) != m_pcSlice->getRefViewIdx( eRefPicList, iRefIdx ) )
+      return false;
+    if( iNeibRefPOC == iCurrRefPOC ) // Same Reference Frame But Diff List//
+    {
+      TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
+
+      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) );
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+    TComMv rcMv;
+
+    if( pcTmpCU->getSlice()->getRefViewIdx( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ) != m_pcSlice->getRefViewIdx( eRefPicList, iRefIdx ) )
+      return false;
+
+    Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+    if ( iScale == 1024 )
+    {
+      rcMv = cMvPred;
+    }
+    else
+    {
+      rcMv = cMvPred.scaleMv( iScale );
+    }
+
+    clipMv(rcMv);
+
+    pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
+    return true;
+  }
+  //---------------------- V2(END) --------------------//
+  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0)
+  {
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
+    TComMv rcMv;
+
+    if( pcTmpCU->getSlice()->getRefViewIdx( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) ) != m_pcSlice->getRefViewIdx( eRefPicList, iRefIdx ) )
+      return false;
+
+    Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+    if ( iScale == 1024 )
+    {
+      rcMv = cMvPred;
+    }
+    else
+    {
+      rcMv = cMvPred.scaleMv( iScale );
+    }
+
+    clipMv(rcMv);
+
+    pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
+    return true;
+  }
+  //---------------------- V3(END) --------------------//
+  return false;
+}
+#endif
+
+/** 
+ * \param eRefPicList
+ * \param uiCUAddr 
+ * \param uiPartUnitIdx
+ * \param riRefIdx
+ * \returns Bool
+ */
+#if MTK_TMVP_H_MRG || MTK_TMVP_H_AMVP
+Bool TComDataCU::xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx )
+{
+  UInt uiAbsPartAddr = uiPartUnitIdx;
+
+  RefPicList  eColRefPicList;
+  Int iColPOC, iColRefPOC, iCurrPOC, iCurrRefPOC, iScale;
+  TComMv cColMv;
+
+  iCurrPOC = m_pcSlice->getPOC();    
+  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+
+  // use coldir.
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? getSlice()->getColDir() : 0), 0);
+  TComDataCU *pColCU = pColPic->getCU( uiCUAddr );
+  iColPOC = pColCU->getSlice()->getPOC();  
+
+  if (pColCU->isIntra(uiAbsPartAddr))
+  {
+    return false;
+  }
+
+  if( m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getViewIdx() != m_pcSlice->getViewIdx() )
+    return false;
+
+  // Prefer a vector crossing us.  Prefer shortest.
+  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(uiAbsPartAddr);
+    if (iColRefIdx < 0)
+    {
+      continue;
+    }
+    iColRefPOC = pColCU->getSlice()->getRefPOC(RefPicList(l), iColRefIdx);
+    if( pColCU->getSlice()->getRefViewIdx(RefPicList(l), iColRefIdx) != pColCU->getSlice()->getViewIdx() )
+      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;
+    }
+#if PANASONIC_AMVPTEMPORALMOD
+    else if (bCrosses == bFirstCrosses && l == eRefPicList)
+#else
+    else if (bCrosses == bFirstCrosses && iColDist < iFirstColDist)
+#endif
+    {
+      bSaveIt = true;
+    }
+    if (bSaveIt)
+    {
+      bFirstCrosses = bCrosses;
+      iFirstColDist = iColDist;
+      eColRefPicList = RefPicList(l);
+    }
+  }
+  if( iFirstColDist < 0 )
+    return false;
+  // Scale the vector.
+  iColRefPOC = pColCU->getSlice()->getRefPOC(eColRefPicList, pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiAbsPartAddr));
+  cColMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+
+  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+  iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
+  if (iScale == 1024)
+  {
+    rcMv = cColMv;
+  }
+  else
+  {
+    rcMv = cColMv.scaleMv( iScale );
+  }
+  clipMv(rcMv);
+  return true;
+}
+#endif
+
+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 1024;
+  }
+  else
+  {
+    Int iTDB      = Clip3( -128, 127, iDiffPocB );
+    Int iTDD      = Clip3( -128, 127, iDiffPocD );
+    Int iX        = (0x4000 + abs(iTDD/2)) / iTDD;
+    Int iScale    = Clip3( -1024, 1023, (iTDB * iX + 32) >> 6 );
+    return iScale;
+  }
+}
+
+Void TComDataCU::xCalcCuCbf( UChar* puhCbf, UInt uiTrDepth, UInt uiCbfDepth, UInt uiCuDepth )
+{
+  if ( uiTrDepth == 0 )
+    return;
+  
+  UInt ui, uiNumSig = 0;
+  
+  UInt uiNumPart  = m_pcPic->getNumPartInCU() >> ( uiCuDepth << 1 );
+  UInt uiQNumPart = uiNumPart >> 2;
+  
+  UInt uiCbfDepth1 = uiCbfDepth + 1;
+  if( uiNumPart == 1 )
+  {
+    if ( ( puhCbf[0] >> uiCbfDepth1 ) & 0x1 )
+    {
+      uiNumSig = 1;
+    }
+    puhCbf[0] |= uiNumSig << uiCbfDepth;
+    
+    return;
+  }
+  assert( uiQNumPart );
+  
+  if ( uiCbfDepth < ( uiTrDepth - 1 ) )
+  {
+    UChar* puhNextCbf = puhCbf;
+    xCalcCuCbf( puhNextCbf, uiTrDepth, uiCbfDepth1, uiCuDepth+1 ); puhNextCbf += uiQNumPart;
+    xCalcCuCbf( puhNextCbf, uiTrDepth, uiCbfDepth1, uiCuDepth+1 ); puhNextCbf += uiQNumPart;
+    xCalcCuCbf( puhNextCbf, uiTrDepth, uiCbfDepth1, uiCuDepth+1 ); puhNextCbf += uiQNumPart;
+    xCalcCuCbf( puhNextCbf, uiTrDepth, uiCbfDepth1, uiCuDepth+1 );
+  }
+  
+  for ( ui = 0; ui < uiNumPart; ui += uiQNumPart )
+  {
+    if ( ( puhCbf[ui] >> uiCbfDepth1 ) & 0x1 )
+    {
+      uiNumSig = 1;
+      break;
+    }
+  }
+  
+  uiNumSig <<= uiCbfDepth;
+  for ( ui = 0; ui < uiNumPart; ui++ )
+  {
+    puhCbf[ui] |= uiNumSig;
+  }
+}
+
+#if FT_TCTR_AMVP || FT_TCTR_MRG
+/** 
+ * \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() -1 )/2*m_pcPic->getNumPartInWidth()
+                                        + ( iPartWidth/m_pcPic->getMinCUWidth()  -1 )/2];
+}
+
+/** 
+ * \param uiPartIdx
+ * \param eRefPicList 
+ * \param iRefIdx
+ * \param pcMv
+ * \returns Bool
+ */
+Bool TComDataCU::xGetCenterCol( UInt uiPartIdx, RefPicList eRefPicList, int iRefIdx, TComMv *pcMv )
+{
+  PartSize eCUMode = m_pePartSize[0];
+  
+  Int iCurrPOC = m_pcSlice->getPOC();
+  
+  // use coldir.
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? getSlice()->getColDir() : 0), 0);
+  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)->getViewIdx() != m_pcSlice->getViewIdx() )
+    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()->getRefViewIdx(RefPicList(l), iColRefIdx) != pColCU->getSlice()->getViewIdx() )
+      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;
+#if PANASONIC_AMVPTEMPORALMOD
+    else if (bCrosses == bFirstCrosses && l == eRefPicList)
+#else
+    else if (bCrosses == bFirstCrosses && iColDist < iFirstColDist)
+#endif
+      bSaveIt = true;
+    
+    if (bSaveIt)
+    {
+      bFirstCrosses = bCrosses;
+      iFirstColDist = iColDist;
+      eColRefPicList = RefPicList(l);
+    }
+  }
+  if( iFirstColDist < 0 )
+    return false;
+
+  // 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 == 1024)
+  {
+    pcMv[0] = cColMv;
+  }
+  else
+  {
+    pcMv[0] = cColMv.scaleMv( iScale );
+  }
+  clipMv(pcMv[0]);
+  
+  return true;
+}
+#endif
+
+#if AMVP_BUFFERCOMPRESS
+Void TComDataCU::compressMV()
+{
+  m_acCUMvField[0].compress(m_pePredMode,m_puhInterDir);
+  m_acCUMvField[1].compress(m_pePredMode,m_puhInterDir);
+}
+#endif 
+
+#if QC_MDCS
+UInt TComDataCU::getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra)
+{
+  static const UChar aucIntraLumaDirToScanIdx[MAX_CU_DEPTH][34] =
+  {
+    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
+    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
+    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
+    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
+    {1, 2, 0, 0, 1, 1, 0, 2, 2, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, },
+    {1, 2, 0, 0, 1, 1, 0, 2, 2, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, },
+    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
+  };
+  static const UChar aucIntraChromaDirToScanIdx[MAX_CU_DEPTH][5] = 
+  {
+    {0, 0, 0, 0, 0, },
+    {0, 0, 0, 0, 0, },
+    {0, 0, 0, 0, 0, },
+    {0, 0, 0, 0, 0, },
+    {0, 0, 0, 0, 0, },
+    {1, 2, 0, 0, 0, },
+    {1, 2, 0, 0, 0, },
+  };
+
+  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 ADD_PLANAR_MODE
+    mapPlanartoDC( uiDirMode );
+#endif
+    uiScanIdx = aucIntraLumaDirToScanIdx[uiCTXIdx][uiDirMode];
+  }
+  else
+  {
+       uiDirMode = getChromaIntraDir(uiAbsPartIdx);
+#if ADD_PLANAR_MODE
+       mapPlanartoDC( uiDirMode );
+#endif
+       if (uiDirMode < 4)
+       {
+         uiScanIdx = (aucIntraChromaDirToScanIdx[uiCTXIdx][uiDirMode]);
+       }
+       else
+       {
+         uiDirMode = getLumaIntraDir(uiAbsPartIdx);
+#if ADD_PLANAR_MODE
+         mapPlanartoDC( uiDirMode );
+#endif
+         uiScanIdx = aucIntraLumaDirToScanIdx[max<UInt>(uiCTXIdx-1,0)][uiDirMode];
+       }
+  }
+
+  return uiScanIdx;
+}
+#endif //QC_MDCS
+
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+Bool TComDataCU::isSuroundingRefIdxException     ( UInt   uiAbsPartIdx )
+{
+  if ( !getSlice()->isInterB() )
+    return true;
+  
+  if ( getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 2 && getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 2)
+  {
+    return false;
+  }
+  
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  TComMvField cMvFieldTemp;
+  
+  if ( getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 0 )  // combined list case
+  {
+    // Left PU
+    pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+    if ( pcTempCU )
+    {
+      if (pcTempCU->getInterDir(uiTempPartIdx) == 1 )
+      {
+        if ( pcTempCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx )) > 3 )
+          return true;
+      }
+      else if (pcTempCU->getInterDir(uiTempPartIdx) == 2 )
+      {
+        if ( pcTempCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx )) > 3 )
+          return true;
+      }
+      else if ( pcTempCU->getInterDir(uiTempPartIdx) == 3 )
+      {
+        if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > 1 )
+          return true;
+        
+        if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > 1 )
+          return true;
+      }
+    }
+    
+    // Above PU
+    pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+    if ( pcTempCU )
+    {
+      if (pcTempCU->getInterDir(uiTempPartIdx) == 1 )
+      {
+        if ( pcTempCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx )) > 3 )
+          return true;
+      }
+      else if (pcTempCU->getInterDir(uiTempPartIdx) == 2 )
+      {
+        if ( pcTempCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx )) > 3 )
+          return true;
+      }
+      else if ( pcTempCU->getInterDir(uiTempPartIdx) == 3 )
+      {
+        if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > 1 )
+          return true;
+        
+        if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > 1 )
+          return true;
+      }
+    }
+    
+    // Above left PU
+    pcTempCU = getPUAboveLeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+    if ( pcTempCU )
+    {
+      if (pcTempCU->getInterDir(uiTempPartIdx) == 1 )
+      {
+        if ( pcTempCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx )) > 3 )
+          return true;
+      }
+      else if (pcTempCU->getInterDir(uiTempPartIdx) == 2 )
+      {
+        if ( pcTempCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx )) > 3 )
+          return true;
+      }
+      else if ( pcTempCU->getInterDir(uiTempPartIdx) == 3 )
+      {
+        if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > 1 )
+          return true;
+        
+        if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > 1 )
+          return true;
+      }
+    }
+    
+    return false;
+  }
+  
+  // not combined list case
+  // Left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  if ( pcTempCU )
+  {
+    if (pcTempCU->getInterDir(uiTempPartIdx) == 1 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > MS_LCEC_UNI_EXCEPTION_THRES )
+        return true;
+    }
+    else if (pcTempCU->getInterDir(uiTempPartIdx) == 2 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > MS_LCEC_UNI_EXCEPTION_THRES )
+        return true;
+    }
+    else if ( pcTempCU->getInterDir(uiTempPartIdx) == 3 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > 1 )
+        return true;
+      
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > 1 )
+        return true;
+    }
+  }
+  
+  // Above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  if ( pcTempCU )
+  {
+    if (pcTempCU->getInterDir(uiTempPartIdx) == 1 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > MS_LCEC_UNI_EXCEPTION_THRES )
+        return true;
+    }
+    else if (pcTempCU->getInterDir(uiTempPartIdx) == 2 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > MS_LCEC_UNI_EXCEPTION_THRES )
+        return true;
+    }
+    else if ( pcTempCU->getInterDir(uiTempPartIdx) == 3 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > 1 )
+        return true;
+      
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > 1 )
+        return true;
+    }
+  }
+  
+  // Above left PU
+  pcTempCU = getPUAboveLeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  if ( pcTempCU )
+  {
+    if (pcTempCU->getInterDir(uiTempPartIdx) == 1 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > MS_LCEC_UNI_EXCEPTION_THRES )
+        return true;
+    }
+    else if (pcTempCU->getInterDir(uiTempPartIdx) == 2 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > MS_LCEC_UNI_EXCEPTION_THRES )
+        return true;
+    }
+    else if ( pcTempCU->getInterDir(uiTempPartIdx) == 3 )
+    {
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiTempPartIdx ) > 1 )
+        return true;
+      
+      if ( pcTempCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiTempPartIdx ) > 1 )
+        return true;
+    }
+  }
+  
+  return false;
+}
+#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()->getSPS()->isDepth() && ! pcCU->getSlice()->getSPS()->isDepth() );
+  UInt uiNumPartition = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  Int iSizeInUchar  = sizeof( UChar ) * uiNumPartition;
+  Int iSizeInInt    = sizeof( Int   ) * uiNumPartition;
+
+  memcpy( m_pePredMode + uiAbsPartIdxDst,  pcCU->getPredictionMode() + uiAbsPartIdxSrc, sizeof( PredMode ) * uiNumPartition );
+  memcpy( m_puhInterDir + uiAbsPartIdxDst, pcCU->getInterDir() + uiAbsPartIdxSrc,       iSizeInUchar );
+
+  memcpy( m_apiMVPIdx[0] + uiAbsPartIdxDst, pcCU->getMVPIdx(REF_PIC_LIST_0) + uiAbsPartIdxSrc, iSizeInInt );
+  memcpy( m_apiMVPIdx[1] + uiAbsPartIdxDst, pcCU->getMVPIdx(REF_PIC_LIST_1) + uiAbsPartIdxSrc, iSizeInInt );
+  memcpy( m_apiMVPNum[0] + uiAbsPartIdxDst, pcCU->getMVPNum(REF_PIC_LIST_0) + uiAbsPartIdxSrc, iSizeInInt );
+  memcpy( m_apiMVPNum[1] + uiAbsPartIdxDst, pcCU->getMVPNum(REF_PIC_LIST_1) + uiAbsPartIdxSrc, iSizeInInt );
+
+  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 HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  for( UInt ui = 0; ui < uiNumPartition; ui++ )
+  {
+    m_acCUMvField[0].getMv( uiAbsPartIdxDst + ui ) += TComMv( 2, 2 );
+    m_acCUMvField[0].getMv( uiAbsPartIdxDst + ui ) >>= 2;
+
+    m_acCUMvField[1].getMv( uiAbsPartIdxDst + ui ) += TComMv( 2, 2 );
+    m_acCUMvField[1].getMv( uiAbsPartIdxDst + ui ) >>= 2;
+
+    m_acCUMvField[0].getMvd( uiAbsPartIdxDst + ui ) += TComMv( 2, 2 );
+    m_acCUMvField[0].getMvd( uiAbsPartIdxDst + ui ) >>= 2;
+
+    m_acCUMvField[1].getMvd( uiAbsPartIdxDst + ui ) += TComMv( 2, 2 );
+    m_acCUMvField[1].getMvd( uiAbsPartIdxDst + ui ) >>= 2;
+  }
+#endif
+}
+#endif
+
+Void TComDataCU::getPosInPic( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY )
+{
+  riPosX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIndex]] + getCUPelX();
+  riPosY = g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIndex]] + getCUPelY();  
+}
Index: /tags/0.2r1/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComDataCU.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComDataCU.h	(revision 19)
@@ -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-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     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"
+#include "TComYuv.h"
+
+#include <algorithm>
+#include <vector>
+
+// ====================================================================================================================
+// 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
+#if HHI_MPI
+  Int*          m_piTextureModeDepth; ///< at which depth is prediction data inherited from texture picture ( -1 : none )
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // CU data
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  PartSize*     m_pePartSize;         ///< array of partition sizes
+  PredMode*     m_pePredMode;         ///< array of prediction modes
+  UChar*        m_phQP;               ///< array of QP values
+  UChar*        m_puhTrIdx;           ///< array of transform indices
+  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 SNY_DQP 
+  Bool          m_bdQP;               ///< signal if LCU dQP encoded
+#endif//SNY_DQP
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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
+  UChar*        m_puhMergeIndex;      ///< array of merge candidate indices
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Bool*         m_pbResPredAvailable; ///< array of residual prediction available flags
+  Bool*         m_pbResPredFlag;      ///< array of residual prediction flags
+#endif
+  UChar*        m_apuhNeighbourCandIdx[ MRG_MAX_NUM_CANDS ];///< array of motion vector predictor candidates indices
+  UChar*        m_puhLumaIntraDir;    ///< array of intra directions (luma)
+  UChar*        m_puhChromaIntraDir;  ///< array of intra directions (chroma)
+  UChar*        m_puhInterDir;        ///< array of inter directions
+  Int*          m_apiMVPIdx[2];       ///< array of motion vector predictor candidates
+  Int*          m_apiMVPNum[2];       ///< array of number of possible motion vectors predictors
+  UInt*         m_puiAlfCtrlFlag;     ///< array of ALF flags
+  UInt*         m_puiTmpAlfCtrlFlag;  ///< temporal array of ALF flags
+#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;
+  Int*          m_piWedgePredTexDeltaDC1;
+  Int*          m_piWedgePredTexDeltaDC2;
+
+  Int*          m_piContourPredTexDeltaDC1;
+  Int*          m_piContourPredTexDeltaDC2;
+#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_uiSliceStartCU;    ///< Start CU address of current slice
+  UInt          m_uiEntropySliceStartCU; ///< Start CU address of current slice
+  
+protected:
+  
+  /// add possible motion vector predictor candidates
+  Bool          xAddMVPCand           ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
+#if MTK_AMVP_SMVP_DERIVATION
+  Bool          xAddMVPCandOrder      ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
+#endif  
+
+#if MTK_TMVP_H_MRG || MTK_TMVP_H_AMVP
+  Void          deriveRightBottomIdx        ( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxRB );
+  Bool          xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx );
+#endif
+  
+  /// remove redundant candidates
+  Void          xUniqueMVPCand        ( AMVPInfo* pInfo );
+
+  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 );
+  
+  /// calculate all CBF's from coefficients
+  Void          xCalcCuCbf            ( UChar* puhCbf, UInt uiTrDepth, UInt uiCbfDepth, UInt uiCuDepth );
+  
+#if FT_TCTR_AMVP || FT_TCTR_MRG
+  Void xDeriveCenterIdx( PartSize eCUMode, UInt uiPartIdx, UInt& ruiPartIdxCenter );
+  Bool xGetCenterCol( UInt uiPartIdx, RefPicList eRefPicList, int iRefIdx, TComMv *pcMv );
+#endif
+  
+public:
+  TComDataCU();
+  virtual ~TComDataCU();
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // create / destroy / initialize / copy
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          create                ( UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu );
+  Void          destroy               ();
+  
+  Void          initCU                ( TComPic* pcPic, UInt uiCUAddr );
+  Void          initEstData           ();
+  Void          initSubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, 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          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;   }
+  
+#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
+
+  Void          setDepthSubParts      ( UInt uiDepth, UInt uiAbsPartIdx );
+  Void          getPosInPic           ( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for CU data
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  PartSize*     getPartitionSize      ()                        { return m_pePartSize;        }
+  PartSize      getPartitionSize      ( UInt uiIdx )            { return m_pePartSize[uiIdx]; }
+  Void          setPartitionSize      ( UInt uiIdx, PartSize uh){ m_pePartSize[uiIdx] = uh;   }
+  Void          setPartSizeSubParts   ( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  PredMode*     getPredictionMode     ()                        { return m_pePredMode;        }
+  PredMode      getPredictionMode     ( UInt uiIdx )            { return 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 );
+  
+  UChar*        getQP                 ()                        { return m_phQP;              }
+  UChar         getQP                 ( UInt uiIdx )            { return m_phQP[uiIdx];       }
+  Void          setQP                 ( UInt uiIdx, UChar  uh ) { m_phQP[uiIdx] = uh;         }
+  Void          setQPSubParts         ( UInt uiQP,   UInt uiAbsPartIdx, UInt uiDepth );
+#if SNY_DQP
+  Bool          getdQPFlag            ()                        { return m_bdQP;              }
+  Void          setdQPFlag            ( Bool b )                { m_bdQP = b;                 }
+#endif//SNY_DQP
+  
+  UChar*        getTransformIdx       ()                        { return m_puhTrIdx;          }
+  UChar         getTransformIdx       ( UInt uiIdx )            { return m_puhTrIdx[uiIdx];   }
+  Void          setTrIdxSubParts      ( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  UInt          getQuadtreeTULog2MinSizeInCU( UInt uiIdx );
+  
+#if HHI_RQT_FORCE_SPLIT_ACC2_PU || HHI_RQT_DISABLE_SUB
+  UInt          getQuadtreeTULog2RootSizeInCU( UInt uiIdx );
+#endif
+  
+  TComCUMvField* getCUMvField         ( RefPicList e )          { return  &m_acCUMvField[e];  }
+  
+  TCoeff*&      getCoeffY             ()                        { return m_pcTrCoeffY;        }
+  TCoeff*&      getCoeffCb            ()                        { return m_pcTrCoeffCb;       }
+  TCoeff*&      getCoeffCr            ()                        { return m_pcTrCoeffCr;       }
+  
+  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                    );
+#if HHI_MRG_SKIP
+  Void          setCbfSubParts        ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth    );
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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 );
+
+  UChar*        getNeighbourCandIdx         ( UInt uiCandIdx )            { return m_apuhNeighbourCandIdx[uiCandIdx];           }
+  UChar         getNeighbourCandIdx         ( UInt uiCandIdx, UInt uiIdx ){ return m_apuhNeighbourCandIdx[uiCandIdx][uiIdx];           }
+  Void          setNeighbourCandIdx         ( UInt uiCandIdx, UInt uiIdx, UChar uhNeighCands ) { m_apuhNeighbourCandIdx[uiCandIdx][uiIdx] = uhNeighCands;}
+  Void          setNeighbourCandIdxSubParts ( UInt uiCandIdx, UChar uhNumCands, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  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
+
+  Void          setSubPartBool        ( Bool bParameter, Bool* pbBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
+  Void          setSubPartUChar       ( UInt bParameter, UChar* pbBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
+
+  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 );
+  
+  UInt*         getAlfCtrlFlag        ()                        { return m_puiAlfCtrlFlag;            }
+  UInt          getAlfCtrlFlag        ( UInt uiIdx )            { return m_puiAlfCtrlFlag[uiIdx];     }
+  Void          setAlfCtrlFlag        ( UInt uiIdx, UInt uiFlag){ m_puiAlfCtrlFlag[uiIdx] = uiFlag;   }
+  Void          setAlfCtrlFlagSubParts( UInt uiFlag, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void          createTmpAlfCtrlFlag  ();
+  Void          destroyTmpAlfCtrlFlag ();
+  Void          copyAlfCtrlFlagToTmp  ();
+  Void          copyAlfCtrlFlagFromTmp();
+  
+#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 );
+
+  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 HHI_INTER_VIEW_MOTION_PRED
+  Int           getPdmMergeCandidate( UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv );
+  Bool          getPdmMvPred( UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv, Bool bMerge = false );
+  Bool          getIViewOrgDepthMvPred( UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Bool          getResidualSamples( UInt uiPartIdx, TComYuv* pcYuv = 0 );
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for accessing partition information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          getPartIndexAndSize   ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight );
+  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 );
+  Void          fillMvpCand           ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo );
+#if DCM_SIMPLIFIED_MVP==0
+  Bool          clearMVPCand          ( TComMv cMvd, AMVPInfo* pInfo );
+#endif
+  Int           searchMVPIdx          ( TComMv cMv,  AMVPInfo* pInfo );
+
+  Void          setMVPIdx             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPIdx)  { m_apiMVPIdx[eRefPicList][uiIdx] = iMVPIdx;  }
+  Int           getMVPIdx             ( RefPicList eRefPicList, UInt uiIdx)               { return m_apiMVPIdx[eRefPicList][uiIdx];     }
+  Int*          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];     }
+  Int*          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(); }
+  
+#if AMVP_BUFFERCOMPRESS
+  Void          compressMV            ();
+#endif 
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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 );
+  TComDataCU*   getPUAbove                  ( UInt&  uiAPartUnitIdx , UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+  TComDataCU*   getPUAboveLeft              ( UInt&  uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+  TComDataCU*   getPUAboveRight             ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+  TComDataCU*   getPUBelowLeft              ( UInt& uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+
+#if CONSTRAINED_INTRA_PRED
+  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 );
+#else
+  TComDataCU*   getPUAboveRightAdi          ( UInt&  uiARPartUnitIdx, UInt uiPuWidth, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+  TComDataCU*   getPUBelowLeftAdi           ( UInt& uiBLPartUnitIdx, UInt uiPuHeight, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true, Bool bEnforceEntropySliceRestriction=true );
+#endif
+  
+  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 );
+  Bool          avoidMergeCandidate         ( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx );
+  Bool          hasEqualMotion              ( UInt uiAbsPartIdx, UInt uiCandInterDir, Int* paiCandRefIdx, TComMv* pacCandMv );
+  Bool          avoidMergeCandidate         ( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, UInt uiCandInterDir, Int* paiCandRefIdx, TComMv* pacCandMv );
+  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, UInt* puiNeighbourCandIdx );
+  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)
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Int           getMostProbableIntraDirLuma     ( UInt uiAbsPartIdx                                       );
+  
+  UInt          getIntraSizeIdx                 ( UInt uiAbsPartIdx                                       );
+  Void          convertTransIdx                 ( UInt uiAbsPartIdx, UInt uiTrIdx, UInt& ruiLumaTrMode, UInt& ruiChromaTrMode );
+  
+#if LCEC_INTRA_MODE
+  Int           getLeftIntraDirLuma             ( UInt uiAbsPartIdx );
+  Int           getAboveIntraDirLuma            ( UInt uiAbsPartIdx );
+#endif
+
+#if MTK_DCM_MPM
+  Int           getIntraDirLumaPredictor        ( UInt uiAbsPartIdx, Int uiIntraDirPred[]                 );
+#endif
+
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  Bool          isSuroundingRefIdxException     ( UInt   uiAbsPartIdx );
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for SBAC context
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          getCtxSplitFlag                 ( UInt   uiAbsPartIdx, UInt uiDepth                   );
+  UInt          getCtxCbf                       ( UInt   uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  UInt          getCtxQtCbf                     ( UInt   uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  UInt          getCtxQtRootCbf                 ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxRefIdx                    ( UInt   uiAbsPartIdx, RefPicList eRefPicList         );
+  UInt          getCtxSkipFlag                  ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxAlfCtrlFlag               ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxInterDir                  ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxIntraDirChroma            ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxMergeFlag                 ( UInt uiAbsPartIdx                                   );
+  
+  Void          setSliceStartCU  ( UInt uiStartCU )    { m_uiSliceStartCU = uiStartCU;    }  
+  UInt          getSliceStartCU  ()                    { return m_uiSliceStartCU;         }
+  Void          setEntropySliceStartCU ( UInt uiStartCU ) { m_uiEntropySliceStartCU = uiStartCU;     }  
+  UInt          getEntropySliceStartCU ()                 { return m_uiEntropySliceStartCU;          }
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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;    }
+
+#if QC_MDCS
+  UInt          getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra);
+#endif //QC_MDCS
+
+};
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComDepthMapGenerator.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComDepthMapGenerator.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComDepthMapGenerator.cpp	(revision 19)
@@ -0,0 +1,1449 @@
+/* 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_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 )
+{
+  destroy();
+  m_bDecoder            = bDecoder;
+  m_uiMaxDepth          = uiMaxCUDepth;
+  m_uiOrgDepthBitDepth  = uiOrgBitDepth;
+  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, uiHeight       );
+    m_ppcCU [ uiDepth ] = new TComDataCU; m_ppcCU [ uiDepth ]->create( uiNumPart, uiWidth, uiHeight, true );
+  }
+  m_cTmpPic.create( uiPicWidth, uiPicHeight, uiMaxCUWidth, uiMaxCUHeight, uiMaxCUDepth );
+  xSetChroma( &m_cTmpPic, ( 1 << uiOrgBitDepth ) >> 1 );
+  m_bCreated    = true;
+}
+
+Void
+TComDepthMapGenerator::destroy()
+{
+  if( m_bCreated )
+  {
+    m_bCreated    = false;
+    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_ppcYuv; m_ppcYuv = 0;
+    delete [] m_ppcCU;  m_ppcCU  = 0;
+    m_cTmpPic.destroy();
+    m_uiMaxDepth          = 0;
+    m_uiOrgDepthBitDepth  = 0;
+    m_bDecoder            = false;
+  }
+}
+
+Void
+TComDepthMapGenerator::init( TComPrediction* pcPrediction, TComSPSAccess* pcSPSAccess, TComAUPicAccess* pcAUPicAccess )
+{
+  AOF( pcPrediction  );
+  AOF( pcSPSAccess   );
+  AOF( pcAUPicAccess );
+  uninit();
+  m_pcPrediction  = pcPrediction;
+  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();
+
+  // update SPS list and AU pic list and set depth map generator in SPS
+  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_NUMBER_VIEWS;
+    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 )
+  {
+    Bool      bCheckVId1  = ( m_uiCurrViewId > 1 && m_auiBaseIdList[0] == 0 );
+    UInt      uiBaseVId   = ( bCheckVId1 ? 1 : m_auiBaseIdList[0] );
+    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
+}
+
+
+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 )
+      {
+        xClearDepthMap( pcBasePic );
+      }
+#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 );
+  }
+  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
+  xPredictDepthMap( pcPic );
+#if PDM_OUTPUT_PRED_DEPTH_MAP
+  if( m_uiCurrViewId )
+  {
+    dumpDepthMap( pcPic, acFilenameBase );
+  }
+#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
+  }
+}
+
+
+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   ();
+  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 )  );
+}
+
+
+#if HHI_INTER_VIEW_MOTION_PRED
+Void  
+TComDepthMapGenerator::covertOrgDepthMap( TComPic* pcPic )
+{
+  AOF  ( m_bCreated && m_bInit   );
+  AOF  ( pcPic );
+  ROFVS( pcPic->getOrgDepthMap() );
+  AOF  ( pcPic->getViewIdx() );
+
+  UInt  uiBaseId = pcPic->getViewIdx();
+  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 HHI_INTER_VIEW_MOTION_PRED
+Int
+TComDepthMapGenerator::getPdmMergeCandidate( TComDataCU* pcCU, UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv )
+{
+  Int  iMaxNumInterPics  = 1;
+  Int  iMaxNumAllPics    = 2;
+
+  // inter-only
+  Bool abPdmAvailable[2] = {false,false};
+  for( Int iRefListId = 0; iRefListId < 2; iRefListId++ )
+  {
+    RefPicList  eRefPicList       = RefPicList( iRefListId );
+    Int         iNumRefPics       = pcCU->getSlice()->getNumRefIdx( eRefPicList );
+    TComMv      cMv;
+    for( Int iPdmRefIdx = 0, iInterPics = 0; iPdmRefIdx < iNumRefPics && iInterPics < iMaxNumInterPics; iPdmRefIdx++ )
+    {
+      if( pcCU->getSlice()->getRefPOC( eRefPicList, iPdmRefIdx ) != pcCU->getSlice()->getPOC() )
+      {
+        if( getPdmMvPred( pcCU, uiPartIdx, eRefPicList, iPdmRefIdx, cMv, true ) )
+        {
+          pcCU->clipMv( cMv );
+          abPdmAvailable[ iRefListId ] = true;
+          paiPdmRefIdx  [ iRefListId ] = iPdmRefIdx;
+          pacPdmMv      [ iRefListId ] = cMv;
+          break;
+        }
+        iInterPics++;
+      }
+    }
+  }
+  Int    iPdmInterDir = ( abPdmAvailable[0] ? 1 : 0 ) + ( abPdmAvailable[1] ? 2 : 0 );
+  if( 0==iPdmInterDir )
+  { // check all, including inter view references
+    for( Int iRefListId = 0; iRefListId < 2; iRefListId++ )
+    {
+      RefPicList  eRefPicList = RefPicList( iRefListId );
+      Int         iNumRefPics = Min( iMaxNumAllPics, pcCU->getSlice()->getNumRefIdx( eRefPicList ) );
+      TComMv      cMv;
+      for( Int iPdmRefIdx = 0; iPdmRefIdx < iNumRefPics; iPdmRefIdx++ )
+      {
+        if( getPdmMvPred( pcCU, uiPartIdx, eRefPicList, iPdmRefIdx, cMv, true ) )
+        {
+          pcCU->clipMv( cMv );
+          abPdmAvailable[ iRefListId ] = true;
+          paiPdmRefIdx  [ iRefListId ] = iPdmRefIdx;
+          pacPdmMv      [ iRefListId ] = cMv;
+          break;
+        }
+      }
+    }
+    iPdmInterDir = ( abPdmAvailable[0] ? 1 : 0 ) + ( abPdmAvailable[1] ? 2 : 0 );
+  }
+  return iPdmInterDir;
+}
+
+
+Bool  
+TComDepthMapGenerator::getPdmMvPred( TComDataCU* pcCU, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv, Bool bMerge )
+{
+  AOF  ( m_bCreated && m_bInit );
+  AOF  ( iRefIdx >= 0 );
+  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 );
+  
+  TComPic*      pcRefPic    = pcSlice->getRefPic( eRefPicList, iRefIdx );
+  UInt          uiRefViewId = pcRefPic->getSPS()->getViewId();
+  Int           iRefPoc     = pcRefPic->getPOC();
+  Bool          bInterview  = ( uiRefViewId < m_uiCurrViewId );
+  AOT(  bInterview && iRefPoc != pcSlice->getPOC() );
+  AOT( !bInterview && iRefPoc == pcSlice->getPOC() );
+
+  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 );
+  ROTRS( ( bInterview && !bMerge ) && !bPdmIView, false );
+  ROTRS( (!bInterview && !bMerge ) && !bPdmInter, false );
+  ROTRS(                  bMerge   && !bPdmMerge, false );
+
+  //===== get predicted depth for middle position of current PU =====  
+  Int  iPrdDepth, iCurrPosX, iCurrPosY;
+  Bool bAvailable  = xGetPredDepth( pcCU, uiPartIdx, iPrdDepth, &iCurrPosX, &iCurrPosY );
+  AOF( bAvailable );
+  
+  //===== inter-view motion vector prediction =====
+  if( bInterview )
+  {
+    Int         iDisparity  = xGetDisparityFromVirtDepth( uiRefViewId, iPrdDepth );
+    rcMv.set  ( iDisparity, 0 );
+    return      true;
+  }
+  
+  //===== inter motion vector prediction =====
+  for( UInt uiBId = 0; uiBId < m_uiCurrViewId; uiBId++ )
+  {
+    //--- get base CU/PU and check prediction mode ---
+    UInt        uiBaseId    = m_auiBaseIdList[ uiBId ];
+    TComPic*    pcBasePic   = m_pcAUPicAccess->getPic( uiBaseId );
+    TComPicYuv* pcBasePdm   = pcBasePic->getPredDepthMap();
+    TComPicYuv* pcBaseRec   = pcBasePic->getPicYuvRec   ();
+    Int         iDisparity  = xGetDisparityFromVirtDepth( uiBaseId, iPrdDepth );
+    Int         iBasePosX   = Clip3( 0, pcBasePdm->getWidth () - 1, iCurrPosX + ( ( iDisparity + 2 ) >> 2 ) );
+    Int         iBasePosY   = Clip3( 0, pcBasePdm->getHeight() - 1, iCurrPosY                               );
+    Int         iBaseCUAddr;
+    Int         iBaseAbsPartIdx;
+    pcBaseRec->getCUAddrAndPartIdx( iBasePosX, iBasePosY, iBaseCUAddr, iBaseAbsPartIdx );
+    TComDataCU* pcBaseCU    = pcBasePic->getCU( iBaseCUAddr );
+    if( pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) != MODE_INTER && pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) != MODE_SKIP )
+    {
+      continue;
+    }
+
+    for( UInt uiBaseRefListId = 0; uiBaseRefListId < 2; uiBaseRefListId++ )
+    {
+      RefPicList  eBaseRefPicList = RefPicList( uiBaseRefListId );
+      TComMvField cBaseMvField;
+      pcBaseCU->getMvField( pcBaseCU, iBaseAbsPartIdx, eBaseRefPicList, cBaseMvField );
+      Int         iBaseRefIdx     = cBaseMvField.getRefIdx();
+      Int         iBaseRefPoc     = ( iBaseRefIdx >= 0 ? pcBaseCU->getSlice()->getRefPic( eBaseRefPicList, iBaseRefIdx )->getPOC() : -(1<<30) );
+      if( iBaseRefIdx >= 0 && iBaseRefPoc == iRefPoc )
+      {
+        rcMv.set( cBaseMvField.getHor(), cBaseMvField.getVer() );
+        return true;
+      }
+    }
+  }
+  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
+
+
+
+
+
+
+/*=======================================================*
+ *=====                                             =====*
+ *=====     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() );
+
+  xClearDepthMap( pcRef );
+  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->getViewIdx();
+  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 + 2 ) >> 2 );
+      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() );
+  AOF( pcRef->getPredDepthMap() );
+  AOF( pcRef->getPredDepthMap()->getWidth () == pcCur->getPredDepthMap()->getWidth () );
+  AOF( pcRef->getPredDepthMap()->getHeight() == pcCur->getPredDepthMap()->getHeight() );
+
+  xClearDepthMap( pcCur );
+  TComPicYuv* pcRefDepthMap =  pcRef->getPredDepthMap    ();
+  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->getViewIdx();
+  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 + 2 ) >> 2 );
+      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 );
+  pcPic->getPredDepthMap()->setBorderExtension( false );
+  pcPic->getPredDepthMap()->extendPicBorder   ();
+  return  bUndefined;
+}
+
+
+Bool
+TComDepthMapGenerator::xFillDepthMapHoles( TComPic* pcPic )
+{
+  Bool        bUndefined  = false;      
+  TComPicYuv* pcDepthMap  = pcPic->getPredDepthMap  ();
+  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 )
+{
+  TComPicYuv* pcDepthMap  = pcPic->getPredDepthMap  ();
+  Int         iWidth      = pcDepthMap->getWidth    ();
+  Int         iHeight     = pcDepthMap->getHeight   ();
+  Int         iStride     = pcDepthMap->getStride   ();
+  Pel*        pDMSamples  = pcDepthMap->getLumaAddr ( 0 );
+  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()->getWidth() || uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() );
+  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()->getWidth() && uiTPelY < pcCU->getSlice()->getSPS()->getHeight() );
+      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();
+  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;
+    UInt  uiHeight        = pcCU->getHeight( 0 ) >> uiTrDepth;
+    UInt  uiStride        = pcCUDepthMap->getStride  ();
+    Pel*  pDepthMap       = pcCUDepthMap->getLumaAddr( uiAbsPartIdx );
+    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, true );
+    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 );
+    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 );
+
+  // 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_NUMBER_VIEWS ); 
+    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 ) >> 2;
+  }
+  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
+  Pel*  pDMSamples  = pcCUDepthMap->getLumaAddr( uiAbsPartIdx );
+  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;
+  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();
+
+  //===== 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 );
+      Int               iCurrBlkPosY        = iCurrPUPosY + ( i4x4BlkY << 2 );
+      Int               iCurrSamplePosX     = iCurrBlkPosX + 1;
+      Int               iCurrSamplePosY     = iCurrBlkPosY + 1;
+      Int               iCurrPredDepth      = piCurrDepthMap[ iCurrSamplePosY * iCurrStride + iCurrSamplePosX ];
+      Int               iCurrPredDisp       = xGetDisparityFromVirtDepth( uiBaseId, iCurrPredDepth );
+      Int               iBaseSamplePosX     = iCurrSamplePosX + ( ( iCurrPredDisp + 2 ) >> 2 );
+      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, iBaseSamplePosY, 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() + 2 ) >> 2 );
+        Int             iCurrRefSamplePosY  = iCurrSamplePosY + ( ( rcCurrMv.getVer() + 2 ) >> 2 );
+        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 + 2 ) >> 2 );
+            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;
+        Int             iCurrSamplePosY     = iCurrPUPosY + ( i4x4BlkY << 2 ) + 1;
+        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 =====
+  Pel* piDepthMap = pcCUDepthMap->getLumaAddr( uiAbsPartIdx );
+  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 >> 2 ][ iCol >> 2 ];
+    }
+  }
+}
+
+
+Void
+TComDepthMapGenerator::xInterPUDepthMapPrediction( TComDataCU* pcCU, TComYuv* pcCUDepthMap, UInt uiPartIdx )
+{
+  m_pcPrediction->motionCompensation( pcCU, pcCUDepthMap, REF_PIC_LIST_X, (Int)uiPartIdx, true );  
+}
+
+
+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 );
+  iCurrPosX  += ( iWidth  - 1 ) >> 1;
+  iCurrPosY  += ( iHeight - 1 ) >> 1;
+  riPrdDepth  = piPredDepthMap[ iCurrPosX + iCurrPosY * iCurrStride ];
+  if( piPosX )
+  {
+    *piPosX   = iCurrPosX;
+  }
+  if( piPosY )
+  {
+    *piPosY   = iCurrPosY;
+  }
+  return        true;
+}
+
+#endif // DEPTH_MAP_GENERATION
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComDepthMapGenerator.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComDepthMapGenerator.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComDepthMapGenerator.h	(revision 19)
@@ -0,0 +1,227 @@
+/* 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
+
+
+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 HHI_INTER_VIEW_RESIDUAL_PRED
+  UInt      getResPrd ()                          { if( m_aacActiveSPS[0][1] ) { return m_aacActiveSPS[0][1]->getMultiviewResPredMode  (); } return 0; }
+#endif
+
+private:
+  TComSPS*  m_aacActiveSPS[ 2 ][ MAX_NUMBER_VIEWS ];
+};
+
+
+
+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_NUMBER_VIEWS ];
+};
+
+
+
+class TComDepthMapGenerator
+{
+public:
+  TComDepthMapGenerator ();
+  ~TComDepthMapGenerator();
+
+  Void  create                ( Bool bDecoder, UInt uiPicWidth, UInt uiPicHeight, UInt uiMaxCUDepth, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiOrgBitDepth );
+  Void  destroy               ();
+
+  Void  init                  ( TComPrediction* pcPrediction, TComSPSAccess* pcSPSAccess, TComAUPicAccess* pcAUPicAccess );
+  Void  uninit                ();
+
+  Void  initViewComponent     ( TComPic*      pcPic );
+  Bool  predictDepthMap       ( TComPic*      pcPic );
+  Void  updateDepthMap        ( TComPic*      pcPic );
+  Void  dumpDepthMap          ( TComPic*      pcPic, char* pFilenameBase );
+
+#if HHI_INTER_VIEW_MOTION_PRED
+  Void  covertOrgDepthMap     ( TComPic*      pcPic );
+#endif
+
+  UInt  getBaseViewId         ( UInt          uiIdx ) { AOF( uiIdx < m_auiBaseIdList.size() );  return m_auiBaseIdList[uiIdx]; }
+  Int   getDisparity          ( TComPic*      pcPic, Int iPosX, Int iPosY, UInt uiRefViewId );
+#if HHI_INTER_VIEW_MOTION_PRED
+  Int   getPdmMergeCandidate  ( TComDataCU*   pcCU, UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv );
+  Bool  getPdmMvPred          ( TComDataCU*   pcCU, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv, Bool bMerge );
+  Bool  getIViewOrgDepthMvPred( TComDataCU*   pcCU, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMv );
+#endif
+
+  TComPrediction*   getPrediction ()  { return m_pcPrediction;  }
+  TComSPSAccess*    getSPSAccess  ()  { return m_pcSPSAccess;   }
+  TComAUPicAccess*  getAUPicAccess()  { return m_pcAUPicAccess; }
+
+private:
+  // picture operations
+  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 );
+  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 );
+
+  // 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;
+  TComSPSAccess*    m_pcSPSAccess;
+  TComAUPicAccess*  m_pcAUPicAccess;
+  UInt              m_uiMaxDepth;
+  UInt              m_uiOrgDepthBitDepth;
+  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_NUMBER_VIEWS ][ 3 ];  // disparity      ==> virtual  depth   (0:scale, 1:add, 2:shift)
+  Int               m_aaiConvParsVirtDepth2Disparity[ MAX_NUMBER_VIEWS ][ 3 ];  // virtual  depth ==> disparity        (0:scale, 1:add, 2:shift)
+  Int               m_aaiConvParsOrigDepth2VirtDepth[ MAX_NUMBER_VIEWS ][ 3 ];  // original depth ==> virtual  depth   (0:scale, 1:add, 2:shift)
+  Int               m_aaiConvParsVirtDepth2OrigDepth[ MAX_NUMBER_VIEWS ][ 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: /tags/0.2r1/source/Lib/TLibCommon/TComList.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComList.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComList.h	(revision 19)
@@ -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-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     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;
+
+// ====================================================================================================================
+// 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: /tags/0.2r1/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 19)
@@ -0,0 +1,968 @@
+/* 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     TComLoopFilter.cpp
+    \brief    deblocking filter
+*/
+
+#include "TComLoopFilter.h"
+#include "TComSlice.h"
+#include "TComMv.h"
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define   EDGE_VER    0
+#define   EDGE_HOR    1
+#define   QpUV(iQpY)  ( g_aucChromaScale[ Max( Min( (iQpY), MAX_QP ), MIN_QP ) ] )
+
+
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+#define   DECIDE_FILTER                0
+#define   EXECUTE_FILTER               1
+#define   DECIDE_AND_EXECUTE_FILTER    2
+#endif
+
+
+
+// ====================================================================================================================
+// 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;
+}
+
+TComLoopFilter::~TComLoopFilter()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TComLoopFilter::setCfg( UInt uiDisableDblkIdc, Int iAlphaOffset, Int iBetaOffset)
+{
+  m_uiDisableDeblockingFilterIdc  = uiDisableDblkIdc;
+}
+
+Void TComLoopFilter::create( UInt uiMaxCUDepth )
+{
+  m_uiNumPartitions = 1 << ( uiMaxCUDepth<<1 );
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    for( UInt uiPlane = 0; uiPlane < 3; uiPlane++ )
+    {
+      m_aapucBS       [uiDir][uiPlane] = new UChar[m_uiNumPartitions];
+      m_aapbEdgeFilter[uiDir][uiPlane] = new Bool [m_uiNumPartitions];
+    }
+  }
+}
+
+Void TComLoopFilter::destroy()
+{
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    for( UInt uiPlane = 0; uiPlane < 3; uiPlane++ )
+    {
+      delete [] m_aapucBS       [uiDir][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;
+  
+#if PARALLEL_MERGED_DEBLK
+  // add extra buffer and copy pic
+  pcPic->addDeblockBuffer();
+  pcPic->getPicYuvRec()->copyToPicLuma(pcPic->getPicYuvDeblkBuf());
+
+  // Horizontal filtering
+  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+
+    for( Int iPlane = 0; iPlane < 3; iPlane++ )
+    {
+      ::memset( m_aapucBS       [EDGE_VER][iPlane], 0, sizeof( UChar ) * m_uiNumPartitions );
+      assert( 0 == false );
+      ::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 );
+
+    for( Int iPlane = 0; iPlane < 3; iPlane++ )
+    {
+      ::memset( m_aapucBS       [EDGE_HOR][iPlane], 0, sizeof( UChar ) * m_uiNumPartitions );
+      assert( 0 == false );
+      ::memset( m_aapbEdgeFilter[EDGE_HOR][iPlane], 0, sizeof( bool  ) * m_uiNumPartitions );
+    }
+
+    // CU-based deblocking
+    xDeblockCU( pcCU, 0, 0, EDGE_HOR );
+  }
+
+  // remove extra pic buffer
+  pcPic->removeDeblockBuffer();
+#else
+  // for every CU
+  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+    
+    for( Int iDir = EDGE_VER; iDir <= EDGE_HOR; iDir++ )
+    {
+      for( Int iPlane = 0; iPlane < 3; iPlane++ )
+      {
+        ::memset( m_aapucBS       [iDir][iPlane], 0, sizeof( UChar ) * m_uiNumPartitions );
+        assert( 0 == false );
+        ::memset( m_aapbEdgeFilter[iDir][iPlane], 0, sizeof( bool  ) * m_uiNumPartitions );
+      }
+    }
+    // CU-based deblocking
+    xDeblockCU( pcCU, 0, 0 );
+  }
+#endif
+}
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+#if PARALLEL_MERGED_DEBLK
+/**
+ - 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 )
+#else
+Void TComLoopFilter::xDeblockCU( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth )
+#endif
+{
+  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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+#if PARALLEL_MERGED_DEBLK
+        xDeblockCU( pcCU, uiAbsZorderIdx, uiDepth+1, Edge );
+#else
+        xDeblockCU( pcCU, uiAbsZorderIdx, uiDepth+1 );
+#endif
+    }
+    return;
+  }
+  
+  xSetLoopfilterParam( pcCU, uiAbsZorderIdx );
+  
+  xSetEdgefilterTU   ( pcCU, uiAbsZorderIdx, uiDepth );
+  xSetEdgefilterPU   ( pcCU, uiAbsZorderIdx );
+  
+#if PARALLEL_MERGED_DEBLK
+  Int iDir = Edge;
+#else
+  for ( Int iDir = EDGE_VER; iDir <= EDGE_HOR; iDir++ )
+#endif
+  {
+    for( UInt uiPartIdx = uiAbsZorderIdx; uiPartIdx < uiAbsZorderIdx + uiCurNumParts; uiPartIdx++ )
+    {
+      if ( m_aapbEdgeFilter[iDir][0][uiPartIdx] )
+      {
+        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);
+  
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+  for ( UInt iEdge = 0; iEdge < uiSizeInPU ; iEdge+=PartIdxIncr)
+  {
+    xEdgeFilterLuma     ( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, iEdge, DECIDE_FILTER);//Decide horizontal filter
+  }
+  for ( UInt iEdge = 0; iEdge < uiSizeInPU ; iEdge+=PartIdxIncr)
+  {
+    xEdgeFilterLuma     ( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, iEdge, DECIDE_AND_EXECUTE_FILTER);//Decide vertical filter
+    if ( (iEdge % ( (DEBLOCK_SMALLEST_BLOCK<<1)/uiPelsInPart ) ) == 0 )
+    {
+      xEdgeFilterChroma   ( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, iEdge );
+    }
+  }  
+  for ( UInt iEdge = 0; iEdge < uiSizeInPU ; iEdge+=PartIdxIncr)
+  {
+    xEdgeFilterLuma     ( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, iEdge, EXECUTE_FILTER );//Execute horizontal filter
+    if ( (iEdge % ( (DEBLOCK_SMALLEST_BLOCK<<1)/uiPelsInPart ) ) == 0 )
+    {
+      xEdgeFilterChroma   ( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, iEdge );
+    }
+  }  
+#else  
+#if !PARALLEL_MERGED_DEBLK
+  for ( Int iDir = EDGE_VER; iDir <= EDGE_HOR; iDir++ )
+#endif
+  {
+    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 );
+    }
+  }
+#endif  
+}
+
+Void TComLoopFilter::xSetEdgefilterMultiple( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdgeIdx, Bool bValue )
+{
+  const UInt uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
+  const UInt uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> uiDepth;
+  const UInt uiNumElem = iDir == 0 ? uiHeightInBaseUnits : uiWidthInBaseUnits;
+  assert( uiNumElem > 0 );
+  for( UInt ui = 0; ui < uiNumElem; ui++ )
+  {
+    const UInt uiBsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdgeIdx, ui );
+    m_aapbEdgeFilter[iDir][0][uiBsIdx] = bValue;
+    m_aapbEdgeFilter[iDir][1][uiBsIdx] = bValue;
+    m_aapbEdgeFilter[iDir][2][uiBsIdx] = bValue;
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterTU( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth )
+{
+  if( pcCU->getTransformIdx( uiAbsZorderIdx ) + pcCU->getDepth( uiAbsZorderIdx) > uiDepth )
+  {
+    const UInt uiCurNumParts = pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1);
+    const UInt uiQNumParts   = uiCurNumParts>>2;
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      xSetEdgefilterTU( pcCU, uiAbsZorderIdx, uiDepth+1 );
+    }
+    return;
+  }
+  xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, 0, m_stLFCUParam.bInternalEdge );
+  xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, 0, m_stLFCUParam.bInternalEdge );
+}
+
+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;
+  
+  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;
+    }
+    default:
+    {
+      assert(0);
+      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 ] ];
+  
+#if MTK_NONCROSS_INLOOP_FILTER
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+#endif
+
+  m_stLFCUParam.bInternalEdge = m_uiDisableDeblockingFilterIdc ? false : true ;
+  
+  if ( (uiX == 0) || (m_uiDisableDeblockingFilterIdc == 1) )
+    m_stLFCUParam.bLeftEdge = false;
+  else
+    m_stLFCUParam.bLeftEdge = true;
+#if MTK_NONCROSS_INLOOP_FILTER
+  if ( m_stLFCUParam.bLeftEdge )
+  {
+    pcTempCU = pcCU->getPULeft( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false );
+    if ( pcTempCU )
+      m_stLFCUParam.bLeftEdge = true;
+    else
+      m_stLFCUParam.bLeftEdge = false;
+  }
+#endif
+  
+  if ( (uiY == 0 ) || (m_uiDisableDeblockingFilterIdc == 1) )
+    m_stLFCUParam.bTopEdge = false;
+  else
+    m_stLFCUParam.bTopEdge = true;
+#if MTK_NONCROSS_INLOOP_FILTER
+  if ( m_stLFCUParam.bTopEdge )
+  {
+    pcTempCU = pcCU->getPUAbove( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false );
+    if ( pcTempCU )
+      m_stLFCUParam.bTopEdge = true;
+    else
+      m_stLFCUParam.bTopEdge = false;
+  }
+#endif
+}
+
+Void TComLoopFilter::xGetBoundaryStrengthSingle ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, UInt uiAbsPartIdx )
+{
+  const UInt uiHWidth  = pcCU->getWidth( uiAbsZorderIdx ) >> 1;
+  const UInt uiHHeight = pcCU->getHeight( uiAbsZorderIdx ) >> 1;
+  const bool bAtCUBoundary = iDir == EDGE_VER ? g_auiRasterToPelX[g_auiZscanToRaster[uiAbsZorderIdx]] == g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIdx]]
+  : g_auiRasterToPelY[g_auiZscanToRaster[uiAbsZorderIdx]] == g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIdx]];
+  const bool bAtCUHalf     = iDir == EDGE_VER ? ( g_auiRasterToPelX[g_auiZscanToRaster[uiAbsZorderIdx]] + uiHWidth ) == g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIdx]]
+  : ( g_auiRasterToPelY[g_auiZscanToRaster[uiAbsZorderIdx]] + uiHHeight ) == g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIdx]];
+  TComSlice* const pcSlice = pcCU->getSlice();
+  
+  const UInt uiPartQ = uiAbsPartIdx;
+  TComDataCU* const pcCUQ = pcCU;
+  
+  UInt uiPartP;
+  TComDataCU* pcCUP;
+  UInt uiBs;
+  
+#if MTK_NONCROSS_INLOOP_FILTER
+  //-- Calculate Block Index
+  if (iDir == EDGE_VER)
+  {
+    pcCUP = pcCUQ->getPULeft(uiPartP, uiPartQ, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false);
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getSPS()->getLFCrossSliceBoundaryFlag(), false);
+  }
+#else
+  //-- Calculate Block Index
+  if (iDir == EDGE_VER)
+  {
+    pcCUP = pcCUQ->getPULeft(uiPartP, uiPartQ, false, false);
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, false, false);
+  }
+#endif
+  
+  //-- Set BS for Intra MB : BS = 4 or 3
+  if ( pcCUP->isIntra(uiPartP) || pcCUQ->isIntra(uiPartQ) )
+  {
+    uiBs = bAtCUBoundary ? 4 : 3;   // Intra MB && MB boundary
+  }
+  
+  //-- Set BS for not Intra MB : BS = 2 or 1 or 0
+  if ( !pcCUP->isIntra(uiPartP) && !pcCUQ->isIntra(uiPartQ) )
+  {
+    if ( pcCUQ->getCbf( uiPartQ, TEXT_LUMA, pcCUQ->getTransformIdx(uiPartQ)) != 0 || pcCUP->getCbf( uiPartP, TEXT_LUMA, pcCUP->getTransformIdx(uiPartP) ) != 0)
+    {
+      uiBs = 2;
+    }
+    else
+    {
+      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 )"
+  
+  m_aapucBS[iDir][0][uiAbsPartIdx] = uiBs;
+  if ( bAtCUBoundary || bAtCUHalf )
+  {
+    m_aapucBS[iDir][1][uiAbsPartIdx] = uiBs;
+    m_aapucBS[iDir][2][uiAbsPartIdx] = uiBs;
+  }
+}
+
+
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+Void TComLoopFilter::xEdgeFilterLuma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge, Int iDecideExecute )
+#else
+Void TComLoopFilter::xEdgeFilterLuma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge  )
+#endif
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Pel* piSrc    = pcPicYuvRec->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx );
+  Pel* piTmpSrc = piSrc;
+#if PARALLEL_MERGED_DEBLK
+  TComPicYuv* pcPicYuvJudge = pcCU->getPic()->getPicYuvDeblkBuf();
+  Pel* piSrcJudge    = pcPicYuvJudge->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx );
+  Pel* piTmpSrcJudge = piSrcJudge;
+#endif
+
+  Int  iStride = pcPicYuvRec->getStride();
+  Int  iQP = pcCU->getQP( uiAbsZorderIdx );
+  UInt uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
+  
+  UInt  uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt  PartIdxIncr = DEBLOCK_SMALLEST_BLOCK / uiPelsInPart ? DEBLOCK_SMALLEST_BLOCK / uiPelsInPart : 1;
+  UInt  uiBlocksInPart = uiPelsInPart / DEBLOCK_SMALLEST_BLOCK ? uiPelsInPart / DEBLOCK_SMALLEST_BLOCK : 1;
+  UInt  uiBsAbsIdx, uiBs;
+  Int   iOffset, iSrcStep;
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+  Pel*  piTmpSrc1;
+  UInt* piDecisions_D;
+  UInt* piDecisions_Sample;
+#endif  
+  if (iDir == EDGE_VER)
+  {
+    iOffset = 1;
+    iSrcStep = iStride;
+    piTmpSrc += iEdge*uiPelsInPart;
+#if PARALLEL_MERGED_DEBLK
+    piTmpSrcJudge += iEdge*uiPelsInPart;
+#endif
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    iOffset = iStride;
+    iSrcStep = 1;
+    piTmpSrc += iEdge*uiPelsInPart*iStride;
+#if PARALLEL_MERGED_DEBLK
+    piTmpSrcJudge += iEdge*uiPelsInPart*iStride;
+#endif
+  }
+  
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx+=PartIdxIncr )
+  {
+    
+    uiBs = 0;
+    for (UInt iIdxInside = 0; iIdxInside<PartIdxIncr; iIdxInside++)
+    {
+      uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx+iIdxInside);
+      if (uiBs < m_aapucBS[iDir][0][uiBsAbsIdx])
+      {
+        uiBs = m_aapucBS[iDir][0][uiBsAbsIdx];
+      }
+    }
+    
+    Int iBitdepthScale = (1<<(g_uiBitIncrement+g_uiBitDepth-8));
+    
+    UInt uiTcOffset = (uiBs>2)?4:0;
+    
+    Int iIndexTC = Clip3(0, MAX_QP+4, iQP + uiTcOffset );
+    Int iIndexB = Clip3(0, MAX_QP, iQP );
+    
+    Int iTc =  tctable_8x8[iIndexTC]*iBitdepthScale;
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+    if (iDecideExecute==DECIDE_AND_EXECUTE_FILTER && uiBs)
+    {
+      Int iBeta = betatable_8x8[iIndexB]*iBitdepthScale;
+      
+      for (UInt iBlkIdx = 0; iBlkIdx< uiBlocksInPart; iBlkIdx ++)
+      {
+        Int iTmp=iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK;
+        Int iD = xCalcD( piTmpSrc+iSrcStep*(iTmp+2), iOffset) + xCalcD( piTmpSrc+iSrcStep*(iTmp+5), iOffset);
+        
+        if (iD < iBeta)
+        {
+          for ( UInt i = 0; i < DEBLOCK_SMALLEST_BLOCK; i++)
+          {
+            xPelFilterLuma( piTmpSrc+iSrcStep*(iTmp+i), iOffset, iD, iBeta, iTc);
+          }
+        }
+      }      
+    }
+    else if (iDecideExecute==DECIDE_FILTER && uiBs)
+    {
+      Int iBeta = betatable_8x8[iIndexB]*iBitdepthScale;
+      
+      piDecisions_D      = (iIdx*uiPelsInPart)/DEBLOCK_SMALLEST_BLOCK + m_decisions_D     [(iEdge*uiPelsInPart)/DEBLOCK_SMALLEST_BLOCK];
+      piDecisions_Sample =  iIdx*uiPelsInPart                         + m_decisions_Sample[(iEdge*uiPelsInPart)/DEBLOCK_SMALLEST_BLOCK];
+      
+      for (UInt iBlkIdx = 0; iBlkIdx< uiBlocksInPart; iBlkIdx ++)
+      {
+        Int iTmp=iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK;
+        Int iD = xCalcD( piTmpSrc+(iTmp+2), iOffset) + xCalcD( piTmpSrc+(iTmp+5), iOffset);
+        piTmpSrc1 = piTmpSrc+iTmp;
+        
+        if (iD < iBeta)
+        {
+          *piDecisions_D++=1;
+          for ( UInt i = 0; i < DEBLOCK_SMALLEST_BLOCK; i++)
+          {
+            *piDecisions_Sample++ = xPelFilterLumaDecision( piTmpSrc1++, iOffset, iD, iBeta, iTc);
+          }
+        }
+        else
+        {
+          *piDecisions_D++=0;
+          piDecisions_Sample+=DEBLOCK_SMALLEST_BLOCK;
+        }
+      }
+    }
+    else if ( uiBs ) // EXECUTE_FILTER
+    {
+      piDecisions_D      = (iIdx*uiPelsInPart)/DEBLOCK_SMALLEST_BLOCK + m_decisions_D     [(iEdge*uiPelsInPart)/DEBLOCK_SMALLEST_BLOCK];
+      piDecisions_Sample =  iIdx*uiPelsInPart                         + m_decisions_Sample[(iEdge*uiPelsInPart)/DEBLOCK_SMALLEST_BLOCK];
+      piTmpSrc1          = piTmpSrc+iIdx*uiPelsInPart;
+      
+      for (UInt iBlkIdx = 0; iBlkIdx< uiBlocksInPart; iBlkIdx ++)
+      {
+        if ( *piDecisions_D++ )
+        {
+          for ( UInt i = 0; i < DEBLOCK_SMALLEST_BLOCK; i++)
+          {
+            xPelFilterLumaExecution( piTmpSrc1++, iOffset, iTc, *piDecisions_Sample++  );
+          }
+        }
+        else
+        {
+          piDecisions_Sample+=DEBLOCK_SMALLEST_BLOCK;
+          piTmpSrc1+=DEBLOCK_SMALLEST_BLOCK;
+        }
+      }
+    }
+#else
+    Int iBeta = betatable_8x8[iIndexB]*iBitdepthScale;
+    
+    
+    for (UInt iBlkIdx = 0; iBlkIdx< uiBlocksInPart; iBlkIdx ++)
+    {
+      if ( uiBs )
+      {
+#if PARALLEL_MERGED_DEBLK
+        Int iD = xCalcD( piTmpSrcJudge+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK+2), iOffset) + xCalcD( piTmpSrcJudge+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK+5), iOffset);
+#else  
+        Int iD = xCalcD( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK+2), iOffset) + xCalcD( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK+5), iOffset);
+#endif
+        if (iD < iBeta)
+        {
+          for ( UInt i = 0; i < DEBLOCK_SMALLEST_BLOCK; i++)
+          {
+#if PARALLEL_MERGED_DEBLK
+            xPelFilterLuma( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK+i), iOffset, iD, iBeta, iTc , piTmpSrcJudge+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK+i));
+#else           
+            xPelFilterLuma( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*DEBLOCK_SMALLEST_BLOCK+i), iOffset, iD, iBeta, iTc );
+#endif
+          }
+        }
+      }
+    }
+#endif
+  }
+}
+
+
+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 = QpUV((Int) pcCU->getQP( uiAbsZorderIdx ));
+  UInt  uiPelsInPartChroma = g_uiMaxCUWidth >> (g_uiMaxCUDepth+1);
+  
+  Int   iOffset, iSrcStep;
+  
+  const UInt uiLCUWidthInBaseUnits = pcCU->getPic()->getNumPartInWidth();
+  
+  // 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][0][uiBsAbsIdx];
+    
+    Int iBitdepthScale = (1<<(g_uiBitIncrement+g_uiBitDepth-8));
+    
+    UInt uiTcOffset = (ucBs>2)?4:0;
+    
+    Int iIndexTC = Clip3(0, MAX_QP+4, iQP + uiTcOffset );
+    
+    Int iTc =  tctable_8x8[iIndexTC]*iBitdepthScale;
+    
+    if ( ucBs > 2)
+    {
+      for ( UInt uiStep = 0; uiStep < uiPelsInPartChroma; uiStep++ )
+      {
+        xPelFilterChroma( piTmpSrcCb + iSrcStep*(uiStep+iIdx*uiPelsInPartChroma), iOffset, iTc );
+        xPelFilterChroma( piTmpSrcCr + iSrcStep*(uiStep+iIdx*uiPelsInPartChroma), iOffset, iTc );
+      }
+    }
+  }
+}
+
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+/**
+ - Decision for one line/column for the luminance component to use strong or weak deblocking
+ .
+ \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
+
+ \returns decision to use strong or weak deblocking
+ */
+__inline Int TComLoopFilter::xPelFilterLumaDecision( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc)
+{
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-iOffset];
+  
+  if ( ((abs(piSrc[-iOffset*4]-m3) + abs(piSrc[ iOffset*3]-m4)) < (beta>>3)) && (d<(beta>>2)) && ( abs(m3-m4) < ((tc*5+1)>>1)) ) //strong filtering
+  {
+    return 1;
+  }
+  else //weak filtering
+  {
+    return 0;
+  }
+}
+
+
+/**
+ - Strong deblocking of one line/column for the luminance component
+ .
+ \param piSrc         pointer to picture data
+ \param iOffset       offset value for picture data
+ \param m0            sample value
+ \param m1            sample value
+ \param m2            sample value
+ \param m3            sample value
+ \param m4            sample value
+ \param m5            sample value
+ \param m6            sample value
+ \param m7            sample value
+ */
+__inline Void TComLoopFilter::xPelFilterLumaStrong(Pel* piSrc, Int iOffset, Pel m0, Pel m1, Pel m2, Pel m3, Pel m4, Pel m5, Pel m6, Pel m7)
+{
+  piSrc[-iOffset] = Clip(( m1 + 2*m2 + 2*m3 + 2*m4 + m5 + 4) >> 3 );
+  piSrc[0] = Clip(( m2 + 2*m3 + 2*m4 + 2*m5 + m6 + 4) >> 3 );
+
+  piSrc[-iOffset*2] = Clip(( m1 + m2 + m3 + m4 + 2)>>2);
+  piSrc[ iOffset] = Clip(( m3 + m4 + m5 + m6 + 2)>>2);
+
+  piSrc[-iOffset*3] = Clip(( 2*m0 + 3*m1 + m2 + m3 + m4 + 4 )>>3);
+  piSrc[ iOffset*2] = Clip(( m3 + m4 + m5 + 3*m6 + 2*m7 +4 )>>3);  
+}
+
+/**
+ - Weak deblocking of one line/column for the luminance component
+ .
+ \param piSrc         pointer to picture data
+ \param iOffset       offset value for picture data
+ \param tc            tc value
+ \param m1            sample value
+ \param m2            sample value
+ \param m3            sample value
+ \param m4            sample value
+ \param m5            sample value
+ \param m6            sample value
+ */
+__inline Void TComLoopFilter::xPelFilterLumaWeak(Pel* piSrc, Int iOffset, Int tc, Pel m1, Pel m2, Pel m3, Pel m4, Pel m5, Pel m6)
+{
+  Int delta = Clip3(-tc, tc, ((13*(m4-m3) + 4*(m5-m2) - 5*(m6-m1)+16)>>5) );
+
+  piSrc[-iOffset] = Clip(m3+delta);
+  piSrc[0] = Clip(m4-delta);
+  piSrc[-iOffset*2] = Clip(m2+delta/2);
+  piSrc[ iOffset] = Clip(m5-delta/2);
+}
+#endif
+
+#if PARALLEL_MERGED_DEBLK
+/**
+ - Deblocking for the luminance component with strong or weak filter
+ .
+ \param piSrcJudge    pointer to picture data for decision
+*/
+__inline Void TComLoopFilter::xPelFilterLuma( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc , Pel* piSrcJudge)
+#else
+__inline Void TComLoopFilter::xPelFilterLuma( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc )
+#endif
+{
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+  Int d_strong;
+#else  
+  Int d_strong, delta;
+#endif
+  
+  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 PARALLEL_MERGED_DEBLK
+  Pel m4j  = piSrcJudge[0];
+  Pel m3j  = piSrcJudge[-iOffset];
+  Pel m7j  = piSrcJudge[ iOffset*3];
+  Pel m0j  = piSrcJudge[-iOffset*4];
+
+  d_strong = abs(m0j-m3j) + abs(m7j-m4j);
+
+  if ( (d_strong < (beta>>3)) && (d<(beta>>2)) && ( abs(m3j-m4j) < ((tc*5+1)>>1)) ) //strong filtering
+#else
+  d_strong = abs(m0-m3) + abs(m7-m4);
+  
+  if ( (d_strong < (beta>>3)) && (d<(beta>>2)) && ( abs(m3-m4) < ((tc*5+1)>>1)) ) //strong filtering
+#endif
+  {
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+    xPelFilterLumaStrong(piSrc, iOffset, m0, m1, m2, m3, m4, m5, m6, m7);
+#else  
+    piSrc[-iOffset] = Clip(( m1 + 2*m2 + 2*m3 + 2*m4 + m5 + 4) >> 3 );
+    piSrc[0] = Clip(( m2 + 2*m3 + 2*m4 + 2*m5 + m6 + 4) >> 3 );
+    
+    piSrc[-iOffset*2] = Clip(( m1 + m2 + m3 + m4 + 2)>>2);
+    piSrc[ iOffset] = Clip(( m3 + m4 + m5 + m6 + 2)>>2);
+    
+    piSrc[-iOffset*3] = Clip(( 2*m0 + 3*m1 + m2 + m3 + m4 + 4 )>>3);
+    piSrc[ iOffset*2] = Clip(( m3 + m4 + m5 + 3*m6 + 2*m7 +4 )>>3);
+#endif
+  }
+  else
+  {
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+    xPelFilterLumaWeak(piSrc, iOffset, tc, m1, m2, m3, m4, m5, m6);
+#else    
+    /* Weak filter */
+    delta = Clip3(-tc, tc, ((13*(m4-m3) + 4*(m5-m2) - 5*(m6-m1)+16)>>5) );
+    
+    piSrc[-iOffset] = Clip(m3+delta);
+    piSrc[0] = Clip(m4-delta);
+    piSrc[-iOffset*2] = Clip(m2+delta/2);
+    piSrc[ iOffset] = Clip(m5-delta/2);
+#endif
+  }
+}
+
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+/**
+ - Deblocking of one line/column for the luminance component
+ .
+ \param piSrc         pointer to picture data
+ \param iOffset       offset value for picture data
+ \param tc            tc value
+ \param strongFilter  indicator to use either strong or weak filter      
+ */
+__inline Void TComLoopFilter::xPelFilterLumaExecution( Pel* piSrc, Int iOffset, Int tc, Int strongFilter)
+{  
+  if (strongFilter) //strong filtering
+  {
+    xPelFilterLumaStrong(piSrc, iOffset, piSrc[-iOffset*4], piSrc[-iOffset*3], piSrc[-iOffset*2], piSrc[-iOffset], piSrc[0], piSrc[ iOffset], piSrc[ iOffset*2], piSrc[ iOffset*3]);
+  }
+  else //weak filtering
+  {
+    xPelFilterLumaWeak(piSrc, iOffset, tc, piSrc[-iOffset*3], piSrc[-iOffset*2], piSrc[-iOffset], piSrc[0], piSrc[ iOffset], piSrc[ iOffset*2]);
+  }
+}
+#endif
+
+__inline Void TComLoopFilter::xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc )
+{
+  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);
+}
+
+
+__inline Int TComLoopFilter::xCalcD( Pel* piSrc, Int iOffset)
+{
+  return abs( piSrc[-iOffset*3] - 2*piSrc[-iOffset*2] + piSrc[-iOffset] ) + abs( piSrc[0] - 2*piSrc[iOffset] + piSrc[iOffset*2] );
+}
Index: /tags/0.2r1/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComLoopFilter.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComLoopFilter.h	(revision 19)
@@ -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-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     TComLoopFilter.h
+    \brief    deblocking filter (header)
+*/
+
+#ifndef __TCOMLOOPFILTER__
+#define __TCOMLOOPFILTER__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+#define DEBLOCK_SMALLEST_BLOCK  8
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// deblocking filter class
+class TComLoopFilter
+{
+private:
+  UInt      m_uiDisableDeblockingFilterIdc; ///< deblocking filter idc
+  UInt      m_uiNumPartitions;
+  UChar*    m_aapucBS[2][3];              ///< Bs for [Ver/Hor][Y/U/V][Blk_Idx]
+  Bool*     m_aapbEdgeFilter[2][3];
+  LFCUParam m_stLFCUParam;                  ///< status structure
+  
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+  UInt m_decisions_D     [MAX_CU_SIZE/DEBLOCK_SMALLEST_BLOCK][MAX_CU_SIZE/DEBLOCK_SMALLEST_BLOCK];
+  UInt m_decisions_Sample[MAX_CU_SIZE/DEBLOCK_SMALLEST_BLOCK][MAX_CU_SIZE];
+#endif
+  
+protected:
+  /// CU-level deblocking function
+#if PARALLEL_MERGED_DEBLK
+  Void xDeblockCU                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge );
+#else
+  Void xDeblockCU                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth );
+#endif
+
+  // set / get functions
+  Void xSetLoopfilterParam        ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  // filtering functions
+  Void xSetEdgefilterTU           ( TComDataCU* pcCU, 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 );
+  
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+  Void xEdgeFilterLuma            ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge, Int iDecideExecute);
+#else
+  Void xEdgeFilterLuma            ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge );
+#endif
+  Void xEdgeFilterChroma          ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge );
+  
+#if (PARALLEL_DEBLK_DECISION && !PARALLEL_MERGED_DEBLK)
+  __inline Void xPelFilterLumaStrong    ( Pel* piSrc, Int iOffset, Pel m0, Pel m1, Pel m2, Pel m3, Pel m4, Pel m5, Pel m6, Pel m7);
+  __inline Void xPelFilterLumaWeak      ( Pel* piSrc, Int iOffset, Int tc, Pel m1, Pel m2, Pel m3, Pel m4, Pel m5, Pel m6);
+  __inline Void xPelFilterLumaExecution ( Pel* piSrc, Int iOffset, Int tc, Int strongFilter);
+  __inline Int  xPelFilterLumaDecision  ( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc);
+#endif
+
+#if PARALLEL_MERGED_DEBLK
+  __inline Void xPelFilterLuma( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc , Pel* piSrcJudge);
+#else
+  __inline Void xPelFilterLuma( Pel* piSrc, Int iOffset, Int d, Int beta, Int tc );
+#endif
+  __inline Void xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc );
+  __inline Int xCalcD( Pel* piSrc, Int iOffset);
+  
+public:
+  TComLoopFilter();
+  virtual ~TComLoopFilter();
+  
+  Void  create                    ( UInt uiMaxCUDepth );
+  Void  destroy                   ();
+  
+  /// set configuration
+  Void setCfg( UInt uiDisableDblkIdc, Int iAlphaOffset, Int iBetaOffset );
+  
+  /// picture-level deblocking filter
+  Void loopFilterPic( TComPic* pcPic );
+};
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComMVDRefData.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComMVDRefData.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComMVDRefData.cpp	(revision 19)
@@ -0,0 +1,112 @@
+/* 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 "TComMVDRefData.h"
+#include "TComPicYuv.h"
+#include <math.h>
+#include <vector>
+#include <iostream>
+#include <fstream>
+
+#if HHI_VSO
+Void TComMVDRefData::setPicYuvBaseView( InterViewReference eView, Bool bDepth, TComPicYuv* pcOrgView, TComPicYuv* pcRecView )
+{
+  if ( bDepth )
+  {
+    m_apcDepthRec[eView] = pcRecView;
+    m_apcDepthOrg[eView] = pcOrgView;
+  }
+  else
+  {
+    m_apcVideoRec[eView] = pcRecView;
+    m_apcVideoOrg[eView] = pcOrgView;
+  }
+}
+
+Void TComMVDRefData::setShiftLUTsBaseView( InterViewReference eView, Double** adInLut, Int** aiInLut )
+{
+  m_aiBaseViewShiftLUT[eView] = aiInLut;
+  m_adBaseViewShiftLUT[eView] = adInLut;
+}
+
+TComMVDRefData::TComMVDRefData()
+{
+  m_adERViewShiftLUT = 0;
+  m_aiERViewShiftLUT = 0;
+  m_apcExternalReferenceViews.resize(0);
+
+  for (UInt uiView = 0; uiView < 3; uiView++)
+  {
+    m_apcVideoOrg[uiView] = NULL;
+    m_apcDepthOrg[uiView] = NULL;
+    m_apcVideoRec[uiView] = NULL;
+    m_apcDepthRec[uiView] = NULL;
+
+    m_adBaseViewShiftLUT [uiView] = NULL;
+    m_aiBaseViewShiftLUT [uiView] = NULL;
+
+  };
+}
+
+Void TComMVDRefData::getRefPicYuvAndLUT( TComPicYuv**& rpacDistRefPicList, Int***& rppaiShiftLut )
+{
+  UInt uiNextEntry = 0;
+  for ( UInt uiViewIdx = 0; uiViewIdx < m_aiExtViewRefInd.size(); uiViewIdx++ )
+  {
+    rppaiShiftLut[uiNextEntry]       = m_aiERViewShiftLUT         [ m_aiExtViewRefLUTInd[uiViewIdx] ];
+    rpacDistRefPicList[uiNextEntry]  = m_apcExternalReferenceViews[ m_aiExtViewRefInd   [uiViewIdx] ];
+    uiNextEntry++;
+  }
+
+  for ( UInt uiViewIdx = 0; uiViewIdx < m_aiBaseViewRefInd.size(); uiViewIdx++ )
+  {
+    rppaiShiftLut[uiNextEntry]      = m_aiBaseViewShiftLUT[ m_aiBaseViewRefInd[uiViewIdx] + 1 ];
+    rpacDistRefPicList[uiNextEntry] = getPicYuvRecVideo( (InterViewReference) (m_aiBaseViewRefInd[uiViewIdx] + 1) ) ?  getPicYuvRecVideo( (InterViewReference) (m_aiBaseViewRefInd[uiViewIdx] + 1) ) : getPicYuvOrgVideo( (InterViewReference) (m_aiBaseViewRefInd[uiViewIdx] + 1) );
+    uiNextEntry++;
+  }
+}
+
+Void TComMVDRefData::getRefPicYuvAndLUTMode1( TComPicYuv**& rpacDistRefPicList, Int***& rppaiShiftLut )
+{
+  rppaiShiftLut[0] = m_aiBaseViewShiftLUT[ PREVVIEW ];
+  rppaiShiftLut[1] = NULL;
+  rppaiShiftLut[2] = m_aiBaseViewShiftLUT[ NEXTVIEW ];
+
+  rpacDistRefPicList[0] = NULL;
+  rpacDistRefPicList[1] = NULL;
+  rpacDistRefPicList[2] = NULL;
+}
+#endif
Index: /tags/0.2r1/source/Lib/TLibCommon/TComMVDRefData.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComMVDRefData.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComMVDRefData.h	(revision 19)
@@ -0,0 +1,121 @@
+/* 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 __TCOMMVDREFDATA__
+#define __TCOMMVDREFDATA__
+
+
+// Include files
+
+#include "CommonDef.h"
+#include "TComPicYuv.h"
+#include <vector>
+#if HHI_VSO
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+
+class TComMVDRefData
+{
+private:
+  // PicYuvs
+  TComPicYuv* m_apcVideoOrg[3];
+  TComPicYuv* m_apcDepthOrg[3];
+  TComPicYuv* m_apcVideoRec[3];
+  TComPicYuv* m_apcDepthRec[3];
+
+  // LUTs
+  Double**    m_adBaseViewShiftLUT[3];
+  Int**       m_aiBaseViewShiftLUT[3];
+
+  //PicYuvs
+  std::vector<TComPicYuv*> m_apcExternalReferenceViews;
+
+  // LUTs
+  Double***   m_adERViewShiftLUT;
+  Int***      m_aiERViewShiftLUT;
+
+  // Indices
+  std::vector<Int> m_aiBaseViewRefInd;
+  std::vector<Int> m_aiExtViewRefInd;
+  std::vector<Int> m_aiExtViewRefLUTInd;
+
+public:
+  TComMVDRefData();
+
+  //  PicYuvs
+  TComPicYuv* getPicYuvRecVideo   ( InterViewReference eIVRef )  { return m_apcVideoRec[eIVRef]; };
+  TComPicYuv* getPicYuvOrgVideo   ( InterViewReference eIVRef )  { return m_apcVideoOrg[eIVRef]; };
+  TComPicYuv* getPicYuvRecDepth   ( InterViewReference eIVRef )  { return m_apcDepthRec[eIVRef]; };
+  TComPicYuv* getPicYuvOrgDepth   ( InterViewReference eIVRef )  { return m_apcDepthOrg[eIVRef]; };
+  Void        setPicYuvBaseView   ( InterViewReference eView, Bool bDepth, TComPicYuv* pcOrgView, TComPicYuv* pcRecView );
+
+
+  TComPicYuv* getPicYuvVideo      ( ) { return getPicYuvOrgVideo( CURRVIEW ); /*return getRecVideo( CURRVIEW ) ?  getRecVideo( CURRVIEW ) : getOrgVideo( CURRVIEW ); */ };
+  //TComPicYuv* getVideoData( ) { return getRecVideo( CURRVIEW ) ?  getRecVideo( CURRVIEW ) : getOrgVideo( CURRVIEW );  };
+
+  // Luts
+  Int**       getShiftLUTLBaseView       ( InterViewReference eIVRef ) { return m_aiBaseViewShiftLUT[eIVRef]; };
+  Double**    getShiftLUTDBaseView       ( InterViewReference eIVRef ) { return m_adBaseViewShiftLUT[eIVRef]; };
+  Void        setShiftLUTsBaseView       ( InterViewReference eView, Double** adInLut, Int** alInLut );
+
+//  Void render( TComPicYuv* pOut ) /*Void render( TComPicYuv* pIn, TComPicYuv* pOut, TComPicYuv* pDepth, Long** aalLUT ) */;
+
+
+  //  PicYuvs
+  TComPicYuv* getPicYuvERView   ( UInt uiReferenceNum )              { return m_apcExternalReferenceViews[uiReferenceNum]; };
+  Void        setPicYuvERViews  ( std::vector<TComPicYuv*> papcIn  ) { m_apcExternalReferenceViews = papcIn; };
+
+  //  LUTS
+  Int**       getShiftLUTIERView         ( UInt uiTargetViewNum )      { return (m_aiERViewShiftLUT)[uiTargetViewNum]; };
+  Double**    getShiftLUTDERView         ( UInt uiTargetViewNum )      { return (m_adERViewShiftLUT)[uiTargetViewNum]; };
+
+  Void        setShiftLUTsERView    ( Double*** adInLut, Int***   aiInLut) { m_aiERViewShiftLUT = aiInLut; m_adERViewShiftLUT = adInLut; };
+
+  // Set Indices of actually used references
+  Void setRefViewInd  ( std::vector<Int> aiBaseViewRef, std::vector<Int> aiEViewRef, std::vector<Int> aiEViewRefLut  ) { m_aiBaseViewRefInd = aiBaseViewRef, m_aiExtViewRefInd = aiEViewRef, m_aiExtViewRefLUTInd = aiEViewRefLut; }
+
+  // Get Reference Data
+  UInt getNumOfRefViews() { return (UInt) m_aiExtViewRefInd.size() + (UInt) m_aiBaseViewRefInd.size(); };
+  Void getRefPicYuvAndLUT     ( TComPicYuv**& rpacDistRefPicList, Int***& rppalShiftLut);
+  Void getRefPicYuvAndLUTMode1( TComPicYuv**& rpacDistRefPicList, Int***& rppaiShiftLut );
+
+}; // END CLASS DEFINITION TComMVDRefData
+#endif // HHI_VSO
+#endif // __TCOMMVDREFDATA__
+
+
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 19)
@@ -0,0 +1,319 @@
+/* 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     TComMotionInfo.cpp
+    \brief    motion information handling classes
+*/
+
+#include <memory.h>
+#include "TComMotionInfo.h"
+#include "assert.h"
+#include <stdlib.h>
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// Create / destroy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::create( UInt uiNumPartition )
+{
+  m_pcMv     = ( TComMv* )xMalloc( TComMv, uiNumPartition );
+  m_pcMvd    = ( TComMv* )xMalloc( TComMv, uiNumPartition );
+  m_piRefIdx = (    Int* )xMalloc( Int,    uiNumPartition );
+  
+  m_uiNumPartition = uiNumPartition;
+}
+
+Void TComCUMvField::destroy()
+{
+  if( m_pcMv )
+  {
+    xFree( m_pcMv );     m_pcMv     = NULL;
+  }
+  if( m_pcMvd )
+  {
+    xFree( m_pcMvd );    m_pcMvd    = NULL;
+  }
+  if( m_piRefIdx )
+  {
+    xFree( m_piRefIdx ); m_piRefIdx = NULL;
+  }
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Clear / copy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::clearMv( Int iPartAddr, UInt uiDepth )
+{
+  Int iNumPartition = m_uiNumPartition >> (uiDepth<<1);
+  
+  for ( Int i = iNumPartition - 1; i >= 0; i-- )
+  {
+    m_pcMv[ i ].setZero();
+  }
+}
+
+Void TComCUMvField::clearMvd( Int iPartAddr, UInt uiDepth )
+{
+  Int iNumPartition = m_uiNumPartition >> (uiDepth<<1);
+  
+  for ( Int i = iNumPartition - 1; i >= 0; i-- )
+  {
+    m_pcMvd[ i ].setZero();
+  }
+}
+
+Void TComCUMvField::clearMvField()
+{
+  for ( Int i = m_uiNumPartition - 1; i >= 0; i-- )
+  {
+    m_pcMv    [ i ].setZero();
+    m_pcMvd   [ i ].setZero();
+    m_piRefIdx[ i ] = NOT_VALID;
+  }
+}
+
+Void TComCUMvField::copyFrom( TComCUMvField* pcCUMvFieldSrc, Int iNumPartSrc, Int iPartAddrDst )
+{
+  Int iSizeInTComMv = sizeof( TComMv ) * iNumPartSrc;
+  
+  memcpy( m_pcMv     + iPartAddrDst, pcCUMvFieldSrc->getMv(),     iSizeInTComMv );
+  memcpy( m_pcMvd    + iPartAddrDst, pcCUMvFieldSrc->getMvd(),    iSizeInTComMv );
+  memcpy( m_piRefIdx + iPartAddrDst, pcCUMvFieldSrc->getRefIdx(), sizeof( Int ) * iNumPartSrc );
+}
+
+Void TComCUMvField::copyTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst )
+{
+  Int iSizeInTComMv = sizeof( TComMv ) * m_uiNumPartition;
+  
+  memcpy( pcCUMvFieldDst->getMv()     + iPartAddrDst, m_pcMv,     iSizeInTComMv );
+  memcpy( pcCUMvFieldDst->getMvd()    + iPartAddrDst, m_pcMvd,    iSizeInTComMv );
+  memcpy( pcCUMvFieldDst->getRefIdx() + iPartAddrDst, m_piRefIdx, sizeof( Int ) * m_uiNumPartition );
+}
+
+Void TComCUMvField::copyTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst, UInt uiOffset, UInt uiNumPart )
+{
+  Int iSizeInTComMv = sizeof( TComMv ) * uiNumPart;
+  Int iOffset = uiOffset + iPartAddrDst;
+  
+  memcpy( pcCUMvFieldDst->getMv()     + iOffset, m_pcMv     + uiOffset, iSizeInTComMv );
+  memcpy( pcCUMvFieldDst->getMvd()    + iOffset, m_pcMvd    + uiOffset, iSizeInTComMv );
+  memcpy( pcCUMvFieldDst->getRefIdx() + iOffset, m_piRefIdx + uiOffset, sizeof( Int ) * uiNumPart );
+}
+
+Void TComCUMvField::copyMvTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst )
+{
+  memcpy( pcCUMvFieldDst->getMv() + iPartAddrDst, m_pcMv, sizeof( TComMv ) * m_uiNumPartition );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Set
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::setAllMv( TComMv& rcMv, PartSize eCUMode, Int iPartAddr, Int iPartIdx, UInt uiDepth )
+{
+  Int i;
+  TComMv* pcMv = m_pcMv + iPartAddr;
+  register TComMv cMv = rcMv;
+  Int iNumPartition = m_uiNumPartition >> (uiDepth<<1);
+  
+  switch( eCUMode )
+  {
+    case SIZE_2Nx2N:
+      for ( i = iNumPartition - 1; i >= 0; i-- )
+      {
+        pcMv[ i ] = cMv;
+      }
+      break;
+    case SIZE_2NxN:
+      for ( i = ( iNumPartition >> 1 ) - 1; i >= 0; i-- )
+      {
+        pcMv[ i ] = cMv;
+      }
+      break;
+    case SIZE_Nx2N:
+    {
+      UInt uiOffset = iNumPartition >> 1;
+      for ( i = ( iNumPartition >> 2 ) - 1; i >= 0; i-- )
+      {
+        pcMv[ i ] = cMv;
+        pcMv[ i + uiOffset ] = cMv;
+      }
+      break;
+    }
+    case SIZE_NxN:
+      for ( i = ( iNumPartition >> 2 ) - 1; i >= 0; i-- )
+      {
+        pcMv[ i ] = cMv;
+      }
+      break;
+    default:
+      assert(0);
+      break;
+  }
+}
+
+Void TComCUMvField::setAllMvd( TComMv& rcMvd, PartSize eCUMode, Int iPartAddr, Int iPartIdx, UInt uiDepth )
+{
+  Int i;
+  TComMv* pcMvd = m_pcMvd + iPartAddr;
+  register TComMv cMvd = rcMvd;
+  Int iNumPartition = m_uiNumPartition >> (uiDepth<<1);
+  
+  switch( eCUMode )
+  {
+    case SIZE_2Nx2N:
+      for ( i = iNumPartition - 1; i >= 0; i-- )
+      {
+        pcMvd[ i ] = cMvd;
+      }
+      break;
+    case SIZE_2NxN:
+      for ( i = ( iNumPartition >> 1 ) - 1; i >= 0; i-- )
+      {
+        pcMvd[ i ] = cMvd;
+      }
+      break;
+    case SIZE_Nx2N:
+    {
+      UInt uiOffset = iNumPartition >> 1;
+      for ( i = ( iNumPartition >> 2 ) - 1; i >= 0; i-- )
+      {
+        pcMvd[ i ] = cMvd;
+        pcMvd[ i + uiOffset ] = cMvd;
+      }
+      break;
+    }
+    case SIZE_NxN:
+      for ( i = ( iNumPartition >> 2 ) - 1; i >= 0; i-- )
+      {
+        pcMvd[ i ] = cMvd;
+      }
+      break;
+    default:
+      assert(0);
+      break;
+  }
+}
+
+Void TComCUMvField::setAllRefIdx ( Int iRefIdx, PartSize eCUMode, Int iPartAddr, Int iPartIdx, UInt uiDepth )
+{
+  Int i;
+  Int* piRefIdx = m_piRefIdx + iPartAddr;
+  Int iNumPartition = m_uiNumPartition >> (uiDepth<<1);
+  
+  switch( eCUMode )
+  {
+    case SIZE_2Nx2N:
+      for ( i = iNumPartition - 1; i >= 0; i-- )
+      {
+        piRefIdx[ i ] = iRefIdx;
+      }
+      break;
+    case SIZE_2NxN:
+      for ( i = ( iNumPartition >> 1 ) - 1; i >= 0; i-- )
+      {
+        piRefIdx[ i ] = iRefIdx;
+      }
+      break;
+    case SIZE_Nx2N:
+    {
+      UInt uiOffset = iNumPartition >> 1;
+      for ( i = ( iNumPartition >> 2 ) - 1; i >= 0; i-- )
+      {
+        piRefIdx[ i ] = iRefIdx;
+        piRefIdx[ i + uiOffset ] = iRefIdx;
+      }
+      break;
+    }
+    case SIZE_NxN:
+      for ( i = ( iNumPartition >> 2 ) - 1; i >= 0; i-- )
+      {
+        piRefIdx[ i ] = iRefIdx;
+      }
+      break;
+    default:
+      assert(0);
+      break;
+  }
+}
+
+Void TComCUMvField::setAllMvField ( TComMv& rcMv, Int iRefIdx, PartSize eCUMode, Int iPartAddr, Int iPartIdx, UInt uiDepth )
+{
+  setAllMv( rcMv, eCUMode, iPartAddr, iPartIdx, uiDepth);
+  setAllRefIdx(iRefIdx, eCUMode,iPartAddr,iPartIdx,uiDepth);
+  return;
+}
+
+#if AMVP_BUFFERCOMPRESS
+/**Subsampling of the stored prediction mode, reference index and motion vector
+ * \param pePredMode
+ * \returns Void
+ */
+Void TComCUMvField::compress(PredMode* pePredMode,UChar* puhInterDir)
+{
+  Int N = AMVP_DECIMATION_FACTOR;
+  for ( Int uiPartIdx = 0; uiPartIdx <m_uiNumPartition; uiPartIdx+=(N*N) )
+  {
+    Int  jj = uiPartIdx+N*N;
+    
+    TComMv cMv(0,0); 
+#if MV_COMPRESS_MODE_REFIDX
+    PredMode predMode = MODE_INTRA;
+    Int iRefIdx = 0;
+    const UChar uhInterDir = puhInterDir[ uiPartIdx ];
+    
+    cMv = m_pcMv[ uiPartIdx ];
+    predMode = pePredMode[ uiPartIdx ];
+    iRefIdx = m_piRefIdx[ uiPartIdx ];
+#else
+    if (pePredMode[uiPartIdx]!=MODE_INTRA) cMv = m_pcMv[ uiPartIdx ]; 
+#endif
+    for ( Int i = jj-1; i >= uiPartIdx; i-- )
+    {
+      m_pcMv[ i ] = cMv;
+#if MV_COMPRESS_MODE_REFIDX
+      pePredMode[ i ] = predMode;
+      m_piRefIdx[ i ] = iRefIdx;
+      puhInterDir[ i ] = uhInterDir;
+#endif
+    }
+  }
+} 
+#endif 
Index: /tags/0.2r1/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComMotionInfo.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComMotionInfo.h	(revision 19)
@@ -0,0 +1,169 @@
+/* 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     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"
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+/// parameters for AMVP
+typedef struct _AMVPInfo
+{
+  TComMv m_acMvCand[ AMVP_MAX_NUM_CANDS ];  ///< array of motion vector predictor candidates
+  Int    iN;                                ///< number of motion vector predictor candidates
+} AMVPInfo;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// class for motion vector with reference index
+class TComMvField
+{
+private:
+  TComMv    m_acMv;
+  Int       m_iRefIdx;
+  
+public:
+  TComMvField() :
+  m_iRefIdx (-1)
+  {
+  }
+  
+  Void setMvField ( TComMv cMv, Int iRefIdx )
+  {
+    m_acMv    = cMv;
+    m_iRefIdx = iRefIdx;
+  }
+  
+  TComMv& getMv     ()      { return  m_acMv;             }
+  Int     getRefIdx ()      { return  m_iRefIdx;          }
+  
+  Int     getHor    ()      { return  m_acMv.getHor();    }
+  Int     getVer    ()      { return  m_acMv.getVer();    }
+};
+
+/// class for motion information in one CU
+class TComCUMvField
+{
+private:
+  TComMv*   m_pcMv;
+  TComMv*   m_pcMvd;
+  Int*      m_piRefIdx;
+  UInt      m_uiNumPartition;
+  AMVPInfo  m_cAMVPInfo;
+public:
+  TComCUMvField()
+  {
+    m_pcMv     = NULL;
+    m_pcMvd    = NULL;
+    m_piRefIdx = NULL;
+  }
+  ~TComCUMvField()
+  {
+    m_pcMv     = NULL;
+    m_pcMvd    = NULL;
+    m_piRefIdx = NULL;
+  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // create / destroy
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    create        ( UInt uiNumPartition );
+  Void    destroy       ();
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // clear / copy
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    clearMv       ( Int iPartAddr, UInt uiDepth );
+  Void    clearMvd      ( Int iPartAddr, UInt uiDepth );
+  Void    clearMvField  ();
+  
+  Void    copyFrom          ( TComCUMvField* pcCUMvFieldSrc, Int iNumPartSrc, Int iPartAddrDst );
+  Void    copyTo            ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst );
+  Void    copyTo            ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst, UInt uiOffset, UInt uiNumPart );
+  Void    copyMvTo          ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst );
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // get
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv& getMv             ( Int iIdx )               { return  m_pcMv    [iIdx]; }
+  TComMv* getMv             ()                         { return  m_pcMv;           }
+  TComMv& getMvd            ( Int iIdx )               { return  m_pcMvd   [iIdx]; }
+  TComMv* getMvd            ()                         { return  m_pcMvd;          }
+  Int     getRefIdx         ( Int iIdx )               { return  m_piRefIdx[iIdx]; }
+  Int*    getRefIdx         ()                         { return  m_piRefIdx;       }
+  
+  AMVPInfo* getAMVPInfo () { return &m_cAMVPInfo; }
+  // ------------------------------------------------------------------------------------------------------------------
+  // set
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    setMv             ( TComMv  cMv,     Int iIdx ) { m_pcMv    [iIdx] = cMv;     }
+  Void    setMvd            ( TComMv  cMvd,    Int iIdx ) { m_pcMvd   [iIdx] = cMvd;    }
+  Void    setRefIdx         ( Int     iRefIdx, Int iIdx ) { m_piRefIdx[iIdx] = iRefIdx; }
+  
+  Void    setMvPtr          ( TComMv*  cMvPtr     ) { m_pcMv    = cMvPtr;         }
+  Void    setMvdPtr         ( TComMv*  cMvdPtr    ) { m_pcMvd  = cMvdPtr;         }
+  Void    setRefIdxPtr      ( Int*     iRefIdxPtr ) { m_piRefIdx = iRefIdxPtr;    }
+  Void    setNumPartition   ( Int      iNumPart   ) { m_uiNumPartition=iNumPart;  }
+  
+  Void    setAllMv          ( TComMv& rcMv,    PartSize eCUMode, Int iPartAddr, Int iPartIdx, UInt uiDepth );
+  Void    setAllMvd         ( TComMv& rcMvd,   PartSize eCUMode, Int iPartAddr, Int iPartIdx, UInt uiDepth );
+  Void    setAllRefIdx      ( Int     iRefIdx, PartSize eMbMode, Int iPartAddr, Int iPartIdx, UInt uiDepth );
+  Void    setAllMvField     ( TComMv& rcMv, Int iRefIdx, PartSize eMbMode, Int iPartAddr, Int iPartIdx, UInt uiDepth );
+  
+#if AMVP_BUFFERCOMPRESS
+  Void    compress          (PredMode* pePredMode,UChar* puhInterDir);
+#endif 
+  
+};
+
+#endif // __TCOMMOTIONINFO__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComMv.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComMv.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComMv.h	(revision 19)
@@ -0,0 +1,163 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-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     TComMv.h
+    \brief    motion vector class (header)
+*/
+
+#ifndef __TCOMMV__
+#define __TCOMMV__
+
+#include <math.h>
+#include "CommonDef.h"
+
+#include <cstdlib>
+using namespace std;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// basic motion vector class
+class TComMv
+{
+private:
+  Int   m_iHor;     ///< horizontal component of motion vector
+  Int   m_iVer;     ///< vertical component of motion vector
+  
+public:
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // constructors
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv() :
+  m_iHor(0),
+  m_iVer(0)
+  {
+  }
+  
+  TComMv( Int iHor, Int iVer ) :
+  m_iHor(iHor),
+  m_iVer(iVer)
+  {
+  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // set
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void  set       ( Int iHor, Int iVer)     { m_iHor = iHor;  m_iVer = iVer;            }
+  Void  setHor    ( Int i )                 { m_iHor = i;                               }
+  Void  setVer    ( Int i )                 { m_iVer = i;                               }
+  Void  setZero   ()                        { m_iHor = m_iVer = 0;  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // get
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Int   getHor    ()  { return m_iHor;          }
+  Int   getVer    ()  { return m_iVer;          }
+  Int   getAbsHor ()  { return abs( m_iHor );   }
+  Int   getAbsVer ()  { 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 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 )
+  {
+    return TComMv( m_iHor + rcMv.m_iHor, m_iVer + rcMv.m_iVer );
+  }
+  
+  Bool operator== ( const TComMv& rcMv )
+  {
+    return (m_iHor==rcMv.m_iHor && m_iVer==rcMv.m_iVer);
+  }
+  
+  Bool operator!= ( const TComMv& rcMv )
+  {
+    return (m_iHor!=rcMv.m_iHor || m_iVer!=rcMv.m_iVer);
+  }
+  
+  const TComMv scaleMv( Int iScale )
+  {
+    return TComMv( (iScale * getHor() + 128) >> 8, (iScale * getVer() + 128) >> 8);
+  }
+};// END CLASS DEFINITION TComMV
+
+
+#endif // __TCOMMV__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPattern.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPattern.cpp	(revision 19)
@@ -0,0 +1,1236 @@
+/* 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     TComPattern.cpp
+    \brief    neighbouring pixel access classes
+*/
+
+#include "TComPic.h"
+#include "TComPattern.h"
+#include "TComDataCU.h"
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar g_aaucAvailableBlkMask[16][8] =
+{
+  // 4x4 block neighbor availability      // MB neighbor availability
+  {0x0,0x0,0x0,0x0,  0x0,0x8,0x0,0x08  }, // L, A, AL, AR   <== WTF (blkIdx < 8)
+  {0x1,0x0,0x0,0x0,  0x1,0x8,0x0,0x08  }, //    A, AL, AR
+  {0xA,0xE,0xE,0x6,  0x0,0x8,0x0,0x08  }, // L,    AL, AR
+  {0xB,0xE,0xE,0x6,  0x1,0x8,0x0,0x08  }, //       AL, AR
+  
+  {0x4,0x0,0x0,0x0,  0x0,0x8,0x0,0x08  }, // L, A,     AR
+  {0x5,0x0,0x0,0x0,  0x1,0x8,0x0,0x08  }, //    A,     AR
+  {0xE,0xE,0xE,0x6,  0x0,0x8,0x0,0x08  }, // L,        AR
+  {0xF,0xE,0xE,0x6,  0x1,0x8,0x0,0x08  }, //           AR
+  
+  {0x0,0x0,0x0,0x8,  0x0,0x8,0x0,0x08  }, // L, A, AL       <== WTF (blkIdx < 8 || blkIdx >= 8)
+  {0x1,0x0,0x0,0x8,  0x1,0x8,0x0,0x08  }, //    A, AL
+  {0xA,0xE,0xE,0xE,  0x0,0x8,0x0,0x08  }, // L,    AL
+  {0xB,0xE,0xE,0xE,  0x1,0x8,0x0,0x08  }, //       AL
+  
+  {0x4,0x0,0x0,0x8,  0x0,0x8,0x0,0x08  }, // L, A,
+  {0x5,0x0,0x0,0x8,  0x1,0x8,0x0,0x08  }, //    A,
+  {0xE,0xE,0xE,0xE,  0x0,0x8,0x0,0x08  }, // L,
+  {0xF,0xE,0xE,0xE,  0x1,0x8,0x0,0x08  }  //
+};
+
+// ====================================================================================================================
+// 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 )
+  {
+    m_iPatternStride  = pcCU->getPic()->getStride();
+    m_piPatternOrigin = pcPic->getLumaAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+  }
+  else
+  {
+    m_iPatternStride = pcCU->getPic()->getCStride();
+    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()->getWidth() )
+    {
+      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 LM_CHROMA 
+  m_bLeftAvailable = uiCurrPicPelX > 0 ? true : false;
+  m_bAboveAvailable = uiCurrPicPelY > 0 ? true : false;
+#endif
+
+#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
+#if DEPTH_MAP_GENERATION
+                                , Bool bPrdDepthMap 
+#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;
+  Int   iPicStride = pcCU->getPic()->getStride();
+  Int   iCuAddr;
+#if REFERENCE_SAMPLE_PADDING
+  Int   iUnitSize = 0;
+  Int   iNumUnitsInCu = 0;
+  Int   iTotalUnits = 0;
+  Bool* bNeighborFlags;
+  Int   iNumIntraNeighbor = 0;
+#else  // REFERENCE_SAMPLE_PADDING
+  Pel*  piRoiTemp;
+  Bool  bAboveFlag      = false;
+  Bool  bAboveRightFlag = false;
+  Bool  bLeftFlag       = false;
+  Bool  bBelowLeftFlag  = false;
+  Bool  bAboveLeftFlag  = false;
+#endif // REFERENCE_SAMPLE_PADDING
+  
+  iCuAddr = pcCU->getAddr();
+  
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB, uiPartDum;
+  
+  pcCU->deriveLeftRightTopIdxAdi( uiPartIdxLT, uiPartIdxRT, uiZorderIdxInPart, uiPartDepth );
+  pcCU->deriveLeftBottomIdxAdi  ( uiPartIdxLB,              uiZorderIdxInPart, uiPartDepth );
+  
+#if CONSTRAINED_INTRA_PRED
+  if ( pcCU->getSlice()->getPPS()->getConstrainedIntraPred() )
+  {
+#if REFERENCE_SAMPLE_PADDING
+    iUnitSize      = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+    iNumUnitsInCu  = uiCuWidth / iUnitSize;
+    iTotalUnits    = (iNumUnitsInCu << 2) + 1;
+    bNeighborFlags = new Bool[iTotalUnits];
+
+    bNeighborFlags[iNumUnitsInCu*2] = isAboveLeftAvailableForCIP( pcCU, uiPartIdxLT );
+    iNumIntraNeighbor  += (Int)(bNeighborFlags[iNumUnitsInCu*2]);
+    iNumIntraNeighbor  += isAboveAvailableForCIP     ( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*2)+1 );
+    iNumIntraNeighbor  += isAboveRightAvailableForCIP( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*3)+1 );
+    iNumIntraNeighbor  += isLeftAvailableForCIP      ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+(iNumUnitsInCu*2)-1 );
+    iNumIntraNeighbor  += isBelowLeftAvailableForCIP ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+ iNumUnitsInCu   -1 );
+#else // REFERENCE_SAMPLE_PADDING
+    bAboveFlag      = isAboveAvailableForCIP     ( pcCU, uiPartIdxLT, uiPartIdxRT );
+    bAboveRightFlag = isAboveRightAvailableForCIP( pcCU, uiPartIdxLT, uiPartIdxRT );
+    bLeftFlag       = isLeftAvailableForCIP      ( pcCU, uiPartIdxLT, uiPartIdxLB );
+    bBelowLeftFlag  = isBelowLeftAvailableForCIP ( pcCU, uiPartIdxLT, uiPartIdxLB );
+    bAboveLeftFlag  = isAboveLeftAvailableForCIP ( pcCU, uiPartIdxLT );
+#endif // REFERENCE_SAMPLE_PADDING
+  }
+  else
+  {
+#if REFERENCE_SAMPLE_PADDING
+    iUnitSize     = uiCuWidth;
+    iNumUnitsInCu = 1;
+    iTotalUnits   = 5;
+    bNeighborFlags = new Bool[iTotalUnits];
+
+    ::memset(bNeighborFlags, false, sizeof(Bool)*iTotalUnits);
+    if( pcCU->getPUAbove        ( uiPartDum,             uiPartIdxLT,    true, false ) ) { bNeighborFlags[3] = true; iNumIntraNeighbor++; }
+    if( pcCU->getPUAboveRightAdi( uiPartDum, uiCuWidth,  uiPartIdxRT, 1, true, false ) ) { bNeighborFlags[4] = true; iNumIntraNeighbor++; }
+    if( pcCU->getPULeft         ( uiPartDum,             uiPartIdxLT,    true, false ) ) { bNeighborFlags[1] = true; iNumIntraNeighbor++; }
+    if( pcCU->getPUBelowLeftAdi ( uiPartDum, uiCuHeight, uiPartIdxLB, 1, true, false ) ) { bNeighborFlags[0] = true; iNumIntraNeighbor++; }
+    if( pcCU->getPUAboveLeft    ( uiPartDum,             uiPartIdxLT,    true, false ) ) { bNeighborFlags[2] = true; iNumIntraNeighbor++; }
+#if MN_DC_PRED_FILTER
+    m_bAboveFlagForDCFilt = bNeighborFlags[3];
+    m_bLeftFlagForDCFilt  = bNeighborFlags[1];
+#endif
+#else // REFERENCE_SAMPLE_PADDING
+    if( pcCU->getPUAbove        ( uiPartDum,             uiPartIdxLT,    true, false ) ) bAboveFlag      = true;
+    if( pcCU->getPUAboveRightAdi( uiPartDum, uiCuWidth,  uiPartIdxRT, 1, true, false ) ) bAboveRightFlag = true;
+    if( pcCU->getPULeft         ( uiPartDum,             uiPartIdxLT,    true, false ) ) bLeftFlag       = true;
+    if( pcCU->getPUBelowLeftAdi ( uiPartDum, uiCuHeight, uiPartIdxLB, 1, true, false ) ) bBelowLeftFlag  = true;
+    if( pcCU->getPUAboveLeft    ( uiPartDum,             uiPartIdxLT,    true, false ) ) bAboveLeftFlag  = true;
+#if MN_DC_PRED_FILTER
+    m_bAboveFlagForDCFilt = bAboveFlag;
+    m_bLeftFlagForDCFilt  = bLeftFlag;
+#endif
+#endif // REFERENCE_SAMPLE_PADDING
+  }
+#else //CONSTRAINED_INTRA_PRED
+#if REFERENCE_SAMPLE_PADDING
+  iUnitSize     = uiCuWidth;
+  iNumUnitsInCu = 1;
+  iTotalUnits   = 5;
+  bNeighborFlags = new Bool[iTotalUnits];
+
+  ::memset(bNeighborFlags, false, sizeof(Bool)*iTotalUnits);
+  if( pcCU->getPUAbove        ( uiPartDum,             uiPartIdxLT, true, false ) ) { bNeighborFlags[3] = true; iNumIntraNeighbor++; }
+  if( pcCU->getPUAboveRightAdi( uiPartDum, uiCuWidth,  uiPartIdxRT, true, false ) ) { bNeighborFlags[4] = true; iNumIntraNeighbor++; }
+  if( pcCU->getPULeft         ( uiPartDum,             uiPartIdxLT, true, false ) ) { bNeighborFlags[1] = true; iNumIntraNeighbor++; }
+  if( pcCU->getPUBelowLeftAdi ( uiPartDum, uiCuHeight, uiPartIdxLB, true, false ) ) { bNeighborFlags[0] = true; iNumIntraNeighbor++; }
+  if( pcCU->getPUAboveLeft    ( uiPartDum,             uiPartIdxLT, true, false ) ) { bNeighborFlags[2] = true; iNumIntraNeighbor++; }
+#if MN_DC_PRED_FILTER
+  m_bAboveFlagForDCFilt = bNeighborFlags[3];
+  m_bLeftFlagForDCFilt  = bNeighborFlags[1];
+#endif
+#else // REFERENCE_SAMPLE_PADDING
+  if( pcCU->getPUAbove        ( uiPartDum,             uiPartIdxLT, true, false ) ) bAboveFlag      = true;
+  if( pcCU->getPUAboveRightAdi( uiPartDum, uiCuWidth,  uiPartIdxRT, true, false ) ) bAboveRightFlag = true;
+  if( pcCU->getPULeft         ( uiPartDum,             uiPartIdxLT, true, false ) ) bLeftFlag       = true;
+  if( pcCU->getPUBelowLeftAdi ( uiPartDum, uiCuHeight, uiPartIdxLB, true, false ) ) bBelowLeftFlag  = true;
+  if( pcCU->getPUAboveLeft    ( uiPartDum,             uiPartIdxLT, true, false ) ) bAboveLeftFlag  = true;
+#if MN_DC_PRED_FILTER
+  m_bAboveFlagForDCFilt = bAboveFlag;
+  m_bLeftFlagForDCFilt  = bLeftFlag;
+#endif
+#endif // REFERENCE_SAMPLE_PADDING
+#endif //CONSTRAINED_INTRA_PRED
+
+#if MN_DC_PRED_FILTER
+  m_bDCPredFilterFlag = (m_bAboveFlagForDCFilt && m_bLeftFlagForDCFilt) ? true : false;
+#endif
+  
+#if REFERENCE_SAMPLE_PADDING
+  bAbove = true;
+  bLeft  = true;
+#else // REFERENCE_SAMPLE_PADDING
+  bAbove = bAboveFlag;
+  bLeft  = bLeftFlag;
+
+  Int iDCValue = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+#endif // REFERENCE_SAMPLE_PADDING
+  
+  uiWidth=uiCuWidth2+1;
+  uiHeight=uiCuHeight2+1;
+  
+  if (((uiWidth<<2)>iOrgBufStride)||((uiHeight<<2)>iOrgBufHeight))
+    return;
+  
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf;
+
+#if DEPTH_MAP_GENERATION
+  if( bPrdDepthMap )
+  {
+    piRoiOrigin = pcCU->getPic()->getPredDepthMap()->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiZorderIdxInPart );
+#if REFERENCE_SAMPLE_PADDING
+#else
+    iDCValue    = PDM_UNDEFINED_DEPTH;
+#endif
+  }
+#endif
+
+
+#if REFERENCE_SAMPLE_PADDING
+#if DEPTH_MAP_GENERATION
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, bPrdDepthMap );
+#else
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride );
+#endif
+  delete [] bNeighborFlags;
+  bNeighborFlags = NULL;
+#else // REFERENCE_SAMPLE_PADDING
+  //BB: fill border with DC value - needed if( bAboveFlag=false || bLeftFlag=false )
+  for (i=0;i<uiWidth;i++)
+    piAdiTemp[i]=iDCValue;
+  for (i=0;i<uiHeight;i++) //BB: can start from 1?
+    piAdiTemp[i*uiWidth]=iDCValue;
+  
+  piRoiTemp=piRoiOrigin; //BB: not needed?
+  
+  if (bAboveFlag)
+  {
+    // BB: fill top border with rec. samples
+    piRoiTemp=piRoiOrigin-iPicStride;
+    for (i=0;i<uiCuWidth;i++)
+      piAdiTemp[1+i]=piRoiTemp[i];
+    // BB: fill top right border with rec. samples
+    if (bAboveRightFlag)
+    {
+      piRoiTemp=piRoiOrigin-iPicStride+uiCuWidth;
+      for (i=0;i<uiCuWidth;i++)
+        piAdiTemp[1+uiCuWidth+i]=piRoiTemp[i];
+    }
+    // BB: fill top right border with last sample from top
+    else
+    {
+      for (i=0;i<uiCuWidth;i++)
+        piAdiTemp[1+uiCuWidth+i]=piAdiTemp[uiCuWidth];
+    }
+  }
+  
+  if (bAboveLeftFlag)
+  {
+    piRoiTemp=piRoiOrigin-iPicStride-1;
+    piAdiTemp[0]=piRoiTemp[0];
+  }
+
+  if (bLeftFlag)
+  {
+    // BB: fill left border with rec. samples
+    piRoiTemp=piRoiOrigin-1;
+    for (i=0;i<uiCuHeight;i++)
+    {
+      piAdiTemp[(1+i)*uiWidth]=piRoiTemp[0];
+      piRoiTemp+=iPicStride;
+    }
+    // BB: fill below left border with rec. samples
+    if (bBelowLeftFlag)
+    {
+      for (i=0;i<uiCuHeight;i++)
+      {
+        piAdiTemp[(1+uiCuHeight+i)*uiWidth]=piRoiTemp[0];
+        piRoiTemp+=iPicStride;
+      }
+    }
+    // BB: fill below left border with last sample from left
+    else
+    {
+      for (i=0;i<uiCuHeight;i++)
+        piAdiTemp[(1+uiCuHeight+i)*uiWidth]=piAdiTemp[(uiCuHeight)*uiWidth];
+    }
+  }
+#endif // REFERENCE_SAMPLE_PADDING
+  
+#if QC_MDIS
+  // 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
+  Int   i;
+
+  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++];
+
+#if !MN_MDIS_SIMPLIFICATION
+  // 2. filtering with [1 2 1]
+  piFilterBuf[0] = piFilterBufN[0];                   
+  piFilterBuf[iBufSize - 1] = piFilterBufN[iBufSize - 1];
+  for (i = 1; i < iBufSize - 1; i++)
+    piFilterBuf[i] = (piFilterBufN[i - 1] + 2 * piFilterBufN[i] + piFilterBufN[i + 1] + 2) >> 2;
+
+  // fill 2. filter buffer with filtered values
+  l=0;
+  for (i = 0; i < uiCuHeight2; i++)
+    piFilteredBuf2[uiWidth * (uiCuHeight2 - i)] = piFilterBuf[l++];
+  piFilteredBuf2[0] = piFilterBuf[l++];
+  for (i = 0; i < uiCuWidth2; i++)
+    piFilteredBuf2[1 + i] = piFilterBuf[l++];
+#endif
+#endif //QC_MDIS
+  
+}
+
+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   iCuAddr;
+#if REFERENCE_SAMPLE_PADDING
+  Int   iUnitSize = 0;
+  Int   iNumUnitsInCu = 0;
+  Int   iTotalUnits = 0;
+  Bool* bNeighborFlags;
+  Int   iNumIntraNeighbor = 0;
+#else // REFERENCE_SAMPLE_PADDING
+  Pel*  piRoiTemp;
+  Int   i;
+  Bool  bAboveFlag=false;
+  Bool  bAboveRightFlag=false;
+  Bool  bLeftFlag=false;
+  Bool  bBelowLeftFlag=false;
+  Bool  bAboveLeftFlag    = false;
+#endif // REFERENCE_SAMPLE_PADDING
+  
+  iCuAddr = pcCU->getAddr();
+  
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB,uiPartDum;
+  
+  pcCU->deriveLeftRightTopIdxAdi( uiPartIdxLT, uiPartIdxRT, uiZorderIdxInPart, uiPartDepth );
+  pcCU->deriveLeftBottomIdxAdi  ( uiPartIdxLB,              uiZorderIdxInPart, uiPartDepth );
+  
+#if CONSTRAINED_INTRA_PRED
+  if ( pcCU->getSlice()->getPPS()->getConstrainedIntraPred() )
+  {
+#if REFERENCE_SAMPLE_PADDING
+    iUnitSize      = (g_uiMaxCUWidth >> g_uiMaxCUDepth) >> 1; // for chroma
+    iNumUnitsInCu  = (uiCuWidth / iUnitSize) >> 1;            // for chroma
+    iTotalUnits    = (iNumUnitsInCu << 2) + 1;
+    bNeighborFlags = new Bool[iTotalUnits];
+
+    bNeighborFlags[iNumUnitsInCu*2] = isAboveLeftAvailableForCIP( pcCU, uiPartIdxLT );
+    iNumIntraNeighbor  += (Int)(bNeighborFlags[iNumUnitsInCu*2]);
+    iNumIntraNeighbor  += isAboveAvailableForCIP     ( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*2)+1 );
+    iNumIntraNeighbor  += isAboveRightAvailableForCIP( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*3)+1 );
+    iNumIntraNeighbor  += isLeftAvailableForCIP      ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+(iNumUnitsInCu*2)-1 );
+    iNumIntraNeighbor  += isBelowLeftAvailableForCIP ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+ iNumUnitsInCu   -1 );
+#else // REFERENCE_SAMPLE_PADDING
+    bAboveFlag      = isAboveAvailableForCIP     ( pcCU, uiPartIdxLT, uiPartIdxRT );
+    bAboveRightFlag = isAboveRightAvailableForCIP( pcCU, uiPartIdxLT, uiPartIdxRT );
+    bLeftFlag       = isLeftAvailableForCIP      ( pcCU, uiPartIdxLT, uiPartIdxLB );
+    bBelowLeftFlag  = isBelowLeftAvailableForCIP ( pcCU, uiPartIdxLT, uiPartIdxLB );
+    bAboveLeftFlag  = isAboveLeftAvailableForCIP ( pcCU, uiPartIdxLT );
+#endif // REFERENCE_SAMPLE_PADDING
+  }
+  else
+  {
+#if REFERENCE_SAMPLE_PADDING
+    iUnitSize     = uiCuWidth >> 1;
+    iNumUnitsInCu = 1;
+    iTotalUnits   = 5;
+    bNeighborFlags = new Bool[iTotalUnits];
+
+    ::memset(bNeighborFlags, false, sizeof(Bool)*iTotalUnits);
+    if( pcCU->getPUAbove        ( uiPartDum,             uiPartIdxLT,    true, false ) ) { bNeighborFlags[3] = true; iNumIntraNeighbor++; }
+    if( pcCU->getPUAboveRightAdi( uiPartDum, uiCuWidth,  uiPartIdxRT, 1, true, false ) ) { bNeighborFlags[4] = true; iNumIntraNeighbor++; }
+    if( pcCU->getPULeft         ( uiPartDum,             uiPartIdxLT,    true, false ) ) { bNeighborFlags[1] = true; iNumIntraNeighbor++; }
+    if( pcCU->getPUBelowLeftAdi ( uiPartDum, uiCuHeight, uiPartIdxLB, 1, true, false ) ) { bNeighborFlags[0] = true; iNumIntraNeighbor++; }
+    if( pcCU->getPUAboveLeft    ( uiPartDum,             uiPartIdxLT,    true, false ) ) { bNeighborFlags[2] = true; iNumIntraNeighbor++; }
+#else // REFERENCE_SAMPLE_PADDING
+    if( pcCU->getPUAbove        ( uiPartDum,             uiPartIdxLT,    true, false ) ) bAboveFlag      = true;
+    if( pcCU->getPUAboveRightAdi( uiPartDum, uiCuWidth,  uiPartIdxRT, 1, true, false ) ) bAboveRightFlag = true;
+    if( pcCU->getPULeft         ( uiPartDum,             uiPartIdxLT,    true, false ) ) bLeftFlag       = true;
+    if( pcCU->getPUBelowLeftAdi ( uiPartDum, uiCuHeight, uiPartIdxLB, 1, true, false ) ) bBelowLeftFlag  = true;
+    if( pcCU->getPUAboveLeft    ( uiPartDum,             uiPartIdxLT,    true, false ) ) bAboveLeftFlag  = true;
+#endif // REFERENCE_SAMPLE_PADDING
+  }
+#else //CONSTRAINED_INTRA_PRED
+#if REFERENCE_SAMPLE_PADDING
+  iUnitSize     = uiCuWidth >> 1;
+  iNumUnitsInCu = 1;
+  iTotalUnits   = 5;
+  bNeighborFlags = new Bool[iTotalUnits];
+
+  ::memset(bNeighborFlags, false, sizeof(Bool)*iTotalUnits);
+  if( pcCU->getPUAbove        ( uiPartDum,             uiPartIdxLT, true, false ) ) { bNeighborFlags[3] = true; iNumIntraNeighbor++; }
+  if( pcCU->getPUAboveRightAdi( uiPartDum, uiCuWidth,  uiPartIdxRT, true, false ) ) { bNeighborFlags[4] = true; iNumIntraNeighbor++; }
+  if( pcCU->getPULeft         ( uiPartDum,             uiPartIdxLT, true, false ) ) { bNeighborFlags[1] = true; iNumIntraNeighbor++; }
+  if( pcCU->getPUBelowLeftAdi ( uiPartDum, uiCuHeight, uiPartIdxLB, true, false ) ) { bNeighborFlags[0] = true; iNumIntraNeighbor++; }
+  if( pcCU->getPUAboveLeft    ( uiPartDum,             uiPartIdxLT, true, false ) ) { bNeighborFlags[2] = true; iNumIntraNeighbor++; }
+#else // REFERENCE_SAMPLE_PADDING
+  if( pcCU->getPUAbove        ( uiPartDum,             uiPartIdxLT, true, false ) ) bAboveFlag      = true;
+  if( pcCU->getPUAboveRightAdi( uiPartDum, uiCuWidth,  uiPartIdxRT, true, false ) ) bAboveRightFlag = true;
+  if( pcCU->getPULeft         ( uiPartDum,             uiPartIdxLT, true, false ) ) bLeftFlag       = true;
+  if( pcCU->getPUBelowLeftAdi ( uiPartDum, uiCuHeight, uiPartIdxLB, true, false ) ) bBelowLeftFlag  = true;
+  if( pcCU->getPUAboveLeft    ( uiPartDum,             uiPartIdxLT, true, false ) ) bAboveLeftFlag  = true;
+#endif // REFERENCE_SAMPLE_PADDING
+#endif //CONSTRAINED_INTRA_PRED
+  
+#if REFERENCE_SAMPLE_PADDING
+  bAbove = true;
+  bLeft  = true;
+#else // REFERENCE_SAMPLE_PADDING
+  bAbove = bAboveFlag;
+  bLeft  = bLeftFlag;
+
+  Int iDCValue = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+#endif // REFERENCE_SAMPLE_PADDING
+  
+  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 REFERENCE_SAMPLE_PADDING
+#if DEPTH_MAP_GENERATION
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, false );
+#else
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride );
+#endif
+#else // REFERENCE_SAMPLE_PADDING
+  for (i=0;i<uiWidth;i++)
+    piAdiTemp[i]=iDCValue;
+  for (i=0;i<uiHeight;i++)
+    piAdiTemp[i*uiWidth]=iDCValue;
+  
+  piRoiTemp=piRoiOrigin;
+  
+  if (bAboveFlag)
+  {
+    piRoiTemp=piRoiOrigin-iPicStride;
+    for (i=0;i<uiCuWidth;i++)
+      piAdiTemp[1+i]=piRoiTemp[i];
+    if (bAboveRightFlag)
+    {
+      piRoiTemp=piRoiOrigin-iPicStride+uiCuWidth;
+      for (i=0;i<uiCuWidth;i++)
+        piAdiTemp[1+uiCuWidth+i]=piRoiTemp[i];
+    }
+    else
+    {
+      for (i=0;i<uiCuWidth;i++)
+        piAdiTemp[1+uiCuWidth+i]=piAdiTemp[uiCuWidth];
+    }
+  }
+  
+  if (bAboveLeftFlag)
+  {
+    piRoiTemp=piRoiOrigin-iPicStride-1;
+    piAdiTemp[0]=piRoiTemp[0];
+  }
+
+  if (bLeftFlag)
+  {
+    piRoiTemp=piRoiOrigin-1;
+    for (i=0;i<uiCuHeight;i++)
+    {
+      piAdiTemp[(1+i)*uiWidth]=piRoiTemp[0];
+      piRoiTemp+=iPicStride;
+    }
+    if (bBelowLeftFlag)
+    {
+      for (i=0;i<uiCuHeight;i++)
+      {
+        piAdiTemp[(1+uiCuHeight+i)*uiWidth]=piRoiTemp[0];
+        piRoiTemp+=iPicStride;
+      }
+    }
+    else
+    {
+      for (i=0;i<uiCuHeight;i++)
+        piAdiTemp[(1+uiCuHeight+i)*uiWidth]=piAdiTemp[(uiCuHeight)*uiWidth];
+    }
+  }
+#endif // REFERENCE_SAMPLE_PADDING
+  
+  // get Cr pattern
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf+uiWidth*uiHeight;
+  
+#if REFERENCE_SAMPLE_PADDING
+#if DEPTH_MAP_GENERATION
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, false );
+#else
+  fillReferenceSamples ( pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride );
+#endif
+  delete [] bNeighborFlags;
+  bNeighborFlags = NULL;
+#else // REFERENCE_SAMPLE_PADDING
+  for (i=0;i<uiWidth;i++)
+    piAdiTemp[i]=iDCValue;
+  for (i=0;i<uiHeight;i++)
+    piAdiTemp[i*uiWidth]=iDCValue;
+  
+  piRoiTemp=piRoiOrigin;
+  
+  if (bAboveFlag)
+  {
+    piRoiTemp=piRoiOrigin-iPicStride;
+    for (i=0;i<uiCuWidth;i++)
+      piAdiTemp[1+i]=piRoiTemp[i];
+    if (bAboveRightFlag)
+    {
+      piRoiTemp=piRoiOrigin-iPicStride+uiCuWidth;
+      for (i=0;i<uiCuWidth;i++)
+        piAdiTemp[1+uiCuWidth+i]=piRoiTemp[i];
+    }
+    else
+    {
+      for (i=0;i<uiCuWidth;i++)
+        piAdiTemp[1+uiCuWidth+i]=piAdiTemp[uiCuWidth];
+    }
+  }
+
+  if (bAboveLeftFlag)
+  {
+    piRoiTemp=piRoiOrigin-iPicStride-1;
+    piAdiTemp[0]=piRoiTemp[0];
+  }
+
+  if (bLeftFlag)
+  {
+    piRoiTemp=piRoiOrigin-1;
+    for (i=0;i<uiCuHeight;i++)
+    {
+      piAdiTemp[(1+i)*uiWidth]=piRoiTemp[0];
+      piRoiTemp+=iPicStride;
+    }
+    if (bBelowLeftFlag)
+    {
+      for (i=0;i<uiCuHeight;i++)
+      {
+        piAdiTemp[(1+uiCuHeight+i)*uiWidth]=piRoiTemp[0];
+        piRoiTemp+=iPicStride;
+      }
+    }
+    else
+    {
+      for (i=0;i<uiCuHeight;i++)
+        piAdiTemp[(1+uiCuHeight+i)*uiWidth]=piAdiTemp[(uiCuHeight)*uiWidth];
+    }
+  }
+#endif // REFERENCE_SAMPLE_PADDING
+}
+
+#if REFERENCE_SAMPLE_PADDING
+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
+#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;
+    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 = new Pel[iTotalSamples];
+    Pel  *piAdiLineTemp; 
+    Bool *pbNeighborFlags;
+    Int  iPrev, 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;
+    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
+    iPrev = -1;
+    iCurr = 0;
+    iNext = 1;
+    piAdiLineTemp = piAdiLine;
+    while (iCurr < iTotalUnits)
+    {
+      if (bNeighborFlags[iCurr])
+      {
+        // Move on to next block if current unit is available
+        piAdiLineTemp += iUnitSize;
+        iPrev++;
+        iCurr++;
+        iNext++;
+      }
+      else
+      {
+        // Interpolate from nearest samples if current unit is not available
+        
+        while (iNext < iTotalUnits && !bNeighborFlags[iNext])
+          iNext++;
+
+        if (iPrev >= 0 && iNext < iTotalUnits)
+          piRef = (piAdiLine[iCurr*iUnitSize-1] + piAdiLine[iNext*iUnitSize] + 1) >> 1;
+        else if (iPrev >= 0)
+          piRef = piAdiLine[iCurr*iUnitSize-1];
+        else if (iNext < iTotalUnits)
+          piRef = piAdiLine[iNext*iUnitSize];
+        else
+          printf("\nERROR! No valid samples to interpolate.\n");
+
+        // Pad unavailable samples with new value
+        while (iCurr < iNext)
+        {
+          for (i=0; i<iUnitSize; i++)
+            piAdiLineTemp[i] = piRef;
+          piAdiLineTemp += iUnitSize;
+          iPrev++;
+          iCurr++;
+        }
+        iNext++;
+      }
+    }
+
+    // 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];
+
+    delete [] piAdiLine;
+    piAdiLine = NULL;
+  }
+}
+#endif // REFERENCE_SAMPLE_PADDING
+
+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);
+}
+
+#if QC_MDIS
+Int* TComPattern::getPredictorPtr ( UInt uiDirMode, UInt uiWidthBits, Int iCuWidth, Int iCuHeight, Int* piAdiBuf )
+{
+#if MN_MDIS_SIMPLIFICATION
+  static const UChar g_aucIntraFilter[7][34] =
+  {
+      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //2x2
+      {0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //4x4
+      {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //8x8
+      {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //16x16
+      {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, //32x32
+      {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //64x64
+      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}  //128x128
+  };
+#else
+  static const UChar g_aucIntraFilter[7][34] =
+  {
+      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //2x2
+      {0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //4x4
+      {0, 0, 0, 1, 1, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //8x8
+      {0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //16x16
+      {0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}, //32x32
+      {0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, //64x64
+      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}  //128x128
+  };
+#endif
+
+  Int* piSrc;
+#if ADD_PLANAR_MODE
+  mapPlanartoDC( uiDirMode );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  UChar ucFiltIdx = 0;
+  if ( uiDirMode < 34 )
+  {
+    ucFiltIdx = g_aucIntraFilter[uiWidthBits][uiDirMode];
+  }
+#else
+  UChar ucFiltIdx = g_aucIntraFilter[uiWidthBits][uiDirMode];
+#endif
+
+#if MN_MDIS_SIMPLIFICATION
+  assert( ucFiltIdx <= 1 );
+#else
+  assert( ucFiltIdx <= 2 );
+#endif
+
+  piSrc = getAdiOrgBuf( iCuWidth, iCuHeight, piAdiBuf );
+
+  if ( ucFiltIdx )
+  {
+#if MN_MDIS_SIMPLIFICATION
+    piSrc += ((iCuWidth << 1) + 1) * ((iCuHeight << 1) + 1);
+#else
+    piSrc += (((iCuWidth << 1) + 1) * ((iCuHeight << 1) + 1) << (ucFiltIdx - 1));
+#endif
+  }
+
+  return piSrc;
+}
+#endif //QC_MDIS
+
+#if CONSTRAINED_INTRA_PRED
+Bool TComPattern::isAboveLeftAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT )
+{
+  Bool bAboveLeftFlag;
+  UInt uiPartAboveLeft;
+  TComDataCU* pcCUAboveLeft = pcCU->getPUAboveLeft( uiPartAboveLeft, uiPartIdxLT, true, false );
+  bAboveLeftFlag = ( pcCUAboveLeft && pcCUAboveLeft->getPredictionMode( uiPartAboveLeft ) == MODE_INTRA );
+  return bAboveLeftFlag;
+}
+
+#if REFERENCE_SAMPLE_PADDING
+Int TComPattern::isAboveAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+#else
+Bool TComPattern::isAboveAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT )
+#endif
+{
+  const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
+  const UInt uiRasterPartEnd = g_auiZscanToRaster[uiPartIdxRT]+1;
+  const UInt uiIdxStep = 1;
+#if REFERENCE_SAMPLE_PADDING
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+#else
+  Bool bAboveFlag = true;
+#endif
+#if MN_DC_PRED_FILTER
+  m_bAboveFlagForDCFilt = true;
+#endif
+
+  for ( UInt uiRasterPart = uiRasterPartBegin; uiRasterPart < uiRasterPartEnd; uiRasterPart += uiIdxStep )
+  {
+    UInt uiPartAbove;
+    TComDataCU* pcCUAbove = pcCU->getPUAbove( uiPartAbove, g_auiRasterToZscan[uiRasterPart], true, false );
+#if REFERENCE_SAMPLE_PADDING
+    if ( pcCUAbove && pcCUAbove->getPredictionMode( uiPartAbove ) == MODE_INTRA )
+    {
+      iNumIntra++;
+      *pbValidFlags = true;
+    }
+    else
+    {
+      *pbValidFlags = false;
+#if MN_DC_PRED_FILTER
+      m_bAboveFlagForDCFilt = false;
+#endif
+    }
+    pbValidFlags++;
+#else
+    if ( !pcCUAbove || pcCUAbove->getPredictionMode( uiPartAbove ) != MODE_INTRA )
+    {
+      bAboveFlag = false;
+#if MN_DC_PRED_FILTER
+      m_bAboveFlagForDCFilt = false;
+#endif
+      break;
+    }
+#endif
+  }
+#if REFERENCE_SAMPLE_PADDING
+  return iNumIntra;
+#else
+  return bAboveFlag;
+#endif
+}
+
+#if REFERENCE_SAMPLE_PADDING
+Int TComPattern::isLeftAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+#else
+Bool TComPattern::isLeftAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB )
+#endif
+{
+  const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
+  const UInt uiRasterPartEnd = g_auiZscanToRaster[uiPartIdxLB]+1;
+  const UInt uiIdxStep = pcCU->getPic()->getNumPartInWidth();
+#if REFERENCE_SAMPLE_PADDING
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+#else
+  Bool bLeftFlag = true;
+#endif
+#if MN_DC_PRED_FILTER
+  m_bLeftFlagForDCFilt = true;
+#endif
+
+  for ( UInt uiRasterPart = uiRasterPartBegin; uiRasterPart < uiRasterPartEnd; uiRasterPart += uiIdxStep )
+  {
+    UInt uiPartLeft;
+    TComDataCU* pcCULeft = pcCU->getPULeft( uiPartLeft, g_auiRasterToZscan[uiRasterPart], true, false );
+#if REFERENCE_SAMPLE_PADDING
+    if ( pcCULeft && pcCULeft->getPredictionMode( uiPartLeft ) == MODE_INTRA )
+    {
+      iNumIntra++;
+      *pbValidFlags = true;
+    }
+    else
+    {
+      *pbValidFlags = false;
+#if MN_DC_PRED_FILTER
+      m_bLeftFlagForDCFilt = false;
+#endif
+    }
+    pbValidFlags--; // opposite direction
+#else
+    if ( !pcCULeft || pcCULeft->getPredictionMode( uiPartLeft ) != MODE_INTRA )
+    {
+      bLeftFlag = false;
+#if MN_DC_PRED_FILTER
+      m_bLeftFlagForDCFilt = false;
+#endif
+      break;
+    }
+#endif
+  }
+
+#if REFERENCE_SAMPLE_PADDING
+  return iNumIntra;
+#else
+  return bLeftFlag;
+#endif
+}
+
+#if REFERENCE_SAMPLE_PADDING
+Int TComPattern::isAboveRightAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+#else
+Bool TComPattern::isAboveRightAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT )
+#endif
+{
+  const UInt uiNumUnitsInPU = g_auiZscanToRaster[uiPartIdxRT] - g_auiZscanToRaster[uiPartIdxLT] + 1;
+  const UInt uiPuWidth = uiNumUnitsInPU * pcCU->getPic()->getMinCUWidth();
+#if REFERENCE_SAMPLE_PADDING
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+#else
+  Bool bAboveRightFlag = true;
+#endif
+
+  for ( UInt uiOffset = 1; uiOffset <= uiNumUnitsInPU; uiOffset++ )
+  {
+    UInt uiPartAboveRight;
+    TComDataCU* pcCUAboveRight = pcCU->getPUAboveRightAdi( uiPartAboveRight, uiPuWidth, uiPartIdxRT, uiOffset, true, false );
+#if REFERENCE_SAMPLE_PADDING
+    if ( pcCUAboveRight && pcCUAboveRight->getPredictionMode( uiPartAboveRight ) == MODE_INTRA )
+    {
+      iNumIntra++;
+      *pbValidFlags = true;
+    }
+    else
+    {
+      *pbValidFlags = false;
+    }
+    pbValidFlags++;
+#else
+    if ( !pcCUAboveRight || pcCUAboveRight->getPredictionMode( uiPartAboveRight ) != MODE_INTRA )
+    {
+      bAboveRightFlag = false;
+      break;
+    }
+#endif
+  }
+
+#if REFERENCE_SAMPLE_PADDING
+  return iNumIntra;
+#else
+  return bAboveRightFlag;
+#endif
+}
+
+#if REFERENCE_SAMPLE_PADDING
+Int TComPattern::isBelowLeftAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+#else
+Bool TComPattern::isBelowLeftAvailableForCIP( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB )
+#endif
+{
+  const UInt uiNumUnitsInPU = (g_auiZscanToRaster[uiPartIdxLB] - g_auiZscanToRaster[uiPartIdxLT]) / pcCU->getPic()->getNumPartInWidth() + 1;
+  const UInt uiPuHeight = uiNumUnitsInPU * pcCU->getPic()->getMinCUHeight();
+#if REFERENCE_SAMPLE_PADDING
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+#else
+  Bool bBelowLeftFlag = true;
+#endif
+
+  for ( UInt uiOffset = 1; uiOffset <= uiNumUnitsInPU; uiOffset++ )
+  {
+    UInt uiPartBelowLeft;
+    TComDataCU* pcCUBelowLeft = pcCU->getPUBelowLeftAdi( uiPartBelowLeft, uiPuHeight, uiPartIdxLB, uiOffset, true, false );
+#if REFERENCE_SAMPLE_PADDING
+    if ( pcCUBelowLeft && pcCUBelowLeft->getPredictionMode( uiPartBelowLeft ) == MODE_INTRA )
+    {
+      iNumIntra++;
+      *pbValidFlags = true;
+    }
+    else
+    {
+      *pbValidFlags = false;
+    }
+    pbValidFlags--; // opposite direction
+#else
+    if ( !pcCUBelowLeft || pcCUBelowLeft->getPredictionMode( uiPartBelowLeft ) != MODE_INTRA )
+    {
+      bBelowLeftFlag = false;
+      break;
+    }
+#endif
+  }
+
+#if REFERENCE_SAMPLE_PADDING
+  return iNumIntra;
+#else
+  return bBelowLeftFlag;
+#endif
+}
+#endif //CONSTRAINED_INTRA_PRED
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPattern.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPattern.h	(revision 19)
@@ -0,0 +1,225 @@
+/* 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     TComPattern.h
+    \brief    neighbouring pixel access classes (header)
+*/
+
+#ifndef __TCOMPATTERN__
+#define __TCOMPATTERN__
+
+// Include files
+#include <stdio.h>
+#include "CommonDef.h"
+
+// ====================================================================================================================
+// 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 MN_DC_PRED_FILTER
+  Bool m_bAboveFlagForDCFilt;
+  Bool m_bLeftFlagForDCFilt;
+  Bool m_bDCPredFilterFlag;
+#endif
+
+#if LM_CHROMA 
+  Bool m_bLeftAvailable;
+  Bool m_bAboveAvailable;
+#endif
+
+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 MN_DC_PRED_FILTER
+  Bool  getDCPredFilterFlag()     { return m_bDCPredFilterFlag; }
+#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 );
+  
+#if QC_MDIS
+  Int*  getPredictorPtr           ( UInt uiDirMode, UInt uiWidthBits, Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
+#endif //QC_MDIS
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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
+#if DEPTH_MAP_GENERATION
+                               ,Bool        bPrdDepthMap = false 
+#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 );
+
+#if LM_CHROMA 
+  Bool  isLeftAvailable()         { return m_bLeftAvailable; }
+  Bool  isAboveAvailable()        { return m_bAboveAvailable; }
+#endif
+
+#if (CONSTRAINED_INTRA_PRED || REFERENCE_SAMPLE_PADDING)
+private:
+
+#if REFERENCE_SAMPLE_PADDING
+  /// 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
+#if DEPTH_MAP_GENERATION
+                                    , Bool bPrdDepthMap 
+#endif
+                                    );
+#endif
+#if CONSTRAINED_INTRA_PRED
+  /// constrained intra prediction
+  Bool  isAboveLeftAvailableForCIP  ( TComDataCU* pcCU, UInt uiPartIdxLT );
+#if REFERENCE_SAMPLE_PADDING
+  Int   isAboveAvailableForCIP      ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
+  Int   isLeftAvailableForCIP       ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
+  Int   isAboveRightAvailableForCIP ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
+  Int   isBelowLeftAvailableForCIP  ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
+#else
+  Bool  isAboveAvailableForCIP      ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT );
+  Bool  isLeftAvailableForCIP       ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB );
+  Bool  isAboveRightAvailableForCIP ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT );
+  Bool  isBelowLeftAvailableForCIP  ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB );
+#endif
+#endif // CONSTRAINED_INTRA_PRED
+#endif
+};
+
+#endif // __TCOMPATTERN__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPic.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPic.cpp	(revision 19)
@@ -0,0 +1,350 @@
+/* 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     TComPic.cpp
+    \brief    picture class
+*/
+
+#include "TComPic.h"
+#include "SEI.h"
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComPic::TComPic()
+{
+  m_apcPicSym         = NULL;
+  m_apcPicYuv[0]      = NULL;
+  m_apcPicYuv[1]      = NULL;
+#if DEPTH_MAP_GENERATION
+  m_pcPredDepthMap    = NULL;
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  m_pcOrgDepthMap     = NULL;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_pcResidual        = NULL;
+#endif
+  m_pcPicYuvPred      = NULL;
+  m_pcPicYuvResi      = NULL;
+#if HHI_INTERVIEW_SKIP
+  m_pcUsedPelsMap     = NULL;
+#endif
+  
+#if PARALLEL_MERGED_DEBLK
+  m_pcPicYuvDeblkBuf     = NULL;
+#endif
+
+  m_bReconstructed    = false;
+
+  m_aiNumRefIdx[0]    = 0;
+  m_aiNumRefIdx[1]    = 0;
+
+  m_iViewIdx          = 0;
+  m_aaiCodedScale     = 0;
+  m_aaiCodedOffset    = 0;
+}
+
+TComPic::~TComPic()
+{
+}
+
+Void TComPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth )
+{
+  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->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;
+
+  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 DEPTH_MAP_GENERATION
+  if( m_pcPredDepthMap )
+  {
+    m_pcPredDepthMap->destroy();
+    delete m_pcPredDepthMap;
+    m_pcPredDepthMap = NULL;
+  }
+#endif
+
+#if HHI_INTER_VIEW_MOTION_PRED
+  if( m_pcOrgDepthMap )
+  {
+    m_pcOrgDepthMap->destroy();
+    delete m_pcOrgDepthMap;
+    m_pcOrgDepthMap = NULL;
+  }
+#endif
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  if( m_pcResidual )
+  {
+    m_pcResidual->destroy();
+    delete m_pcResidual;
+    m_pcResidual = NULL;
+  }
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  if( m_pcUsedPelsMap )
+  {
+    m_pcUsedPelsMap->destroy();
+    delete m_pcUsedPelsMap;
+    m_pcUsedPelsMap = NULL;
+  }
+#endif
+
+#if PARALLEL_MERGED_DEBLK
+  if (m_pcPicYuvDeblkBuf)
+  {
+    m_pcPicYuvDeblkBuf->destroy();
+    delete m_pcPicYuvDeblkBuf;
+    m_pcPicYuvDeblkBuf  = NULL;
+  }
+#endif
+
+  delete m_SEIs;
+}
+
+#if AMVP_BUFFERCOMPRESS
+Void TComPic::compressMotion()
+{
+  TComPicSym* pPicSym = getPicSym(); 
+  for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getFrameHeightInCU()*pPicSym->getFrameWidthInCU(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pPicSym->getCU(uiCUAddr);
+    pcCU->compressMV(); 
+  } 
+}
+#endif
+
+
+
+Void
+TComPic::addOriginalBuffer()
+{
+  AOT( m_apcPicYuv[0] );
+  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_apcPicYuv[0]      = new TComPicYuv;
+  m_apcPicYuv[0]      ->create( iWidth, iHeight, uiMaxCuWidth, uiMaxCuHeight, uiMaxCuDepth );
+}
+
+#if PARALLEL_MERGED_DEBLK
+Void
+TComPic::addDeblockBuffer()
+{
+  AOT( m_pcPicYuvDeblkBuf );
+  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_pcPicYuvDeblkBuf  = new TComPicYuv;
+  m_pcPicYuvDeblkBuf  ->create( iWidth, iHeight, uiMaxCuWidth, uiMaxCuHeight, uiMaxCuDepth );
+}
+#endif
+
+#if DEPTH_MAP_GENERATION
+Void
+TComPic::addPrdDepthMapBuffer()
+{
+  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, iHeight, uiMaxCuWidth, uiMaxCuHeight, uiMaxCuDepth );
+}
+#endif
+
+#if HHI_INTER_VIEW_MOTION_PRED
+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 HHI_INTER_VIEW_RESIDUAL_PRED
+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 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_apcPicYuv[1]->getMaxCuWidth ();
+  UInt  uiMaxCuHeight = m_apcPicYuv[1]->getMaxCuHeight();
+  UInt  uiMaxCuDepth  = m_apcPicYuv[1]->getMaxCuDepth ();
+  m_pcUsedPelsMap     = new TComPicYuv;
+  m_pcUsedPelsMap     ->create( iWidth, iHeight, uiMaxCuWidth, uiMaxCuHeight, uiMaxCuDepth );
+}
+#endif
+
+Void
+TComPic::removeOriginalBuffer()
+{
+  if( m_apcPicYuv[0] )
+  {
+    m_apcPicYuv[0]->destroy();
+    delete m_apcPicYuv[0];
+    m_apcPicYuv[0]  = NULL;
+  }
+}
+
+#if PARALLEL_MERGED_DEBLK
+Void
+TComPic::removeDeblockBuffer()
+{
+  if( m_pcPicYuvDeblkBuf )
+  {
+    m_pcPicYuvDeblkBuf->destroy();
+    delete m_pcPicYuvDeblkBuf;
+    m_pcPicYuvDeblkBuf  = NULL;
+  }
+}
+#endif
+
+#if DEPTH_MAP_GENERATION
+Void
+TComPic::removePrdDepthMapBuffer()
+{
+  if( m_pcPredDepthMap )
+  {
+    m_pcPredDepthMap->destroy();
+    delete m_pcPredDepthMap;
+    m_pcPredDepthMap = NULL;
+  }
+}
+#endif
+
+#if HHI_INTER_VIEW_MOTION_PRED
+Void
+TComPic::removeOrgDepthMapBuffer()
+{
+  if( m_pcOrgDepthMap )
+  {
+    m_pcOrgDepthMap->destroy();
+    delete m_pcOrgDepthMap;
+    m_pcOrgDepthMap = NULL;
+  }
+}
+#endif
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+Void
+TComPic::removeResidualBuffer()
+{
+  if( m_pcResidual )
+  {
+    m_pcResidual->destroy();
+    delete m_pcResidual;
+    m_pcResidual = NULL;
+  }
+}
+#endif
+
+#if HHI_INTERVIEW_SKIP
+Void
+TComPic::removeUsedPelsMapBuffer()
+{
+  if( m_pcUsedPelsMap )
+  {
+    m_pcUsedPelsMap->destroy();
+    delete m_pcUsedPelsMap;
+    m_pcUsedPelsMap = NULL;
+  }
+}
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPic.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPic.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPic.h	(revision 19)
@@ -0,0 +1,253 @@
+/* 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     TComPic.h
+    \brief    picture class (header)
+*/
+
+#ifndef __TCOMPIC__
+#define __TCOMPIC__
+
+// Include files
+#include "CommonDef.h"
+#include "TComPicSym.h"
+#include "TComPicYuv.h"
+#include "TComBitStream.h"
+#include "TComMVDRefData.h"
+
+class SEImessages;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture class (symbol + YUV buffers)
+class TComPic
+{
+private:
+  TComPicSym*           m_apcPicSym;              //  Symbol
+
+  TComPicYuv*           m_apcPicYuv[2];           //  Texture,  0:org / 1:rec
+#if DEPTH_MAP_GENERATION
+  TComPicYuv*           m_pcPredDepthMap;         //  estimated depth map
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  TComPicYuv*           m_pcOrgDepthMap;          //  original depth map
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  TComPicYuv*           m_pcResidual;             //  residual buffer (coded or inter-view predicted residual)
+#endif
+
+  TComPicYuv*           m_pcPicYuvPred;           //  Prediction
+  TComPicYuv*           m_pcPicYuvResi;           //  Residual
+#if PARALLEL_MERGED_DEBLK
+  TComPicYuv*           m_pcPicYuvDeblkBuf;
+#endif
+  Bool                  m_bReconstructed;
+  UInt                  m_uiCurrSliceIdx;         // Index of current slice
+
+  SEImessages* m_SEIs; ///< Any SEI messages that have been received.  If !NULL we own the object.
+
+  SliceType             m_eSliceType;
+  double                m_dQP;
+  Bool                  m_bReferenced;
+  UInt                  m_uiColDir;
+  Int                   m_aiRefPOCList[2][MAX_NUM_REF];
+  Int                   m_aiRefViewIdxList[2][MAX_NUM_REF];
+  Int                   m_aiNumRefIdx[2];    //  for multiple reference of current slice
+
+  Int                   m_iViewIdx;
+  Int**                 m_aaiCodedScale;
+  Int**                 m_aaiCodedOffset;
+
+#if HHI_VSO  
+  TComMVDRefData        m_cReferenceInfo;
+#endif
+#if HHI_INTERVIEW_SKIP
+  TComPicYuv*           m_pcUsedPelsMap;
+#endif
+
+
+public:
+  TComPic();
+  virtual ~TComPic();
+
+
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
+  Void          destroy();
+
+  TComPicSym*   getPicSym()           { return  m_apcPicSym;    }
+  TComSlice*    getSlice(Int i)       { return  m_apcPicSym->getSlice(i);  }
+  TComSlice*    getCurrSlice()        { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx);  }
+  TComSPS*      getSPS()              { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getSPS();  }
+  Int           getPOC()              { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getPOC();  }
+#if 0
+  Bool          getDRBFlag()          { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getDRBFlag();  }
+  Int           getERBIndex()         { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getERBIndex();  }
+#endif
+  TComDataCU*&  getCU( UInt uiCUAddr )  { return  m_apcPicSym->getCU( uiCUAddr ); }
+
+  SliceType     getSliceType()        { return m_eSliceType ;}
+  double        getQP()               { return m_dQP ;}
+  Bool          getReferenced()       { return m_bReferenced ;}
+
+  TComPicYuv*   getPicYuvOrg()        { return  m_apcPicYuv[0]; }
+  TComPicYuv*   getPicYuvRec()        { return  m_apcPicYuv[1]; }
+
+#if DEPTH_MAP_GENERATION
+  TComPicYuv*   getPredDepthMap()     { return  m_pcPredDepthMap; }
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  TComPicYuv*   getOrgDepthMap()      { return  m_pcOrgDepthMap; }
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  TComPicYuv*   getResidual()         { return  m_pcResidual; }
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  TComPicYuv*   getUsedPelsMap()      { return  m_pcUsedPelsMap; }
+#endif
+
+
+  TComPicYuv*   getPicYuvPred()       { return  m_pcPicYuvPred; }
+  TComPicYuv*   getPicYuvResi()       { return  m_pcPicYuvResi; }
+  Void          setPicYuvPred( TComPicYuv* pcPicYuv )       { m_pcPicYuvPred = pcPicYuv; }
+  Void          setPicYuvResi( TComPicYuv* pcPicYuv )       { m_pcPicYuvResi = pcPicYuv; }
+  Void          setQP( double dQP )   { m_dQP = dQP; }
+  Void          setSliceType( SliceType eSliceType ) { m_eSliceType = eSliceType; }
+  Void          setReferenced( Bool bReferenced )    { m_bReferenced = bReferenced; }
+  Void          setColDir( UInt uiColDir )           { m_uiColDir = uiColDir; }
+  UInt          getColDir()                          { return m_uiColDir; }
+  Void          setRefPOC( Int i, RefPicList e, Int iRefIdx ) { m_aiRefPOCList[e][iRefIdx] = i; }
+  Int           getRefPOC( RefPicList e, Int iRefIdx )        { return m_aiRefPOCList[e][iRefIdx]; }
+  Void          setRefViewIdx( Int i, RefPicList e, Int iRefIdx ) { m_aiRefViewIdxList[e][iRefIdx] = i; }
+  Int           getRefViewIdx( RefPicList e, Int iRefIdx )        { return m_aiRefViewIdxList[e][iRefIdx]; }
+  Int           getNumRefs( RefPicList e )                    { return m_aiNumRefIdx[e]; }
+  Void          setNumRefs( Int i, RefPicList e )             { m_aiNumRefIdx[e] = i; }
+  Void          setViewIdx( Int i )                           { m_iViewIdx = i; }
+  Int           getViewIdx()                                  { return m_iViewIdx; }
+
+  Void          setScaleOffset( Int** pS, Int** pO )  { m_aaiCodedScale = pS; m_aaiCodedOffset = pO; }
+  Int**         getCodedScale ()                      { return m_aaiCodedScale;  }
+  Int**         getCodedOffset()                      { return m_aaiCodedOffset; }
+
+#if HHI_VSO
+  TComMVDRefData* getMVDReferenceInfo() { return &m_cReferenceInfo; }
+#endif
+
+  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;  }
+
+#if AMVP_BUFFERCOMPRESS
+  Void          compressMotion();
+#endif
+  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();         }
+
+  Void          addOriginalBuffer       ();
+#if PARALLEL_MERGED_DEBLK
+  Void          addDeblockBuffer        ();
+#endif
+#if DEPTH_MAP_GENERATION
+  Void          addPrdDepthMapBuffer    ();
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  Void          addOrgDepthMapBuffer    ();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Void          addResidualBuffer       ();
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  Void          addUsedPelsMapBuffer    ();
+#endif
+
+  Void          removeOriginalBuffer    ();
+#if PARALLEL_MERGED_DEBLK
+  Void          removeDeblockBuffer     ();
+#endif
+#if DEPTH_MAP_GENERATION
+  Void          removePrdDepthMapBuffer ();
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  Void          removeOrgDepthMapBuffer ();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Void          removeResidualBuffer    ();
+#endif
+#if HHI_INTERVIEW_SKIP
+  Void          removeUsedPelsMapBuffer ();
+#endif
+
+#if PARALLEL_MERGED_DEBLK
+  TComPicYuv*   getPicYuvDeblkBuf()      { return  m_pcPicYuvDeblkBuf; }
+#endif
+
+  /** 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: /tags/0.2r1/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPicSym.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPicSym.cpp	(revision 19)
@@ -0,0 +1,91 @@
+
+
+/** \file     TComPicSym.cpp
+    \brief    picture symbol class
+*/
+
+#include "TComPicSym.h"
+
+// ====================================================================================================================
+// 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_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 );
+  }
+}
+
+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;
+}
+
+Void TComPicSym::allocateNewSlice()
+{
+  assert(m_uiNumCUsInFrame >= m_uiNumAllocatedSlice);
+  m_apcTComSlice[m_uiNumAllocatedSlice ++] = new TComSlice;
+}
+
+Void TComPicSym::clearSliceBuffer()
+{
+  UInt i;
+  for (i = 1; i < m_uiNumAllocatedSlice; i++)
+  {
+    delete m_apcTComSlice[i];
+  }
+  m_uiNumAllocatedSlice = 1;
+}
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPicSym.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPicSym.h	(revision 19)
@@ -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-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     TComPicSym.h
+    \brief    picture symbol class (header)
+*/
+
+#ifndef __TCOMPICSYM__
+#define __TCOMPICSYM__
+
+
+// Include files
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComDataCU.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// 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
+  
+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;               }
+  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;           }
+};// END CLASS DEFINITION TComPicSym
+
+
+#endif // __TCOMPICSYM__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 19)
@@ -0,0 +1,456 @@
+
+
+/** \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"
+
+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;
+  
+  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_uiMaxCuDepth    = uiMaxCUDepth;
+  
+  m_iNumCuInWidth   = m_iPicWidth / m_iCuWidth;
+  m_iNumCuInWidth  += ( m_iPicWidth % m_iCuWidth ) ? 1 : 0;
+  
+  m_iBaseUnitWidth  = uiMaxCUWidth  >> uiMaxCUDepth;
+  m_iBaseUnitHeight = uiMaxCUHeight >> uiMaxCUDepth;
+  
+  m_iLumaMarginX    = g_uiMaxCUWidth  + 12; // up to 12-tap DIF
+  m_iLumaMarginY    = g_uiMaxCUHeight + 12; // up to 12-tap DIF
+  
+  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;
+  
+  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; }
+}
+
+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;
+  
+  m_iLumaMarginX    = g_uiMaxCUWidth  + 12; // up to 12-tap DIF
+  m_iLumaMarginY    = g_uiMaxCUHeight + 12; // up to 12-tap DIF
+  
+  m_apiPicBufY      = (Pel*)xMalloc( Pel, ( m_iPicWidth       + (m_iLumaMarginX  <<1)) * ( m_iPicHeight       + (m_iLumaMarginY  <<1)));
+  m_piPicOrgY       = m_apiPicBufY + m_iLumaMarginY   * getStride()  + m_iLumaMarginX;
+  
+  return;
+}
+
+Void TComPicYuv::destroyLuma()
+{
+  m_piPicOrgY       = NULL;
+  
+  if( m_apiPicBufY ){ xFree( m_apiPicBufY );    m_apiPicBufY = NULL; }
+}
+
+Pel*  TComPicYuv::getLumaAddr( int iCuAddr )
+{
+  Int iCuX = iCuAddr % m_iNumCuInWidth;
+  Int iCuY = iCuAddr / m_iNumCuInWidth;
+  
+  return ( m_piPicOrgY + iCuY*m_iCuHeight*getStride() + iCuX*m_iCuWidth );
+}
+
+Pel*  TComPicYuv::getLumaAddr( Int iCuAddr, Int uiAbsZorderIdx )
+{
+  Int iCuX           = iCuAddr % m_iNumCuInWidth;
+  Int iCuY           = iCuAddr / m_iNumCuInWidth;
+  Int iOffsetCu      = iCuY*m_iCuHeight*getStride() + iCuX*m_iCuWidth;
+  
+  Int iCuSizeInBases = m_iCuWidth / m_iBaseUnitWidth;
+  Int iRastPartIdx   = g_auiZscanToRaster[uiAbsZorderIdx];
+  Int iBaseX         = iRastPartIdx % iCuSizeInBases;
+  Int iBaseY         = iRastPartIdx / iCuSizeInBases;
+  Int iOffsetBase    = iBaseY*m_iBaseUnitHeight*getStride() + iBaseX*m_iBaseUnitWidth;
+  
+  return (m_piPicOrgY + iOffsetCu + iOffsetBase);
+}
+
+Pel*  TComPicYuv::getCbAddr( int iCuAddr )
+{
+  Int iCuX = iCuAddr % m_iNumCuInWidth;
+  Int iCuY = iCuAddr / m_iNumCuInWidth;
+  
+  return ( m_piPicOrgU + ( ( iCuY*m_iCuHeight*getCStride() + iCuX*m_iCuWidth )>>1 ) );
+}
+
+Pel*  TComPicYuv::getCbAddr( Int iCuAddr, Int uiAbsZorderIdx )
+{
+  Int iCuX           = iCuAddr % m_iNumCuInWidth;
+  Int iCuY           = iCuAddr / m_iNumCuInWidth;
+  Int iOffsetCu      = iCuY*m_iCuHeight*getCStride() + iCuX*m_iCuWidth;
+  
+  Int iCuSizeInBases = m_iCuWidth / m_iBaseUnitWidth;
+  Int iRastPartIdx   = g_auiZscanToRaster[uiAbsZorderIdx];
+  Int iBaseX         = iRastPartIdx % iCuSizeInBases;
+  Int iBaseY         = iRastPartIdx / iCuSizeInBases;
+  Int iOffsetBase    = iBaseY*m_iBaseUnitHeight*getCStride() + iBaseX*m_iBaseUnitWidth;
+  
+  return (m_piPicOrgU + ( ( iOffsetCu + iOffsetBase)>>1 ) );
+}
+
+Pel*  TComPicYuv::getCrAddr( int iCuAddr )
+{
+  Int iCuX = iCuAddr % m_iNumCuInWidth;
+  Int iCuY = iCuAddr / m_iNumCuInWidth;
+  
+  return ( m_piPicOrgV + ( ( iCuY*m_iCuHeight*getCStride() + iCuX*m_iCuWidth )>>1 ) );
+}
+
+Pel*  TComPicYuv::getCrAddr( Int iCuAddr, Int uiAbsZorderIdx )
+{
+  Int iCuX           = iCuAddr % m_iNumCuInWidth;
+  Int iCuY           = iCuAddr / m_iNumCuInWidth;
+  Int iOffsetCu      = iCuY*m_iCuHeight*getCStride() + iCuX*m_iCuWidth;
+  
+  Int iCuSizeInBases = m_iCuWidth / m_iBaseUnitWidth;
+  Int iRastPartIdx   = g_auiZscanToRaster[uiAbsZorderIdx];
+  Int iBaseX         = iRastPartIdx % iCuSizeInBases;
+  Int iBaseY         = iRastPartIdx / iCuSizeInBases;
+  Int iOffsetBase    = iBaseY*m_iBaseUnitHeight*getCStride() + iBaseX*m_iBaseUnitWidth;
+  
+  return (m_piPicOrgV + ( ( iOffsetCu + iOffsetBase)>>1 ) );
+}
+
+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(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(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(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() >> 1, 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: /tags/0.2r1/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPicYuv.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPicYuv.h	(revision 19)
@@ -0,0 +1,182 @@
+/* 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     TComPicYuv.h
+    \brief    picture YUV buffer class (header)
+*/
+
+#ifndef __TCOMPICYUV__
+#define __TCOMPICYUV__
+
+#include <stdio.h>
+#include "CommonDef.h"
+
+// ====================================================================================================================
+// 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_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 );
+  Pel*  getCbAddr   ( Int iCuAddr );
+  Pel*  getCrAddr   ( Int iCuAddr );
+  Pel*  getLumaAddr ( Int iCuAddr, Int uiAbsZorderIdx );
+  Pel*  getCbAddr   ( Int iCuAddr, Int uiAbsZorderIdx );
+  Pel*  getCrAddr   ( Int iCuAddr, Int 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: /tags/0.2r1/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 19)
@@ -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-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 "TComPicYuv.h"
+#include "../libmd5/MD5.h"
+
+/**
+ * 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: /tags/0.2r1/source/Lib/TLibCommon/TComPredFilter.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPredFilter.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPredFilter.cpp	(revision 19)
@@ -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     TComPredFilter.cpp
+    \brief    interpolation filter class
+*/
+
+#include "TComPredFilter.h"
+
+// ====================================================================================================================
+// Constructor
+// ====================================================================================================================
+
+TComPredFilter::TComPredFilter()
+{
+  // initial number of taps for Luma
+}
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPredFilter.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPredFilter.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPredFilter.h	(revision 19)
@@ -0,0 +1,2235 @@
+/* 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     TComPredFilter.h
+    \brief    interpolation filter class (header)
+*/
+
+#ifndef __TCOMPREDFILTER__
+#define __TCOMPREDFILTER__
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+// Local type definitions
+#define HAL_IDX   1
+#define QU0_IDX   0
+#define QU1_IDX   2
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// interpolation filter class
+class TComPredFilter
+{
+public:
+  TComPredFilter();
+  
+  // 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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 TComPredFilter::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 // __TCOMPREDFILTER__
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPrediction.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPrediction.cpp	(revision 19)
@@ -0,0 +1,3011 @@
+/* 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     TComPrediction.cpp
+    \brief    prediction class
+*/
+
+#include <memory.h>
+#include "TComPrediction.h"
+
+// ====================================================================================================================
+// Constructor / destructor / initialize
+// ====================================================================================================================
+
+TComPrediction::TComPrediction()
+: m_pLumaRecBuffer(0)
+{
+  m_piYuvExt = NULL;
+}
+
+TComPrediction::~TComPrediction()
+{
+  m_cYuvExt.destroy();
+
+  delete[] m_piYuvExt;
+
+  m_acYuvPred[0].destroy();
+  m_acYuvPred[1].destroy();
+
+  m_cYuvPredTemp.destroy();
+
+#if LM_CHROMA  
+  if( m_pLumaRecBuffer )
+    delete [] m_pLumaRecBuffer;  
+#endif
+}
+
+Void TComPrediction::initTempBuff()
+{
+  if( m_piYuvExt == NULL )
+  {
+    m_iYuvExtHeight  = ((g_uiMaxCUHeight + 2) << 4);
+    m_iYuvExtStride = ((g_uiMaxCUWidth  + 8) << 4);
+    m_cYuvExt.create( m_iYuvExtStride, m_iYuvExtHeight );
+    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 );
+  }
+
+#if LM_CHROMA                      
+  m_iLumaRecStride =  (g_uiMaxCUWidth>>1) + 1;
+  m_pLumaRecBuffer = new Pel[ m_iLumaRecStride * m_iLumaRecStride ];
+
+  for( Int i = 1; i < 66; i++ )
+    m_uiaShift[i-1] = ( (1 << 15) + i/2 ) / i;
+#endif
+}
+
+// ====================================================================================================================
+// 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 )
+{
+  Int k,l;
+  Int blkSize        = width;
+  Pel* pDst          = rpDst;
+
+  // Map the mode index to main prediction direction and angle
+  Bool modeDC        = dirMode == 0;
+  Bool modeVer       = !modeDC && (dirMode < 18);
+  Bool modeHor       = !modeDC && !modeVer;
+  Int intraPredAngle = modeVer ? dirMode - 9 : modeHor ? dirMode - 25 : 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;
+    }
+
+    if (intraPredAngle == 0)
+    {
+      for (k=0;k<blkSize;k++)
+      {
+        for (l=0;l<blkSize;l++)
+        {
+          pDst[k*dstStride+l] = refMain[l+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;
+
+  // only assign variable in debug mode
+#ifndef NDEBUG
+  // get intra direction
+  Int iIntraSizeIdx = g_aucConvertToBit[ iWidth ] + 1;
+
+  assert( iIntraSizeIdx >= 1 ); //   4x  4
+  assert( iIntraSizeIdx <= 6 ); // 128x128
+  assert( iWidth == iHeight  );
+#endif //NDEBUG
+
+#if QC_MDIS
+  ptrSrc = pcTComPattern->getPredictorPtr( uiDirMode, g_aucConvertToBit[ iWidth ] + 1, iWidth, iHeight, m_piYuvExt );
+#else
+  ptrSrc = pcTComPattern->getAdiOrgBuf( iWidth, iHeight, m_piYuvExt );
+#endif //QC_MDIS
+
+  // get starting pixel in block
+  Int sw = ( iWidth<<1 ) + 1;
+
+#if ADD_PLANAR_MODE
+  if ( uiDirMode == PLANAR_IDX )
+  {
+#if REFERENCE_SAMPLE_PADDING
+    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
+#else
+    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, bAbove, bLeft );
+#endif
+    return;
+  }
+#endif
+
+  // get converted direction
+  uiDirMode = g_aucAngIntraModeOrder[ uiDirMode ];
+
+  // Create the prediction
+  xPredIntraAng( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove,  bLeft );
+
+#if MN_DC_PRED_FILTER
+  if ((uiDirMode == 0) && pcTComPattern->getDCPredFilterFlag())
+    xDCPredFiltering( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight);
+#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;
+  uiDirMode     = g_aucAngIntraModeOrder[ uiDirMode ];
+  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 == 0 ) // 0
+  {
+    iDC1  = xGetDCValDepth( iDCAbove, iDCAboveRight, iDCLeft,  iDCBelowLeft  );
+    iDC2  = xGetDCValDepth( iDCLeft,  iDCBelowLeft,  iDCAbove, iDCAboveRight );
+    iWgt  = 8;
+  }
+  else if( dirMode < 10 ) // 1..9
+  {
+    iDC1  = xGetDCValDepth( iDCAbove, iDCAboveRight, iDCLeft,  iDCBelowLeft  );
+    iDC2  = xGetDCValDepth( iDCLeft,  iDCBelowLeft,  iDCAbove, iDCAboveRight );
+    iWgt  = 7 + dirMode;
+  }
+  else if( dirMode < 18 ) // 10..17
+  {
+    iDC1  = xGetDCValDepth( iDCAbove, iDCAboveRight, iDCLeft,  iDCBelowLeft  );
+    iDC2  = xGetDCValDepth( iDCAboveRight, iDCAbove, iDCLeft,  iDCBelowLeft  );
+    iWgt  = 25 - dirMode;
+  }
+  else if( dirMode < 26 ) // 18..25
+  {
+    iDC1  = xGetDCValDepth( iDCAbove, iDCAboveRight, iDCLeft,  iDCBelowLeft  );
+    iDC2  = xGetDCValDepth( iDCLeft,  iDCBelowLeft,  iDCAbove, iDCAboveRight );
+    iWgt  = 25 - dirMode;
+  }
+  else if( dirMode < 34 )  // 26..33
+  {
+    iDC1  = xGetDCValDepth( iDCLeft,  iDCBelowLeft,  iDCAbove, iDCAboveRight );
+    iDC2  = xGetDCValDepth( iDCBelowLeft,  iDCLeft,  iDCAbove, iDCAboveRight );
+    iWgt  = 41 - dirMode;
+  }
+  else // 34 (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;
+    }
+  }
+}
+
+
+// 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 = ( iWidth<<1 ) + 1;
+
+#if ADD_PLANAR_MODE
+  if ( uiDirMode == PLANAR_IDX )
+  {
+#if REFERENCE_SAMPLE_PADDING
+    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
+#else
+    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, bAbove, bLeft );
+#endif
+    return;
+  }
+#endif
+
+  // get converted direction
+  uiDirMode = g_aucAngIntraModeOrder[ uiDirMode ];
+
+  // Create the prediction
+  xPredIntraAng( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove,  bLeft );
+}
+
+#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::xDeltaDCQuantScaleUp( TComDataCU* pcCU, Int& riDeltaDC )
+{
+  Int  iSign  = riDeltaDC < 0 ? -1 : 1;
+  UInt uiAbs  = abs( riDeltaDC );
+
+  Int iQp = pcCU->getQP(0);
+  Int iMax = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+  Double dStepSize = Clip3( 1, iMax, pow( 2.0, iQp/10.0 + g_dDeltaDCsQuantOffset ) );
+
+  riDeltaDC = iSign * roftoi( uiAbs * dStepSize );
+  return;
+}
+
+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::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( bAbove )
+  {
+    for( Int k = 0; k < pcWedgelet->getWidth(); k++ )
+    {
+      if( true == pabWedgePattern[k] )
+      {
+        iPredDC2 += piMask[k-iMaskStride];
+        uiNumSmpDC2++;
+      }
+      else
+      {
+        iPredDC1 += piMask[k-iMaskStride];
+        uiNumSmpDC1++;
+      }
+    }
+  }
+  if( bLeft )
+  {
+    for( Int k = 0; k < pcWedgelet->getHeight(); k++ )
+    {
+      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;
+  }
+}
+#endif
+
+#if HHI_DMM_WEDGE_INTRA
+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 );
+
+  if( bDelta ) 
+  {
+    xDeltaDCQuantScaleUp( pcCU, iDeltaDC1 );
+    xDeltaDCQuantScaleUp( pcCU, iDeltaDC2 );
+  }
+
+  // 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           ); }
+}
+
+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 );
+  WedgeList*    pacContDWedgeList    = &g_aacWedgeLists   [(g_aucConvertToBit[uiThisBlockSize])];
+  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 );
+        getWedgeListIdx( pacContDWedgeList, 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 );
+        getWedgeListIdx( pacContDWedgeList, 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 );
+    getWedgeListIdx( pacContDWedgeList, pacContDWedgeRefList, uiPredDirWedgeTabIdx, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye );
+    return uiPredDirWedgeTabIdx;
+  }
+
+  return uiPredDirWedgeTabIdx;
+}
+
+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 angTable[9] = {0,2,5,9,13,17,21,26,32};
+
+  Int uiPreds[2] = {-1, -1};
+  Int uiPredNum = pcCU->getIntraDirLumaPredictor( uiAbsPartIdx, uiPreds );
+
+  UInt uiDirMode = 0;
+  if( uiPredNum == 1 )
+  {
+    uiDirMode = g_aucAngIntraModeOrder[uiPreds[0]];
+  }
+  else if( uiPredNum == 2 )
+  {
+    uiDirMode = g_aucAngIntraModeOrder[uiPreds[1]];
+  }
+
+  if( uiDirMode == 0 ) 
+  { 
+    return false; 
+  }
+
+  Bool modeVer       = (uiDirMode < 18);
+  Bool modeHor       = !modeVer;
+  Int intraPredAngle = modeVer ? uiDirMode - 9 : modeHor ? uiDirMode - 25 : 0;
+  Int absAng         = abs(intraPredAngle);
+  Int signAng        = intraPredAngle < 0 ? -1 : 1;
+  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;
+  UInt uiOri;
+
+  // 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; }
+}
+
+  // case above
+  if( uiScaledStartPosX > 0 && uiScaledStartPosY == 0 )
+  {
+    ruhXs = (UChar)uiScaledStartPosX;
+    ruhYs = 0;
+
+    if( iDeltaY == 0 )
+{
+      if( iDeltaX < 0 )
+      {
+        uiOri = 0;
+        ruhXe = 0;
+        ruhYe = (UChar)Min( Max( iDeltaEnd, 0 ), (uiScaledBlockSize-1) );
+        return;
+      }
+      else
+      {
+        uiOri = 1;
+        ruhXe = (UChar)(uiScaledBlockSize-1); ;
+        ruhYe = (UChar)Min( Max( -iDeltaEnd, 0 ), (uiScaledBlockSize-1) );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+
+    // regular case
+    Int iVirtualEndX = (Int)ruhXs + roftoi( (Double)(uiScaledBlockSize-1) * ((Double)iDeltaX / (Double)iDeltaY) );
+
+    if( iVirtualEndX < 0 )
+    {
+      Int iYe = roftoi( (Double)(0 - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) + iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        uiOri = 0;
+        ruhXe = 0;
+        ruhYe = (UChar)Max( iYe, 0 );
+        return;
+      }
+      else
+      {
+        uiOri = 4;
+        ruhXe = (UChar)Min( (iYe - (uiScaledBlockSize-1)), (uiScaledBlockSize-1) );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+    else if( iVirtualEndX > (uiScaledBlockSize-1) )
+    {
+      Int iYe = roftoi( (Double)((Int)(uiScaledBlockSize-1) - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) - iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        uiOri = 1;
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)Max( iYe, 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        uiOri = 4;
+        ruhXe = (UChar)Max( ((uiScaledBlockSize-1) - (iYe - (uiScaledBlockSize-1))), 0 );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+    else
+    {
+      Int iXe = iVirtualEndX + iDeltaEnd;
+      if( iXe < 0 )
+      {
+        uiOri = 0;
+        ruhXe = 0;
+        ruhYe = (UChar)Max( ((uiScaledBlockSize-1) + iXe), 0 );
+        return;
+      }
+      else if( iXe > (uiScaledBlockSize-1) )
+      {
+        uiOri = 1;
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)Max( ((uiScaledBlockSize-1) - (iXe - (uiScaledBlockSize-1))), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        uiOri = 4;
+        ruhXe = (UChar)iXe;
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+  }
+
+  // case left
+  if( uiScaledStartPosY > 0 && uiScaledStartPosX == 0 )
+  {
+    ruhXs = 0;
+    ruhYs = (UChar)uiScaledStartPosY;
+
+    if( iDeltaX == 0 )
+    {
+      if( iDeltaY < 0 )
+      {
+        uiOri = 0;
+        ruhXe = (UChar)Min( Max( -iDeltaEnd, 0 ), (uiScaledBlockSize-1) );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        uiOri = 3;
+        ruhXe = (UChar)Min( Max( iDeltaEnd, 0 ), (uiScaledBlockSize-1) );
+        ruhYe = (UChar)(uiScaledBlockSize-1); 
+        return; 
+      }
+    }
+
+    // regular case
+    Int iVirtualEndY = (Int)ruhYs + roftoi( (Double)(uiScaledBlockSize-1) * ((Double)iDeltaY / (Double)iDeltaX) );
+
+    if( iVirtualEndY < 0 )
+    {
+      Int iXe = roftoi( (Double)(0 - (Int)ruhYs ) * ((Double)iDeltaX / (Double)iDeltaY) ) - iDeltaEnd;
+      if( iXe < (Int)uiScaledBlockSize )
+      {
+        uiOri = 0;
+        ruhXe = (UChar)Max( iXe, 0 );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        uiOri = 5;
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)Min( (iXe - (uiScaledBlockSize-1)), (uiScaledBlockSize-1) );
+        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 )
+      {
+        uiOri = 3;
+        ruhXe = (UChar)Max( iXe, 0 );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+      else
+      {
+        uiOri = 5;
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)Max( ((uiScaledBlockSize-1) - (iXe - (uiScaledBlockSize-1))), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+    else
+    {
+      Int iYe = iVirtualEndY - iDeltaEnd;
+      if( iYe < 0 )
+      {
+        uiOri = 0;
+        ruhXe = (UChar)Max( ((uiScaledBlockSize-1) + iYe), 0 );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else if( iYe > (uiScaledBlockSize-1) )
+      {
+        uiOri = 3;
+        ruhXe = (UChar)Max( ((uiScaledBlockSize-1) - (iYe - (uiScaledBlockSize-1))), 0 );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+      else
+      {
+        uiOri = 5;
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        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 )
+    {
+      uiOri = 1;
+      ruhXe = (UChar)(uiScaledBlockSize-1);
+      ruhYe = 0;
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+  }
+
+    if( iDeltaX == 0 )
+    {
+      uiOri = 0;
+      ruhXe = 0;
+      ruhYe = (UChar)(uiScaledBlockSize-1);
+      return;
+  }
+
+    Int iVirtualEndX = (Int)ruhXs + roftoi( (Double)(uiScaledBlockSize-1) * ((Double)iDeltaX / (Double)iDeltaY) );
+
+    if( iVirtualEndX > (uiScaledBlockSize-1) )
+    {
+      Int iYe = roftoi( (Double)((Int)(uiScaledBlockSize-1) - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) - iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        uiOri = 1;
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)Max( iYe, 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        uiOri = 3;
+        ruhXe = (UChar)Max( ((uiScaledBlockSize-1) - (iYe - (uiScaledBlockSize-1))), 0 );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+    else
+    {
+      Int iXe = iVirtualEndX + iDeltaEnd;
+      if( iXe < 0 )
+      {
+        uiOri = 0;
+        ruhXe = 0;
+        ruhYe = (UChar)Max( ((uiScaledBlockSize-1) + iXe), 0 );
+        return;
+      }
+      else if( iXe > (uiScaledBlockSize-1) )
+      {
+        uiOri = 1;
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)Max( ((uiScaledBlockSize-1) - (iXe - (uiScaledBlockSize-1))), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        uiOri = 3;
+        ruhXe = (UChar)iXe;
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+  }
+}
+
+Bool TComPrediction::getWedgeListIdx( WedgeList* pcWedgeList, WedgeRefList* pcWedgeRefList, UInt& ruiTabIdx, UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe )
+{
+  ruiTabIdx = 0;
+
+  for( UInt uiIdx = 0; uiIdx < pcWedgeList->size(); uiIdx++ )
+  {
+    TComWedgelet* pcTestWedge = &(pcWedgeList->at(uiIdx));
+
+    if( pcTestWedge->getStartX() == uhXs &&
+        pcTestWedge->getStartY() == uhYs &&
+        pcTestWedge->getEndX()   == uhXe &&
+        pcTestWedge->getEndY()   == uhYe    )
+    {
+      ruiTabIdx = uiIdx;
+      return true;
+    }
+  }
+
+  // additionally search in WedgeRef lists of duplicated patterns
+  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::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 );
+
+  if( bDelta ) 
+  {
+    xDeltaDCQuantScaleUp( pcCU, iDeltaDC1 );
+    xDeltaDCQuantScaleUp( pcCU, iDeltaDC2 );
+  }
+
+  // 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             ); }
+}
+#endif
+
+#if HHI_DMM_PRED_TEX
+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
+    uiTextureWedgeTabIdx = getBestWedgeFromText( pcCU, uiAbsPartIdx, (UInt)iWidth, (UInt)iHeight );
+    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 );
+
+  if( bDelta ) 
+  {
+    xDeltaDCQuantScaleUp( pcCU, iDeltaDC1 );
+    xDeltaDCQuantScaleUp( pcCU, iDeltaDC2 );
+  }
+
+  // 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 );
+  getBestContourFromText( 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 );
+
+  if( bDelta ) 
+  {
+    xDeltaDCQuantScaleUp( pcCU, iDeltaDC1 );
+    xDeltaDCQuantScaleUp( pcCU, iDeltaDC2 );
+  }
+
+  // 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;
+}
+
+Void TComPrediction::getBestContourFromText( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, TComWedgelet* pcContourWedge, Pel* piTextureBlock )
+{
+  pcContourWedge->clear();
+  Bool* pabContourPattern = pcContourWedge->getPattern();
+
+  // get copy of according texture luma block
+  Pel* piTempY = NULL;
+  TComYuv cTempYuv;
+
+  if ( piTextureBlock )
+  {
+    piTempY = piTextureBlock;
+  }
+  else
+  {
+    cTempYuv.create( uiWidth, uiHeight ); cTempYuv.clear();
+    piTempY      = cTempYuv.getLumaAddr();
+
+    fillTexturePicTempBlock( pcCU, uiAbsPartIdx, piTempY, uiWidth, uiHeight );
+
+    piTempY = cTempYuv.getLumaAddr();
+  }
+
+  // find contour for texture luma block
+  UInt iDC = 0;
+  for( UInt k = 0; k < (uiWidth*uiHeight); k++ ) { iDC += piTempY[k]; }
+  iDC /= (uiWidth*uiHeight);
+
+  if ( piTextureBlock )
+  {
+    piTempY = piTextureBlock;
+  }
+  else
+  {
+    piTempY = cTempYuv.getLumaAddr();
+  }
+
+  for( UInt k = 0; k < (uiWidth*uiHeight); k++ ) 
+  { 
+    pabContourPattern[k] = (piTempY[k] > iDC) ? true : false;
+  }
+
+  cTempYuv.destroy();
+}
+
+UInt TComPrediction::getBestWedgeFromText( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, WedgeDist eWedgeDist, Pel* piTextureBlock )
+{
+  assert( uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+
+  // get copy of according texture luma block
+  Pel* piTempY = NULL;    
+  TComYuv     cTempYuv; 
+
+  if ( piTextureBlock )
+  {
+    piTempY = piTextureBlock;
+  } 
+  else
+  {
+    cTempYuv.create( uiWidth, uiHeight ); cTempYuv.clear();
+    piTempY      = cTempYuv.getLumaAddr();
+
+    fillTexturePicTempBlock( pcCU, uiAbsPartIdx, piTempY, uiWidth, uiHeight );
+
+    piTempY = cTempYuv.getLumaAddr();
+  }
+  
+  TComWedgeDist cWedgeDist;
+  UInt uiTextureWedgeTabIdx = 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
+  UInt uiBestDist   = MAX_UINT;
+  UInt uiBestTabIdx = 0;
+
+  for( UInt uiIdx = 0; uiIdx < pacWedgeList->size(); uiIdx++ )
+  {
+    calcWedgeDCs       ( &(pacWedgeList->at(uiIdx)), piTempY,  uiWidth,  iDC1, iDC2 );
+    assignWedgeDCs2Pred( &(pacWedgeList->at(uiIdx)), piPred, uiPredStride, iDC1, iDC2 );
+
+    UInt uiActDist = cWedgeDist.getDistPart( piPred, uiPredStride, piTempY, uiWidth, uiWidth, uiHeight, eWedgeDist );
+
+    if( uiActDist < uiBestDist || uiBestDist == MAX_UINT )
+    {
+      uiBestDist   = uiActDist;
+      uiBestTabIdx = uiIdx;
+    }
+  }
+  uiTextureWedgeTabIdx = uiBestTabIdx;
+
+  cPredYuv.destroy();
+  cTempYuv.destroy();
+  return uiTextureWedgeTabIdx;
+}
+
+Void TComPrediction::fillTexturePicTempBlock( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piTempBlockY, 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(piTempBlockY, piRefY, sizeof(Pel)*uiWidth);
+    piTempBlockY += uiWidth;
+    piRefY += iRefStride;
+  }
+}
+#endif
+
+Void TComPrediction::motionCompensation ( TComDataCU* pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList, Int iPartIdx, Bool bPrdDepthMap )
+{
+  Int         iWidth;
+  Int         iHeight;
+  UInt        uiPartAddr;
+
+  if ( iPartIdx >= 0 )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+    if ( eRefPicList != REF_PIC_LIST_X )
+    {
+      xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap );
+#ifdef WEIGHT_PRED
+      if ( pcCU->getSlice()->getPPS()->getUseWP() )
+      {
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx );
+      }
+#endif    
+    }
+    else
+    {
+      xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred, iPartIdx, bPrdDepthMap );
+
+    }
+    return;
+  }
+
+  for ( iPartIdx = 0; iPartIdx < pcCU->getNumPartInter(); iPartIdx++ )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+
+    if ( eRefPicList != REF_PIC_LIST_X )
+    {
+      xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx, bPrdDepthMap );
+#ifdef WEIGHT_PRED
+      if ( pcCU->getSlice()->getPPS()->getUseWP() )
+      {
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, iPartIdx );
+      }
+#endif
+    }
+    else
+    {
+      xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred, iPartIdx, bPrdDepthMap );
+    }
+  }
+  return;
+}
+
+#if HIGH_ACCURACY_BI
+#if DEPTH_MAP_GENERATION
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap, Bool bi )
+#else
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bi )
+#endif
+#else
+#if DEPTH_MAP_GENERATION
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap )
+#else
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx )
+#endif
+#endif
+{
+  Int         iRefIdx     = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           assert (iRefIdx >= 0);
+  TComMv      cMv         = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
+  pcCU->clipMv(cMv);
+
+#if DEPTH_MAP_GENERATION
+  if( bPrdDepthMap )
+  {
+#if HIGH_ACCURACY_BI
+    UInt uiRShift = ( bi ? 14-g_uiBitDepth-g_uiBitIncrement : 0 );
+#else
+    UInt uiRShift = 0;
+#endif
+    xPredInterPrdDepthMap( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPredDepthMap(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, uiRShift, PDM_DEPTH_MAP_MCP_FILTER );
+    return;
+  }
+#endif
+
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getSPS()->isDepth() )
+  {
+#if HIGH_ACCURACY_BI
+    UInt uiRShift = ( bi ? 14-g_uiBitDepth-g_uiBitIncrement : 0 );
+#else
+    UInt uiRShift = 0;
+#endif
+    xPredInterPrdDepthMap( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, uiRShift, 2 );
+  }
+  else
+  {
+#endif
+#if HIGH_ACCURACY_BI
+  if(!bi)
+  {
+    xPredInterLumaBlk ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec()    , uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred );
+  }
+  else
+  {
+    xPredInterLumaBlk_ha  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec()    , uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred );
+  }
+#else
+  xPredInterLumaBlk       ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred );
+#endif
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  }
+#endif
+
+#if HIGH_ACCURACY_BI
+  if (!bi)
+  {
+    xPredInterChromaBlk     ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred );
+  }
+  else
+  {
+    xPredInterChromaBlk_ha ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec()    , uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred );
+  }
+#else
+  xPredInterChromaBlk     ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred );
+#endif
+}
+
+Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap )
+{
+  TComYuv* pcMbYuv;
+  Int      iRefIdx[2] = {-1, -1};
+
+  for ( Int iRefList = 0; iRefList < 2; iRefList++ )
+  {
+    RefPicList eRefPicList = (iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
+    iRefIdx[iRefList] = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+
+    if ( iRefIdx[iRefList] < 0 )
+    {
+      continue;
+    }
+
+    assert( iRefIdx[iRefList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );
+
+    pcMbYuv = &m_acYuvPred[iRefList];
+#if HIGH_ACCURACY_BI
+    if( pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiPartAddr ) >= 0 && pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiPartAddr ) >= 0 )
+#if DEPTH_MAP_GENERATION
+      xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap, true );
+#else
+      xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, true );
+#endif
+    else
+#if DEPTH_MAP_GENERATION
+     xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap );
+#else
+     xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx );
+#endif
+#else
+#if DEPTH_MAP_GENERATION
+    xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx, bPrdDepthMap );
+#else
+    xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, iPartIdx );
+#endif
+#endif
+  }
+
+#ifdef WEIGHT_PRED
+  if ( pcCU->getSlice()->getPPS()->getWPBiPredIdc() )
+  {
+    xWeightedPredictionBi( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+  }
+  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, TComYuv*& rpcYuv, UInt uiRShift, UInt uiFilterMode ) // 0:std, 1:bilin, 2:nearest neighbour
+{
+  AOF( uiFilterMode <= 2 );
+
+  Int     iFPelMask   = ~3;
+  Int     iRefStride  = pcPicYuvRef->getStride();
+  Int     iDstStride  = rpcYuv->getStride();
+  Int     iHor        = ( uiFilterMode == 2 ? ( pcMv->getHor() + 2 ) & iFPelMask : pcMv->getHor() );
+  Int     iVer        = ( uiFilterMode == 2 ? ( pcMv->getVer() + 2 ) & iFPelMask : pcMv->getVer() );
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getSPS()->isDepth() )
+  {
+    assert( uiFilterMode == 2 );
+    iHor = pcMv->getHor() * 4;
+    iVer = pcMv->getVer() * 4;
+  }
+#endif
+  Int     iRefOffset  = ( iHor >> 2 ) + ( iVer >> 2 ) * iRefStride;
+  Int     ixFrac      = iHor & 0x3;
+  Int     iyFrac      = iVer & 0x3;
+  Pel*    piRefY      = pcPicYuvRef->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+  Pel*    piDstY      = rpcYuv->getLumaAddr( uiPartAddr );
+
+  //  Integer position
+  if( ixFrac == 0 && iyFrac == 0 )
+  {
+    for( Int y = 0; y < iHeight; y++, piDstY += iDstStride, piRefY += iRefStride )
+    {
+      for( Int x = 0; x < iWidth; x++ )
+      {
+        piDstY[ x ] = piRefY[ x ] << uiRShift;
+      }
+    }
+    return;
+  }
+
+  // bi-linear interpolation
+  if( uiFilterMode == 1 )
+  {
+    Int   iW00    = ( 4 - ixFrac ) * ( 4 - iyFrac );
+    Int   iW01    = (     ixFrac ) * ( 4 - iyFrac );
+    Int   iW10    = ( 4 - ixFrac ) * (     iyFrac );
+    Int   iW11    = (     ixFrac ) * (     iyFrac );
+    Pel*  piRefY1 = piRefY + iRefStride;
+    for( Int y = 0; y < iHeight; y++, piDstY += iDstStride, piRefY += iRefStride, piRefY1 += iRefStride )
+    {
+      for( Int x = 0; x < iWidth; x++ )
+      {
+        Int iSV     = iW00 * piRefY [ x ] + iW01 * piRefY [ x + 1 ]
+                    + iW10 * piRefY1[ x ] + iW11 * piRefY1[ x + 1 ];
+        iSV       <<= uiRShift;
+        piDstY[ x ] = ( iSV + 8 ) >> 4;
+      }
+    }
+    return;
+  }
+
+  xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, pcMv, iWidth, iHeight, rpcYuv );
+  return;
+}
+
+
+
+#if HIGH_ACCURACY_BI
+
+Void  TComPrediction::xPredInterLumaBlk_ha( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight, TComYuv*& rpcYuv )
+{
+  Int     iRefStride = pcPicYuvRef->getStride();
+  Int     iDstStride = rpcYuv->getStride();
+
+  Int     iRefOffset = ( pcMv->getHor() >> 2 ) + ( pcMv->getVer() >> 2 ) * iRefStride;
+  Pel*    piRefY     = pcPicYuvRef->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+
+  Int     ixFrac  = pcMv->getHor() & 0x3;
+  Int     iyFrac  = pcMv->getVer() & 0x3;
+
+  Pel* piDstY = rpcYuv->getLumaAddr( uiPartAddr );
+    UInt shiftNum = 14-g_uiBitDepth-g_uiBitIncrement;
+  //  Integer point
+  if ( ixFrac == 0 && iyFrac == 0 )
+  {
+    for ( Int y = 0; y < iHeight; y++ )
+    {
+      for(Int x=0; x<iWidth; x++)
+        piDstY[x] = piRefY[x]<<shiftNum;
+      piDstY += iDstStride;
+      piRefY += iRefStride;
+    }
+    return;
+  }
+
+  //  Half-pel horizontal
+  if ( ixFrac == 2 && iyFrac == 0 )
+  {
+    xCTI_FilterHalfHor_ha ( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+    return;
+  }
+
+  //  Half-pel vertical
+  if ( ixFrac == 0 && iyFrac == 2 )
+  {
+    xCTI_FilterHalfVer_ha ( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+    return;
+  }
+
+  Int   iExtStride = m_iYuvExtStride;//m_cYuvExt.getStride();
+  Int*  piExtY     = m_piYuvExt;//m_cYuvExt.getLumaAddr();
+
+  //  Half-pel center
+  if ( ixFrac == 2 && iyFrac == 2 )
+  {
+    xCTI_FilterHalfVer (piRefY - 3,  iRefStride, 1, iWidth +7, iHeight, iExtStride, 1, piExtY );
+    xCTI_FilterHalfHor_ha (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+    return;
+  }
+
+  //  Quater-pel horizontal
+  if ( iyFrac == 0)
+  {
+    if ( ixFrac == 1)
+    {
+      xCTI_FilterQuarter0Hor_ha( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if ( ixFrac == 3)
+    {
+      xCTI_FilterQuarter1Hor_ha( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+  if ( iyFrac == 2 )
+  {
+    if ( ixFrac == 1)
+    {
+      xCTI_FilterHalfVer (piRefY -3,  iRefStride, 1, iWidth +7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter0Hor_ha (piExtY + 3,  iExtStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if ( ixFrac == 3)
+    {
+      xCTI_FilterHalfVer (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter1Hor_ha (piExtY + 3,  iExtStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+
+  //  Quater-pel vertical
+  if( ixFrac == 0 )
+  {
+    if( iyFrac == 1 )
+    {
+      xCTI_FilterQuarter0Ver_ha( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if( iyFrac == 3 )
+    {
+      xCTI_FilterQuarter1Ver_ha( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+
+  if( ixFrac == 2 )
+  {
+    if( iyFrac == 1 )
+    {
+      xCTI_FilterQuarter0Ver (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterHalfHor_ha (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+
+      return;
+    }
+    if( iyFrac == 3 )
+    {
+      xCTI_FilterQuarter1Ver (piRefY -3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterHalfHor_ha (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+
+  /// Quarter-pel center
+  if ( iyFrac == 1)
+  {
+    if ( ixFrac == 1)
+    {
+      xCTI_FilterQuarter0Ver (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter0Hor_ha (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if ( ixFrac == 3)
+    {
+      xCTI_FilterQuarter0Ver (piRefY - 3,  iRefStride, 1, iWidth +7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter1Hor_ha (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+
+      return;
+    }
+  }
+  if ( iyFrac == 3 )
+  {
+    if ( ixFrac == 1)
+    {
+      xCTI_FilterQuarter1Ver (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter0Hor_ha (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if ( ixFrac == 3)
+    {
+      xCTI_FilterQuarter1Ver (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter1Hor_ha (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+}
+
+#endif
+
+Void  TComPrediction::xPredInterLumaBlk( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight, TComYuv*& rpcYuv )
+{
+  Int     iRefStride = pcPicYuvRef->getStride();
+  Int     iDstStride = rpcYuv->getStride();
+
+  Int     iRefOffset = ( pcMv->getHor() >> 2 ) + ( pcMv->getVer() >> 2 ) * iRefStride;
+  Pel*    piRefY     = pcPicYuvRef->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+
+  Int     ixFrac  = pcMv->getHor() & 0x3;
+  Int     iyFrac  = pcMv->getVer() & 0x3;
+
+  Pel* piDstY = rpcYuv->getLumaAddr( uiPartAddr );
+
+  //  Integer point
+  if ( ixFrac == 0 && iyFrac == 0 )
+  {
+    for ( Int y = 0; y < iHeight; y++ )
+    {
+      ::memcpy(piDstY, piRefY, sizeof(Pel)*iWidth);
+      piDstY += iDstStride;
+      piRefY += iRefStride;
+    }
+    return;
+  }
+
+  //  Half-pel horizontal
+  if ( ixFrac == 2 && iyFrac == 0 )
+  {
+    xCTI_FilterHalfHor ( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+    return;
+  }
+
+  //  Half-pel vertical
+  if ( ixFrac == 0 && iyFrac == 2 )
+  {
+    xCTI_FilterHalfVer ( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+    return;
+  }
+
+  Int   iExtStride = m_iYuvExtStride;//m_cYuvExt.getStride();
+  Int*  piExtY     = m_piYuvExt;//m_cYuvExt.getLumaAddr();
+
+  //  Half-pel center
+  if ( ixFrac == 2 && iyFrac == 2 )
+  {
+
+    xCTI_FilterHalfVer (piRefY - 3,  iRefStride, 1, iWidth +7, iHeight, iExtStride, 1, piExtY );
+    xCTI_FilterHalfHor (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+    return;
+  }
+
+  //  Quater-pel horizontal
+  if ( iyFrac == 0)
+  {
+    if ( ixFrac == 1)
+    {
+      xCTI_FilterQuarter0Hor( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if ( ixFrac == 3)
+    {
+      xCTI_FilterQuarter1Hor( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+  if ( iyFrac == 2 )
+  {
+    if ( ixFrac == 1)
+    {
+      xCTI_FilterHalfVer (piRefY -3,  iRefStride, 1, iWidth +7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter0Hor (piExtY + 3,  iExtStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if ( ixFrac == 3)
+    {
+      xCTI_FilterHalfVer (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter1Hor (piExtY + 3,  iExtStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+
+  //  Quater-pel vertical
+  if( ixFrac == 0 )
+  {
+    if( iyFrac == 1 )
+    {
+      xCTI_FilterQuarter0Ver( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if( iyFrac == 3 )
+    {
+      xCTI_FilterQuarter1Ver( piRefY, iRefStride, 1, iWidth, iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+
+  if( ixFrac == 2 )
+  {
+    if( iyFrac == 1 )
+    {
+      xCTI_FilterQuarter0Ver (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterHalfHor (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if( iyFrac == 3 )
+    {
+      xCTI_FilterQuarter1Ver (piRefY -3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterHalfHor (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+
+  /// Quarter-pel center
+  if ( iyFrac == 1)
+  {
+    if ( ixFrac == 1)
+    {
+      xCTI_FilterQuarter0Ver (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter0Hor (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if ( ixFrac == 3)
+    {
+      xCTI_FilterQuarter0Ver (piRefY - 3,  iRefStride, 1, iWidth +7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter1Hor (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+  if ( iyFrac == 3 )
+  {
+    if ( ixFrac == 1)
+    {
+      xCTI_FilterQuarter1Ver (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter0Hor (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+    if ( ixFrac == 3)
+    {
+      xCTI_FilterQuarter1Ver (piRefY - 3,  iRefStride, 1, iWidth + 7, iHeight, iExtStride, 1, piExtY );
+      xCTI_FilterQuarter1Hor (piExtY + 3,  iExtStride, 1, iWidth    , iHeight, iDstStride, 1, piDstY );
+      return;
+    }
+  }
+}
+
+#if HIGH_ACCURACY_BI
+Void TComPrediction::xPredInterChromaBlk_ha( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight, TComYuv*& rpcYuv )
+{
+  Int     iRefStride  = pcPicYuvRef->getCStride();
+  Int     iDstStride  = rpcYuv->getCStride();
+
+  Int     iRefOffset  = (pcMv->getHor() >> 3) + (pcMv->getVer() >> 3) * iRefStride;
+
+  Pel*    piRefCb     = pcPicYuvRef->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+  Pel*    piRefCr     = pcPicYuvRef->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+
+  Pel* piDstCb = rpcYuv->getCbAddr( uiPartAddr );
+  Pel* piDstCr = rpcYuv->getCrAddr( uiPartAddr );
+
+  Int     ixFrac  = pcMv->getHor() & 0x7;
+  Int     iyFrac  = pcMv->getVer() & 0x7;
+  UInt    uiCWidth  = iWidth  >> 1;
+  UInt    uiCHeight = iHeight >> 1;
+
+  xDCTIF_FilterC_ha(piRefCb, iRefStride,piDstCb,iDstStride,uiCWidth,uiCHeight, iyFrac, ixFrac);
+  xDCTIF_FilterC_ha(piRefCr, iRefStride,piDstCr,iDstStride,uiCWidth,uiCHeight, iyFrac, ixFrac);
+  return;
+}
+#endif
+
+//--
+Void TComPrediction::xPredInterChromaBlk( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight, TComYuv*& rpcYuv )
+{
+  Int     iRefStride  = pcPicYuvRef->getCStride();
+  Int     iDstStride  = rpcYuv->getCStride();
+
+  Int     iRefOffset  = (pcMv->getHor() >> 3) + (pcMv->getVer() >> 3) * iRefStride;
+
+  Pel*    piRefCb     = pcPicYuvRef->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+  Pel*    piRefCr     = pcPicYuvRef->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr ) + iRefOffset;
+
+  Pel* piDstCb = rpcYuv->getCbAddr( uiPartAddr );
+  Pel* piDstCr = rpcYuv->getCrAddr( uiPartAddr );
+
+  Int     ixFrac  = pcMv->getHor() & 0x7;
+  Int     iyFrac  = pcMv->getVer() & 0x7;
+  UInt    uiCWidth  = iWidth  >> 1;
+  UInt    uiCHeight = iHeight >> 1;
+
+  xDCTIF_FilterC(piRefCb, iRefStride,piDstCb,iDstStride,uiCWidth,uiCHeight, iyFrac, ixFrac);
+  xDCTIF_FilterC(piRefCr, iRefStride,piDstCr,iDstStride,uiCWidth,uiCHeight, iyFrac, ixFrac);
+  return;
+}
+
+Void  TComPrediction::xDCTIF_FilterC ( Pel*  piRefC, Int iRefStride,Pel*  piDstC,Int iDstStride,
+                                       Int iWidth, Int iHeight,Int iMVyFrac,Int iMVxFrac)
+{
+  // Integer point
+  if ( iMVxFrac == 0 && iMVyFrac == 0 )
+  {
+    for ( Int y = 0; y < iHeight; y++ )
+    {
+      ::memcpy(piDstC, piRefC, sizeof(Pel)*iWidth);
+      piDstC += iDstStride;
+      piRefC += iRefStride;
+    }
+    return;
+  }
+
+  if ( iMVyFrac == 0 )
+  {
+    xCTI_Filter1DHorC (piRefC, iRefStride,  iWidth, iHeight, iDstStride,  piDstC, iMVxFrac );
+    return;
+  }
+
+  if ( iMVxFrac == 0 )
+  {
+    xCTI_Filter1DVerC (piRefC, iRefStride,  iWidth, iHeight, iDstStride,  piDstC, iMVyFrac );
+    return;
+}
+
+  Int   iExtStride = m_iYuvExtStride;
+  Int*  piExtC     = m_piYuvExt;
+
+  xCTI_Filter2DVerC (piRefC - 1,  iRefStride,  iWidth + 3, iHeight, iExtStride,  piExtC, iMVyFrac );
+  xCTI_Filter2DHorC (piExtC + 1,  iExtStride,  iWidth             , iHeight, iDstStride,  piDstC, iMVxFrac );
+}
+
+#if HIGH_ACCURACY_BI
+
+Void  TComPrediction::xDCTIF_FilterC_ha ( Pel*  piRefC, Int iRefStride,Pel*  piDstC,Int iDstStride,
+                                       Int iWidth, Int iHeight,Int iMVyFrac,Int iMVxFrac)
+{
+  UInt    shiftNumOrg = 6 - g_uiBitIncrement + 8 - g_uiBitDepth;
+  // Integer point
+  if ( iMVxFrac == 0 && iMVyFrac == 0 )
+  {
+    for (Int y = 0; y < iHeight; y++ )
+    {
+      for(Int x=0; x<iWidth; x++)
+      {
+        piDstC[x] = (piRefC[x]<<shiftNumOrg);
+      }
+      piDstC += iDstStride;
+      piRefC += iRefStride;
+    }
+    return;
+  }
+
+  if ( iMVyFrac == 0 )
+  {
+    xCTI_Filter1DHorC_ha (piRefC, iRefStride,  iWidth, iHeight, iDstStride,  piDstC, iMVxFrac );
+    return;
+
+  }
+
+  if ( iMVxFrac == 0 )
+  {
+    xCTI_Filter1DVerC_ha (piRefC, iRefStride,  iWidth, iHeight, iDstStride,  piDstC, iMVyFrac );
+    return;
+  }
+
+  Int   iExtStride = m_iYuvExtStride;
+  Int*  piExtC     = m_piYuvExt;
+
+  xCTI_Filter2DVerC (piRefC - 1,  iRefStride,  iWidth + 3, iHeight, iExtStride,  piExtC, iMVyFrac );
+  xCTI_Filter2DHorC_ha (piExtC + 1,  iExtStride,  iWidth , iHeight, iDstStride,  piDstC, iMVxFrac );
+  return;
+
+}
+
+#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 )
+  {
+#ifdef ROUNDING_CONTROL_BIPRED
+    rpcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight, pcCU->getSlice()->isRounding());
+#else
+    rpcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight );
+#endif
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    pcYuvSrc0->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    pcYuvSrc1->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+  else
+  {
+    assert (0);
+  }
+}
+
+// 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;
+}
+
+#if ADD_PLANAR_MODE
+/** Function for deriving planar intra prediction.
+ * \param pSrc pointer to reconstructed sample array
+ * \param srcStride the stride of the reconstructed sample array
+ * \param rpDst reference to pointer for the prediction sample array
+ * \param dstStride the stride of the prediction sample array
+ * \param width the width of the block
+ * \param height the height of the block
+ * \param 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 planar mode (intra coding).
+ */
+#if REFERENCE_SAMPLE_PADDING
+Void TComPrediction::xPredIntraPlanar( Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height )
+#else
+Void TComPrediction::xPredIntraPlanar( Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, Bool blkAboveAvailable, Bool blkLeftAvailable )
+#endif
+{
+  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
+#if REFERENCE_SAMPLE_PADDING
+  for(k=0;k<blkSize;k++)
+  {
+    topRow[k] = pSrc[k-srcStride];
+    leftColumn[k] = pSrc[k*srcStride-1];
+  }
+#else
+  if (!blkAboveAvailable && !blkLeftAvailable)
+  {
+    for(k=0;k<blkSize;k++)
+    {
+      leftColumn[k] = topRow[k] = ( 1 << ( g_uiBitDepth + g_uiBitIncrement - 1 ) );
+    }
+  }
+  else
+  {
+    if(blkAboveAvailable)
+    {
+      for(k=0;k<blkSize;k++)
+      {
+        topRow[k] = pSrc[k-srcStride];
+      }
+    }
+    else
+    {
+      Int leftSample = pSrc[-1];
+      for(k=0;k<blkSize;k++)
+      {
+        topRow[k] = leftSample;
+      }
+    }
+    if(blkLeftAvailable)
+    {
+      for(k=0;k<blkSize;k++)
+      {
+        leftColumn[k] = pSrc[k*srcStride-1];
+      }
+    }
+    else
+    {
+      Int aboveSample = pSrc[-srcStride];
+      for(k=0;k<blkSize;k++)
+      {
+        leftColumn[k] = aboveSample;
+      }
+    }
+  }
+#endif
+
+  // Prepare intermediate variables used in interpolation
+  bottomLeft = leftColumn[blkSize-1];
+  topRight   = topRow[blkSize-1];
+  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 );
+    }
+  }
+}
+#endif
+
+#if LM_CHROMA
+/** Function for deriving chroma LM intra prediction.
+ * \param pcPattern pointer to neighbouring pixel access pattern
+ * \param pSrc 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  = uiCWidth << 1;
+  UInt uiHeight = uiCHeight << 1;
+
+  if (uiChromaId == 0)
+    xGetRecPixels( pcPattern, pcPattern->getROIY(), pcPattern->getPatternLStride(), m_pLumaRecBuffer + m_iLumaRecStride + 1, m_iLumaRecStride, uiWidth, uiHeight );
+
+  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 pRecSrc pointer to reconstructed luma sample array
+ * \param iRecSrcStride the stride of reconstructed luma sample array
+ * \param pDst0 pointer to downsampled luma sample array
+ * \param iDstStride the stride of downsampled luma sample array
+ * \param uiWidth0 the width of the luma block
+ * \param uiHeight0 the height of the luma block
+
+ \ This function derives downsampled luma sample of current chroma block and its above, left causal pixel
+ */
+
+Void TComPrediction::xGetRecPixels( TComPattern* pcPattern, Pel* pRecSrc, Int iRecSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth0, UInt uiHeight0 )
+{
+  Pel* pSrc = pRecSrc;
+  Pel* pDst = pDst0;
+
+  Int uiCWidth = uiWidth0/2;
+  Int uiCHeight = uiHeight0/2;
+
+  if( pcPattern->isLeftAvailable() )
+  {
+    pSrc = pSrc - 2;
+    pDst = pDst - 1;
+
+    uiCWidth += 1;
+  }
+
+  if( pcPattern->isAboveAvailable() )
+  {
+    pSrc = pSrc - 2*iRecSrcStride;
+    pDst = pDst - iDstStride;
+
+    uiCHeight += 1;
+  }
+
+  for( Int j = 0; j < uiCHeight; j++ )
+    {
+      for( Int i = 0, ii = i << 1; i < uiCWidth; i++, ii = i << 1 )
+        pDst[i] = (pSrc[ii] + pSrc[ii + iRecSrcStride]) >> 1;
+
+      pDst += iDstStride;
+      pSrc += iRecSrcStride*2;
+    }  
+}
+
+/** 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 )
+{
+#if 1
+  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;
+
+#else
+
+  Int iMSB = 0;
+  while( x > 0 )
+  {
+    x >>= 1;
+    iMSB++;
+  }
+#endif
+
+  return iMSB;
+}
+
+/** 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;
+
+  if( pcPattern->isAboveAvailable() )
+  {
+    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;
+  }
+
+  if( pcPattern->isLeftAvailable() )
+  {
+    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 iBitdepth = ( ( g_uiBitDepth + g_uiBitIncrement ) + g_aucConvertToBit[ uiWidth ] + 3 ) * 2;
+  Int iTempShift = Max( ( iBitdepth - 31 + 1) / 2, 0);
+
+  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 = 128 << g_uiBitIncrement;
+    iShift = 0;
+  }
+  else
+  {
+    Int a1 = ( xy << iCountShift ) - y * x;
+    Int a2 = ( xx << iCountShift ) - x * x;              
+
+    if( a2 == 0 || a1 == 0 )
+    {
+      a = 0;
+      b = ( y + ( 1 << ( iCountShift - 1 ) ) )>> iCountShift;
+      iShift = 0;
+    }
+    else
+    {
+      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;
+
+      a = a1s * m_uiaShift[ abs( a2s ) ];
+      
+      if( iScaleShiftA < 0 )
+        a = a << -iScaleShiftA;
+      else
+        a = a >> iScaleShiftA;
+
+      if( a > ( 1 << 15 ) - 1 )
+        a = ( 1 << 15 ) - 1;
+      else if( a < -( 1 << 15 ) )
+        a = -( 1 << 15 );
+
+      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
+
+}
+#endif
+
+#if MN_DC_PRED_FILTER
+/** 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;
+  Int iIntraSizeIdx = g_aucConvertToBit[ iWidth ] + 1;
+  static const UChar g_aucDCPredFilter[7] = { 0, 3, 2, 1, 0, 0, 0};
+
+  switch (g_aucDCPredFilter[iIntraSizeIdx])
+  {
+  case 0:
+    {}
+    break;
+  case 1:
+    {
+      // boundary pixels processing
+      pDst[0] = (Pel)((pSrc[-iSrcStride] + pSrc[-1] + 6 * pDst[0] + 4) >> 3);
+
+      for ( x = 1; x < iWidth; x++ )
+        pDst[x] = (Pel)((pSrc[x - iSrcStride] + 7 * pDst[x] + 4) >> 3);
+
+      for ( y = 1, iDstStride2 = iDstStride, iSrcStride2 = iSrcStride-1; y < iHeight; y++, iDstStride2+=iDstStride, iSrcStride2+=iSrcStride )
+        pDst[iDstStride2] = (Pel)((pSrc[iSrcStride2] + 7 * pDst[iDstStride2] + 4) >> 3);
+    }
+    break;
+  case 2:
+    {
+      // 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);
+    }
+    break;
+  case 3:
+    {
+      // boundary pixels processing
+      pDst[0] = (Pel)((3 * (pSrc[-iSrcStride] + pSrc[-1]) + 2 * pDst[0] + 4) >> 3);
+
+      for ( x = 1; x < iWidth; x++ )
+        pDst[x] = (Pel)((3 * pSrc[x - iSrcStride] + 5 * pDst[x] + 4) >> 3);
+
+      for ( y = 1, iDstStride2 = iDstStride, iSrcStride2 = iSrcStride-1; y < iHeight; y++, iDstStride2+=iDstStride, iSrcStride2+=iSrcStride )
+        pDst[iDstStride2] = (Pel)((3 * pSrc[iSrcStride2] + 5 * pDst[iDstStride2] + 4) >> 3);
+    }
+    break;
+  }
+
+  return;
+}
+#endif
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+TComWedgeDist::TComWedgeDist()
+{
+  init();
+}
+
+TComWedgeDist::~TComWedgeDist()
+{
+}
+
+Void TComWedgeDist::init()
+{
+  //   m_afpDistortFunc[0]  = NULL;                  // for DF_DEFAULT
+
+  //   m_afpDistortFunc[8]  = TComRdCost::xGetSAD;
+  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;
+
+  //   m_afpDistortFunc[13] = TComRdCost::xGetSAD64;
+#ifdef ROUNDING_CONTROL_BIPRED
+  //   m_afpDistortFuncRnd[0]  = NULL;
+  //   m_afpDistortFuncRnd[8]  = TComRdCost::xGetSAD;
+  m_afpDistortFuncRnd[9]  = TComRdCost::xGetSAD4;
+  m_afpDistortFuncRnd[10] = TComRdCost::xGetSAD8;
+  m_afpDistortFuncRnd[11] = TComRdCost::xGetSAD16;
+  m_afpDistortFuncRnd[12] = TComRdCost::xGetSAD32;
+  //   m_afpDistortFuncRnd[13] = TComRdCost::xGetSAD64;
+#endif
+}
+
+UInt TComWedgeDist::xGetSAD4( DistParam* 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( DistParam* 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( DistParam* 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( DistParam* 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( 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;
+  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( 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;
+  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( 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;
+  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( 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;
+  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, DistParam& 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 )
+{
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eWDist, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix since DistParam is lacking a constructor and the variable iStep is not initialized
+  cDtParam.iStep      = 1;
+#endif
+  return cDtParam.DistFunc( &cDtParam );
+}
+#endif
Index: /tags/0.2r1/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComPrediction.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComPrediction.h	(revision 19)
@@ -0,0 +1,253 @@
+/* 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     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 "TComPredFilter.h"
+#ifdef WEIGHT_PRED
+  #include "TComWeightPrediction.h"
+#endif
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// prediction class
+class TComPrediction : public TComPredFilter
+#ifdef WEIGHT_PRED
+  , public TComWeightPrediction
+#endif
+{
+protected:
+  Int*      m_piYuvExt;
+  Int       m_iYuvExtStride;
+  Int       m_iYuvExtHeight;
+  
+  TComYuv   m_acYuvPred[2];
+  TComYuv   m_cYuvPredTemp;
+  TComYuv   m_cYuvExt;
+  
+#if LM_CHROMA
+  Pel*   m_pLumaRecBuffer;       // array for downsampled reconstructed luma sample 
+  Int    m_iLumaRecStride;
+  UInt   m_uiaShift[ 65 ];       // Table for multiplication to substitue of division operation
+#endif
+
+  Void xPredIntraAng            ( Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable );
+#if ADD_PLANAR_MODE
+#if REFERENCE_SAMPLE_PADDING
+  Void xPredIntraPlanar         ( Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height );
+#else
+  Void xPredIntraPlanar         ( Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, Bool blkAboveAvailable, Bool blkLeftAvailable );
+#endif
+#endif
+  
+  // motion compensation functions
+#if HIGH_ACCURACY_BI
+#if DEPTH_MAP_GENERATION
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap, Bool bi=false );
+#else
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bi=false );
+#endif
+#else
+#if DEPTH_MAP_GENERATION
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap );
+#else
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx );
+#endif
+#endif
+  Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight,                         TComYuv*& rpcYuvPred, Int iPartIdx, Bool bPrdDepthMap );
+  Void xPredInterPrdDepthMap    ( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight,                         TComYuv*& rpcYuv, UInt uiRShift, UInt uiFilterMode ); // 0:std, 1:bilin, 2:nearest neighbour
+  Void xPredInterLumaBlk        ( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight,                         TComYuv*& rpcYuv );
+  Void xPredInterChromaBlk      ( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight,                         TComYuv*& rpcYuv                            );
+  Void xWeightedAverage         ( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst );
+  Void xDCTIF_FilterC ( Pel*  piRefC, Int iRefStride,Pel*  piDstC,Int iDstStride,Int iWidth, Int iHeight,Int iMVyFrac,Int iMVxFrac);
+
+#if HIGH_ACCURACY_BI
+  Void xPredInterLumaBlk_ha        ( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight,                         TComYuv*& rpcYuv );
+  Void xPredInterChromaBlk_ha      ( TComDataCU* pcCU, TComPicYuv* pcPicYuvRef, UInt uiPartAddr, TComMv* pcMv, Int iWidth, Int iHeight,                         TComYuv*& rpcYuv                            );
+  Void xDCTIF_FilterC_ha ( Pel*  piRefC, Int iRefStride,Pel*  piDstC,Int iDstStride,Int iWidth, Int iHeight,Int iMVyFrac,Int iMVxFrac);
+#endif
+
+#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 );
+#endif
+
+#if LM_CHROMA
+  Void xGetRecPixels     ( TComPattern* pcPattern, Pel* pRecSrc, Int iRecSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth0, UInt uiHeight0 );   
+  Void xGetLLSPrediction ( TComPattern* pcPattern, Int* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0 );
+#endif
+
+#if MN_DC_PRED_FILTER
+  Void xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight );
+#endif
+
+public:
+  TComPrediction();
+  virtual ~TComPrediction();
+  
+  Void    initTempBuff();
+  
+  // inter
+  Void motionCompensation         ( TComDataCU*  pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList = REF_PIC_LIST_X, Int iPartIdx = -1, Bool bPrdDepthMap = false );
+  
+  // 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 );
+  
+#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  getBestContourFromText   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, TComWedgelet* pcContourWedge, Pel* piTextureBlock = NULL );
+  UInt  getBestWedgeFromText     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, WedgeDist eWedgeDist = WedgeDist_SAD, Pel* piTextureBlock = NULL );
+  Void  fillTexturePicTempBlock  ( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piTempBlockY, UInt uiWidth, UInt uiHeight );
+#endif
+#if HHI_DMM_WEDGE_INTRA
+  UInt  getBestContinueWedge     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Int iDeltaEnd = 0 );
+  Bool  getWedgeListIdx          ( WedgeList* pcWedgeList, WedgeRefList* pcWedgeRefList, UInt& ruiTabIdx, UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe );
+#endif
+  
+  Pel  predIntraGetPredValDC      ( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft );
+  
+  Int* getPredicBuf()             { return m_piYuvExt;      }
+  Int  getPredicBufWidth()        { return m_iYuvExtStride; }
+  Int  getPredicBufHeight()       { return m_iYuvExtHeight; }
+
+#if LM_CHROMA
+  Void predLMIntraChroma( TComPattern* pcPattern, Int* piSrc, Pel* pPred, UInt uiPredStride, UInt uiCWidth, UInt uiCHeight, UInt uiChromaId );
+#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 );
+};
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+// ====================================================================================================================
+// Class definition TComWedgeDist
+// ====================================================================================================================
+class TComWedgeDist
+{
+private:
+  // for distortion
+  Int                     m_iBlkWidth;
+  Int                     m_iBlkHeight;
+
+  FpDistFunc              m_afpDistortFunc[8]; // [eDFunc]
+#ifdef ROUNDING_CONTROL_BIPRED
+  FpDistFuncRnd           m_afpDistortFuncRnd[4];
+#endif
+
+public:
+  TComWedgeDist();
+  virtual ~TComWedgeDist();
+
+  // Distortion Functions
+  Void    init();
+
+  Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, WedgeDist eWDist, DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
+  Void    setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
+
+#ifdef ROUNDING_CONTROL_BIPRED
+  Void    setDistParam_Bi( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+  Void    setDistParam_Bi( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
+#endif
+
+private:
+
+  //   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 xGetSSE4          ( DistParam* pcDtParam );
+  static UInt xGetSSE8          ( DistParam* pcDtParam );
+  static UInt xGetSSE16         ( DistParam* pcDtParam );
+  static UInt xGetSSE32         ( DistParam* pcDtParam );
+
+#ifdef ROUNDING_CONTROL_BIPRED
+  //   static UInt xGetSAD           ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD4          ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD8          ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD16         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD32         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  //   static UInt xGetSAD64         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+#endif
+
+public:
+  UInt   getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, WedgeDist eWDist = WedgeDist_SAD );
+
+};// END CLASS DEFINITION TComWedgeDist
+#endif
+
+#endif // __TCOMPREDICTION__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComRdCost.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComRdCost.cpp	(revision 19)
@@ -0,0 +1,4896 @@
+/* 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     TComRdCost.cpp
+    \brief    RD cost computation class
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRdCost.h"
+#include "TComDataCU.h"
+
+
+TComRdCost::TComRdCost()
+{
+  init();
+}
+
+TComRdCost::~TComRdCost()
+{
+  xUninit();
+}
+
+// Calculate RD functions
+Double TComRdCost::calcRdCost( UInt uiBits, Dist 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...
+    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;
+}
+
+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...
+    dRdCost = (((Double)(Int64)uiDistortion) + ((Double)(Int64)uiBits * dLambda));
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+    }
+    else
+    {
+      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+    }
+  }
+  
+  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 HHI_INTER_VIEW_MOTION_PRED
+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::xGetSADs;
+  m_afpDistortFunc[16] = TComRdCost::xGetSADs4;
+  m_afpDistortFunc[17] = TComRdCost::xGetSADs8;
+  m_afpDistortFunc[18] = TComRdCost::xGetSADs16;
+  m_afpDistortFunc[19] = TComRdCost::xGetSADs32;
+  m_afpDistortFunc[20] = TComRdCost::xGetSADs64;
+  m_afpDistortFunc[21] = TComRdCost::xGetSADs16N;
+  
+  m_afpDistortFunc[22] = TComRdCost::xGetHADs;
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix since xGetHADs4 and xGetHADs8 assume that the row size cannot be 1, 2, 3 or 6 when the column size is 4 or 8.
+  m_afpDistortFunc[23] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[24] = TComRdCost::xGetHADs;
+#else
+  m_afpDistortFunc[23] = TComRdCost::xGetHADs4;
+  m_afpDistortFunc[24] = TComRdCost::xGetHADs8;
+#endif
+  m_afpDistortFunc[25] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[26] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[27] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[28] = TComRdCost::xGetHADs;
+  
+#ifdef ROUNDING_CONTROL_BIPRED
+  m_afpDistortFuncRnd[0]  = NULL;
+  m_afpDistortFuncRnd[1]  = TComRdCost::xGetSSE;
+  m_afpDistortFuncRnd[2]  = TComRdCost::xGetSSE4;
+  m_afpDistortFuncRnd[3]  = TComRdCost::xGetSSE8;
+  m_afpDistortFuncRnd[4]  = TComRdCost::xGetSSE16;
+  m_afpDistortFuncRnd[5]  = TComRdCost::xGetSSE32;
+  m_afpDistortFuncRnd[6]  = TComRdCost::xGetSSE64;
+  m_afpDistortFuncRnd[7]  = TComRdCost::xGetSSE16N;
+  
+  m_afpDistortFuncRnd[8]  = TComRdCost::xGetSAD;
+  m_afpDistortFuncRnd[9]  = TComRdCost::xGetSAD4;
+  m_afpDistortFuncRnd[10] = TComRdCost::xGetSAD8;
+  m_afpDistortFuncRnd[11] = TComRdCost::xGetSAD16;
+  m_afpDistortFuncRnd[12] = TComRdCost::xGetSAD32;
+  m_afpDistortFuncRnd[13] = TComRdCost::xGetSAD64;
+  m_afpDistortFuncRnd[14] = TComRdCost::xGetSAD16N;
+  
+  m_afpDistortFuncRnd[15] = TComRdCost::xGetSADs;
+  m_afpDistortFuncRnd[16] = TComRdCost::xGetSADs4;
+  m_afpDistortFuncRnd[17] = TComRdCost::xGetSADs8;
+  m_afpDistortFuncRnd[18] = TComRdCost::xGetSADs16;
+  m_afpDistortFuncRnd[19] = TComRdCost::xGetSADs32;
+  m_afpDistortFuncRnd[20] = TComRdCost::xGetSADs64;
+  m_afpDistortFuncRnd[21] = TComRdCost::xGetSADs16N;
+  
+  m_afpDistortFuncRnd[22] = TComRdCost::xGetHADs;
+  m_afpDistortFuncRnd[23] = TComRdCost::xGetHADs4;
+  m_afpDistortFuncRnd[24] = TComRdCost::xGetHADs8;
+  m_afpDistortFuncRnd[25] = TComRdCost::xGetHADs;
+  m_afpDistortFuncRnd[26] = TComRdCost::xGetHADs;
+  m_afpDistortFuncRnd[27] = TComRdCost::xGetHADs;
+  m_afpDistortFuncRnd[28] = TComRdCost::xGetHADs;
+#endif
+  
+  m_puiComponentCostOriginP = NULL;
+  m_puiComponentCost        = NULL;
+  m_puiVerCost              = NULL;
+  m_puiHorCost              = NULL;
+  m_uiCost                  = 0;
+  m_iCostScale              = 0;
+  m_iSearchLimit            = 0xdeaddead;
+
+  m_puiMultiviewRegCostHorOrgP  = 0;
+  m_puiMultiviewRegCostVerOrgP  = 0;
+  m_puiMultiviewRegCostHor      = 0;
+  m_puiMultiviewRegCostVer      = 0;
+
+#if HHI_VSO
+  m_apRefPics               = NULL;
+  m_paaiShiftLUTs           = NULL; 
+  m_uiNumberRefPics         = 0;
+  m_bUseVSO                 = false;
+  m_uiVSOMode               = 0; 
+  m_fpDistortFuncVSO        = NULL; 
+  m_pcRenModel              = NULL; 
+#endif
+
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  m_dLambdaScale            = 1;
+#endif
+}
+
+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;
+  }
+
+#if HHI_VSO
+  if ( m_apRefPics != NULL )
+  {
+    delete[] m_apRefPics;
+    m_apRefPics = NULL;
+  }
+
+  if ( m_paaiShiftLUTs != NULL ) { // Delete only first dimension, other dimension are not create in this class
+    delete[] m_paaiShiftLUTs; 
+    m_paaiShiftLUTs = 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;
+}
+
+#ifdef ROUNDING_CONTROL_BIPRED
+// Setting the Distortion Parameter for Inter (ME)
+Void TComRdCost::setDistParam_Bi( 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.DistFuncRnd = m_afpDistortFuncRnd[DF_SAD + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+// Setting the Distortion Parameter for Inter (subpel ME with step)
+Void TComRdCost::setDistParam_Bi( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
+{
+  // 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();
+  
+  // set distortion function
+  if ( !bHADME )
+  {
+    rcDistParam.DistFuncRnd = m_afpDistortFuncRnd[DF_SADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  }
+  else
+  {
+    rcDistParam.DistFuncRnd = m_afpDistortFuncRnd[DF_HADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  }
+  
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+#endif
+
+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 ];
+  
+  // 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)
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
+{
+  // 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();
+  
+  // set distortion function
+  if ( !bHADME )
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  }
+  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
+TComRdCost::setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
+{
+  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
+}
+
+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
+  return cDtParam.DistFunc( &cDtParam );
+}
+#endif
+
+UInt TComRdCost::getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc )
+{
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eDFunc, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+#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
+  return cDtParam.DistFunc( &cDtParam );
+}
+
+// ====================================================================================================================
+// Distortion functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+
+#ifdef ROUNDING_CONTROL_BIPRED
+UInt TComRdCost::xGetSAD( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      pred = (piCur[n] + piRef[n] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n] - pred );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iCols;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD4( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  Int  iStrideRef = pcDtParam->iCols*iSubStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;
+    uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[1] + piRef[1] + bRound) >> 1 ;
+    uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[2] + piRef[2] + bRound) >> 1 ;
+    uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[3] + piRef[3] + bRound) >> 1 ;
+    uiSum += abs( piOrg[3] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD8( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Pel* piRef      = pRefY;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  Int  iStrideRef = pcDtParam->iCols*iSubStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;
+    uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[1] + piRef[1] + bRound) >> 1 ;
+    uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[2] + piRef[2] + bRound) >> 1 ;
+    uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[3] + piRef[3] + bRound) >> 1 ;
+    uiSum += abs( piOrg[3] - pred );
+    pred = (piCur[4] + piRef[4] + bRound) >> 1 ;
+    uiSum += abs( piOrg[4] - pred );
+    pred = (piCur[5] + piRef[5] + bRound) >> 1 ;
+    uiSum += abs( piOrg[5] - pred );
+    pred = (piCur[6] + piRef[6] + bRound) >> 1 ;
+    uiSum += abs( piOrg[6] - pred );
+    pred = (piCur[7] + piRef[7] + bRound) >> 1 ;
+    uiSum += abs( piOrg[7] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD16( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  Int  iStrideRef = pcDtParam->iCols*iSubStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;
+    uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[1] + piRef[1] + bRound) >> 1 ;
+    uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[2] + piRef[2] + bRound) >> 1 ;
+    uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[3] + piRef[3] + bRound) >> 1 ;
+    uiSum += abs( piOrg[3] - pred );
+    pred = (piCur[4] + piRef[4] + bRound) >> 1 ;
+    uiSum += abs( piOrg[4] - pred );
+    pred = (piCur[5] + piRef[5] + bRound) >> 1 ;
+    uiSum += abs( piOrg[5] - pred );
+    pred = (piCur[6] + piRef[6] + bRound) >> 1 ;
+    uiSum += abs( piOrg[6] - pred );
+    pred = (piCur[7] + piRef[7] + bRound) >> 1 ;
+    uiSum += abs( piOrg[7] - pred );
+    pred = (piCur[8] + piRef[8] + bRound) >> 1 ;
+    uiSum += abs( piOrg[8] - pred );
+    pred = (piCur[9] + piRef[9] + bRound) >> 1 ;
+    uiSum += abs( piOrg[9] - pred );
+    pred = (piCur[10] + piRef[10] + bRound) >> 1 ;
+    uiSum += abs( piOrg[10] - pred );
+    pred = (piCur[11] + piRef[11] + bRound) >> 1 ;
+    uiSum += abs( piOrg[11] - pred );
+    pred = (piCur[12] + piRef[12] + bRound) >> 1 ;
+    uiSum += abs( piOrg[12] - pred );
+    pred = (piCur[13] + piRef[13] + bRound) >> 1 ;
+    uiSum += abs( piOrg[13] - pred );
+    pred = (piCur[14] + piRef[14] + bRound) >> 1 ;
+    uiSum += abs( piOrg[14] - pred );
+    pred = (piCur[15] + piRef[15] + bRound) >> 1 ;
+    uiSum += abs( piOrg[15] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD16N( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  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;
+  Int  iStrideRef = iCols*iSubStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      
+      pred = (piCur[n+ 0] + piRef[n+ 0] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 0] - pred );
+      pred = (piCur[n+ 1] + piRef[n+ 1] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 1] - pred );
+      pred = (piCur[n+ 2] + piRef[n+ 2] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 2] - pred );
+      pred = (piCur[n+ 3] + piRef[n+ 3] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 3] - pred );
+      pred = (piCur[n+ 4] + piRef[n+ 4] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 4] - pred );
+      pred = (piCur[n+ 5] + piRef[n+ 5] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 5] - pred );
+      pred = (piCur[n+ 6] + piRef[n+ 6] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 6] - pred );
+      pred = (piCur[n+ 7] + piRef[n+ 7] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 7] - pred );
+      pred = (piCur[n+ 8] + piRef[n+ 8] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 8] - pred );
+      pred = (piCur[n+ 9] + piRef[n+ 9] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 9] - pred );
+      pred = (piCur[n+ 10] + piRef[n+ 10] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 10] - pred );
+      pred = (piCur[n+ 11] + piRef[n+ 11] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 11] - pred );
+      pred = (piCur[n+ 12] + piRef[n+ 12] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 12] - pred );
+      pred = (piCur[n+ 13] + piRef[n+ 13] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 13] - pred );
+      pred = (piCur[n+ 14] + piRef[n+ 14] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 14] - pred );
+      pred = (piCur[n+ 15] + piRef[n+ 15] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n+ 15] - pred );
+      
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD32( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  Int  iStrideRef = pcDtParam->iCols*iSubStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;
+    uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[1] + piRef[1] + bRound) >> 1 ;
+    uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[2] + piRef[2] + bRound) >> 1 ;
+    uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[3] + piRef[3] + bRound) >> 1 ;
+    uiSum += abs( piOrg[3] - pred );
+    pred = (piCur[4] + piRef[4] + bRound) >> 1 ;
+    uiSum += abs( piOrg[4] - pred );
+    pred = (piCur[5] + piRef[5] + bRound) >> 1 ;
+    uiSum += abs( piOrg[5] - pred );
+    pred = (piCur[6] + piRef[6] + bRound) >> 1 ;
+    uiSum += abs( piOrg[6] - pred );
+    pred = (piCur[7] + piRef[7] + bRound) >> 1 ;
+    uiSum += abs( piOrg[7] - pred );
+    pred = (piCur[8] + piRef[8] + bRound) >> 1 ;
+    uiSum += abs( piOrg[8] - pred );
+    pred = (piCur[9] + piRef[9] + bRound) >> 1 ;
+    uiSum += abs( piOrg[9] - pred );
+    
+    pred = (piCur[10] + piRef[10] + bRound) >> 1 ;
+    uiSum += abs( piOrg[10] - pred );
+    pred = (piCur[11] + piRef[11] + bRound) >> 1 ;
+    uiSum += abs( piOrg[11] - pred );
+    pred = (piCur[12] + piRef[12] + bRound) >> 1 ;
+    uiSum += abs( piOrg[12] - pred );
+    pred = (piCur[13] + piRef[13] + bRound) >> 1 ;
+    uiSum += abs( piOrg[13] - pred );
+    pred = (piCur[14] + piRef[14] + bRound) >> 1 ;
+    uiSum += abs( piOrg[14] - pred );
+    pred = (piCur[15] + piRef[15] + bRound) >> 1 ;
+    uiSum += abs( piOrg[15] - pred );
+    pred = (piCur[16] + piRef[16] + bRound) >> 1 ;
+    uiSum += abs( piOrg[16] - pred );
+    pred = (piCur[17] + piRef[17] + bRound) >> 1 ;
+    uiSum += abs( piOrg[17] - pred );
+    pred = (piCur[18] + piRef[18] + bRound) >> 1 ;
+    uiSum += abs( piOrg[18] - pred );
+    pred = (piCur[19] + piRef[19] + bRound) >> 1 ;
+    uiSum += abs( piOrg[19] - pred );
+    
+    pred = (piCur[20] + piRef[20] + bRound) >> 1 ;
+    uiSum += abs( piOrg[20] - pred );
+    pred = (piCur[21] + piRef[21] + bRound) >> 1 ;
+    uiSum += abs( piOrg[21] - pred );
+    pred = (piCur[22] + piRef[22] + bRound) >> 1 ;
+    uiSum += abs( piOrg[22] - pred );
+    pred = (piCur[23] + piRef[23] + bRound) >> 1 ;
+    uiSum += abs( piOrg[23] - pred );
+    pred = (piCur[24] + piRef[24] + bRound) >> 1 ;
+    uiSum += abs( piOrg[24] - pred );
+    pred = (piCur[25] + piRef[25] + bRound) >> 1 ;
+    uiSum += abs( piOrg[25] - pred );
+    pred = (piCur[26] + piRef[26] + bRound) >> 1 ;
+    uiSum += abs( piOrg[26] - pred );
+    pred = (piCur[27] + piRef[27] + bRound) >> 1 ;
+    uiSum += abs( piOrg[27] - pred );
+    pred = (piCur[28] + piRef[28] + bRound) >> 1 ;
+    uiSum += abs( piOrg[28] - pred );
+    pred = (piCur[29] + piRef[29] + bRound) >> 1 ;
+    uiSum += abs( piOrg[29] - pred );
+    
+    pred = (piCur[30] + piRef[30] + bRound) >> 1 ;
+    uiSum += abs( piOrg[30] - pred );
+    pred = (piCur[31] + piRef[31] + bRound) >> 1 ;
+    uiSum += abs( piOrg[31] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSAD64( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  Int  iStrideRef = pcDtParam->iCols*iSubStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;
+    uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[1] + piRef[1] + bRound) >> 1 ;
+    uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[2] + piRef[2] + bRound) >> 1 ;
+    uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[3] + piRef[3] + bRound) >> 1 ;
+    uiSum += abs( piOrg[3] - pred );
+    pred = (piCur[4] + piRef[4] + bRound) >> 1 ;
+    uiSum += abs( piOrg[4] - pred );
+    pred = (piCur[5] + piRef[5] + bRound) >> 1 ;
+    uiSum += abs( piOrg[5] - pred );
+    pred = (piCur[6] + piRef[6] + bRound) >> 1 ;
+    uiSum += abs( piOrg[6] - pred );
+    pred = (piCur[7] + piRef[7] + bRound) >> 1 ;
+    uiSum += abs( piOrg[7] - pred );
+    pred = (piCur[8] + piRef[8] + bRound) >> 1 ;
+    uiSum += abs( piOrg[8] - pred );
+    pred = (piCur[9] + piRef[9] + bRound) >> 1 ;
+    uiSum += abs( piOrg[9] - pred );
+    
+    pred = (piCur[10] + piRef[10] + bRound) >> 1 ;
+    uiSum += abs( piOrg[10] - pred );
+    pred = (piCur[11] + piRef[11] + bRound) >> 1 ;
+    uiSum += abs( piOrg[11] - pred );
+    pred = (piCur[12] + piRef[12] + bRound) >> 1 ;
+    uiSum += abs( piOrg[12] - pred );
+    pred = (piCur[13] + piRef[13] + bRound) >> 1 ;
+    uiSum += abs( piOrg[13] - pred );
+    pred = (piCur[14] + piRef[14] + bRound) >> 1 ;
+    uiSum += abs( piOrg[14] - pred );
+    pred = (piCur[15] + piRef[15] + bRound) >> 1 ;
+    uiSum += abs( piOrg[15] - pred );
+    pred = (piCur[16] + piRef[16] + bRound) >> 1 ;
+    uiSum += abs( piOrg[16] - pred );
+    pred = (piCur[17] + piRef[17] + bRound) >> 1 ;
+    uiSum += abs( piOrg[17] - pred );
+    pred = (piCur[18] + piRef[18] + bRound) >> 1 ;
+    uiSum += abs( piOrg[18] - pred );
+    pred = (piCur[19] + piRef[19] + bRound) >> 1 ;
+    uiSum += abs( piOrg[19] - pred );
+    
+    pred = (piCur[20] + piRef[20] + bRound) >> 1 ;
+    uiSum += abs( piOrg[20] - pred );
+    pred = (piCur[21] + piRef[21] + bRound) >> 1 ;
+    uiSum += abs( piOrg[21] - pred );
+    pred = (piCur[22] + piRef[22] + bRound) >> 1 ;
+    uiSum += abs( piOrg[22] - pred );
+    pred = (piCur[23] + piRef[23] + bRound) >> 1 ;
+    uiSum += abs( piOrg[23] - pred );
+    pred = (piCur[24] + piRef[24] + bRound) >> 1 ;
+    uiSum += abs( piOrg[24] - pred );
+    pred = (piCur[25] + piRef[25] + bRound) >> 1 ;
+    uiSum += abs( piOrg[25] - pred );
+    pred = (piCur[26] + piRef[26] + bRound) >> 1 ;
+    uiSum += abs( piOrg[26] - pred );
+    pred = (piCur[27] + piRef[27] + bRound) >> 1 ;
+    uiSum += abs( piOrg[27] - pred );
+    pred = (piCur[28] + piRef[28] + bRound) >> 1 ;
+    uiSum += abs( piOrg[28] - pred );
+    pred = (piCur[29] + piRef[29] + bRound) >> 1 ;
+    uiSum += abs( piOrg[29] - pred );
+    
+    pred = (piCur[30] + piRef[30] + bRound) >> 1 ;
+    uiSum += abs( piOrg[30] - pred );
+    pred = (piCur[31] + piRef[31] + bRound) >> 1 ;
+    uiSum += abs( piOrg[31] - pred );
+    pred = (piCur[32] + piRef[32] + bRound) >> 1 ;
+    uiSum += abs( piOrg[32] - pred );
+    pred = (piCur[33] + piRef[33] + bRound) >> 1 ;
+    uiSum += abs( piOrg[33] - pred );
+    pred = (piCur[34] + piRef[34] + bRound) >> 1 ;
+    uiSum += abs( piOrg[34] - pred );
+    pred = (piCur[35] + piRef[35] + bRound) >> 1 ;
+    uiSum += abs( piOrg[35] - pred );
+    pred = (piCur[36] + piRef[36] + bRound) >> 1 ;
+    uiSum += abs( piOrg[36] - pred );
+    pred = (piCur[37] + piRef[37] + bRound) >> 1 ;
+    uiSum += abs( piOrg[37] - pred );
+    pred = (piCur[38] + piRef[38] + bRound) >> 1 ;
+    uiSum += abs( piOrg[38] - pred );
+    pred = (piCur[39] + piRef[39] + bRound) >> 1 ;
+    uiSum += abs( piOrg[39] - pred );
+    
+    pred = (piCur[40] + piRef[40] + bRound) >> 1 ;
+    uiSum += abs( piOrg[40] - pred );
+    pred = (piCur[41] + piRef[41] + bRound) >> 1 ;
+    uiSum += abs( piOrg[41] - pred );
+    pred = (piCur[42] + piRef[42] + bRound) >> 1 ;
+    uiSum += abs( piOrg[42] - pred );
+    pred = (piCur[43] + piRef[43] + bRound) >> 1 ;
+    uiSum += abs( piOrg[43] - pred );
+    pred = (piCur[44] + piRef[44] + bRound) >> 1 ;
+    uiSum += abs( piOrg[44] - pred );
+    pred = (piCur[45] + piRef[45] + bRound) >> 1 ;
+    uiSum += abs( piOrg[45] - pred );
+    pred = (piCur[46] + piRef[46] + bRound) >> 1 ;
+    uiSum += abs( piOrg[46] - pred );
+    pred = (piCur[47] + piRef[47] + bRound) >> 1 ;
+    uiSum += abs( piOrg[47] - pred );
+    pred = (piCur[48] + piRef[48] + bRound) >> 1 ;
+    uiSum += abs( piOrg[48] - pred );
+    pred = (piCur[49] + piRef[49] + bRound) >> 1 ;
+    uiSum += abs( piOrg[49] - pred );
+    
+    pred = (piCur[50] + piRef[50] + bRound) >> 1 ;
+    uiSum += abs( piOrg[50] - pred );
+    pred = (piCur[51] + piRef[51] + bRound) >> 1 ;
+    uiSum += abs( piOrg[51] - pred );
+    pred = (piCur[52] + piRef[52] + bRound) >> 1 ;
+    uiSum += abs( piOrg[52] - pred );
+    pred = (piCur[53] + piRef[53] + bRound) >> 1 ;
+    uiSum += abs( piOrg[53] - pred );
+    pred = (piCur[54] + piRef[54] + bRound) >> 1 ;
+    uiSum += abs( piOrg[54] - pred );
+    pred = (piCur[55] + piRef[55] + bRound) >> 1 ;
+    uiSum += abs( piOrg[55] - pred );
+    pred = (piCur[56] + piRef[56] + bRound) >> 1 ;
+    uiSum += abs( piOrg[56] - pred );
+    pred = (piCur[57] + piRef[57] + bRound) >> 1 ;
+    uiSum += abs( piOrg[57] - pred );
+    pred = (piCur[58] + piRef[58] + bRound) >> 1 ;
+    uiSum += abs( piOrg[58] - pred );
+    pred = (piCur[59] + piRef[59] + bRound) >> 1 ;
+    uiSum += abs( piOrg[59] - pred );
+    
+    pred = (piCur[60] + piRef[60] + bRound) >> 1 ;
+    uiSum += abs( piOrg[60] - pred );
+    pred = (piCur[61] + piRef[61] + bRound) >> 1 ;
+    uiSum += abs( piOrg[61] - pred );
+    pred = (piCur[62] + piRef[62] + bRound) >> 1 ;
+    uiSum += abs( piOrg[62] - pred );
+    pred = (piCur[63] + piRef[63] + bRound) >> 1 ;
+    uiSum += abs( piOrg[63] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+UInt TComRdCost::xGetSAD( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert(pcDtParam->iSubShift==0);
+    return xGetSADw( 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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight ) 
+  {
+    return xGetSADw( 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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADw( 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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADw( 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 );
+}
+
+UInt TComRdCost::xGetSAD16N( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSAD16Nw( 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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADw( 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 );
+}
+
+UInt TComRdCost::xGetSAD64( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADw( 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 );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+
+#ifdef ROUNDING_CONTROL_BIPRED
+UInt TComRdCost::xGetSADs( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      pred = (piCur[n*iStep] + piRef[n] + bRound) >> 1 ;
+      uiSum += abs( piOrg[n] - pred );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iCols;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs4( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideRef = pcDtParam->iCols;
+  Int  iStep  = pcDtParam->iStep;
+  Int  iStep2 = iStep<<1;
+  Int  iStep3 = iStep2 + iStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;           uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[iStep ] + piRef[1] + bRound) >> 1 ;      uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[iStep2] + piRef[2] + bRound) >> 1 ;      uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[iStep3] + piRef[3] + bRound) >> 1 ;      uiSum += abs( piOrg[3] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs8( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideRef = pcDtParam->iCols;
+  Int  iStep  = pcDtParam->iStep;
+  Int  iStep2 = iStep<<1;
+  Int  iStep3 = iStep2 + iStep;
+  Int  iStep4 = iStep3 + iStep;
+  Int  iStep5 = iStep4 + iStep;
+  Int  iStep6 = iStep5 + iStep;
+  Int  iStep7 = iStep6 + iStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;           uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[iStep ] + piRef[1] + bRound) >> 1 ;      uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[iStep2] + piRef[2] + bRound) >> 1 ;      uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[iStep3] + piRef[3] + bRound) >> 1 ;      uiSum += abs( piOrg[3] - pred );
+    pred = (piCur[iStep4] + piRef[4] + bRound) >> 1 ;      uiSum += abs( piOrg[4] - pred );
+    pred = (piCur[iStep5] + piRef[5] + bRound) >> 1 ;      uiSum += abs( piOrg[5] - pred );
+    pred = (piCur[iStep6] + piRef[6] + bRound) >> 1 ;      uiSum += abs( piOrg[6] - pred );
+    pred = (piCur[iStep7] + piRef[7] + bRound) >> 1 ;      uiSum += abs( piOrg[7] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs16( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideRef = pcDtParam->iCols;
+  Int  iStep   = pcDtParam->iStep;
+  Int  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;           uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[iStep ] + piRef[1] + bRound) >> 1 ;      uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[iStep2] + piRef[2] + bRound) >> 1 ;      uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[iStep3] + piRef[3] + bRound) >> 1 ;      uiSum += abs( piOrg[3] - pred );
+    pred = (piCur[iStep4] + piRef[4] + bRound) >> 1 ;      uiSum += abs( piOrg[4] - pred );
+    pred = (piCur[iStep5] + piRef[5] + bRound) >> 1 ;      uiSum += abs( piOrg[5] - pred );
+    pred = (piCur[iStep6] + piRef[6] + bRound) >> 1 ;      uiSum += abs( piOrg[6] - pred );
+    pred = (piCur[iStep7] + piRef[7] + bRound) >> 1 ;      uiSum += abs( piOrg[7] - pred );
+    pred = (piCur[iStep8] + piRef[8] + bRound) >> 1 ;      uiSum += abs( piOrg[8] - pred );
+    pred = (piCur[iStep9] + piRef[9] + bRound) >> 1 ;      uiSum += abs( piOrg[9] - pred );
+    pred = (piCur[iStep10] + piRef[10] + bRound) >> 1 ;    uiSum += abs( piOrg[10] - pred );
+    pred = (piCur[iStep11] + piRef[11] + bRound) >> 1 ;    uiSum += abs( piOrg[11] - pred );
+    pred = (piCur[iStep12] + piRef[12] + bRound) >> 1 ;    uiSum += abs( piOrg[12] - pred );
+    pred = (piCur[iStep13] + piRef[13] + bRound) >> 1 ;    uiSum += abs( piOrg[13] - pred );
+    pred = (piCur[iStep14] + piRef[14] + bRound) >> 1 ;    uiSum += abs( piOrg[14] - pred );
+    pred = (piCur[iStep15] + piRef[15] + bRound) >> 1 ;    uiSum += abs( piOrg[15] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs16N( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideRef = pcDtParam->iCols;
+  Int  iStep  = pcDtParam->iStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      pred = (piCur[iStep*(n +0)] + piRef[n + 0] + bRound) >> 1 ;       uiSum += abs( piOrg[n +0] -  pred );
+      pred = (piCur[iStep*(n +1)] + piRef[n + 1] + bRound) >> 1 ;       uiSum += abs( piOrg[n +1] -  pred );
+      pred = (piCur[iStep*(n +2)] + piRef[n + 2] + bRound) >> 1 ;       uiSum += abs( piOrg[n +2] -  pred );
+      pred = (piCur[iStep*(n +3)] + piRef[n + 3] + bRound) >> 1 ;       uiSum += abs( piOrg[n +3] -  pred );
+      pred = (piCur[iStep*(n +4)] + piRef[n + 4] + bRound) >> 1 ;       uiSum += abs( piOrg[n +4] -  pred );
+      pred = (piCur[iStep*(n +5)] + piRef[n + 5] + bRound) >> 1 ;       uiSum += abs( piOrg[n +5] -  pred );
+      pred = (piCur[iStep*(n +6)] + piRef[n + 6] + bRound) >> 1 ;       uiSum += abs( piOrg[n +6] -  pred );
+      pred = (piCur[iStep*(n +7)] + piRef[n + 7] + bRound) >> 1 ;       uiSum += abs( piOrg[n +7] -  pred );
+      pred = (piCur[iStep*(n +8)] + piRef[n + 8] + bRound) >> 1 ;       uiSum += abs( piOrg[n +8] -  pred );
+      pred = (piCur[iStep*(n +9)] + piRef[n + 9] + bRound) >> 1 ;       uiSum += abs( piOrg[n +9] -  pred );
+      pred = (piCur[iStep*(n +10)] + piRef[n + 10] + bRound) >> 1 ;     uiSum += abs( piOrg[n +10] -  pred );
+      pred = (piCur[iStep*(n +11)] + piRef[n + 11] + bRound) >> 1 ;     uiSum += abs( piOrg[n +11] -  pred );
+      pred = (piCur[iStep*(n +12)] + piRef[n + 12] + bRound) >> 1 ;     uiSum += abs( piOrg[n +12] -  pred );
+      pred = (piCur[iStep*(n +13)] + piRef[n + 13] + bRound) >> 1 ;     uiSum += abs( piOrg[n +13] -  pred );
+      pred = (piCur[iStep*(n +14)] + piRef[n + 14] + bRound) >> 1 ;     uiSum += abs( piOrg[n +14] -  pred );
+      pred = (piCur[iStep*(n +15)] + piRef[n + 15] + bRound) >> 1 ;     uiSum += abs( piOrg[n +15] -  pred );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs32( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideRef = pcDtParam->iCols;
+  Int  iStep  = pcDtParam->iStep;
+  Int  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+  Int  iStep16 = iStep15 + iStep;
+  Int  iStep17 = iStep16 + iStep;
+  Int  iStep18 = iStep17 + iStep;
+  Int  iStep19 = iStep18 + iStep;
+  Int  iStep20 = iStep19 + iStep;
+  Int  iStep21 = iStep20 + iStep;
+  Int  iStep22 = iStep21 + iStep;
+  Int  iStep23 = iStep22 + iStep;
+  Int  iStep24 = iStep23 + iStep;
+  Int  iStep25 = iStep24 + iStep;
+  Int  iStep26 = iStep25 + iStep;
+  Int  iStep27 = iStep26 + iStep;
+  Int  iStep28 = iStep27 + iStep;
+  Int  iStep29 = iStep28 + iStep;
+  Int  iStep30 = iStep29 + iStep;
+  Int  iStep31 = iStep30 + iStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;           uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[iStep ] + piRef[1] + bRound) >> 1 ;      uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[iStep2] + piRef[2] + bRound) >> 1 ;      uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[iStep3] + piRef[3] + bRound) >> 1 ;      uiSum += abs( piOrg[3] - pred );
+    pred = (piCur[iStep4] + piRef[4] + bRound) >> 1 ;      uiSum += abs( piOrg[4] - pred );
+    pred = (piCur[iStep5] + piRef[5] + bRound) >> 1 ;      uiSum += abs( piOrg[5] - pred );
+    pred = (piCur[iStep6] + piRef[6] + bRound) >> 1 ;      uiSum += abs( piOrg[6] - pred );
+    pred = (piCur[iStep7] + piRef[7] + bRound) >> 1 ;      uiSum += abs( piOrg[7] - pred );
+    pred = (piCur[iStep8] + piRef[8] + bRound) >> 1 ;      uiSum += abs( piOrg[8] - pred );
+    pred = (piCur[iStep9] + piRef[9] + bRound) >> 1 ;      uiSum += abs( piOrg[9] - pred );
+    pred = (piCur[iStep10] + piRef[10] + bRound) >> 1 ;    uiSum += abs( piOrg[10] - pred );
+    pred = (piCur[iStep11] + piRef[11] + bRound) >> 1 ;    uiSum += abs( piOrg[11] - pred );      
+    pred = (piCur[iStep12] + piRef[12] + bRound) >> 1 ;    uiSum += abs( piOrg[12] - pred );      
+    pred = (piCur[iStep13] + piRef[13] + bRound) >> 1 ;    uiSum += abs( piOrg[13] - pred );
+    pred = (piCur[iStep14] + piRef[14] + bRound) >> 1 ;    uiSum += abs( piOrg[14] - pred );
+    pred = (piCur[iStep15] + piRef[15] + bRound) >> 1 ;    uiSum += abs( piOrg[15] - pred );
+    pred = (piCur[iStep16] + piRef[16] + bRound) >> 1 ;      uiSum += abs( piOrg[16] - pred );
+    pred = (piCur[iStep17] + piRef[17] + bRound) >> 1 ;      uiSum += abs( piOrg[17] - pred );
+    pred = (piCur[iStep18] + piRef[18] + bRound) >> 1 ;      uiSum += abs( piOrg[18] - pred );
+    pred = (piCur[iStep19] + piRef[19] + bRound) >> 1 ;      uiSum += abs( piOrg[19] - pred );
+    pred = (piCur[iStep20] + piRef[20] + bRound) >> 1 ;      uiSum += abs( piOrg[20] - pred );
+    pred = (piCur[iStep21] + piRef[21] + bRound) >> 1 ;      uiSum += abs( piOrg[21] - pred );
+    pred = (piCur[iStep22] + piRef[22] + bRound) >> 1 ;      uiSum += abs( piOrg[22] - pred );
+    pred = (piCur[iStep23] + piRef[23] + bRound) >> 1 ;      uiSum += abs( piOrg[23] - pred );
+    pred = (piCur[iStep24] + piRef[24] + bRound) >> 1 ;      uiSum += abs( piOrg[24] - pred );
+    pred = (piCur[iStep25] + piRef[25] + bRound) >> 1 ;      uiSum += abs( piOrg[25] - pred );
+    pred = (piCur[iStep26] + piRef[26] + bRound) >> 1 ;      uiSum += abs( piOrg[26] - pred );
+    pred = (piCur[iStep27] + piRef[27] + bRound) >> 1 ;      uiSum += abs( piOrg[27] - pred );
+    pred = (piCur[iStep28] + piRef[28] + bRound) >> 1 ;      uiSum += abs( piOrg[28] - pred );
+    pred = (piCur[iStep29] + piRef[29] + bRound) >> 1 ;      uiSum += abs( piOrg[29] - pred );
+    pred = (piCur[iStep30] + piRef[30] + bRound) >> 1 ;      uiSum += abs( piOrg[30] - pred );
+    pred = (piCur[iStep31] + piRef[31] + bRound) >> 1 ;      uiSum += abs( piOrg[31] - pred );      
+    
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs64( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideRef = pcDtParam->iCols;
+  Int  iStep  = pcDtParam->iStep;
+  Int  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+  Int  iStep16 = iStep15 + iStep;
+  Int  iStep17 = iStep16 + iStep;
+  Int  iStep18 = iStep17 + iStep;
+  Int  iStep19 = iStep18 + iStep;
+  Int  iStep20 = iStep19 + iStep;
+  Int  iStep21 = iStep20 + iStep;
+  Int  iStep22 = iStep21 + iStep;
+  Int  iStep23 = iStep22 + iStep;
+  Int  iStep24 = iStep23 + iStep;
+  Int  iStep25 = iStep24 + iStep;
+  Int  iStep26 = iStep25 + iStep;
+  Int  iStep27 = iStep26 + iStep;
+  Int  iStep28 = iStep27 + iStep;
+  Int  iStep29 = iStep28 + iStep;
+  Int  iStep30 = iStep29 + iStep;
+  Int  iStep31 = iStep30 + iStep;
+  Int  iStep32 = iStep31 + iStep;
+  Int  iStep33 = iStep32 + iStep;
+  Int  iStep34 = iStep33 + iStep;
+  Int  iStep35 = iStep34 + iStep;
+  Int  iStep36 = iStep35 + iStep;
+  Int  iStep37 = iStep36 + iStep;
+  Int  iStep38 = iStep37 + iStep;
+  Int  iStep39 = iStep38 + iStep;
+  Int  iStep40 = iStep39 + iStep;
+  Int  iStep41 = iStep40 + iStep;
+  Int  iStep42 = iStep41 + iStep;
+  Int  iStep43 = iStep42 + iStep;
+  Int  iStep44 = iStep43 + iStep;
+  Int  iStep45 = iStep44 + iStep;
+  Int  iStep46 = iStep45 + iStep;
+  Int  iStep47 = iStep46 + iStep;
+  Int  iStep48 = iStep47 + iStep;
+  Int  iStep49 = iStep48 + iStep;
+  Int  iStep50 = iStep49 + iStep;
+  Int  iStep51 = iStep50 + iStep;
+  Int  iStep52 = iStep51 + iStep;
+  Int  iStep53 = iStep52 + iStep;
+  Int  iStep54 = iStep53 + iStep;
+  Int  iStep55 = iStep54 + iStep;
+  Int  iStep56 = iStep55 + iStep;
+  Int  iStep57 = iStep56 + iStep;
+  Int  iStep58 = iStep57 + iStep;
+  Int  iStep59 = iStep58 + iStep;
+  Int  iStep60 = iStep59 + iStep;
+  Int  iStep61 = iStep60 + iStep;
+  Int  iStep62 = iStep61 + iStep;
+  Int  iStep63 = iStep62 + iStep;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1 ;           uiSum += abs( piOrg[0] - pred );
+    pred = (piCur[iStep ] + piRef[1] + bRound) >> 1 ;      uiSum += abs( piOrg[1] - pred );
+    pred = (piCur[iStep2] + piRef[2] + bRound) >> 1 ;      uiSum += abs( piOrg[2] - pred );
+    pred = (piCur[iStep3] + piRef[3] + bRound) >> 1 ;      uiSum += abs( piOrg[3] - pred );
+    pred = (piCur[iStep4] + piRef[4] + bRound) >> 1 ;      uiSum += abs( piOrg[4] - pred );
+    pred = (piCur[iStep5] + piRef[5] + bRound) >> 1 ;      uiSum += abs( piOrg[5] - pred );
+    pred = (piCur[iStep6] + piRef[6] + bRound) >> 1 ;      uiSum += abs( piOrg[6] - pred );
+    pred = (piCur[iStep7] + piRef[7] + bRound) >> 1 ;      uiSum += abs( piOrg[7] - pred );
+    pred = (piCur[iStep8] + piRef[8] + bRound) >> 1 ;      uiSum += abs( piOrg[8] - pred );
+    pred = (piCur[iStep9] + piRef[9] + bRound) >> 1 ;      uiSum += abs( piOrg[9] - pred );
+    
+    pred = (piCur[iStep10] + piRef[10] + bRound) >> 1 ;    uiSum += abs( piOrg[10] - pred );
+    pred = (piCur[iStep11] + piRef[11] + bRound) >> 1 ;    uiSum += abs( piOrg[11] - pred );      
+    pred = (piCur[iStep12] + piRef[12] + bRound) >> 1 ;    uiSum += abs( piOrg[12] - pred );      
+    pred = (piCur[iStep13] + piRef[13] + bRound) >> 1 ;    uiSum += abs( piOrg[13] - pred );
+    pred = (piCur[iStep14] + piRef[14] + bRound) >> 1 ;    uiSum += abs( piOrg[14] - pred );
+    pred = (piCur[iStep15] + piRef[15] + bRound) >> 1 ;    uiSum += abs( piOrg[15] - pred );
+    pred = (piCur[iStep16] + piRef[16] + bRound) >> 1 ;      uiSum += abs( piOrg[16] - pred );
+    pred = (piCur[iStep17] + piRef[17] + bRound) >> 1 ;      uiSum += abs( piOrg[17] - pred );
+    pred = (piCur[iStep18] + piRef[18] + bRound) >> 1 ;      uiSum += abs( piOrg[18] - pred );
+    pred = (piCur[iStep19] + piRef[19] + bRound) >> 1 ;      uiSum += abs( piOrg[19] - pred );
+    pred = (piCur[iStep20] + piRef[20] + bRound) >> 1 ;      uiSum += abs( piOrg[20] - pred );
+    
+    pred = (piCur[iStep21] + piRef[21] + bRound) >> 1 ;      uiSum += abs( piOrg[21] - pred );
+    pred = (piCur[iStep22] + piRef[22] + bRound) >> 1 ;      uiSum += abs( piOrg[22] - pred );
+    pred = (piCur[iStep23] + piRef[23] + bRound) >> 1 ;      uiSum += abs( piOrg[23] - pred );
+    pred = (piCur[iStep24] + piRef[24] + bRound) >> 1 ;      uiSum += abs( piOrg[24] - pred );
+    pred = (piCur[iStep25] + piRef[25] + bRound) >> 1 ;      uiSum += abs( piOrg[25] - pred );
+    pred = (piCur[iStep26] + piRef[26] + bRound) >> 1 ;      uiSum += abs( piOrg[26] - pred );
+    pred = (piCur[iStep27] + piRef[27] + bRound) >> 1 ;      uiSum += abs( piOrg[27] - pred );
+    pred = (piCur[iStep28] + piRef[28] + bRound) >> 1 ;      uiSum += abs( piOrg[28] - pred );
+    pred = (piCur[iStep29] + piRef[29] + bRound) >> 1 ;      uiSum += abs( piOrg[29] - pred );
+    
+    pred = (piCur[iStep30] + piRef[30] + bRound) >> 1 ;    uiSum += abs( piOrg[30] - pred );
+    pred = (piCur[iStep31] + piRef[31] + bRound) >> 1 ;    uiSum += abs( piOrg[31] - pred );      
+    pred = (piCur[iStep32] + piRef[32] + bRound) >> 1 ;    uiSum += abs( piOrg[32] - pred );      
+    pred = (piCur[iStep33] + piRef[33] + bRound) >> 1 ;    uiSum += abs( piOrg[33] - pred );
+    pred = (piCur[iStep34] + piRef[34] + bRound) >> 1 ;    uiSum += abs( piOrg[34] - pred );
+    pred = (piCur[iStep35] + piRef[35] + bRound) >> 1 ;    uiSum += abs( piOrg[35] - pred );
+    pred = (piCur[iStep36] + piRef[36] + bRound) >> 1 ;      uiSum += abs( piOrg[36] - pred );
+    pred = (piCur[iStep37] + piRef[37] + bRound) >> 1 ;      uiSum += abs( piOrg[37] - pred );
+    pred = (piCur[iStep38] + piRef[38] + bRound) >> 1 ;      uiSum += abs( piOrg[38] - pred );
+    pred = (piCur[iStep39] + piRef[39] + bRound) >> 1 ;      uiSum += abs( piOrg[39] - pred );
+    
+    pred = (piCur[iStep40] + piRef[40] + bRound) >> 1 ;      uiSum += abs( piOrg[40] - pred );
+    pred = (piCur[iStep41] + piRef[41] + bRound) >> 1 ;      uiSum += abs( piOrg[41] - pred );
+    pred = (piCur[iStep42] + piRef[42] + bRound) >> 1 ;      uiSum += abs( piOrg[42] - pred );
+    pred = (piCur[iStep43] + piRef[43] + bRound) >> 1 ;      uiSum += abs( piOrg[43] - pred );
+    pred = (piCur[iStep44] + piRef[44] + bRound) >> 1 ;      uiSum += abs( piOrg[44] - pred );
+    pred = (piCur[iStep45] + piRef[45] + bRound) >> 1 ;      uiSum += abs( piOrg[45] - pred );
+    pred = (piCur[iStep46] + piRef[46] + bRound) >> 1 ;      uiSum += abs( piOrg[46] - pred );
+    pred = (piCur[iStep47] + piRef[47] + bRound) >> 1 ;      uiSum += abs( piOrg[47] - pred );
+    pred = (piCur[iStep48] + piRef[48] + bRound) >> 1 ;      uiSum += abs( piOrg[48] - pred );
+    pred = (piCur[iStep49] + piRef[49] + bRound) >> 1 ;      uiSum += abs( piOrg[49] - pred );
+    
+    pred = (piCur[iStep50] + piRef[50] + bRound) >> 1 ;    uiSum += abs( piOrg[50] - pred );
+    pred = (piCur[iStep51] + piRef[51] + bRound) >> 1 ;    uiSum += abs( piOrg[51] - pred );      
+    pred = (piCur[iStep52] + piRef[52] + bRound) >> 1 ;    uiSum += abs( piOrg[52] - pred );      
+    pred = (piCur[iStep53] + piRef[53] + bRound) >> 1 ;    uiSum += abs( piOrg[53] - pred );
+    pred = (piCur[iStep54] + piRef[54] + bRound) >> 1 ;    uiSum += abs( piOrg[54] - pred );
+    pred = (piCur[iStep55] + piRef[55] + bRound) >> 1 ;    uiSum += abs( piOrg[55] - pred );
+    pred = (piCur[iStep56] + piRef[56] + bRound) >> 1 ;      uiSum += abs( piOrg[56] - pred );
+    pred = (piCur[iStep57] + piRef[57] + bRound) >> 1 ;      uiSum += abs( piOrg[57] - pred );
+    pred = (piCur[iStep58] + piRef[58] + bRound) >> 1 ;      uiSum += abs( piOrg[58] - pred );
+    pred = (piCur[iStep59] + piRef[59] + bRound) >> 1 ;      uiSum += abs( piOrg[59] - pred );
+    
+    pred = (piCur[iStep60] + piRef[60] + bRound) >> 1 ;      uiSum += abs( piOrg[60] - pred );
+    pred = (piCur[iStep61] + piRef[61] + bRound) >> 1 ;      uiSum += abs( piOrg[61] - pred );
+    pred = (piCur[iStep62] + piRef[62] + bRound) >> 1 ;      uiSum += abs( piOrg[62] - pred );
+    pred = (piCur[iStep63] + piRef[63] + bRound) >> 1 ;      uiSum += abs( piOrg[63] - pred );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+#endif
+
+UInt TComRdCost::xGetSADs( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADsw( 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;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      uiSum += abs( piOrg[n] - piCur[n*iStep] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs4( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADs4w( pcDtParam );
+  }
+#endif
+  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  iStep2 = iStep<<1;
+  Int  iStep3 = iStep2 + iStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[0] - piCur[     0] );
+    uiSum += abs( piOrg[1] - piCur[iStep ] );
+    uiSum += abs( piOrg[2] - piCur[iStep2] );
+    uiSum += abs( piOrg[3] - piCur[iStep3] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs8( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADs8w( pcDtParam );
+  }
+#endif
+  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  iStep2 = iStep<<1;
+  Int  iStep3 = iStep2 + iStep;
+  Int  iStep4 = iStep3 + iStep;
+  Int  iStep5 = iStep4 + iStep;
+  Int  iStep6 = iStep5 + iStep;
+  Int  iStep7 = iStep6 + iStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[0] - piCur[     0] );
+    uiSum += abs( piOrg[1] - piCur[iStep ] );
+    uiSum += abs( piOrg[2] - piCur[iStep2] );
+    uiSum += abs( piOrg[3] - piCur[iStep3] );
+    uiSum += abs( piOrg[4] - piCur[iStep4] );
+    uiSum += abs( piOrg[5] - piCur[iStep5] );
+    uiSum += abs( piOrg[6] - piCur[iStep6] );
+    uiSum += abs( piOrg[7] - piCur[iStep7] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs16( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADs16w( pcDtParam );
+  }
+#endif
+  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  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[ 0] - piCur[      0] );
+    uiSum += abs( piOrg[ 1] - piCur[iStep  ] );
+    uiSum += abs( piOrg[ 2] - piCur[iStep2 ] );
+    uiSum += abs( piOrg[ 3] - piCur[iStep3 ] );
+    uiSum += abs( piOrg[ 4] - piCur[iStep4 ] );
+    uiSum += abs( piOrg[ 5] - piCur[iStep5 ] );
+    uiSum += abs( piOrg[ 6] - piCur[iStep6 ] );
+    uiSum += abs( piOrg[ 7] - piCur[iStep7 ] );
+    uiSum += abs( piOrg[ 8] - piCur[iStep8 ] );
+    uiSum += abs( piOrg[ 9] - piCur[iStep9 ] );
+    uiSum += abs( piOrg[10] - piCur[iStep10] );
+    uiSum += abs( piOrg[11] - piCur[iStep11] );
+    uiSum += abs( piOrg[12] - piCur[iStep12] );
+    uiSum += abs( piOrg[13] - piCur[iStep13] );
+    uiSum += abs( piOrg[14] - piCur[iStep14] );
+    uiSum += abs( piOrg[15] - piCur[iStep15] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs16N( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADs16Nw( 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;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      uiSum += abs( piOrg[n +0] - piCur[iStep*(n +0)] );
+      uiSum += abs( piOrg[n +1] - piCur[iStep*(n +1)] );
+      uiSum += abs( piOrg[n +2] - piCur[iStep*(n +2)] );
+      uiSum += abs( piOrg[n +3] - piCur[iStep*(n +3)] );
+      uiSum += abs( piOrg[n +4] - piCur[iStep*(n +4)] );
+      uiSum += abs( piOrg[n +5] - piCur[iStep*(n +5)] );
+      uiSum += abs( piOrg[n +6] - piCur[iStep*(n +6)] );
+      uiSum += abs( piOrg[n +7] - piCur[iStep*(n +7)] );
+      uiSum += abs( piOrg[n +8] - piCur[iStep*(n +8)] );
+      uiSum += abs( piOrg[n +9] - piCur[iStep*(n +9)] );
+      uiSum += abs( piOrg[n+10] - piCur[iStep*(n+10)] );
+      uiSum += abs( piOrg[n+11] - piCur[iStep*(n+11)] );
+      uiSum += abs( piOrg[n+12] - piCur[iStep*(n+12)] );
+      uiSum += abs( piOrg[n+13] - piCur[iStep*(n+13)] );
+      uiSum += abs( piOrg[n+14] - piCur[iStep*(n+14)] );
+      uiSum += abs( piOrg[n+15] - piCur[iStep*(n+15)] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs32( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADs32w( pcDtParam );
+  }
+#endif
+  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  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+  Int  iStep16 = iStep15 + iStep;
+  Int  iStep17 = iStep16 + iStep;
+  Int  iStep18 = iStep17 + iStep;
+  Int  iStep19 = iStep18 + iStep;
+  Int  iStep20 = iStep19 + iStep;
+  Int  iStep21 = iStep20 + iStep;
+  Int  iStep22 = iStep21 + iStep;
+  Int  iStep23 = iStep22 + iStep;
+  Int  iStep24 = iStep23 + iStep;
+  Int  iStep25 = iStep24 + iStep;
+  Int  iStep26 = iStep25 + iStep;
+  Int  iStep27 = iStep26 + iStep;
+  Int  iStep28 = iStep27 + iStep;
+  Int  iStep29 = iStep28 + iStep;
+  Int  iStep30 = iStep29 + iStep;
+  Int  iStep31 = iStep30 + iStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[ 0] - piCur[      0] );
+    uiSum += abs( piOrg[ 1] - piCur[iStep  ] );
+    uiSum += abs( piOrg[ 2] - piCur[iStep2 ] );
+    uiSum += abs( piOrg[ 3] - piCur[iStep3 ] );
+    uiSum += abs( piOrg[ 4] - piCur[iStep4 ] );
+    uiSum += abs( piOrg[ 5] - piCur[iStep5 ] );
+    uiSum += abs( piOrg[ 6] - piCur[iStep6 ] );
+    uiSum += abs( piOrg[ 7] - piCur[iStep7 ] );
+    uiSum += abs( piOrg[ 8] - piCur[iStep8 ] );
+    uiSum += abs( piOrg[ 9] - piCur[iStep9 ] );
+    uiSum += abs( piOrg[10] - piCur[iStep10] );
+    uiSum += abs( piOrg[11] - piCur[iStep11] );
+    uiSum += abs( piOrg[12] - piCur[iStep12] );
+    uiSum += abs( piOrg[13] - piCur[iStep13] );
+    uiSum += abs( piOrg[14] - piCur[iStep14] );
+    uiSum += abs( piOrg[15] - piCur[iStep15] );
+    uiSum += abs( piOrg[16] - piCur[iStep16] );
+    uiSum += abs( piOrg[17] - piCur[iStep17] );
+    uiSum += abs( piOrg[18] - piCur[iStep18] );
+    uiSum += abs( piOrg[19] - piCur[iStep19] );
+    uiSum += abs( piOrg[20] - piCur[iStep20] );
+    uiSum += abs( piOrg[21] - piCur[iStep21] );
+    uiSum += abs( piOrg[22] - piCur[iStep22] );
+    uiSum += abs( piOrg[23] - piCur[iStep23] );
+    uiSum += abs( piOrg[24] - piCur[iStep24] );
+    uiSum += abs( piOrg[25] - piCur[iStep25] );
+    uiSum += abs( piOrg[26] - piCur[iStep26] );
+    uiSum += abs( piOrg[27] - piCur[iStep27] );
+    uiSum += abs( piOrg[28] - piCur[iStep28] );
+    uiSum += abs( piOrg[29] - piCur[iStep29] );
+    uiSum += abs( piOrg[30] - piCur[iStep30] );
+    uiSum += abs( piOrg[31] - piCur[iStep31] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetSADs64( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSADs64w( pcDtParam );
+  }
+#endif
+  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  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+  Int  iStep16 = iStep15 + iStep;
+  Int  iStep17 = iStep16 + iStep;
+  Int  iStep18 = iStep17 + iStep;
+  Int  iStep19 = iStep18 + iStep;
+  Int  iStep20 = iStep19 + iStep;
+  Int  iStep21 = iStep20 + iStep;
+  Int  iStep22 = iStep21 + iStep;
+  Int  iStep23 = iStep22 + iStep;
+  Int  iStep24 = iStep23 + iStep;
+  Int  iStep25 = iStep24 + iStep;
+  Int  iStep26 = iStep25 + iStep;
+  Int  iStep27 = iStep26 + iStep;
+  Int  iStep28 = iStep27 + iStep;
+  Int  iStep29 = iStep28 + iStep;
+  Int  iStep30 = iStep29 + iStep;
+  Int  iStep31 = iStep30 + iStep;
+  Int  iStep32 = iStep31 + iStep;
+  Int  iStep33 = iStep32 + iStep;
+  Int  iStep34 = iStep33 + iStep;
+  Int  iStep35 = iStep34 + iStep;
+  Int  iStep36 = iStep35 + iStep;
+  Int  iStep37 = iStep36 + iStep;
+  Int  iStep38 = iStep37 + iStep;
+  Int  iStep39 = iStep38 + iStep;
+  Int  iStep40 = iStep39 + iStep;
+  Int  iStep41 = iStep40 + iStep;
+  Int  iStep42 = iStep41 + iStep;
+  Int  iStep43 = iStep42 + iStep;
+  Int  iStep44 = iStep43 + iStep;
+  Int  iStep45 = iStep44 + iStep;
+  Int  iStep46 = iStep45 + iStep;
+  Int  iStep47 = iStep46 + iStep;
+  Int  iStep48 = iStep47 + iStep;
+  Int  iStep49 = iStep48 + iStep;
+  Int  iStep50 = iStep49 + iStep;
+  Int  iStep51 = iStep50 + iStep;
+  Int  iStep52 = iStep51 + iStep;
+  Int  iStep53 = iStep52 + iStep;
+  Int  iStep54 = iStep53 + iStep;
+  Int  iStep55 = iStep54 + iStep;
+  Int  iStep56 = iStep55 + iStep;
+  Int  iStep57 = iStep56 + iStep;
+  Int  iStep58 = iStep57 + iStep;
+  Int  iStep59 = iStep58 + iStep;
+  Int  iStep60 = iStep59 + iStep;
+  Int  iStep61 = iStep60 + iStep;
+  Int  iStep62 = iStep61 + iStep;
+  Int  iStep63 = iStep62 + iStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[ 0] - piCur[      0] );
+    uiSum += abs( piOrg[ 1] - piCur[iStep  ] );
+    uiSum += abs( piOrg[ 2] - piCur[iStep2 ] );
+    uiSum += abs( piOrg[ 3] - piCur[iStep3 ] );
+    uiSum += abs( piOrg[ 4] - piCur[iStep4 ] );
+    uiSum += abs( piOrg[ 5] - piCur[iStep5 ] );
+    uiSum += abs( piOrg[ 6] - piCur[iStep6 ] );
+    uiSum += abs( piOrg[ 7] - piCur[iStep7 ] );
+    uiSum += abs( piOrg[ 8] - piCur[iStep8 ] );
+    uiSum += abs( piOrg[ 9] - piCur[iStep9 ] );
+    uiSum += abs( piOrg[10] - piCur[iStep10] );
+    uiSum += abs( piOrg[11] - piCur[iStep11] );
+    uiSum += abs( piOrg[12] - piCur[iStep12] );
+    uiSum += abs( piOrg[13] - piCur[iStep13] );
+    uiSum += abs( piOrg[14] - piCur[iStep14] );
+    uiSum += abs( piOrg[15] - piCur[iStep15] );
+    uiSum += abs( piOrg[16] - piCur[iStep16] );
+    uiSum += abs( piOrg[17] - piCur[iStep17] );
+    uiSum += abs( piOrg[18] - piCur[iStep18] );
+    uiSum += abs( piOrg[19] - piCur[iStep19] );
+    uiSum += abs( piOrg[20] - piCur[iStep20] );
+    uiSum += abs( piOrg[21] - piCur[iStep21] );
+    uiSum += abs( piOrg[22] - piCur[iStep22] );
+    uiSum += abs( piOrg[23] - piCur[iStep23] );
+    uiSum += abs( piOrg[24] - piCur[iStep24] );
+    uiSum += abs( piOrg[25] - piCur[iStep25] );
+    uiSum += abs( piOrg[26] - piCur[iStep26] );
+    uiSum += abs( piOrg[27] - piCur[iStep27] );
+    uiSum += abs( piOrg[28] - piCur[iStep28] );
+    uiSum += abs( piOrg[29] - piCur[iStep29] );
+    uiSum += abs( piOrg[30] - piCur[iStep30] );
+    uiSum += abs( piOrg[31] - piCur[iStep31] );
+    uiSum += abs( piOrg[32] - piCur[iStep32] );
+    uiSum += abs( piOrg[33] - piCur[iStep33] );
+    uiSum += abs( piOrg[34] - piCur[iStep34] );
+    uiSum += abs( piOrg[35] - piCur[iStep35] );
+    uiSum += abs( piOrg[36] - piCur[iStep36] );
+    uiSum += abs( piOrg[37] - piCur[iStep37] );
+    uiSum += abs( piOrg[38] - piCur[iStep38] );
+    uiSum += abs( piOrg[39] - piCur[iStep39] );
+    uiSum += abs( piOrg[40] - piCur[iStep40] );
+    uiSum += abs( piOrg[41] - piCur[iStep41] );
+    uiSum += abs( piOrg[42] - piCur[iStep42] );
+    uiSum += abs( piOrg[43] - piCur[iStep43] );
+    uiSum += abs( piOrg[44] - piCur[iStep44] );
+    uiSum += abs( piOrg[45] - piCur[iStep45] );
+    uiSum += abs( piOrg[46] - piCur[iStep46] );
+    uiSum += abs( piOrg[47] - piCur[iStep47] );
+    uiSum += abs( piOrg[48] - piCur[iStep48] );
+    uiSum += abs( piOrg[49] - piCur[iStep49] );
+    uiSum += abs( piOrg[50] - piCur[iStep50] );
+    uiSum += abs( piOrg[51] - piCur[iStep51] );
+    uiSum += abs( piOrg[52] - piCur[iStep52] );
+    uiSum += abs( piOrg[53] - piCur[iStep53] );
+    uiSum += abs( piOrg[54] - piCur[iStep54] );
+    uiSum += abs( piOrg[55] - piCur[iStep55] );
+    uiSum += abs( piOrg[56] - piCur[iStep56] );
+    uiSum += abs( piOrg[57] - piCur[iStep57] );
+    uiSum += abs( piOrg[58] - piCur[iStep58] );
+    uiSum += abs( piOrg[59] - piCur[iStep59] );
+    uiSum += abs( piOrg[60] - piCur[iStep60] );
+    uiSum += abs( piOrg[61] - piCur[iStep61] );
+    uiSum += abs( piOrg[62] - piCur[iStep62] );
+    uiSum += abs( piOrg[63] - piCur[iStep63] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+
+#if IBDI_DISTORTION
+#ifdef ROUNDING_CONTROL_BIPRED
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Pel  pred;
+
+  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++ )
+    {
+      pred = (piCur[n] + piRef[n] + bRound) >> 1 ;
+      iTemp = ((piOrg[n]+iOffset)>>iShift) - ((pred+iOffset)>>iShift);
+      uiSum += iTemp * iTemp;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iCols;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE4( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement; 
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0; 
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE8( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement; 
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0; 
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[4] + piRef[4] + bRound) >> 1;    iTemp = ((piOrg[4]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[5] + piRef[5] + bRound) >> 1;    iTemp = ((piOrg[5]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[6] + piRef[6] + bRound) >> 1;    iTemp = ((piOrg[6]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[7] + piRef[7] + bRound) >> 1;    iTemp = ((piOrg[7]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement; 
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0; 
+
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[4] + piRef[4] + bRound) >> 1;    iTemp = ((piOrg[4]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[5] + piRef[5] + bRound) >> 1;    iTemp = ((piOrg[5]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[6] + piRef[6] + bRound) >> 1;    iTemp = ((piOrg[6]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[7] + piRef[7] + bRound) >> 1;    iTemp = ((piOrg[7]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[8] + piRef[8] + bRound) >> 1;    iTemp = ((piOrg[8]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[9] + piRef[9] + bRound) >> 1;    iTemp = ((piOrg[9]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[10] + piRef[10] + bRound) >> 1;    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[11] + piRef[11] + bRound) >> 1;    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[12] + piRef[12] + bRound) >> 1;    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[13] + piRef[13] + bRound) >> 1;    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[14] + piRef[14] + bRound) >> 1;    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[15] + piRef[15] + bRound) >> 1;    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16N( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Pel  pred;
+
+  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 )
+    {
+      pred = (piCur[n+ 0] + piRef[n+ 0] + bRound) >> 1;    iTemp = ((piOrg[n+ 0]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 1] + piRef[n+ 1] + bRound) >> 1;    iTemp = ((piOrg[n+ 1]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 2] + piRef[n+ 2] + bRound) >> 1;    iTemp = ((piOrg[n+ 2]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 3] + piRef[n+ 3] + bRound) >> 1;    iTemp = ((piOrg[n+ 3]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 4] + piRef[n+ 4] + bRound) >> 1;    iTemp = ((piOrg[n+ 4]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 5] + piRef[n+ 5] + bRound) >> 1;    iTemp = ((piOrg[n+ 5]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 6] + piRef[n+ 6] + bRound) >> 1;    iTemp = ((piOrg[n+ 6]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 7] + piRef[n+ 7] + bRound) >> 1;    iTemp = ((piOrg[n+ 7]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 8] + piRef[n+ 8] + bRound) >> 1;    iTemp = ((piOrg[n+ 8]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 9] + piRef[n+ 9] + bRound) >> 1;    iTemp = ((piOrg[n+ 9]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 10] + piRef[n+ 10] + bRound) >> 1;    iTemp = ((piOrg[n+ 10]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 11] + piRef[n+ 11] + bRound) >> 1;    iTemp = ((piOrg[n+ 11]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 12] + piRef[n+ 12] + bRound) >> 1;    iTemp = ((piOrg[n+ 12]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 13] + piRef[n+ 13] + bRound) >> 1;    iTemp = ((piOrg[n+ 13]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 14] + piRef[n+ 14] + bRound) >> 1;    iTemp = ((piOrg[n+ 14]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+      pred = (piCur[n+ 15] + piRef[n+ 15] + bRound) >> 1;    iTemp = ((piOrg[n+ 15]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iCols;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE32( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement; 
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0; 
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[4] + piRef[4] + bRound) >> 1;    iTemp = ((piOrg[4]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[5] + piRef[5] + bRound) >> 1;    iTemp = ((piOrg[5]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[6] + piRef[6] + bRound) >> 1;    iTemp = ((piOrg[6]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[7] + piRef[7] + bRound) >> 1;    iTemp = ((piOrg[7]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[8] + piRef[8] + bRound) >> 1;    iTemp = ((piOrg[8]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[9] + piRef[9] + bRound) >> 1;    iTemp = ((piOrg[9]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[10] + piRef[10] + bRound) >> 1;    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[11] + piRef[11] + bRound) >> 1;    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[12] + piRef[12] + bRound) >> 1;    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[13] + piRef[13] + bRound) >> 1;    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[14] + piRef[14] + bRound) >> 1;    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[15] + piRef[15] + bRound) >> 1;    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[16] + piRef[16] + bRound) >> 1;    iTemp = ((piOrg[16]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[17] + piRef[17] + bRound) >> 1;    iTemp = ((piOrg[17]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[18] + piRef[18] + bRound) >> 1;    iTemp = ((piOrg[18]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[19] + piRef[19] + bRound) >> 1;    iTemp = ((piOrg[19]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[20] + piRef[20] + bRound) >> 1;    iTemp = ((piOrg[20]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[21] + piRef[21] + bRound) >> 1;    iTemp = ((piOrg[21]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[22] + piRef[22] + bRound) >> 1;    iTemp = ((piOrg[22]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[23] + piRef[23] + bRound) >> 1;    iTemp = ((piOrg[23]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[24] + piRef[24] + bRound) >> 1;    iTemp = ((piOrg[24]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[25] + piRef[25] + bRound) >> 1;    iTemp = ((piOrg[25]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[26] + piRef[26] + bRound) >> 1;    iTemp = ((piOrg[26]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[27] + piRef[27] + bRound) >> 1;    iTemp = ((piOrg[27]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[28] + piRef[28] + bRound) >> 1;    iTemp = ((piOrg[28]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[29] + piRef[29] + bRound) >> 1;    iTemp = ((piOrg[29]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[30] + piRef[30] + bRound) >> 1;    iTemp = ((piOrg[30]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[31] + piRef[31] + bRound) >> 1;    iTemp = ((piOrg[31]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE64( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+
+  UInt uiSum = 0;
+  Int  iShift = g_uiBitIncrement; 
+  Int  iOffset = (g_uiBitIncrement>0)? (1<<(g_uiBitIncrement-1)):0; 
+  Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;    iTemp = ((piOrg[0]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;    iTemp = ((piOrg[1]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;    iTemp = ((piOrg[2]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;    iTemp = ((piOrg[3]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[4] + piRef[4] + bRound) >> 1;    iTemp = ((piOrg[4]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[5] + piRef[5] + bRound) >> 1;    iTemp = ((piOrg[5]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[6] + piRef[6] + bRound) >> 1;    iTemp = ((piOrg[6]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[7] + piRef[7] + bRound) >> 1;    iTemp = ((piOrg[7]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[8] + piRef[8] + bRound) >> 1;    iTemp = ((piOrg[8]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[9] + piRef[9] + bRound) >> 1;    iTemp = ((piOrg[9]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[10] + piRef[10] + bRound) >> 1;    iTemp = ((piOrg[10]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[11] + piRef[11] + bRound) >> 1;    iTemp = ((piOrg[11]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[12] + piRef[12] + bRound) >> 1;    iTemp = ((piOrg[12]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[13] + piRef[13] + bRound) >> 1;    iTemp = ((piOrg[13]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[14] + piRef[14] + bRound) >> 1;    iTemp = ((piOrg[14]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[15] + piRef[15] + bRound) >> 1;    iTemp = ((piOrg[15]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[16] + piRef[16] + bRound) >> 1;    iTemp = ((piOrg[16]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[17] + piRef[17] + bRound) >> 1;    iTemp = ((piOrg[17]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[18] + piRef[18] + bRound) >> 1;    iTemp = ((piOrg[18]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[19] + piRef[19] + bRound) >> 1;    iTemp = ((piOrg[19]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[20] + piRef[20] + bRound) >> 1;    iTemp = ((piOrg[20]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[21] + piRef[21] + bRound) >> 1;    iTemp = ((piOrg[21]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[22] + piRef[22] + bRound) >> 1;    iTemp = ((piOrg[22]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[23] + piRef[23] + bRound) >> 1;    iTemp = ((piOrg[23]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[24] + piRef[24] + bRound) >> 1;    iTemp = ((piOrg[24]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[25] + piRef[25] + bRound) >> 1;    iTemp = ((piOrg[25]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[26] + piRef[26] + bRound) >> 1;    iTemp = ((piOrg[26]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[27] + piRef[27] + bRound) >> 1;    iTemp = ((piOrg[27]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[28] + piRef[28] + bRound) >> 1;    iTemp = ((piOrg[28]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[29] + piRef[29] + bRound) >> 1;    iTemp = ((piOrg[29]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    pred = (piCur[30] + piRef[30] + bRound) >> 1;    iTemp = ((piOrg[30]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[31] + piRef[31] + bRound) >> 1;    iTemp = ((piOrg[31]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[32] + piRef[32] + bRound) >> 1;    iTemp = ((piOrg[32]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[33] + piRef[33] + bRound) >> 1;    iTemp = ((piOrg[33]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[34] + piRef[34] + bRound) >> 1;    iTemp = ((piOrg[34]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[35] + piRef[35] + bRound) >> 1;    iTemp = ((piOrg[35]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[36] + piRef[36] + bRound) >> 1;    iTemp = ((piOrg[36]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[37] + piRef[37] + bRound) >> 1;    iTemp = ((piOrg[37]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[38] + piRef[38] + bRound) >> 1;    iTemp = ((piOrg[38]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[39] + piRef[39] + bRound) >> 1;    iTemp = ((piOrg[39]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    pred = (piCur[40] + piRef[40] + bRound) >> 1;    iTemp = ((piOrg[40]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[41] + piRef[41] + bRound) >> 1;    iTemp = ((piOrg[41]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[42] + piRef[42] + bRound) >> 1;    iTemp = ((piOrg[42]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[43] + piRef[43] + bRound) >> 1;    iTemp = ((piOrg[43]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[44] + piRef[44] + bRound) >> 1;    iTemp = ((piOrg[44]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[45] + piRef[45] + bRound) >> 1;    iTemp = ((piOrg[45]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[46] + piRef[46] + bRound) >> 1;    iTemp = ((piOrg[46]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[47] + piRef[47] + bRound) >> 1;    iTemp = ((piOrg[47]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[48] + piRef[48] + bRound) >> 1;    iTemp = ((piOrg[48]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[49] + piRef[49] + bRound) >> 1;    iTemp = ((piOrg[49]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    pred = (piCur[50] + piRef[50] + bRound) >> 1;    iTemp = ((piOrg[50]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[51] + piRef[51] + bRound) >> 1;    iTemp = ((piOrg[51]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[52] + piRef[52] + bRound) >> 1;    iTemp = ((piOrg[52]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[53] + piRef[53] + bRound) >> 1;    iTemp = ((piOrg[53]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[54] + piRef[54] + bRound) >> 1;    iTemp = ((piOrg[54]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[55] + piRef[55] + bRound) >> 1;    iTemp = ((piOrg[55]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[56] + piRef[56] + bRound) >> 1;    iTemp = ((piOrg[56]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[57] + piRef[57] + bRound) >> 1;    iTemp = ((piOrg[57]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[58] + piRef[58] + bRound) >> 1;    iTemp = ((piOrg[58]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[59] + piRef[59] + bRound) >> 1;    iTemp = ((piOrg[59]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    pred = (piCur[60] + piRef[60] + bRound) >> 1;    iTemp = ((piOrg[60]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[61] + piRef[61] + bRound) >> 1;    iTemp = ((piOrg[61]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[62] + piRef[62] + bRound) >> 1;    iTemp = ((piOrg[62]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+    pred = (piCur[63] + piRef[63] + bRound) >> 1;    iTemp = ((piOrg[63]+iOffset)>>iShift) - ((pred+iOffset)>>iShift); uiSum += iTemp * iTemp;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+
+  return ( uiSum );
+}
+#endif
+
+
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSSEw( pcDtParam , pRefY, bRound );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 4 );
+    return xGetSSEw( pcDtParam , pRefY, bRound );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 8 );
+    return xGetSSEw( pcDtParam , pRefY, bRound );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 16 );
+    return xGetSSEw( pcDtParam , pRefY, bRound );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 16 );
+    return xGetSSEw( pcDtParam , pRefY, bRound );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 32 );
+    return xGetSSEw( pcDtParam , pRefY, bRound );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 64 );
+    return xGetSSEw( pcDtParam , pRefY, bRound );
+  }
+#endif
+  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
+#ifdef ROUNDING_CONTROL_BIPRED
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      pred = (piCur[n] + piRef[n] + bRound) >> 1 ;
+      iTemp = piOrg[n] - pred;
+      uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iCols;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE4( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;   iTemp = piOrg[0] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;   iTemp = piOrg[1] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;   iTemp = piOrg[2] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;   iTemp = piOrg[3] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE8( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;   iTemp = piOrg[0] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;   iTemp = piOrg[1] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;   iTemp = piOrg[2] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;   iTemp = piOrg[3] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[4] + piRef[4] + bRound) >> 1;   iTemp = piOrg[4] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[5] + piRef[5] + bRound) >> 1;   iTemp = piOrg[5] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[6] + piRef[6] + bRound) >> 1;   iTemp = piOrg[6] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[7] + piRef[7] + bRound) >> 1;   iTemp = piOrg[7] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;   iTemp = piOrg[0] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;   iTemp = piOrg[1] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;   iTemp = piOrg[2] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;   iTemp = piOrg[3] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[4] + piRef[4] + bRound) >> 1;   iTemp = piOrg[4] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[5] + piRef[5] + bRound) >> 1;   iTemp = piOrg[5] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[6] + piRef[6] + bRound) >> 1;   iTemp = piOrg[6] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[7] + piRef[7] + bRound) >> 1;   iTemp = piOrg[7] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[8] + piRef[8] + bRound) >> 1;   iTemp = piOrg[8] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[9] + piRef[9] + bRound) >> 1;   iTemp = piOrg[9] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[10] + piRef[10] + bRound) >> 1;   iTemp = piOrg[10] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[11] + piRef[11] + bRound) >> 1;   iTemp = piOrg[11] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[12] + piRef[12] + bRound) >> 1;   iTemp = piOrg[12] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[13] + piRef[13] + bRound) >> 1;   iTemp = piOrg[13] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[14] + piRef[14] + bRound) >> 1;   iTemp = piOrg[14] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[15] + piRef[15] + bRound) >> 1;   iTemp = piOrg[15] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16N( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      pred = (piCur[n+ 0] + piRef[n+ 0] + bRound) >> 1;  iTemp = piOrg[n+ 0] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 1] + piRef[n+ 1] + bRound) >> 1;  iTemp = piOrg[n+ 1] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 2] + piRef[n+ 2] + bRound) >> 1;  iTemp = piOrg[n+ 2] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 3] + piRef[n+ 3] + bRound) >> 1;  iTemp = piOrg[n+ 3] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 4] + piRef[n+ 4] + bRound) >> 1;  iTemp = piOrg[n+ 4] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 5] + piRef[n+ 5] + bRound) >> 1;  iTemp = piOrg[n+ 5] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 6] + piRef[n+ 6] + bRound) >> 1;  iTemp = piOrg[n+ 6] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 7] + piRef[n+ 7] + bRound) >> 1;  iTemp = piOrg[n+ 7] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 8] + piRef[n+ 8] + bRound) >> 1;  iTemp = piOrg[n+ 8] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 9] + piRef[n+ 9] + bRound) >> 1;  iTemp = piOrg[n+ 9] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 10] + piRef[n+ 10] + bRound) >> 1;  iTemp = piOrg[n+ 10] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 11] + piRef[n+ 11] + bRound) >> 1;  iTemp = piOrg[n+ 11] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 12] + piRef[n+ 12] + bRound) >> 1;  iTemp = piOrg[n+ 12] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 13] + piRef[n+ 13] + bRound) >> 1;  iTemp = piOrg[n+ 13] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 14] + piRef[n+ 14] + bRound) >> 1;  iTemp = piOrg[n+ 14] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+      pred = (piCur[n+ 15] + piRef[n+ 15] + bRound) >> 1;  iTemp = piOrg[n+ 15] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iCols;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE32( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;   iTemp = piOrg[0] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;   iTemp = piOrg[1] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;   iTemp = piOrg[2] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;   iTemp = piOrg[3] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[4] + piRef[4] + bRound) >> 1;   iTemp = piOrg[4] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[5] + piRef[5] + bRound) >> 1;   iTemp = piOrg[5] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[6] + piRef[6] + bRound) >> 1;   iTemp = piOrg[6] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[7] + piRef[7] + bRound) >> 1;   iTemp = piOrg[7] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[8] + piRef[8] + bRound) >> 1;   iTemp = piOrg[8] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[9] + piRef[9] + bRound) >> 1;   iTemp = piOrg[9] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[10] + piRef[10] + bRound) >> 1;   iTemp = piOrg[10] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[11] + piRef[11] + bRound) >> 1;   iTemp = piOrg[11] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[12] + piRef[12] + bRound) >> 1;   iTemp = piOrg[12] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[13] + piRef[13] + bRound) >> 1;   iTemp = piOrg[13] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[14] + piRef[14] + bRound) >> 1;   iTemp = piOrg[14] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[15] + piRef[15] + bRound) >> 1;   iTemp = piOrg[15] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[16] + piRef[16] + bRound) >> 1;   iTemp = piOrg[16] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[17] + piRef[17] + bRound) >> 1;   iTemp = piOrg[17] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[18] + piRef[18] + bRound) >> 1;   iTemp = piOrg[18] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[19] + piRef[19] + bRound) >> 1;   iTemp = piOrg[19] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[20] + piRef[20] + bRound) >> 1;   iTemp = piOrg[20] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[21] + piRef[21] + bRound) >> 1;   iTemp = piOrg[21] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[22] + piRef[22] + bRound) >> 1;   iTemp = piOrg[22] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[23] + piRef[23] + bRound) >> 1;   iTemp = piOrg[23] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[24] + piRef[24] + bRound) >> 1;   iTemp = piOrg[24] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[25] + piRef[25] + bRound) >> 1;   iTemp = piOrg[25] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[26] + piRef[26] + bRound) >> 1;   iTemp = piOrg[26] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[27] + piRef[27] + bRound) >> 1;   iTemp = piOrg[27] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[28] + piRef[28] + bRound) >> 1;   iTemp = piOrg[28] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[29] + piRef[29] + bRound) >> 1;   iTemp = piOrg[29] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[30] + piRef[30] + bRound) >> 1;   iTemp = piOrg[30] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[31] + piRef[31] + bRound) >> 1;   iTemp = piOrg[31] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE64( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideRef =  pcDtParam->iCols;
+  Pel  pred;
+  
+  UInt uiSum = 0;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    pred = (piCur[0] + piRef[0] + bRound) >> 1;   iTemp = piOrg[0] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[1] + piRef[1] + bRound) >> 1;   iTemp = piOrg[1] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[2] + piRef[2] + bRound) >> 1;   iTemp = piOrg[2] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[3] + piRef[3] + bRound) >> 1;   iTemp = piOrg[3] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[4] + piRef[4] + bRound) >> 1;   iTemp = piOrg[4] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[5] + piRef[5] + bRound) >> 1;   iTemp = piOrg[5] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[6] + piRef[6] + bRound) >> 1;   iTemp = piOrg[6] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[7] + piRef[7] + bRound) >> 1;   iTemp = piOrg[7] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[8] + piRef[8] + bRound) >> 1;   iTemp = piOrg[8] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[9] + piRef[9] + bRound) >> 1;   iTemp = piOrg[9] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[10] + piRef[10] + bRound) >> 1;   iTemp = piOrg[10] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[11] + piRef[11] + bRound) >> 1;   iTemp = piOrg[11] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[12] + piRef[12] + bRound) >> 1;   iTemp = piOrg[12] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[13] + piRef[13] + bRound) >> 1;   iTemp = piOrg[13] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[14] + piRef[14] + bRound) >> 1;   iTemp = piOrg[14] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[15] + piRef[15] + bRound) >> 1;   iTemp = piOrg[15] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[16] + piRef[16] + bRound) >> 1;   iTemp = piOrg[16] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[17] + piRef[17] + bRound) >> 1;   iTemp = piOrg[17] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[18] + piRef[18] + bRound) >> 1;   iTemp = piOrg[18] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[19] + piRef[19] + bRound) >> 1;   iTemp = piOrg[19] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[20] + piRef[20] + bRound) >> 1;   iTemp = piOrg[20] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[21] + piRef[21] + bRound) >> 1;   iTemp = piOrg[21] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[22] + piRef[22] + bRound) >> 1;   iTemp = piOrg[22] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[23] + piRef[23] + bRound) >> 1;   iTemp = piOrg[23] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[24] + piRef[24] + bRound) >> 1;   iTemp = piOrg[24] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[25] + piRef[25] + bRound) >> 1;   iTemp = piOrg[25] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[26] + piRef[26] + bRound) >> 1;   iTemp = piOrg[26] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[27] + piRef[27] + bRound) >> 1;   iTemp = piOrg[27] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[28] + piRef[28] + bRound) >> 1;   iTemp = piOrg[28] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[29] + piRef[29] + bRound) >> 1;   iTemp = piOrg[29] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    pred = (piCur[30] + piRef[30] + bRound) >> 1;   iTemp = piOrg[30] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[31] + piRef[31] + bRound) >> 1;   iTemp = piOrg[31] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[32] + piRef[32] + bRound) >> 1;   iTemp = piOrg[32] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[33] + piRef[33] + bRound) >> 1;   iTemp = piOrg[33] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[34] + piRef[34] + bRound) >> 1;   iTemp = piOrg[34] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[35] + piRef[35] + bRound) >> 1;   iTemp = piOrg[35] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[36] + piRef[36] + bRound) >> 1;   iTemp = piOrg[36] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[37] + piRef[37] + bRound) >> 1;   iTemp = piOrg[37] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[38] + piRef[38] + bRound) >> 1;   iTemp = piOrg[38] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[39] + piRef[39] + bRound) >> 1;   iTemp = piOrg[39] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    pred = (piCur[40] + piRef[40] + bRound) >> 1;   iTemp = piOrg[40] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[41] + piRef[41] + bRound) >> 1;   iTemp = piOrg[41] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[42] + piRef[42] + bRound) >> 1;   iTemp = piOrg[42] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[43] + piRef[43] + bRound) >> 1;   iTemp = piOrg[43] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[44] + piRef[44] + bRound) >> 1;   iTemp = piOrg[44] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[45] + piRef[45] + bRound) >> 1;   iTemp = piOrg[45] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[46] + piRef[46] + bRound) >> 1;   iTemp = piOrg[46] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[47] + piRef[47] + bRound) >> 1;   iTemp = piOrg[47] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[48] + piRef[48] + bRound) >> 1;   iTemp = piOrg[48] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[49] + piRef[49] + bRound) >> 1;   iTemp = piOrg[49] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    pred = (piCur[50] + piRef[50] + bRound) >> 1;   iTemp = piOrg[50] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[51] + piRef[51] + bRound) >> 1;   iTemp = piOrg[51] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[52] + piRef[52] + bRound) >> 1;   iTemp = piOrg[52] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[53] + piRef[53] + bRound) >> 1;   iTemp = piOrg[53] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[54] + piRef[54] + bRound) >> 1;   iTemp = piOrg[54] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[55] + piRef[55] + bRound) >> 1;   iTemp = piOrg[55] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[56] + piRef[56] + bRound) >> 1;   iTemp = piOrg[56] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[57] + piRef[57] + bRound) >> 1;   iTemp = piOrg[57] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[58] + piRef[58] + bRound) >> 1;   iTemp = piOrg[58] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[59] + piRef[59] + bRound) >> 1;   iTemp = piOrg[59] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    pred = (piCur[60] + piRef[60] + bRound) >> 1;   iTemp = piOrg[60] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[61] + piRef[61] + bRound) >> 1;   iTemp = piOrg[61] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[62] + piRef[62] + bRound) >> 1;   iTemp = piOrg[62] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    pred = (piCur[63] + piRef[63] + bRound) >> 1;   iTemp = piOrg[63] - pred; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    piRef += iStrideRef;
+  }
+  
+  return ( uiSum );
+}
+#endif
+
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSSEw( pcDtParam );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 4 );
+    return xGetSSEw( pcDtParam );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 8 );
+    return xGetSSEw( pcDtParam );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 16 );
+    return xGetSSEw( pcDtParam );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetSSEw( pcDtParam );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 32 );
+    return xGetSSEw( pcDtParam );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    assert( pcDtParam->iCols == 64 );
+    return xGetSSEw( pcDtParam );
+  }
+#endif
+  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
+
+// --------------------------------------------------------------------------------------------------------------------
+// HADAMARD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+
+#ifdef ROUNDING_CONTROL_BIPRED
+
+UInt TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep, Pel* pRefY, Int refYStride, Bool bRound )
+{
+  Int satd = 0, diff[4], m[4];
+  Pel pred;
+  
+  pred = ( (piCur[0] + pRefY[0] + bRound) >> 1);
+  diff[0] = (piOrg[0             ] - pred) << 1;
+  pred = ( (piCur[iStep] + pRefY[1] + bRound) >> 1);
+  diff[1] = (piOrg[1             ] - pred) << 1;
+  pred = ( (piCur[iStrideCur] + pRefY[refYStride] + bRound) >> 1);
+  diff[2] = (piOrg[iStrideOrg    ] - pred) << 1;
+  pred = ( (piCur[iStep + iStrideCur] + pRefY[refYStride + 1] + bRound) >> 1);
+  diff[3] = (piOrg[iStrideOrg + 1] - pred) << 1;
+  
+  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, Pel* pRefY, Int refYStride, Bool bRound )
+{
+  Int k, satd = 0, diff[16], m[16], d[16];
+  Pel pred;
+  Pel* piRef = pRefY;
+  
+  for( k = 0; k < 16; k+=4 )
+  {
+    pred = ( (piCur[0*iStep] + piRef[0] + bRound) >> 1);
+    diff[k+0] = (piOrg[0] - pred) << 1;
+    pred = ( (piCur[1*iStep] + piRef[1] + bRound) >> 1);
+    diff[k+1] = (piOrg[1] - pred) << 1;
+    pred = ( (piCur[2*iStep] + piRef[2] + bRound) >> 1);
+    diff[k+2] = (piOrg[2] - pred) << 1;
+    pred = ( (piCur[3*iStep] + piRef[3] + bRound) >> 1);
+    diff[k+3] = (piOrg[3] - pred) << 1;
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+    piRef += refYStride;
+  }
+  
+  /*===== 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, Pel* pRefY, Int refYStride, Bool bRound )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[8][8], m2[8][8], m3[8][8];
+  Pel pred;
+  Pel* piRef = pRefY;
+  Int iStep2 = iStep<<1;
+  Int iStep3 = iStep2 + iStep;
+  Int iStep4 = iStep3 + iStep;
+  Int iStep5 = iStep4 + iStep;
+  Int iStep6 = iStep5 + iStep;
+  Int iStep7 = iStep6 + iStep;
+  
+  for( k = 0; k < 64; k+=8 )
+  {
+    pred = ( (piCur[0     ] + piRef[0] + bRound) >> 1 );  diff[k  ] = (piOrg[0] - pred) << 1;
+    pred = ( (piCur[iStep ] + piRef[1] + bRound) >> 1 );  diff[k+1] = (piOrg[1] - pred) << 1;
+    pred = ( (piCur[iStep2] + piRef[2] + bRound) >> 1 );  diff[k+2] = (piOrg[2] - pred) << 1;
+    pred = ( (piCur[iStep3] + piRef[3] + bRound) >> 1 );  diff[k+3] = (piOrg[3] - pred) << 1;
+    pred = ( (piCur[iStep4] + piRef[4] + bRound) >> 1 );  diff[k+4] = (piOrg[4] - pred) << 1;
+    pred = ( (piCur[iStep5] + piRef[5] + bRound) >> 1 );  diff[k+5] = (piOrg[5] - pred) << 1;
+    pred = ( (piCur[iStep6] + piRef[6] + bRound) >> 1 );  diff[k+6] = (piOrg[6] - pred) << 1;
+    pred = ( (piCur[iStep7] + piRef[7] + bRound) >> 1 );  diff[k+7] = (piOrg[7] - pred) << 1;
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+    piRef += refYStride;
+  }
+  //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;
+}
+
+UInt TComRdCost::xGetHADs4( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  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, piRef, pcDtParam->iCols, bRound );
+    piOrg += iOffsetOrg;
+    piCur += iOffsetCur;
+    piRef += (pcDtParam->iCols << 2);
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetHADs8( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  
+  UInt uiSum = 0;
+  
+  if ( iRows == 4 ) // 8x4 case
+  {
+    uiSum += xCalcHADs4x4( piOrg+0, piCur        , iStrideOrg, iStrideCur, iStep, piRef, pcDtParam->iCols, bRound );
+    uiSum += xCalcHADs4x4( piOrg+4, piCur+4*iStep, iStrideOrg, iStrideCur, iStep, piRef+4, pcDtParam->iCols, bRound );
+  }
+  else
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      uiSum += xCalcHADs8x8( piOrg, piCur, iStrideOrg, iStrideCur, iStep, piRef, pcDtParam->iCols, bRound );
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+      piRef += (pcDtParam->iCols << 3);
+    }
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCost::xGetHADs( DistParam* pcDtParam, Pel* pRefY, Bool bRound )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piRef   = pRefY;
+  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( ( 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 )  // do HAD over 8xiCols pixels
+      {
+        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep, &piRef[x], iCols, bRound );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+      piRef += (iCols << 3);
+    }
+  }
+  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 ) // do HAD over 4xiCols pixels 
+      {
+        uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep, &piRef[x], iCols, bRound );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+      piRef += (iCols << 2);
+    }
+  }
+  else
+  {
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )// do HAD over 2xiCols pixels 
+      {
+        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep, &piRef[x], iCols, bRound );
+      }
+      piOrg += iStrideOrg;  // should this be (iStrideOrg << 1) ? 
+      piCur += iStrideCur;
+      piRef += iCols;
+    }
+  }
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#endif
+
+UInt TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int satd = 0, diff[4], m[4];
+  diff[0] = piOrg[0             ] - piCur[0*iStep];
+  diff[1] = piOrg[1             ] - piCur[1*iStep];
+  diff[2] = piOrg[iStrideOrg    ] - piCur[0*iStep + iStrideCur];
+  diff[3] = piOrg[iStrideOrg + 1] - piCur[1*iStep + 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];
+  
+  for( k = 0; k < 16; k+=4 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0*iStep];
+    diff[k+1] = piOrg[1] - piCur[1*iStep];
+    diff[k+2] = piOrg[2] - piCur[2*iStep];
+    diff[k+3] = piOrg[3] - piCur[3*iStep];
+    
+    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];
+  Int iStep2 = iStep<<1;
+  Int iStep3 = iStep2 + iStep;
+  Int iStep4 = iStep3 + iStep;
+  Int iStep5 = iStep4 + iStep;
+  Int iStep6 = iStep5 + iStep;
+  Int iStep7 = iStep6 + iStep;
+  
+  for( k = 0; k < 64; k+=8 )
+  {
+    diff[k+0] = piOrg[0] - piCur[     0];
+    diff[k+1] = piOrg[1] - piCur[iStep ];
+    diff[k+2] = piOrg[2] - piCur[iStep2];
+    diff[k+3] = piOrg[3] - piCur[iStep3];
+    diff[k+4] = piOrg[4] - piCur[iStep4];
+    diff[k+5] = piOrg[5] - piCur[iStep5];
+    diff[k+6] = piOrg[6] - piCur[iStep6];
+    diff[k+7] = piOrg[7] - piCur[iStep7];
+    
+    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;
+}
+
+UInt TComRdCost::xGetHADs4( DistParam* pcDtParam )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetHADs4w( pcDtParam );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetHADs8w( pcDtParam );
+  }
+#endif
+  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 )
+{
+#ifdef WEIGHT_PRED
+  if ( pcDtParam->applyWeight )
+  {
+    return xGetHADsw( 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( ( 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 += xCalcHADs8x8( &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 += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix since row size can be 1 or 3 for chroma (such a case does not occur under current encoder settings)
+  else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<1;
+    Int  iOffsetCur = iStrideCur<<1;
+#else
+  else
+  {
+#endif
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix since we need to increment by 2*iStride instead of iStride
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+#else
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+#endif
+    }
+  }
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix to return MAX_UINT until this case is properly handled
+  else
+  {
+    printf("xGetHADs not supported for this dimension. Skipping computation of HAD and returning MAX_UINT\n");
+    return (MAX_UINT);
+  }
+#endif
+  
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+
+#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); 
+  RMDist iDist = m_pcRenModel->getDist( iStartPosX, iStartPosY, (Int) uiBlkWidth, (Int) uiBlkHeight, iCurStride, piCur );  
+
+  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::setRefDataFromMVDInfo( TComMVDRefData* pRefInfo )
+{
+  if ( m_apRefPics != NULL )
+  {
+    delete[] m_apRefPics;
+    m_apRefPics = NULL;
+  }; 
+
+  if ( m_paaiShiftLUTs != NULL )
+  { // Delete only first dimension, other dimension are not create in this class
+    delete[] m_paaiShiftLUTs; 
+    m_paaiShiftLUTs = NULL;
+  }; 
+
+
+  m_uiNumberRefPics = ( m_uiVSOMode == 1 ) ? 3 : pRefInfo->getNumOfRefViews();
+  m_apRefPics     = new TComPicYuv*[ m_uiNumberRefPics ];
+  m_paaiShiftLUTs = new Int**[ m_uiNumberRefPics ];
+
+  if ( m_uiVSOMode == 1 )
+  {
+    pRefInfo->getRefPicYuvAndLUTMode1(m_apRefPics, m_paaiShiftLUTs); 
+  }
+  else
+  {
+    pRefInfo->getRefPicYuvAndLUT(m_apRefPics, m_paaiShiftLUTs); 
+  }
+  m_pcVideoPicYuv = pRefInfo->getPicYuvVideo();
+}
+
+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: /tags/0.2r1/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComRdCost.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComRdCost.h	(revision 19)
@@ -0,0 +1,390 @@
+/* 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     TComRdCost.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOST__
+#define __TCOMRDCOST__
+
+
+#include "CommonDef.h"
+#include "TComMVDRefData.h"
+#include "TComDataCU.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+#ifdef WEIGHT_PRED
+  #include "TComSlice.h"
+  #include "TComRdCostWeightPrediction.h"
+#endif
+#include "TComYuv.h"
+#include "TComMVDRefData.h"
+#include "../TLibRenderer/TRenModel.h"
+
+class DistParam;
+class TComPattern;
+class TComRdCost;
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+// for function pointer
+typedef UInt (*FpDistFunc) (DistParam*);
+
+//GT VSO
+typedef Dist (TComRdCost::*FpDistFuncVSO) ( Int, Int, Pel*, Int, Pel*, Int, UInt, UInt, Bool );
+//GT VSO end
+
+#ifdef ROUNDING_CONTROL_BIPRED
+typedef UInt (*FpDistFuncRnd) (DistParam*, Pel*, Bool);
+#endif
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// distortion parameter class
+class DistParam
+{
+public:
+  Pel*  pOrg;
+  Pel*  pCur;
+  Int   iStrideOrg;
+  Int   iStrideCur;
+  Int   iRows;
+  Int   iCols;
+  Int   iStep;
+  FpDistFunc DistFunc;
+#ifdef ROUNDING_CONTROL_BIPRED
+  FpDistFuncRnd DistFuncRnd;
+#endif
+#if HHI_INTERVIEW_SKIP
+  Pel*  pUsed;
+  Int   iStrideUsed;
+#endif
+
+#ifdef WEIGHT_PRED
+  Bool            applyWeight;      // whether weithed prediction is used or not
+  wpScalingParam  *wpCur, *wpRef;   // weithed prediction scaling parameters for ref0 (or ref1) and ref1 (resp. ref0)
+  UInt            uiComp;           // uiComp = 0 (luma Y), 1 (chroma U), 2 (chroma V)
+#endif
+
+  // (vertical) subsampling shift (for reducing complexity)
+  // - 0 = no subsampling, 1 = even rows, 2 = every 4th, etc.
+  Int   iSubShift;
+
+  DistParam()
+  {
+    pOrg = NULL;
+    pCur = NULL;
+    iStrideOrg = 0;
+    iStrideCur = 0;
+    iRows = 0;
+    iCols = 0;
+    iStep = 1;
+    DistFunc = NULL;
+#ifdef ROUNDING_CONTROL_BIPRED
+    DistFuncRnd = NULL;
+#endif
+    iSubShift = 0;
+#if HHI_INTERVIEW_SKIP
+    pUsed       = 0;
+    iStrideUsed = 0;
+#endif
+  }
+};
+
+/// RD cost computation class
+class TComRdCost
+#ifdef WEIGHT_PRED
+  : public TComRdCostWeightPrediction
+#endif
+{
+private:
+  // for distortion
+  Int                     m_iBlkWidth;
+  Int                     m_iBlkHeight;
+
+  FpDistFunc              m_afpDistortFunc[33]; // [eDFunc]
+#ifdef ROUNDING_CONTROL_BIPRED
+  FpDistFuncRnd           m_afpDistortFuncRnd[33];
+#endif
+
+  Double                  m_dLambda;
+  Double                  m_sqrtLambda;
+  UInt                    m_uiLambdaMotionSAD;
+  UInt                    m_uiLambdaMotionSSE;
+  Double                  m_dFrameLambda;
+
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  Double                  m_dLambdaScale ;
+#endif
+  // for motion cost
+  UInt*                   m_puiComponentCostOriginP;
+  UInt*                   m_puiComponentCost;
+  UInt*                   m_puiVerCost;
+  UInt*                   m_puiHorCost;
+  UInt                    m_uiCost;
+  Int                     m_iCostScale;
+  Int                     m_iSearchLimit;
+
+  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, Dist   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+
+  Void    setLambda      ( Double dLambda );
+#if HHI_INTER_VIEW_MOTION_PRED
+  Void    setLambdaMVReg ( Double dLambda );
+#endif
+  Void    setFrameLambda ( Double dLambda ) { m_dFrameLambda = dLambda; }
+
+#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 );
+  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 );
+
+#ifdef ROUNDING_CONTROL_BIPRED
+  Void    setDistParam_Bi( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+  Void    setDistParam_Bi( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
+#endif
+
+  UInt    calcHAD         ( Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
+
+  // for motion cost
+  Void    initRateDistortionModel( Int iSubPelSearchLimit );
+  Void    xUninit();
+  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 )
+  {
+    m_puiHorCost = m_puiComponentCost - rcMv.getHor();
+    m_puiVerCost = m_puiComponentCost - rcMv.getVer();
+  }
+  Void    setCostScale( Int iCostScale )    { m_iCostScale = iCostScale; }
+  __inline UInt getCost( Int x, Int y )
+  {
+    return (( m_uiCost * (m_puiHorCost[ x * (1<<m_iCostScale) ] + m_puiVerCost[ y * (1<<m_iCostScale) ]) ) >> 16);
+  }
+  UInt    getCost( UInt b )                 { return ( m_uiCost * b ) >> 16; }
+  UInt    getBits( Int x, Int y )           { return m_puiHorCost[ x * (1<<m_iCostScale)] + m_puiVerCost[ y * (1<<m_iCostScale) ]; }
+
+  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 )
+  {
+    return ( ( m_uiLambdaMVReg * ( m_puiHorRegCost[ x * ( 1 << m_iCostScale ) ] + m_puiVerRegCost[ y * ( 1 << m_iCostScale ) ] ) ) >> 16 );
+  }
+
+private:
+
+  static UInt xGetSSE           ( DistParam* pcDtParam );
+  static UInt xGetSSE4          ( DistParam* pcDtParam );
+  static UInt xGetSSE8          ( DistParam* pcDtParam );
+  static UInt xGetSSE16         ( DistParam* pcDtParam );
+  static UInt xGetSSE32         ( DistParam* pcDtParam );
+  static UInt xGetSSE64         ( DistParam* pcDtParam );
+  static UInt xGetSSE16N        ( DistParam* pcDtParam );
+
+  static 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 );
+
+  static UInt xGetSADs          ( DistParam* pcDtParam );
+  static UInt xGetSADs4         ( DistParam* pcDtParam );
+  static UInt xGetSADs8         ( DistParam* pcDtParam );
+  static UInt xGetSADs16        ( DistParam* pcDtParam );
+  static UInt xGetSADs32        ( DistParam* pcDtParam );
+  static UInt xGetSADs64        ( DistParam* pcDtParam );
+  static UInt xGetSADs16N       ( DistParam* pcDtParam );
+
+  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 );
+
+#ifdef ROUNDING_CONTROL_BIPRED
+
+  static UInt xGetSSE           ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSSE4          ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSSE8          ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSSE16         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSSE32         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSSE64         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSSE16N        ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+
+  static UInt xGetSAD           ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD4          ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD8          ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD16         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD32         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD64         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSAD16N        ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+
+  static UInt xGetSADs          ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSADs4         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSADs8         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSADs16        ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSADs32        ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSADs64        ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetSADs16N       ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+
+  static UInt xGetHADs4         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetHADs8         ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xGetHADs          ( DistParam* pcDtParam, Pel* pRefY, Bool bRound );
+  static UInt xCalcHADs2x2      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep, Pel* pRefY, Int refYStride, Bool bRound );
+  static UInt xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep, Pel* pRefY, Int refYStride, Bool bRound );
+  static UInt xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep, Pel* pRefY, Int refYStride, Bool bRound );
+
+#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
+  UInt   getDistPart( Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc = DF_SSE );
+
+#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
+
+  TComPicYuv *            m_pcVideoPicYuv;
+  TComPicYuv**            m_apRefPics;
+  Int      ***            m_paaiShiftLUTs;
+  UInt                    m_uiNumberRefPics;
+  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    setRefDataFromMVDInfo( TComMVDRefData* pRefInfo );
+
+  Void    setUseVSO ( Bool bIn )         { m_bUseVSO = bIn; };
+  Bool    getUseVSO ( )                  { return m_bUseVSO;};
+
+  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 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: /tags/0.2r1/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 19)
@@ -0,0 +1,1598 @@
+/* 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     TComRdCostWeightPrediction.cpp
+    \brief    RD cost computation class with Weighted-Prediction
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRdCost.h"
+#include "TComRdCostWeightPrediction.h"
+
+#ifdef WEIGHT_PRED
+
+Int   TComRdCostWeightPrediction::m_w0        = 0,
+      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
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCostWeightPrediction::xGetSADw( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel  pred;
+  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            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-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+        if( piUsed[n])
+        {
+      pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+      //uiSum += abs( piOrg[n] - piCur[n] );
+      uiSum += abs( piOrg[n] - pred );
+    }
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+      piUsed += iStrideUsed;
+    }
+#else
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      for (Int n = 0; n < iCols; n++ )
+      {
+        pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+
+        //uiSum += abs( piOrg[n] - piCur[n] );
+        uiSum += abs( piOrg[n] - pred );
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+#endif
+#if HHI_INTERVIEW_SKIP
+  }
+#endif
+  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCostWeightPrediction::xGetSAD4w( DistParam* 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;
+
+  printf("TComRdCostWeightPrediction::xGetSAD4w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(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 TComRdCostWeightPrediction::xGetSAD8w( DistParam* 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;
+
+  printf("TComRdCostWeightPrediction::xGetSAD8w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(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 TComRdCostWeightPrediction::xGetSAD16w( DistParam* 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;
+
+  printf("TComRdCostWeightPrediction::xGetSAD16w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(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 TComRdCostWeightPrediction::xGetSAD16Nw( 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;
+
+  printf("TComRdCostWeightPrediction::xGetSAD16Nw():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(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 TComRdCostWeightPrediction::xGetSAD32w( DistParam* 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;
+
+  printf("TComRdCostWeightPrediction::xGetSAD32w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(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 TComRdCostWeightPrediction::xGetSAD64w( DistParam* 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;
+
+  printf("TComRdCostWeightPrediction::xGetSAD64w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(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 );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCostWeightPrediction::xGetSADsw( 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;
+
+  UInt uiSum = 0;
+
+  printf("TComRdCostWeightPrediction::xGetSADsw():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(0);
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      uiSum += abs( piOrg[n] - piCur[n*iStep] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCostWeightPrediction::xGetSADs4w( 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  iStep2 = iStep<<1;
+  Int  iStep3 = iStep2 + iStep;
+
+  UInt uiSum = 0;
+
+  printf("TComRdCostWeightPrediction::xGetSADs4w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(0);
+
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[0] - piCur[     0] );
+    uiSum += abs( piOrg[1] - piCur[iStep ] );
+    uiSum += abs( piOrg[2] - piCur[iStep2] );
+    uiSum += abs( piOrg[3] - piCur[iStep3] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCostWeightPrediction::xGetSADs8w( 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  iStep2 = iStep<<1;
+  Int  iStep3 = iStep2 + iStep;
+  Int  iStep4 = iStep3 + iStep;
+  Int  iStep5 = iStep4 + iStep;
+  Int  iStep6 = iStep5 + iStep;
+  Int  iStep7 = iStep6 + iStep;
+
+  UInt uiSum = 0;
+
+  printf("TComRdCostWeightPrediction::xGetSADs8w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(0);
+
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[0] - piCur[     0] );
+    uiSum += abs( piOrg[1] - piCur[iStep ] );
+    uiSum += abs( piOrg[2] - piCur[iStep2] );
+    uiSum += abs( piOrg[3] - piCur[iStep3] );
+    uiSum += abs( piOrg[4] - piCur[iStep4] );
+    uiSum += abs( piOrg[5] - piCur[iStep5] );
+    uiSum += abs( piOrg[6] - piCur[iStep6] );
+    uiSum += abs( piOrg[7] - piCur[iStep7] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCostWeightPrediction::xGetSADs16w( 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  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+
+  UInt uiSum = 0;
+
+  printf("TComRdCostWeightPrediction::xGetSADs16w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(0);
+
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[ 0] - piCur[      0] );
+    uiSum += abs( piOrg[ 1] - piCur[iStep  ] );
+    uiSum += abs( piOrg[ 2] - piCur[iStep2 ] );
+    uiSum += abs( piOrg[ 3] - piCur[iStep3 ] );
+    uiSum += abs( piOrg[ 4] - piCur[iStep4 ] );
+    uiSum += abs( piOrg[ 5] - piCur[iStep5 ] );
+    uiSum += abs( piOrg[ 6] - piCur[iStep6 ] );
+    uiSum += abs( piOrg[ 7] - piCur[iStep7 ] );
+    uiSum += abs( piOrg[ 8] - piCur[iStep8 ] );
+    uiSum += abs( piOrg[ 9] - piCur[iStep9 ] );
+    uiSum += abs( piOrg[10] - piCur[iStep10] );
+    uiSum += abs( piOrg[11] - piCur[iStep11] );
+    uiSum += abs( piOrg[12] - piCur[iStep12] );
+    uiSum += abs( piOrg[13] - piCur[iStep13] );
+    uiSum += abs( piOrg[14] - piCur[iStep14] );
+    uiSum += abs( piOrg[15] - piCur[iStep15] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCostWeightPrediction::xGetSADs16Nw( 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;
+
+  UInt uiSum = 0;
+
+  printf("TComRdCostWeightPrediction::xGetSADs16Nw():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(0);
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      uiSum += abs( piOrg[n +0] - piCur[iStep*(n +0)] );
+      uiSum += abs( piOrg[n +1] - piCur[iStep*(n +1)] );
+      uiSum += abs( piOrg[n +2] - piCur[iStep*(n +2)] );
+      uiSum += abs( piOrg[n +3] - piCur[iStep*(n +3)] );
+      uiSum += abs( piOrg[n +4] - piCur[iStep*(n +4)] );
+      uiSum += abs( piOrg[n +5] - piCur[iStep*(n +5)] );
+      uiSum += abs( piOrg[n +6] - piCur[iStep*(n +6)] );
+      uiSum += abs( piOrg[n +7] - piCur[iStep*(n +7)] );
+      uiSum += abs( piOrg[n +8] - piCur[iStep*(n +8)] );
+      uiSum += abs( piOrg[n +9] - piCur[iStep*(n +9)] );
+      uiSum += abs( piOrg[n+10] - piCur[iStep*(n+10)] );
+      uiSum += abs( piOrg[n+11] - piCur[iStep*(n+11)] );
+      uiSum += abs( piOrg[n+12] - piCur[iStep*(n+12)] );
+      uiSum += abs( piOrg[n+13] - piCur[iStep*(n+13)] );
+      uiSum += abs( piOrg[n+14] - piCur[iStep*(n+14)] );
+      uiSum += abs( piOrg[n+15] - piCur[iStep*(n+15)] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCostWeightPrediction::xGetSADs32w( 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  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+  Int  iStep16 = iStep15 + iStep;
+  Int  iStep17 = iStep16 + iStep;
+  Int  iStep18 = iStep17 + iStep;
+  Int  iStep19 = iStep18 + iStep;
+  Int  iStep20 = iStep19 + iStep;
+  Int  iStep21 = iStep20 + iStep;
+  Int  iStep22 = iStep21 + iStep;
+  Int  iStep23 = iStep22 + iStep;
+  Int  iStep24 = iStep23 + iStep;
+  Int  iStep25 = iStep24 + iStep;
+  Int  iStep26 = iStep25 + iStep;
+  Int  iStep27 = iStep26 + iStep;
+  Int  iStep28 = iStep27 + iStep;
+  Int  iStep29 = iStep28 + iStep;
+  Int  iStep30 = iStep29 + iStep;
+  Int  iStep31 = iStep30 + iStep;
+
+  UInt uiSum = 0;
+
+  printf("TComRdCostWeightPrediction::xGetSADs32w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(0);
+
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[ 0] - piCur[      0] );
+    uiSum += abs( piOrg[ 1] - piCur[iStep  ] );
+    uiSum += abs( piOrg[ 2] - piCur[iStep2 ] );
+    uiSum += abs( piOrg[ 3] - piCur[iStep3 ] );
+    uiSum += abs( piOrg[ 4] - piCur[iStep4 ] );
+    uiSum += abs( piOrg[ 5] - piCur[iStep5 ] );
+    uiSum += abs( piOrg[ 6] - piCur[iStep6 ] );
+    uiSum += abs( piOrg[ 7] - piCur[iStep7 ] );
+    uiSum += abs( piOrg[ 8] - piCur[iStep8 ] );
+    uiSum += abs( piOrg[ 9] - piCur[iStep9 ] );
+    uiSum += abs( piOrg[10] - piCur[iStep10] );
+    uiSum += abs( piOrg[11] - piCur[iStep11] );
+    uiSum += abs( piOrg[12] - piCur[iStep12] );
+    uiSum += abs( piOrg[13] - piCur[iStep13] );
+    uiSum += abs( piOrg[14] - piCur[iStep14] );
+    uiSum += abs( piOrg[15] - piCur[iStep15] );
+    uiSum += abs( piOrg[16] - piCur[iStep16] );
+    uiSum += abs( piOrg[17] - piCur[iStep17] );
+    uiSum += abs( piOrg[18] - piCur[iStep18] );
+    uiSum += abs( piOrg[19] - piCur[iStep19] );
+    uiSum += abs( piOrg[20] - piCur[iStep20] );
+    uiSum += abs( piOrg[21] - piCur[iStep21] );
+    uiSum += abs( piOrg[22] - piCur[iStep22] );
+    uiSum += abs( piOrg[23] - piCur[iStep23] );
+    uiSum += abs( piOrg[24] - piCur[iStep24] );
+    uiSum += abs( piOrg[25] - piCur[iStep25] );
+    uiSum += abs( piOrg[26] - piCur[iStep26] );
+    uiSum += abs( piOrg[27] - piCur[iStep27] );
+    uiSum += abs( piOrg[28] - piCur[iStep28] );
+    uiSum += abs( piOrg[29] - piCur[iStep29] );
+    uiSum += abs( piOrg[30] - piCur[iStep30] );
+    uiSum += abs( piOrg[31] - piCur[iStep31] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+UInt TComRdCostWeightPrediction::xGetSADs64w( 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  iStep2  = iStep<<1;
+  Int  iStep3  = iStep2  + iStep;
+  Int  iStep4  = iStep3  + iStep;
+  Int  iStep5  = iStep4  + iStep;
+  Int  iStep6  = iStep5  + iStep;
+  Int  iStep7  = iStep6  + iStep;
+  Int  iStep8  = iStep7  + iStep;
+  Int  iStep9  = iStep8  + iStep;
+  Int  iStep10 = iStep9  + iStep;
+  Int  iStep11 = iStep10 + iStep;
+  Int  iStep12 = iStep11 + iStep;
+  Int  iStep13 = iStep12 + iStep;
+  Int  iStep14 = iStep13 + iStep;
+  Int  iStep15 = iStep14 + iStep;
+  Int  iStep16 = iStep15 + iStep;
+  Int  iStep17 = iStep16 + iStep;
+  Int  iStep18 = iStep17 + iStep;
+  Int  iStep19 = iStep18 + iStep;
+  Int  iStep20 = iStep19 + iStep;
+  Int  iStep21 = iStep20 + iStep;
+  Int  iStep22 = iStep21 + iStep;
+  Int  iStep23 = iStep22 + iStep;
+  Int  iStep24 = iStep23 + iStep;
+  Int  iStep25 = iStep24 + iStep;
+  Int  iStep26 = iStep25 + iStep;
+  Int  iStep27 = iStep26 + iStep;
+  Int  iStep28 = iStep27 + iStep;
+  Int  iStep29 = iStep28 + iStep;
+  Int  iStep30 = iStep29 + iStep;
+  Int  iStep31 = iStep30 + iStep;
+  Int  iStep32 = iStep31 + iStep;
+  Int  iStep33 = iStep32 + iStep;
+  Int  iStep34 = iStep33 + iStep;
+  Int  iStep35 = iStep34 + iStep;
+  Int  iStep36 = iStep35 + iStep;
+  Int  iStep37 = iStep36 + iStep;
+  Int  iStep38 = iStep37 + iStep;
+  Int  iStep39 = iStep38 + iStep;
+  Int  iStep40 = iStep39 + iStep;
+  Int  iStep41 = iStep40 + iStep;
+  Int  iStep42 = iStep41 + iStep;
+  Int  iStep43 = iStep42 + iStep;
+  Int  iStep44 = iStep43 + iStep;
+  Int  iStep45 = iStep44 + iStep;
+  Int  iStep46 = iStep45 + iStep;
+  Int  iStep47 = iStep46 + iStep;
+  Int  iStep48 = iStep47 + iStep;
+  Int  iStep49 = iStep48 + iStep;
+  Int  iStep50 = iStep49 + iStep;
+  Int  iStep51 = iStep50 + iStep;
+  Int  iStep52 = iStep51 + iStep;
+  Int  iStep53 = iStep52 + iStep;
+  Int  iStep54 = iStep53 + iStep;
+  Int  iStep55 = iStep54 + iStep;
+  Int  iStep56 = iStep55 + iStep;
+  Int  iStep57 = iStep56 + iStep;
+  Int  iStep58 = iStep57 + iStep;
+  Int  iStep59 = iStep58 + iStep;
+  Int  iStep60 = iStep59 + iStep;
+  Int  iStep61 = iStep60 + iStep;
+  Int  iStep62 = iStep61 + iStep;
+  Int  iStep63 = iStep62 + iStep;
+
+  UInt uiSum = 0;
+
+  printf("TComRdCostWeightPrediction::xGetSADs64w():\tnot implemented, use xGetSADw().\n"); fflush(stdout); exit(0);
+
+  for( ; iRows != 0; iRows-- )
+  {
+    uiSum += abs( piOrg[ 0] - piCur[      0] );
+    uiSum += abs( piOrg[ 1] - piCur[iStep  ] );
+    uiSum += abs( piOrg[ 2] - piCur[iStep2 ] );
+    uiSum += abs( piOrg[ 3] - piCur[iStep3 ] );
+    uiSum += abs( piOrg[ 4] - piCur[iStep4 ] );
+    uiSum += abs( piOrg[ 5] - piCur[iStep5 ] );
+    uiSum += abs( piOrg[ 6] - piCur[iStep6 ] );
+    uiSum += abs( piOrg[ 7] - piCur[iStep7 ] );
+    uiSum += abs( piOrg[ 8] - piCur[iStep8 ] );
+    uiSum += abs( piOrg[ 9] - piCur[iStep9 ] );
+    uiSum += abs( piOrg[10] - piCur[iStep10] );
+    uiSum += abs( piOrg[11] - piCur[iStep11] );
+    uiSum += abs( piOrg[12] - piCur[iStep12] );
+    uiSum += abs( piOrg[13] - piCur[iStep13] );
+    uiSum += abs( piOrg[14] - piCur[iStep14] );
+    uiSum += abs( piOrg[15] - piCur[iStep15] );
+    uiSum += abs( piOrg[16] - piCur[iStep16] );
+    uiSum += abs( piOrg[17] - piCur[iStep17] );
+    uiSum += abs( piOrg[18] - piCur[iStep18] );
+    uiSum += abs( piOrg[19] - piCur[iStep19] );
+    uiSum += abs( piOrg[20] - piCur[iStep20] );
+    uiSum += abs( piOrg[21] - piCur[iStep21] );
+    uiSum += abs( piOrg[22] - piCur[iStep22] );
+    uiSum += abs( piOrg[23] - piCur[iStep23] );
+    uiSum += abs( piOrg[24] - piCur[iStep24] );
+    uiSum += abs( piOrg[25] - piCur[iStep25] );
+    uiSum += abs( piOrg[26] - piCur[iStep26] );
+    uiSum += abs( piOrg[27] - piCur[iStep27] );
+    uiSum += abs( piOrg[28] - piCur[iStep28] );
+    uiSum += abs( piOrg[29] - piCur[iStep29] );
+    uiSum += abs( piOrg[30] - piCur[iStep30] );
+    uiSum += abs( piOrg[31] - piCur[iStep31] );
+    uiSum += abs( piOrg[32] - piCur[iStep32] );
+    uiSum += abs( piOrg[33] - piCur[iStep33] );
+    uiSum += abs( piOrg[34] - piCur[iStep34] );
+    uiSum += abs( piOrg[35] - piCur[iStep35] );
+    uiSum += abs( piOrg[36] - piCur[iStep36] );
+    uiSum += abs( piOrg[37] - piCur[iStep37] );
+    uiSum += abs( piOrg[38] - piCur[iStep38] );
+    uiSum += abs( piOrg[39] - piCur[iStep39] );
+    uiSum += abs( piOrg[40] - piCur[iStep40] );
+    uiSum += abs( piOrg[41] - piCur[iStep41] );
+    uiSum += abs( piOrg[42] - piCur[iStep42] );
+    uiSum += abs( piOrg[43] - piCur[iStep43] );
+    uiSum += abs( piOrg[44] - piCur[iStep44] );
+    uiSum += abs( piOrg[45] - piCur[iStep45] );
+    uiSum += abs( piOrg[46] - piCur[iStep46] );
+    uiSum += abs( piOrg[47] - piCur[iStep47] );
+    uiSum += abs( piOrg[48] - piCur[iStep48] );
+    uiSum += abs( piOrg[49] - piCur[iStep49] );
+    uiSum += abs( piOrg[50] - piCur[iStep50] );
+    uiSum += abs( piOrg[51] - piCur[iStep51] );
+    uiSum += abs( piOrg[52] - piCur[iStep52] );
+    uiSum += abs( piOrg[53] - piCur[iStep53] );
+    uiSum += abs( piOrg[54] - piCur[iStep54] );
+    uiSum += abs( piOrg[55] - piCur[iStep55] );
+    uiSum += abs( piOrg[56] - piCur[iStep56] );
+    uiSum += abs( piOrg[57] - piCur[iStep57] );
+    uiSum += abs( piOrg[58] - piCur[iStep58] );
+    uiSum += abs( piOrg[59] - piCur[iStep59] );
+    uiSum += abs( piOrg[60] - piCur[iStep60] );
+    uiSum += abs( piOrg[61] - piCur[iStep61] );
+    uiSum += abs( piOrg[62] - piCur[iStep62] );
+    uiSum += abs( piOrg[63] - piCur[iStep63] );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+
+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  ] - piCur[n  ];
+      iTemp = piOrg[n  ] - pred;
+      uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  return ( uiSum );
+}
+
+UInt TComRdCostWeightPrediction::xGetSSE4w( 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;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int  iTemp;
+
+  printf("TComRdCostWeightPrediction::xGetSSE4w():\tnot implemented, use xGetSSEw().\n"); fflush(stdout); exit(0);
+
+  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 TComRdCostWeightPrediction::xGetSSE8w( 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;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int  iTemp;
+
+  printf("TComRdCostWeightPrediction::xGetSSE8w():\tnot implemented, use xGetSSEw().\n"); fflush(stdout); exit(0);
+
+  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 TComRdCostWeightPrediction::xGetSSE16w( 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;
+  UInt uiShift = g_uiBitIncrement<<1;
+
+  Int  iTemp;
+
+  printf("TComRdCostWeightPrediction::xGetSSE16w():\tnot implemented, use xGetSSEw().\n"); fflush(stdout); exit(0);
+
+  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 TComRdCostWeightPrediction::xGetSSE16Nw( 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;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+
+  printf("TComRdCostWeightPrediction::xGetSSE16Nw():\tnot implemented, use xGetSSEw().\n"); fflush(stdout); exit(0);
+
+  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;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCostWeightPrediction::xGetSSE32w( 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;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+
+  printf("TComRdCostWeightPrediction::xGetSSE32w():\tnot implemented, use xGetSSEw().\n"); fflush(stdout); exit(0);
+
+  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 );
+}
+
+UInt TComRdCostWeightPrediction::xGetSSE64w( 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;
+  UInt uiShift = g_uiBitIncrement<<1;
+  Int  iTemp;
+
+  printf("TComRdCostWeightPrediction::xGetSSE64w():\tnot implemented, use xGetSSEw().\n"); fflush(stdout); exit(0);
+
+  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;
+  }
+
+  return ( uiSum );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// HADAMARD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCostWeightPrediction::xCalcHADs2x2w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int satd = 0, diff[4], m[4];
+  diff[0] = piOrg[0             ] - piCur[0*iStep];
+  diff[1] = piOrg[1             ] - piCur[1*iStep];
+  diff[2] = piOrg[iStrideOrg    ] - piCur[0*iStep + iStrideCur];
+  diff[3] = piOrg[iStrideOrg + 1] - piCur[1*iStep + 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 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 )
+  {
+/*
+    diff[k+0] = piOrg[0] - piCur[0*iStep];
+    diff[k+1] = piOrg[1] - piCur[1*iStep];
+    diff[k+2] = piOrg[2] - piCur[2*iStep];
+    diff[k+3] = piOrg[3] - piCur[3*iStep];
+*/
+    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;
+}
+
+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 )
+  {
+/*
+    diff[k+0] = piOrg[0] - piCur[     0];
+    diff[k+1] = piOrg[1] - piCur[iStep ];
+    diff[k+2] = piOrg[2] - piCur[iStep2];
+    diff[k+3] = piOrg[3] - piCur[iStep3];
+    diff[k+4] = piOrg[4] - piCur[iStep4];
+    diff[k+5] = piOrg[5] - piCur[iStep5];
+    diff[k+6] = piOrg[6] - piCur[iStep6];
+    diff[k+7] = piOrg[7] - piCur[iStep7];
+*/
+    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;
+}
+
+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 );
+}
+
+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 );
+}
+
+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;
+    }
+  }
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix since row size can be 1 or 3 for chroma (such a case does not occur under current encoder settings)
+  else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<1;
+    Int  iOffsetCur = iStrideCur<<1;
+#else
+  else
+  {
+#endif
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix since we need to increment by 2*iStride instead of iStride
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+#else
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+#endif
+    }
+  }
+#ifdef DCM_RDCOST_TEMP_FIX //Temporary fix to return MAX_UINT until this case is properly handled
+  else
+  {
+    printf("xGetHADsw not supported for this dimension. Skipping computation of HAD and returning MAX_UINT\n");
+    return (MAX_UINT);
+  }
+#endif
+
+  m_xSetDone  = false;
+
+  return ( uiSum >> g_uiBitIncrement );
+}
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 19)
@@ -0,0 +1,122 @@
+/* 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     TComRdCostWeightPrediction.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOSTWEIGHTPREDICTION__
+#define __TCOMRDCOSTWEIGHTPREDICTION__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+#include "TComRdCost.h"
+#ifdef WEIGHT_PRED
+  #include "TComSlice.h"
+#endif
+
+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 xGetSSE4w         ( DistParam* pcDtParam );
+  static UInt xGetSSE8w         ( DistParam* pcDtParam );
+  static UInt xGetSSE16w        ( DistParam* pcDtParam );
+  static UInt xGetSSE32w        ( DistParam* pcDtParam );
+  static UInt xGetSSE64w        ( DistParam* pcDtParam );
+  static UInt xGetSSE16Nw       ( DistParam* pcDtParam );
+  
+  static UInt xGetSADw          ( DistParam* pcDtParam );
+  static UInt xGetSAD4w         ( DistParam* pcDtParam );
+  static UInt xGetSAD8w         ( DistParam* pcDtParam );
+  static UInt xGetSAD16w        ( DistParam* pcDtParam );
+  static UInt xGetSAD32w        ( DistParam* pcDtParam );
+  static UInt xGetSAD64w        ( DistParam* pcDtParam );
+  static UInt xGetSAD16Nw       ( DistParam* pcDtParam );
+  
+  static UInt xGetSADsw         ( DistParam* pcDtParam );
+  static UInt xGetSADs4w        ( DistParam* pcDtParam );
+  static UInt xGetSADs8w        ( DistParam* pcDtParam );
+  static UInt xGetSADs16w       ( DistParam* pcDtParam );
+  static UInt xGetSADs32w       ( DistParam* pcDtParam );
+  static UInt xGetSADs64w       ( DistParam* pcDtParam );
+  static UInt xGetSADs16Nw      ( 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: /tags/0.2r1/source/Lib/TLibCommon/TComResidualGenerator.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComResidualGenerator.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComResidualGenerator.cpp	(revision 19)
@@ -0,0 +1,579 @@
+/* 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 HHI_INTER_VIEW_RESIDUAL_PRED
+
+
+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 );
+  }
+  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( 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
+    }
+  }
+}
+
+
+Bool
+TComResidualGenerator::getResidualSamples( TComDataCU* pcCU, UInt uiPUIdx, TComYuv* pcYuv )
+{
+  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 );
+  return getResidualSamples( pcCU->getPic(), (UInt)iXPos, (UInt)iYPos, (UInt)iBlkWidth, (UInt)iBlkHeight, pcYuv );
+}
+  
+Bool
+TComResidualGenerator::getResidualSamples( TComPic* pcPic, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv )
+{
+  UInt  uiBaseViewId  = m_pcDepthMapGenerator->getBaseViewId( 0 );
+
+  if( !pcYuv )
+  {
+    pcYuv = m_ppcYuvTmp[1];
+  }
+  xSetPredResidualBlock( pcPic, uiBaseViewId, uiXPos, uiYPos, uiBlkWidth, uiBlkHeight, pcYuv );
+  return xIsNonZero( pcYuv, uiBlkWidth, uiBlkHeight );
+}
+
+
+
+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()->getWidth() || uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() );
+  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()->getWidth() && uiTPelY < pcCU->getSlice()->getSPS()->getHeight() );
+      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 );
+  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 );
+  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 );
+
+  if( pcCU->getResPredFlag( 0 ) )
+  {
+    AOF( pcCU->getResPredAvail( 0 ) );
+    Bool bOK = pcCU->getResidualSamples( 0, m_ppcYuvTmp[0] );
+    AOF( bOK );
+    pcCUResidual->add( m_ppcYuvTmp[0], pcCU->getWidth( 0 ), pcCU->getHeight( 0 ) );
+  }
+
+  //===== 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 ) );
+  }
+}
+
+
+
+Void  
+TComResidualGenerator::xSetPredResidualBlock( TComPic* pcPic, UInt uiBaseViewId, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv )
+{
+  //===== 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 =====
+  Int           iMidPosX    = Int( uiXPos + ( ( uiBlkWidth  - 1 ) >> 1 ) );
+  Int           iMidPosY    = Int( uiYPos + ( ( uiBlkHeight - 1 ) >> 1 ) );
+  Int           iDisparity  = m_pcDepthMapGenerator->getDisparity( pcPic, iMidPosX, iMidPosY, uiBaseViewId );
+
+  //===== 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           iYMaxPosX   = Int( uiPicWidth ) - 1;
+  Int           iSrcStrideY = pcBaseRes->getStride   ();
+  Int           iDesStrideY = pcYuv    ->getStride   ();
+  Pel*          pSrcSamplesY= pcBaseRes->getLumaAddr ( 0 ) + uiYPos * iSrcStrideY;
+  Pel*          pDesSamplesY= pcYuv    ->getLumaAddr ();
+  for(   Int iY = 0; iY < iYHeight; iY++, pSrcSamplesY += 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 ) );
+      pDesSamplesY[iX]  = ( iYWeight0 * pSrcSamplesY[iXPic0] + iYWeight1 * pSrcSamplesY[iXPic1] + 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           iCMaxPosX   = Int( uiPicWidth >> 1 ) - 1;
+  Int           iSrcStrideC = pcBaseRes->getCStride();
+  Int           iDesStrideC = pcYuv    ->getCStride();
+  Pel*          pSrcSamplesU= pcBaseRes->getCbAddr ( 0 ) + ( uiYPos >> 1 ) * iSrcStrideC;
+  Pel*          pSrcSamplesV= pcBaseRes->getCrAddr ( 0 ) + ( uiYPos >> 1 ) * iSrcStrideC;
+  Pel*          pDesSamplesU= pcYuv    ->getCbAddr ();
+  Pel*          pDesSamplesV= pcYuv    ->getCrAddr ();
+  for(   Int iY = 0; iY < iCHeight; iY++, pSrcSamplesU += iSrcStrideC, pDesSamplesU += iDesStrideC,
+                                          pSrcSamplesV += 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 ) );
+      pDesSamplesU[iX]  = ( iCWeight0 * pSrcSamplesU[iXPic0] + iCWeight1 * pSrcSamplesU[iXPic1] + 4 ) >> 3;
+      pDesSamplesV[iX]  = ( iCWeight0 * pSrcSamplesV[iXPic0] + iCWeight1 * pSrcSamplesV[iXPic1] + 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 // HHI_INTER_VIEW_RESIDUAL_PRED
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComResidualGenerator.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComResidualGenerator.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComResidualGenerator.h	(revision 19)
@@ -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     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 HHI_INTER_VIEW_RESIDUAL_PRED
+
+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 );
+
+  Bool  getResidualSamples    ( TComDataCU*   pcCU,  UInt uiPUIdx, TComYuv* pcYuv );
+  Bool  getResidualSamples    ( TComPic* pcPic, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv );
+
+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 );
+
+  Void  xSetPredResidualBlock ( TComPic*      pcPic, UInt uiBaseViewId, UInt uiXPos, UInt uiYPos, UInt uiBlkWidth, UInt uiBlkHeight, TComYuv* pcYuv );
+  Bool  xIsNonZero            ( TComYuv*      pcYuv, 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 // HHI_INTER_VIEW_RESIDUAL_PRED
+
+
+
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComRom.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComRom.cpp	(revision 19)
@@ -0,0 +1,2885 @@
+/* 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     TComRom.cpp
+    \brief    global variables & functions
+*/
+
+#include "TComRom.h"
+#include <memory.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+// ====================================================================================================================
+// Initialize / destroy functions
+// ====================================================================================================================
+
+// 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 );
+#if QC_MDCS
+    g_auiSigLastScan[0][i] = new UInt[ c*c ];
+    g_auiSigLastScan[1][i] = new UInt[ c*c ];
+    g_auiSigLastScan[2][i] = new UInt[ c*c ];
+    initSigLastScan( g_auiSigLastScan[0][i], g_auiSigLastScan[1][i], g_auiSigLastScan[2][i], c, c, i);
+#endif //QC_MDCS
+
+    c <<= 1;
+  }  
+}
+
+Void destroyROM()
+{
+  Int i;
+  
+  for ( i=0; i<MAX_CU_DEPTH; i++ )
+  {
+    delete[] g_auiFrameScanXY[i];
+    delete[] g_auiFrameScanX [i];
+    delete[] g_auiFrameScanY [i];
+#if QC_MDCS
+    delete[] g_auiSigLastScan[0][i];
+    delete[] g_auiSigLastScan[1][i];
+    delete[] g_auiSigLastScan[2][i];
+#endif //QC_MDCS
+  }
+
+#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();
+  }
+#endif
+}
+
+// ====================================================================================================================
+// Data structure related table & variable
+// ====================================================================================================================
+
+UInt g_uiMaxCUWidth  = MAX_CU_SIZE;
+UInt g_uiMaxCUHeight = MAX_CU_SIZE;
+UInt g_uiMaxCUDepth  = MAX_CU_DEPTH;
+UInt g_uiAddCUDepth  = 0;
+
+UInt g_auiZscanToRaster [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToZscan [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToPelX  [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToPelY  [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+
+UInt g_auiPUOffset[4] = { 0, 8, 4, 4 };
+
+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;
+  }
+}
+
+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 MTK_SAO
+Int  LevelRowCol2Idx(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;
+}
+
+void Idx2LevelRowCol(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;
+  }
+}
+#endif
+
+#if E243_CORE_TRANSFORMS
+  UInt g_auiQ[6] = {26214,23302,20560,18396,16384,14564};    
+  UInt g_auiIQ[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}
+  };
+
+#else //E243_CORE_TRANSFORMS
+// ====================================================================================================================
+// Quantization & DeQuantization
+// ====================================================================================================================
+
+UInt g_aiQuantCoef4[6] =
+{
+  102, 93, 79, 73, 64, 57
+};
+
+Int g_aiDequantCoef4[6] =
+{
+  10, 11, 13, 14, 16,18
+};
+
+UInt g_aiQuantCoef[6][16] =
+{
+  {
+    13107, 8066,13107, 8066,
+    8066, 5243, 8066, 5243,
+    13107, 8066,13107, 8066,
+    8066, 5243, 8066, 5243
+  },
+  {
+    11916, 7490,11916, 7490,
+    7490, 4660, 7490, 4660,
+    11916, 7490,11916, 7490,
+    7490, 4660, 7490, 4660
+  },
+  {
+    10082, 6554,10082, 6554,
+    6554, 4194, 6554, 4194,
+    10082, 6554,10082, 6554,
+    6554, 4194, 6554, 4194
+  },
+  {
+    9362, 5825, 9362, 5825,
+    5825, 3647, 5825, 3647,
+    9362, 5825, 9362, 5825,
+    5825, 3647, 5825, 3647
+  },
+  {
+    8192, 5243, 8192, 5243,
+    5243, 3355, 5243, 3355,
+    8192, 5243, 8192, 5243,
+    5243, 3355, 5243, 3355
+  },
+  {
+    7282, 4559, 7282, 4559,
+    4559, 2893, 4559, 2893,
+    7282, 4559, 7282, 4559,
+    4559, 2893, 4559, 2893
+  }
+};
+
+Int g_aiDequantCoef[6][16] =
+{
+  {
+    10, 13, 10, 13,
+    13, 16, 13, 16,
+    10, 13, 10, 13,
+    13, 16, 13, 16
+  },
+  {
+    11, 14, 11, 14,
+    14, 18, 14, 18,
+    11, 14, 11, 14,
+    14, 18, 14, 18
+  },
+  {
+    13, 16, 13, 16,
+    16, 20, 16, 20,
+    13, 16, 13, 16,
+    16, 20, 16, 20
+  },
+  {
+    14, 18, 14, 18,
+    18, 23, 18, 23,
+    14, 18, 14, 18,
+    18, 23, 18, 23
+  },
+  {
+    16, 20, 16, 20,
+    20, 25, 20, 25,
+    16, 20, 16, 20,
+    20, 25, 20, 25
+  },
+  {
+    18, 23, 18, 23,
+    23, 29, 23, 29,
+    18, 23, 18, 23,
+    23, 29, 23, 29
+  }
+};
+
+UInt g_aiQuantCoef4096[6] =
+{
+  26, 23, 20, 18, 16, 14
+}; // 9
+// {51, 47, 39, 37, 32, 28}; // 10
+// {102, 93, 79, 73, 64, 57}; // 11
+
+UInt g_aiDeQuantCoef4096[6] =
+{
+  10, 11, 13, 14, 16, 18
+}; // 9
+// {20, 22, 26, 28, 32, 36}; // 10
+// {40, 44, 52, 56, 64, 72}; // 11
+
+UInt g_aiQuantCoef1024[6][1024] =
+{
+  {
+    102, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 102, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 104, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 104, 103, 103, 103, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 103, 103, 103, 104, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 104, 103, 103, 103, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 103, 103, 103, 104, 103, 103, 103, 103, 103,
+    103, 104, 104, 104, 103, 104, 104, 103, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 103, 104, 104, 103, 104, 104, 104,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 104, 104, 104, 103, 104, 104, 103, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 103, 104, 104, 103, 104, 104, 104,
+    103, 103, 103, 103, 103, 103, 104, 103, 103, 103, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 103, 103, 103, 104, 103, 103, 103, 103, 103,
+    103, 104, 104, 104, 103, 104, 104, 103, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 103, 104, 104, 103, 104, 104, 104,
+    102, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 102, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 104, 104, 104, 103, 104, 104, 103, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 103, 104, 104, 103, 104, 104, 104,
+    103, 103, 103, 103, 103, 103, 104, 103, 103, 103, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 103, 103, 103, 104, 103, 103, 103, 103, 103,
+    103, 104, 104, 104, 103, 104, 104, 103, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 103, 104, 104, 103, 104, 104, 104,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 104, 104, 104, 103, 104, 104, 103, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 103, 104, 104, 103, 104, 104, 104,
+    103, 103, 103, 103, 103, 103, 104, 103, 103, 103, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 103, 103, 103, 104, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 104, 103, 103, 103, 103, 104, 103, 103, 103, 104, 104, 103, 104, 104, 104, 103, 104, 104, 104, 103, 104, 104, 103, 103, 103, 104, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103
+  },
+  {
+    93, 94, 94, 94, 93, 94, 94, 93, 93, 94, 94, 94, 93, 94, 94, 94, 93, 94, 94, 94, 93, 94, 94, 94, 93, 93, 94, 94, 93, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 93, 93, 94, 94, 94, 93, 94, 94, 94, 93, 94, 94, 94, 93, 94, 94, 94, 93, 93, 94, 94, 93, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 93, 93, 94, 94, 94, 93, 94, 94, 94, 93, 94, 94, 94, 93, 94, 94, 94, 93, 93, 94, 94, 93, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    93, 94, 94, 94, 93, 94, 94, 93, 93, 94, 94, 94, 93, 94, 94, 94, 93, 94, 94, 94, 93, 94, 94, 94, 94, 93, 94, 94, 93, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
+    94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94
+  },
+  {
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 79, 79, 80, 80, 79, 79, 79, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 80, 79, 79, 80, 80,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 80, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 80, 79, 80, 79, 80, 79, 80, 79, 80, 79, 80, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 80, 79, 79, 79, 80, 80, 79, 79, 79, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 79, 79, 79, 79, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 80, 79, 80, 79, 80, 79, 80, 79, 80, 79, 80, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 80, 80, 80, 79, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 80, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 79, 80, 80, 80,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 80, 79, 80, 79, 80, 79, 80, 79, 80, 79, 80, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 80, 80, 80, 79, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 79, 79, 79, 80, 80, 79, 79, 79, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 79, 79, 79, 79, 80,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 80, 79, 80, 79, 80, 79, 80, 79, 80, 79, 80, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 80, 79, 79, 79, 80, 79, 80, 79, 79, 79, 80, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 80, 79, 79, 80, 80,
+    79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
+    79, 80, 80, 79, 79, 80, 80, 79, 79, 79, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 79, 79, 79, 79, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 79, 79, 79, 80, 80, 79, 79, 80, 80,
+    79, 80, 80, 80, 79, 80, 80, 79, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 80, 80, 80, 79, 79, 80, 80, 79, 80, 80, 80
+  },
+  {
+    73, 74, 74, 73, 73, 74, 74, 73, 73, 73, 74, 74, 73, 74, 74, 74, 73, 74, 74, 74, 73, 74, 74, 73, 73, 73, 74, 73, 73, 73, 73, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 73, 74, 74, 73, 73, 74, 74, 74, 73, 74, 74, 74, 73, 74, 74, 74, 73, 74, 74, 74, 73, 73, 74, 74, 73, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74,
+    73, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74,
+    73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 73, 73, 73, 74, 74, 73, 73, 73, 74, 74, 73, 74, 74, 74, 73, 74, 74, 74, 73, 74, 74, 73, 73, 73, 74, 73, 73, 73, 73, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74,
+    73, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 73, 74, 74, 73, 73, 74, 74, 74, 73, 74, 74, 74, 73, 74, 74, 74, 73, 74, 74, 74, 73, 73, 74, 74, 73, 74, 74, 74,
+    73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74,
+    74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74
+  },
+  {
+    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,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    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,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 64, 64, 64, 64, 64, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 64, 64, 64, 64, 64,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 64, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    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,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 64, 64, 64, 64, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 64, 64, 64, 64, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    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,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65
+  },
+  {
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 58, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 58, 57, 57, 57, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 57, 57, 57, 58, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 58, 57, 57, 57, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 57, 57, 57, 58, 57, 57, 57, 57, 57,
+    57, 58, 58, 58, 57, 58, 58, 57, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 57, 58, 58, 57, 58, 58, 58,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 58, 58, 58, 57, 58, 58, 57, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 57, 58, 58, 57, 58, 58, 58,
+    57, 57, 57, 57, 57, 57, 58, 57, 57, 57, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 57, 57, 57, 58, 57, 57, 57, 57, 57,
+    57, 58, 58, 58, 57, 58, 58, 57, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 57, 58, 58, 57, 58, 58, 58,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 58, 58, 58, 57, 58, 58, 57, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 57, 58, 58, 57, 58, 58, 58,
+    57, 57, 57, 57, 57, 57, 58, 57, 57, 57, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 57, 57, 57, 58, 57, 57, 57, 57, 57,
+    57, 58, 58, 58, 57, 58, 58, 57, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 57, 58, 58, 57, 58, 58, 58,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 58, 58, 58, 57, 58, 58, 57, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 57, 58, 58, 57, 58, 58, 58,
+    57, 57, 57, 57, 57, 57, 58, 57, 57, 57, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 57, 57, 57, 58, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 58, 57, 57, 57, 57, 58, 57, 57, 57, 58, 58, 57, 58, 58, 58, 57, 58, 58, 58, 57, 58, 58, 57, 57, 57, 58, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
+    57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57
+  }
+};
+UInt g_aiDeQuantCoef1024[6][1024] =
+{
+  {
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
+  },
+  {
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 44, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 45, 44, 44, 44, 45, 45, 44, 44, 44, 45, 45, 44, 45, 45, 45, 44, 45, 45, 45, 44, 45, 45, 44, 44, 44, 45, 44, 44, 44, 44, 45,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 45, 44, 44, 44, 45, 45, 44, 44, 44, 45, 45, 44, 45, 45, 45, 44, 45, 45, 45, 44, 45, 45, 44, 44, 44, 45, 44, 44, 44, 44, 45,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 45, 45, 44, 44, 45, 45, 44, 44, 44, 45, 45, 44, 45, 45, 45, 44, 45, 45, 45, 44, 45, 45, 44, 44, 44, 45, 44, 44, 44, 44, 45,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 45, 45, 44, 44, 45, 45, 44, 44, 44, 45, 45, 44, 45, 45, 45, 44, 45, 45, 45, 44, 45, 45, 44, 44, 44, 45, 45, 44, 44, 45, 45,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 45, 44, 44, 44, 45, 45, 44, 44, 44, 45, 45, 44, 45, 45, 45, 44, 45, 45, 45, 44, 45, 45, 44, 44, 44, 45, 44, 44, 44, 44, 45,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 45, 45, 44, 44, 45, 45, 44, 44, 44, 45, 45, 44, 45, 45, 45, 44, 45, 45, 45, 44, 45, 45, 44, 44, 44, 45, 44, 44, 44, 44, 45,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 45, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
+    44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44
+  },
+  {
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 53, 52, 52, 53, 53,
+    52, 53, 52, 52, 52, 53, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 52, 52, 52, 52, 53,
+    52, 53, 52, 52, 52, 52, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 52, 52, 52, 52, 52,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 53, 53, 52, 52, 53, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 53, 52, 52, 53, 53,
+    52, 53, 53, 53, 52, 53, 53, 52, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 52, 53, 53, 52, 53, 53, 53,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 52, 53, 52, 53, 52, 53, 52, 53, 52, 53, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 52, 52, 52, 52, 52, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 52, 52, 52, 52, 52,
+    52, 53, 53, 53, 52, 53, 53, 52, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 52, 53, 53, 52, 53, 53, 53,
+    52, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 52, 53, 52, 53, 52, 53, 52, 53, 52, 53, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53,
+    52, 53, 53, 53, 52, 53, 53, 52, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 52, 53, 53, 52, 53, 53, 53,
+    52, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53,
+    52, 53, 53, 53, 52, 53, 53, 52, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 52, 53, 53, 52, 53, 53, 53,
+    52, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 52, 53, 52, 53, 52, 53, 52, 53, 52, 53, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 53, 53, 53, 53, 53, 53, 52, 53, 53, 52, 53, 53, 53,
+    52, 53, 53, 53, 52, 53, 53, 52, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 52, 53, 53, 52, 53, 53, 53,
+    52, 52, 52, 52, 52, 52, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 52, 52, 52, 52, 52,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 52, 53, 52, 53, 52, 53, 52, 53, 52, 53, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 53, 53, 53, 52, 53, 53, 52, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 52, 53, 53, 52, 53, 53, 53,
+    52, 53, 52, 52, 52, 53, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 52, 52, 52, 52, 53,
+    52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
+    52, 52, 52, 52, 52, 52, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 52, 52, 52, 52, 52,
+    52, 53, 52, 52, 52, 53, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 52, 52, 52, 52, 53,
+    52, 53, 53, 52, 52, 53, 53, 52, 52, 52, 53, 53, 52, 53, 53, 53, 52, 53, 53, 53, 52, 53, 53, 52, 52, 52, 53, 53, 52, 52, 53, 53
+  },
+  {
+    56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 57, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 56, 57, 57, 57,
+    56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
+    56, 56, 56, 56, 56, 56, 57, 56, 56, 56, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 56, 56, 56, 57, 56, 56, 56, 56, 56,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 56, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 56, 56, 56, 57, 57, 56, 56, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57,
+    56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 56, 56, 56, 57, 56, 56, 56, 56, 56,
+    56, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57,
+    56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
+    56, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57,
+    56, 56, 56, 56, 56, 56, 57, 56, 56, 56, 57, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 56, 56, 56, 57, 56, 56, 56, 56, 56,
+    56, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 56, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 56, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 56, 56, 56, 56, 56, 57, 56, 56, 56, 57, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 56, 56, 56, 57, 56, 56, 56, 56, 56,
+    56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
+    56, 57, 57, 57, 56, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 57, 57, 57, 57, 57, 57, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 56, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57,
+    56, 57, 57, 57, 56, 57, 57, 56, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 57, 57, 57, 56, 56, 57, 57, 56, 57, 57, 57
+  },
+  {
+    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,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    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,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 64, 64, 64, 64, 64, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 64, 64, 64, 64, 64,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 64, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    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,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 64, 64, 64, 64, 65, 64, 64, 64, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 64, 64, 64, 65, 64, 64, 64, 64, 65,
+    64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    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,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 64, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65,
+    64, 65, 65, 65, 64, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 65, 65, 65
+  },
+  {
+    72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 73, 72, 73, 72, 73, 72, 73, 72, 73, 72, 73, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 72, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 72, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 72, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 72, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 72, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 72, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
+    72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
+    72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 72, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 72, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 72, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 72, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 72, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 73, 73, 73, 72, 72, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 73, 72, 73, 72, 73, 72, 73, 72, 73, 72, 73, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73,
+    72, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 73, 73, 73
+  }
+};
+
+UInt g_aiQuantCoef256[6][256] =
+{
+  {
+    207, 209, 209, 208, 207, 209, 208, 209, 207, 209, 208, 209, 207, 208, 209, 209,
+    209, 212, 212, 211, 209, 211, 210, 212, 209, 212, 210, 211, 209, 211, 212, 212,
+    209, 212, 212, 211, 209, 211, 210, 212, 209, 212, 210, 211, 209, 211, 212, 212,
+    208, 211, 211, 210, 208, 210, 209, 211, 208, 211, 209, 210, 208, 210, 211, 211,
+    207, 209, 209, 208, 207, 208, 208, 209, 207, 209, 208, 208, 207, 208, 209, 209,
+    209, 211, 211, 210, 208, 210, 210, 211, 209, 211, 210, 210, 208, 210, 211, 211,
+    208, 210, 210, 209, 208, 210, 209, 210, 208, 211, 209, 210, 208, 209, 210, 210,
+    209, 212, 212, 211, 209, 211, 210, 212, 209, 212, 210, 211, 209, 211, 212, 212,
+    207, 209, 209, 208, 207, 209, 208, 209, 207, 210, 208, 209, 207, 208, 209, 209,
+    209, 212, 212, 211, 209, 211, 211, 212, 210, 212, 210, 211, 209, 211, 212, 212,
+    208, 210, 210, 209, 208, 210, 209, 210, 208, 210, 209, 210, 208, 209, 210, 210,
+    209, 211, 211, 210, 208, 210, 210, 211, 209, 211, 210, 210, 208, 210, 211, 211,
+    207, 209, 209, 208, 207, 208, 208, 209, 207, 209, 208, 208, 207, 208, 209, 209,
+    208, 211, 211, 210, 208, 210, 209, 211, 208, 211, 209, 210, 208, 210, 211, 211,
+    209, 212, 212, 211, 209, 211, 210, 212, 209, 212, 210, 211, 209, 211, 212, 212,
+    209, 212, 212, 211, 209, 211, 210, 212, 209, 212, 210, 211, 209, 211, 212, 212
+  },
+  {
+    188, 190, 190, 189, 188, 190, 189, 190, 188, 190, 189, 190, 188, 189, 190, 190,
+    190, 192, 192, 191, 190, 192, 191, 192, 190, 193, 191, 192, 190, 191, 192, 192,
+    190, 192, 192, 191, 190, 192, 191, 192, 190, 192, 191, 192, 190, 191, 192, 192,
+    189, 191, 191, 190, 189, 191, 190, 191, 189, 192, 190, 191, 189, 190, 191, 191,
+    188, 190, 190, 189, 188, 189, 189, 190, 188, 190, 189, 189, 188, 189, 190, 190,
+    190, 192, 192, 191, 189, 191, 191, 192, 190, 192, 191, 191, 189, 191, 192, 192,
+    189, 191, 191, 190, 189, 191, 190, 191, 189, 191, 190, 191, 189, 190, 191, 191,
+    190, 192, 192, 191, 190, 192, 191, 193, 190, 193, 191, 192, 190, 191, 192, 192,
+    188, 190, 190, 189, 188, 190, 189, 190, 188, 190, 189, 190, 188, 189, 190, 190,
+    190, 193, 192, 192, 190, 192, 191, 193, 190, 193, 191, 192, 190, 192, 192, 193,
+    189, 191, 191, 190, 189, 191, 190, 191, 189, 191, 190, 191, 189, 190, 191, 191,
+    190, 192, 192, 191, 189, 191, 191, 192, 190, 192, 191, 191, 189, 191, 192, 192,
+    188, 190, 190, 189, 188, 189, 189, 190, 188, 190, 189, 189, 188, 189, 190, 190,
+    189, 191, 191, 190, 189, 191, 190, 191, 189, 192, 190, 191, 189, 190, 191, 191,
+    190, 192, 192, 191, 190, 192, 191, 192, 190, 192, 191, 192, 190, 191, 192, 192,
+    190, 192, 192, 191, 190, 192, 191, 192, 190, 193, 191, 192, 190, 191, 192, 192
+  },
+  {
+    159, 161, 161, 160, 159, 160, 160, 161, 159, 161, 160, 160, 159, 160, 161, 161,
+    161, 163, 163, 162, 161, 162, 162, 163, 161, 163, 162, 162, 161, 162, 163, 163,
+    161, 163, 163, 162, 161, 162, 162, 163, 161, 163, 162, 162, 161, 162, 163, 163,
+    160, 162, 162, 161, 160, 161, 161, 162, 160, 162, 161, 161, 160, 161, 162, 162,
+    159, 161, 161, 160, 159, 160, 160, 161, 159, 161, 160, 160, 159, 160, 161, 161,
+    160, 162, 162, 161, 160, 162, 161, 162, 160, 162, 161, 162, 160, 161, 162, 162,
+    160, 162, 162, 161, 160, 161, 161, 162, 160, 162, 161, 161, 160, 161, 162, 162,
+    161, 163, 163, 162, 161, 162, 162, 163, 161, 163, 162, 162, 161, 162, 163, 163,
+    159, 161, 161, 160, 159, 160, 160, 161, 159, 161, 160, 160, 159, 160, 161, 161,
+    161, 163, 163, 162, 161, 162, 162, 163, 161, 163, 162, 162, 161, 162, 163, 163,
+    160, 162, 162, 161, 160, 161, 161, 162, 160, 162, 161, 161, 160, 161, 162, 162,
+    160, 162, 162, 161, 160, 162, 161, 162, 160, 162, 161, 162, 160, 161, 162, 162,
+    159, 161, 161, 160, 159, 160, 160, 161, 159, 161, 160, 160, 159, 160, 161, 161,
+    160, 162, 162, 161, 160, 161, 161, 162, 160, 162, 161, 161, 160, 161, 162, 162,
+    161, 163, 163, 162, 161, 162, 162, 163, 161, 163, 162, 162, 161, 162, 163, 163,
+    161, 163, 163, 162, 161, 162, 162, 163, 161, 163, 162, 162, 161, 162, 163, 163
+  },
+  {
+    148, 150, 150, 149, 148, 149, 149, 150, 148, 150, 149, 149, 148, 149, 150, 150,
+    150, 151, 151, 150, 149, 151, 150, 151, 150, 151, 150, 151, 149, 150, 151, 151,
+    150, 151, 151, 150, 149, 151, 150, 151, 150, 151, 150, 151, 149, 150, 151, 151,
+    149, 150, 150, 150, 149, 150, 150, 150, 149, 150, 150, 150, 149, 150, 150, 150,
+    148, 149, 149, 149, 148, 149, 149, 149, 148, 149, 149, 149, 148, 149, 149, 149,
+    149, 151, 151, 150, 149, 150, 150, 151, 149, 151, 150, 150, 149, 150, 151, 151,
+    149, 150, 150, 150, 149, 150, 149, 150, 149, 150, 149, 150, 149, 150, 150, 150,
+    150, 151, 151, 150, 149, 151, 150, 151, 150, 151, 150, 151, 149, 150, 151, 151,
+    148, 150, 150, 149, 148, 149, 149, 150, 148, 150, 149, 149, 148, 149, 150, 150,
+    150, 151, 151, 150, 149, 151, 150, 151, 150, 151, 150, 151, 149, 150, 151, 151,
+    149, 150, 150, 150, 149, 150, 149, 150, 149, 150, 149, 150, 149, 150, 150, 150,
+    149, 151, 151, 150, 149, 150, 150, 151, 149, 151, 150, 150, 149, 150, 151, 151,
+    148, 149, 149, 149, 148, 149, 149, 149, 148, 149, 149, 149, 148, 149, 149, 149,
+    149, 150, 150, 150, 149, 150, 150, 150, 149, 150, 150, 150, 149, 150, 150, 150,
+    150, 151, 151, 150, 149, 151, 150, 151, 150, 151, 150, 151, 149, 150, 151, 151,
+    150, 151, 151, 150, 149, 151, 150, 151, 150, 151, 150, 151, 149, 150, 151, 151
+  },
+  {
+    129, 131, 131, 130, 129, 130, 130, 131, 129, 131, 130, 130, 129, 130, 131, 131,
+    131, 132, 132, 132, 131, 132, 131, 132, 131, 132, 131, 132, 131, 132, 132, 132,
+    131, 132, 132, 132, 131, 132, 131, 132, 131, 132, 131, 132, 131, 132, 132, 132,
+    130, 132, 132, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 132, 132,
+    129, 131, 131, 130, 129, 130, 130, 131, 129, 131, 130, 130, 129, 130, 131, 131,
+    130, 132, 132, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 132, 132,
+    130, 131, 131, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 131, 131,
+    131, 132, 132, 132, 131, 132, 132, 132, 131, 132, 132, 132, 131, 132, 132, 132,
+    129, 131, 131, 130, 129, 130, 130, 131, 129, 131, 130, 130, 129, 130, 131, 131,
+    131, 132, 132, 132, 131, 132, 132, 132, 131, 132, 132, 132, 131, 132, 132, 132,
+    130, 131, 131, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 131, 131,
+    130, 132, 132, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 132, 132,
+    129, 131, 131, 130, 129, 130, 130, 131, 129, 131, 130, 130, 129, 130, 131, 131,
+    130, 132, 132, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 132, 132,
+    131, 132, 132, 132, 131, 132, 131, 132, 131, 132, 131, 132, 131, 132, 132, 132,
+    131, 132, 132, 132, 131, 132, 131, 132, 131, 132, 131, 132, 131, 132, 132, 132
+  },
+  {
+    115, 116, 116, 116, 115, 116, 116, 116, 115, 116, 116, 116, 115, 116, 116, 116,
+    116, 118, 118, 117, 116, 117, 117, 118, 116, 118, 117, 117, 116, 117, 118, 118,
+    116, 118, 118, 117, 116, 117, 117, 118, 116, 118, 117, 117, 116, 117, 118, 118,
+    116, 117, 117, 116, 116, 117, 116, 117, 116, 117, 116, 117, 116, 116, 117, 117,
+    115, 116, 116, 116, 115, 116, 116, 116, 115, 116, 116, 116, 115, 116, 116, 116,
+    116, 117, 117, 117, 116, 117, 116, 117, 116, 117, 116, 117, 116, 117, 117, 117,
+    116, 117, 117, 116, 116, 116, 116, 117, 116, 117, 116, 116, 116, 116, 117, 117,
+    116, 118, 118, 117, 116, 117, 117, 118, 116, 118, 117, 117, 116, 117, 118, 118,
+    115, 116, 116, 116, 115, 116, 116, 116, 115, 116, 116, 116, 115, 116, 116, 116,
+    116, 118, 118, 117, 116, 117, 117, 118, 116, 118, 117, 117, 116, 117, 118, 118,
+    116, 117, 117, 116, 116, 116, 116, 117, 116, 117, 116, 116, 116, 116, 117, 117,
+    116, 117, 117, 117, 116, 117, 116, 117, 116, 117, 116, 117, 116, 117, 117, 117,
+    115, 116, 116, 116, 115, 116, 116, 116, 115, 116, 116, 116, 115, 116, 116, 116,
+    116, 117, 117, 116, 116, 117, 116, 117, 116, 117, 116, 117, 116, 116, 117, 117,
+    116, 118, 118, 117, 116, 117, 117, 118, 116, 118, 117, 117, 116, 117, 118, 118,
+    116, 118, 118, 117, 116, 117, 117, 118, 116, 118, 117, 117, 116, 117, 118, 118
+  }
+  
+};
+UInt g_aiDeQuantCoef256[6][256] =
+{
+  {
+    81, 82, 82, 81, 81, 81, 81, 82, 81, 82, 81, 81, 81, 81, 82, 82,
+    82, 83, 83, 82, 82, 82, 82, 83, 82, 83, 82, 82, 82, 82, 83, 83,
+    82, 83, 83, 82, 82, 82, 82, 83, 82, 83, 82, 82, 82, 82, 83, 83,
+    81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82,
+    81, 82, 82, 81, 81, 81, 81, 82, 81, 82, 81, 81, 81, 81, 82, 82,
+    81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82,
+    81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82,
+    82, 83, 83, 82, 82, 82, 82, 83, 82, 83, 82, 82, 82, 82, 83, 83,
+    81, 82, 82, 81, 81, 81, 81, 82, 81, 82, 81, 81, 81, 81, 82, 82,
+    82, 83, 83, 82, 82, 82, 82, 83, 82, 83, 82, 82, 82, 82, 83, 83,
+    81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82,
+    81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82,
+    81, 82, 82, 81, 81, 81, 81, 82, 81, 82, 81, 81, 81, 81, 82, 82,
+    81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82, 81, 82, 82, 82,
+    82, 83, 83, 82, 82, 82, 82, 83, 82, 83, 82, 82, 82, 82, 83, 83,
+    82, 83, 83, 82, 82, 82, 82, 83, 82, 83, 82, 82, 82, 82, 83, 83
+  },
+  {
+    89, 90, 90, 90, 89, 90, 89, 90, 89, 90, 89, 90, 89, 90, 90, 90,
+    90, 91, 91, 90, 90, 91, 90, 91, 90, 91, 90, 91, 90, 90, 91, 91,
+    90, 91, 91, 90, 90, 91, 90, 91, 90, 91, 90, 91, 90, 90, 91, 91,
+    90, 90, 90, 90, 89, 90, 90, 91, 90, 91, 90, 90, 89, 90, 90, 90,
+    89, 90, 90, 89, 89, 90, 89, 90, 89, 90, 89, 90, 89, 89, 90, 90,
+    90, 91, 91, 90, 90, 90, 90, 91, 90, 91, 90, 90, 90, 90, 91, 91,
+    89, 90, 90, 90, 89, 90, 90, 90, 89, 90, 90, 90, 89, 90, 90, 90,
+    90, 91, 91, 91, 90, 91, 90, 91, 90, 91, 90, 91, 90, 91, 91, 91,
+    89, 90, 90, 90, 89, 90, 89, 90, 89, 90, 89, 90, 89, 90, 90, 90,
+    90, 91, 91, 91, 90, 91, 90, 91, 90, 91, 90, 91, 90, 91, 91, 91,
+    89, 90, 90, 90, 89, 90, 90, 90, 89, 90, 90, 90, 89, 90, 90, 90,
+    90, 91, 91, 90, 90, 90, 90, 91, 90, 91, 90, 90, 90, 90, 91, 91,
+    89, 90, 90, 89, 89, 90, 89, 90, 89, 90, 89, 90, 89, 89, 90, 90,
+    90, 90, 90, 90, 89, 90, 90, 91, 90, 91, 90, 90, 89, 90, 90, 90,
+    90, 91, 91, 90, 90, 91, 90, 91, 90, 91, 90, 91, 90, 90, 91, 91,
+    90, 91, 91, 90, 90, 91, 90, 91, 90, 91, 90, 91, 90, 90, 91, 91
+  },
+  {
+    105, 106, 106, 106, 105, 106, 106, 106, 105, 106, 106, 106, 105, 106, 106, 106,
+    106, 107, 107, 107, 106, 107, 107, 108, 106, 108, 107, 107, 106, 107, 107, 107,
+    106, 107, 107, 107, 106, 107, 107, 107, 106, 108, 107, 107, 106, 107, 107, 107,
+    106, 107, 107, 106, 106, 107, 106, 107, 106, 107, 106, 107, 106, 106, 107, 107,
+    105, 106, 106, 106, 105, 106, 106, 106, 105, 106, 106, 106, 105, 106, 106, 106,
+    106, 107, 107, 107, 106, 107, 106, 107, 106, 107, 106, 107, 106, 107, 107, 107,
+    106, 107, 107, 106, 106, 106, 106, 107, 106, 107, 106, 106, 106, 106, 107, 107,
+    106, 108, 107, 107, 106, 107, 107, 108, 106, 108, 107, 107, 106, 107, 107, 108,
+    105, 106, 106, 106, 105, 106, 106, 106, 105, 106, 106, 106, 105, 106, 106, 106,
+    106, 108, 108, 107, 106, 107, 107, 108, 106, 108, 107, 107, 106, 107, 108, 108,
+    106, 107, 107, 106, 106, 106, 106, 107, 106, 107, 106, 106, 106, 106, 107, 107,
+    106, 107, 107, 107, 106, 107, 106, 107, 106, 107, 106, 107, 106, 107, 107, 107,
+    105, 106, 106, 106, 105, 106, 106, 106, 105, 106, 106, 106, 105, 106, 106, 106,
+    106, 107, 107, 106, 106, 107, 106, 107, 106, 107, 106, 107, 106, 106, 107, 107,
+    106, 107, 107, 107, 106, 107, 107, 107, 106, 108, 107, 107, 106, 107, 107, 107,
+    106, 107, 107, 107, 106, 107, 107, 108, 106, 108, 107, 107, 106, 107, 107, 107
+  },
+  {
+    113, 115, 114, 114, 113, 114, 114, 115, 113, 115, 114, 114, 113, 114, 114, 114,
+    115, 116, 116, 115, 114, 115, 115, 116, 115, 116, 115, 115, 114, 115, 116, 116,
+    114, 116, 116, 115, 114, 115, 115, 116, 114, 116, 115, 115, 114, 115, 116, 116,
+    114, 115, 115, 115, 114, 115, 114, 115, 114, 115, 114, 115, 114, 115, 115, 115,
+    113, 114, 114, 114, 113, 114, 114, 114, 113, 114, 114, 114, 113, 114, 114, 114,
+    114, 115, 115, 115, 114, 115, 115, 115, 114, 115, 115, 115, 114, 115, 115, 115,
+    114, 115, 115, 114, 114, 115, 114, 115, 114, 115, 114, 115, 114, 114, 115, 115,
+    115, 116, 116, 115, 114, 115, 115, 116, 115, 116, 115, 115, 114, 115, 116, 116,
+    113, 115, 114, 114, 113, 114, 114, 115, 113, 115, 114, 114, 113, 114, 114, 115,
+    115, 116, 116, 115, 114, 115, 115, 116, 115, 116, 115, 115, 114, 115, 116, 116,
+    114, 115, 115, 114, 114, 115, 114, 115, 114, 115, 114, 115, 114, 114, 115, 115,
+    114, 115, 115, 115, 114, 115, 115, 115, 114, 115, 115, 115, 114, 115, 115, 115,
+    113, 114, 114, 114, 113, 114, 114, 114, 113, 114, 114, 114, 113, 114, 114, 114,
+    114, 115, 115, 115, 114, 115, 114, 115, 114, 115, 114, 115, 114, 115, 115, 115,
+    114, 116, 116, 115, 114, 115, 115, 116, 114, 116, 115, 115, 114, 115, 116, 116,
+    114, 116, 116, 115, 114, 115, 115, 116, 115, 116, 115, 115, 114, 115, 116, 116
+  },
+  {
+    129, 131, 131, 130, 129, 130, 130, 131, 129, 131, 130, 130, 129, 130, 131, 131,
+    131, 132, 132, 132, 131, 132, 131, 132, 131, 132, 131, 132, 131, 132, 132, 132,
+    131, 132, 132, 132, 131, 132, 131, 132, 131, 132, 131, 132, 131, 132, 132, 132,
+    130, 132, 132, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 132, 132,
+    129, 131, 131, 130, 129, 130, 130, 131, 129, 131, 130, 130, 129, 130, 131, 131,
+    130, 132, 132, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 132, 132,
+    130, 131, 131, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 131, 131,
+    131, 132, 132, 132, 131, 132, 132, 132, 131, 132, 132, 132, 131, 132, 132, 132,
+    129, 131, 131, 130, 129, 130, 130, 131, 129, 131, 130, 130, 129, 130, 131, 131,
+    131, 132, 132, 132, 131, 132, 132, 132, 131, 132, 132, 132, 131, 132, 132, 132,
+    130, 131, 131, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 131, 131,
+    130, 132, 132, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 132, 132,
+    129, 131, 131, 130, 129, 130, 130, 131, 129, 131, 130, 130, 129, 130, 131, 131,
+    130, 132, 132, 131, 130, 131, 131, 132, 130, 132, 131, 131, 130, 131, 132, 132,
+    131, 132, 132, 132, 131, 132, 131, 132, 131, 132, 131, 132, 131, 132, 132, 132,
+    131, 132, 132, 132, 131, 132, 131, 132, 131, 132, 131, 132, 131, 132, 132, 132
+  },
+  {
+    146, 147, 147, 146, 146, 147, 146, 147, 146, 147, 146, 147, 145, 146, 147, 147,
+    147, 149, 149, 148, 147, 148, 148, 149, 147, 149, 148, 148, 147, 148, 149, 149,
+    147, 149, 149, 148, 147, 148, 148, 149, 147, 149, 148, 148, 147, 148, 149, 149,
+    146, 148, 148, 147, 146, 147, 147, 148, 146, 148, 147, 147, 146, 147, 148, 148,
+    146, 147, 147, 146, 145, 147, 146, 147, 146, 147, 146, 147, 145, 146, 147, 147,
+    147, 148, 148, 147, 147, 148, 147, 148, 147, 148, 147, 148, 147, 147, 148, 148,
+    146, 148, 148, 147, 146, 147, 147, 148, 146, 148, 147, 147, 146, 147, 148, 148,
+    147, 149, 149, 148, 147, 148, 148, 149, 147, 149, 148, 148, 147, 148, 149, 149,
+    146, 147, 147, 146, 146, 147, 146, 147, 146, 147, 146, 147, 146, 146, 147, 147,
+    147, 149, 149, 148, 147, 148, 148, 149, 147, 149, 148, 148, 147, 148, 149, 149,
+    146, 148, 148, 147, 146, 147, 147, 148, 146, 148, 147, 147, 146, 147, 148, 148,
+    147, 148, 148, 147, 147, 148, 147, 148, 147, 148, 147, 148, 147, 147, 148, 148,
+    145, 147, 147, 146, 145, 147, 146, 147, 146, 147, 146, 147, 145, 146, 147, 147,
+    146, 148, 148, 147, 146, 147, 147, 148, 146, 148, 147, 147, 146, 147, 148, 148,
+    147, 149, 149, 148, 147, 148, 148, 149, 147, 149, 148, 148, 147, 148, 149, 149,
+    147, 149, 149, 148, 147, 148, 148, 149, 147, 149, 148, 148, 147, 148, 149, 149
+  }
+};
+
+
+Int g_aiDequantCoef64[6][64] =
+{
+  {
+    20,  19, 25, 19, 20, 19, 25, 19,
+    19,  18, 24, 18, 19, 18, 24, 18,
+    25,  24, 32, 24, 25, 24, 32, 24,
+    19,  18, 24, 18, 19, 18, 24, 18,
+    20,  19, 25, 19, 20, 19, 25, 19,
+    19,  18, 24, 18, 19, 18, 24, 18,
+    25,  24, 32, 24, 25, 24, 32, 24,
+    19,  18, 24, 18, 19, 18, 24, 18
+  },
+  {
+    22,  21, 28, 21, 22, 21, 28, 21,
+    21,  19, 26, 19, 21, 19, 26, 19,
+    28,  26, 35, 26, 28, 26, 35, 26,
+    21,  19, 26, 19, 21, 19, 26, 19,
+    22,  21, 28, 21, 22, 21, 28, 21,
+    21,  19, 26, 19, 21, 19, 26, 19,
+    28,  26, 35, 26, 28, 26, 35, 26,
+    21,  19, 26, 19, 21, 19, 26, 19
+  },
+  {
+    26,  24, 33, 24, 26, 24, 33, 24,
+    24,  23, 31, 23, 24, 23, 31, 23,
+    33,  31, 42, 31, 33, 31, 42, 31,
+    24,  23, 31, 23, 24, 23, 31, 23,
+    26,  24, 33, 24, 26, 24, 33, 24,
+    24,  23, 31, 23, 24, 23, 31, 23,
+    33,  31, 42, 31, 33, 31, 42, 31,
+    24,  23, 31, 23, 24, 23, 31, 23
+  },
+  {
+    28,  26, 35, 26, 28, 26, 35, 26,
+    26,  25, 33, 25, 26, 25, 33, 25,
+    35,  33, 45, 33, 35, 33, 45, 33,
+    26,  25, 33, 25, 26, 25, 33, 25,
+    28,  26, 35, 26, 28, 26, 35, 26,
+    26,  25, 33, 25, 26, 25, 33, 25,
+    35,  33, 45, 33, 35, 33, 45, 33,
+    26,  25, 33, 25, 26, 25, 33, 25
+  },
+  {
+    32,  30, 40, 30, 32, 30, 40, 30,
+    30,  28, 38, 28, 30, 28, 38, 28,
+    40,  38, 51, 38, 40, 38, 51, 38,
+    30,  28, 38, 28, 30, 28, 38, 28,
+    32,  30, 40, 30, 32, 30, 40, 30,
+    30,  28, 38, 28, 30, 28, 38, 28,
+    40,  38, 51, 38, 40, 38, 51, 38,
+    30,  28, 38, 28, 30, 28, 38, 28
+  },
+  {
+    36,  34, 46, 34, 36, 34, 46, 34,
+    34,  32, 43, 32, 34, 32, 43, 32,
+    46,  43, 58, 43, 46, 43, 58, 43,
+    34,  32, 43, 32, 34, 32, 43, 32,
+    36,  34, 46, 34, 36, 34, 46, 34,
+    34,  32, 43, 32, 34, 32, 43, 32,
+    46,  43, 58, 43, 46, 43, 58, 43,
+    34,  32, 43, 32, 34, 32, 43, 32
+  }
+  
+};
+
+UInt g_aiQuantCoef64[6][64] =
+{
+  {
+    0x3333, 0x2fbe, 0x4189, 0x2fbe, 0x3333, 0x2fbe, 0x4189, 0x2fbe,
+    0x2fbe, 0x2ca4, 0x3c79, 0x2ca4, 0x2fbe, 0x2ca4, 0x3c79, 0x2ca4,
+    0x4189, 0x3c79, 0x51ec, 0x3c79, 0x4189, 0x3c79, 0x51ec, 0x3c79,
+    0x2fbe, 0x2ca4, 0x3c79, 0x2ca4, 0x2fbe, 0x2ca4, 0x3c79, 0x2ca4,
+    0x3333, 0x2fbe, 0x4189, 0x2fbe, 0x3333, 0x2fbe, 0x4189, 0x2fbe,
+    0x2fbe, 0x2ca4, 0x3c79, 0x2ca4, 0x2fbe, 0x2ca4, 0x3c79, 0x2ca4,
+    0x4189, 0x3c79, 0x51ec, 0x3c79, 0x4189, 0x3c79, 0x51ec, 0x3c79,
+    0x2fbe, 0x2ca4, 0x3c79, 0x2ca4, 0x2fbe, 0x2ca4, 0x3c79, 0x2ca4,
+  },
+  {
+    0x2e8c, 0x2b32, 0x3a84, 0x2b32, 0x2e8c, 0x2b32, 0x3a84, 0x2b32,
+    0x2b32, 0x2a4a, 0x37d2, 0x2a4a, 0x2b32, 0x2a4a, 0x37d2, 0x2a4a,
+    0x3a84, 0x37d2, 0x4ae6, 0x37d2, 0x3a84, 0x37d2, 0x4ae6, 0x37d2,
+    0x2b32, 0x2a4a, 0x37d2, 0x2a4a, 0x2b32, 0x2a4a, 0x37d2, 0x2a4a,
+    0x2e8c, 0x2b32, 0x3a84, 0x2b32, 0x2e8c, 0x2b32, 0x3a84, 0x2b32,
+    0x2b32, 0x2a4a, 0x37d2, 0x2a4a, 0x2b32, 0x2a4a, 0x37d2, 0x2a4a,
+    0x3a84, 0x37d2, 0x4ae6, 0x37d2, 0x3a84, 0x37d2, 0x4ae6, 0x37d2,
+    0x2b32, 0x2a4a, 0x37d2, 0x2a4a, 0x2b32, 0x2a4a, 0x37d2, 0x2a4a,
+  },
+  {
+    0x2762, 0x25cb, 0x31a6, 0x25cb, 0x2762, 0x25cb, 0x31a6, 0x25cb,
+    0x25cb, 0x22ef, 0x2ed1, 0x22ef, 0x25cb, 0x22ef, 0x2ed1, 0x22ef,
+    0x31a6, 0x2ed1, 0x3e6a, 0x2ed1, 0x31a6, 0x2ed1, 0x3e6a, 0x2ed1,
+    0x25cb, 0x22ef, 0x2ed1, 0x22ef, 0x25cb, 0x22ef, 0x2ed1, 0x22ef,
+    0x2762, 0x25cb, 0x31a6, 0x25cb, 0x2762, 0x25cb, 0x31a6, 0x25cb,
+    0x25cb, 0x22ef, 0x2ed1, 0x22ef, 0x25cb, 0x22ef, 0x2ed1, 0x22ef,
+    0x31a6, 0x2ed1, 0x3e6a, 0x2ed1, 0x31a6, 0x2ed1, 0x3e6a, 0x2ed1,
+    0x25cb, 0x22ef, 0x2ed1, 0x22ef, 0x25cb, 0x22ef, 0x2ed1, 0x22ef,
+  },
+  {
+    0x2492, 0x22e3, 0x2ed0, 0x22e3, 0x2492, 0x22e3, 0x2ed0, 0x22e3,
+    0x22e3, 0x2024, 0x2bfb, 0x2024, 0x22e3, 0x2024, 0x2bfb, 0x2024,
+    0x2ed0, 0x2bfb, 0x3a41, 0x2bfb, 0x2ed0, 0x2bfb, 0x3a41, 0x2bfb,
+    0x22e3, 0x2024, 0x2bfb, 0x2024, 0x22e3, 0x2024, 0x2bfb, 0x2024,
+    0x2492, 0x22e3, 0x2ed0, 0x22e3, 0x2492, 0x22e3, 0x2ed0, 0x22e3,
+    0x22e3, 0x2024, 0x2bfb, 0x2024, 0x22e3, 0x2024, 0x2bfb, 0x2024,
+    0x2ed0, 0x2bfb, 0x3a41, 0x2bfb, 0x2ed0, 0x2bfb, 0x3a41, 0x2bfb,
+    0x22e3, 0x2024, 0x2bfb, 0x2024, 0x22e3, 0x2024, 0x2bfb, 0x2024,
+  },
+  {
+    0x2000, 0x1e3c, 0x28f6, 0x1e3c, 0x2000, 0x1e3c, 0x28f6, 0x1e3c,
+    0x1e3c, 0x1cb2, 0x2631, 0x1cb2, 0x1e3c, 0x1cb2, 0x2631, 0x1cb2,
+    0x28f6, 0x2631, 0x3367, 0x2631, 0x28f6, 0x2631, 0x3367, 0x2631,
+    0x1e3c, 0x1cb2, 0x2631, 0x1cb2, 0x1e3c, 0x1cb2, 0x2631, 0x1cb2,
+    0x2000, 0x1e3c, 0x28f6, 0x1e3c, 0x2000, 0x1e3c, 0x28f6, 0x1e3c,
+    0x1e3c, 0x1cb2, 0x2631, 0x1cb2, 0x1e3c, 0x1cb2, 0x2631, 0x1cb2,
+    0x28f6, 0x2631, 0x3367, 0x2631, 0x28f6, 0x2631, 0x3367, 0x2631,
+    0x1e3c, 0x1cb2, 0x2631, 0x1cb2, 0x1e3c, 0x1cb2, 0x2631, 0x1cb2,
+  },
+  {
+    0x1c72, 0x1aae, 0x239e, 0x1aae, 0x1c72, 0x1aae, 0x239e, 0x1aae,
+    0x1aae, 0x191c, 0x21c0, 0x191c, 0x1aae, 0x191c, 0x21c0, 0x191c,
+    0x239e, 0x21c0, 0x2d32, 0x21c0, 0x239e, 0x21c0, 0x2d32, 0x21c0,
+    0x1aae, 0x191c, 0x21c0, 0x191c, 0x1aae, 0x191c, 0x21c0, 0x191c,
+    0x1c72, 0x1aae, 0x239e, 0x1aae, 0x1c72, 0x1aae, 0x239e, 0x1aae,
+    0x1aae, 0x191c, 0x21c0, 0x191c, 0x1aae, 0x191c, 0x21c0, 0x191c,
+    0x239e, 0x21c0, 0x2d32, 0x21c0, 0x239e, 0x21c0, 0x2d32, 0x21c0,
+    0x1aae, 0x191c, 0x21c0, 0x191c, 0x1aae, 0x191c, 0x21c0, 0x191c,
+  }
+};
+#endif //E243_CORE_TRANSFORMS
+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
+};
+// ====================================================================================================================
+// TENTM VLC table
+// ====================================================================================================================
+
+#if RUNLEVEL_TABLE_CUT || CAVLC_RQT_CBP
+#define M1 MAX_UINT
+#else
+#define M1 (UInt)-1
+#endif
+
+// Below table need to be optimized
+const UInt g_auiCbpVlcNum[2][8] =
+{
+  {0, 0, 0, 0, 0, 0, 0, 0},
+  {0, 0, 0, 0, 0, 0, 0, 0}
+};
+
+#if CAVLC_RQT_CBP
+const UInt g_auiCBP_YUV_TableE[4][8] = 
+{
+  {2,5,6,7,0,3,4,1},
+  {0,4,6,7,1,2,3,5},
+  {2,5,6,7,0,3,4,1},
+  {0,4,6,7,1,2,3,5}
+};
+const UInt g_auiCBP_YUV_TableD[4][8] = 
+{
+  {4,7,0,5,6,1,2,3},
+  {0,4,5,6,1,7,2,3},
+  {4,7,0,5,6,1,2,3},
+  {0,4,5,6,1,7,2,3}
+};
+const UInt g_auiCBP_YS_TableE[2][4] = 
+{
+  {3,  2, 0, 1},
+  {2, M1, 0, 1}
+};
+
+const UInt g_auiCBP_YS_TableD[2][4] = 
+{
+  {  2,  3,  1,  0},
+  {  2,  3,  0, M1}
+};
+
+const UInt g_auiCBP_YC_TableE[2][4] =
+{ 
+  {  2,  1,  3,  0}, 
+  {  0,  2,  1,  3}
+};
+
+const UInt g_auiCBP_YC_TableD[2][4] =
+{ 
+  {3,1,0,2}, 
+  {0,2,1,3}
+};
+
+const UInt g_auiCBP_YCS_Table[2][8] = 
+{
+  {  0,  3,  9, 11,  8, 20, 42, 43},
+  {  1,  1,  1,  1,  1,  1,  0, M1}
+};
+
+const UInt g_auiCBP_YCS_TableLen[2][8] = 
+{
+  {  1,  2,  4,  4,  4,  5,  6,  6},
+  {  1,  2,  3,  4,  5,  6,  6,  0}
+};
+
+const UInt g_auiCBP_YCS_TableE[2][8] = 
+{
+  {4,  5,  6,  7,  1,  2,  0,  3},
+  {0,  7,  5,  6,  2,  1,  4,  3}
+};
+
+const UInt g_auiCBP_YCS_TableD[2][8] = 
+{
+  {6,  4,  5,  7,  0,  1,  2,  3},
+  {0,  5,  4,  7,  6,  2,  3, 1}
+};
+
+const UInt g_auiCBP_4Y_TableE[2][15] = 
+{
+  {14, 13, 10, 12,  9,  8,  4, 11,  7,  6,  3,  5,  2,  1,  0},
+  { 0,  1,  4,  2,  5,  6, 10,  3,  7,  8, 11,  9, 12, 13, 14}
+};
+
+const UInt g_auiCBP_4Y_TableD[2][15] = 
+{
+  {14, 13, 12, 10, 6, 11, 9, 8, 5, 4, 2, 7, 3, 1, 0},
+  {0, 1, 3, 7, 2, 4, 5, 8, 9, 11, 6, 10 ,12, 13, 14} 
+};
+
+const UInt g_auiCBP_4Y_VlcNum[15] = 
+{
+  1,  2,  2,  2, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11
+};
+#else
+const UInt g_auiCBPTableE[2][8] = 
+{
+  {2,0,6,4,5,3,7,1},
+  {0,1,6,3,4,2,7,5}
+};
+
+const UInt g_auiCBPTableD[2][8] = 
+{
+  {1,7,0,5,3,4,2,6},
+  {0,1,5,3,4,7,2,6}
+};
+
+const UInt g_auiBlkCBPTableE[2][15] = 
+{
+  {14, 13, 10, 12, 9, 8, 4, 11, 7, 6, 3, 5, 2, 1, 0},
+  {0, 1, 4, 2, 5, 6, 10, 3, 7, 8, 11, 9, 12, 13, 14}
+};
+
+const UInt g_auiBlkCBPTableD[2][15] = 
+{
+  {14, 13, 12, 10, 6, 11, 9, 8, 5, 4, 2, 7, 3, 1, 0},
+  {0, 1, 3, 7, 2, 4, 5, 8, 9, 11, 6, 10 ,12, 13, 14} 
+};
+
+const UInt g_auiBlkCbpVlcNum[15] = 
+{
+  1,  2,  2,  2, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11
+};
+#endif
+
+#if UNIFY_INTER_TABLE
+const UInt g_auiComMI1TableE[9] = {0,1,2,3,4,5,6,7,8};
+const UInt g_auiComMI1TableD[9] = {0,1,2,3,4,5,6,7,8};
+#else
+const UInt g_auiMI1TableE[8] = {0,2,1,4,3,6,5,7};
+const UInt g_auiMI1TableD[8] = {0,2,1,4,3,6,5,7};
+const UInt g_auiMI2TableE[15] = {0,1,3,2,6,5,4,7,9,8,13,12,11,14,10};
+const UInt g_auiMI2TableD[15] = {0,1,3,2,6,5,4,7,9,8,14,12,11,10,13};
+
+const UInt g_auiMI1TableENoL1[8] = {0,1,6,7,2,4,3,5};
+const UInt g_auiMI1TableDNoL1[8] = {0,1,4,6,5,7,2,3};
+const UInt g_auiMI2TableENoL1[15] = {0,1,2,12,14,13,3,4,6,5,10,9,8,11,7};
+const UInt g_auiMI2TableDNoL1[15] = {0,1,2,6,7,9,8,14,12,11,10,13,3,5,4};
+
+#if MS_LCEC_ONE_FRAME
+// as there are two lists used for bi-directional prediction, and one list for uni-directional prediction
+// for uni-directional prediction, when pcSlice->getNoBackPredFlag() is true, list 0 is used for uni-directional prediction
+// when pcSlice->getNoBackPredFlag() is false, combined list is used for uni-directional prediction
+// the meaning of the elements are as follows:
+/*
+ 0: uni-directional prediction, frame 0
+ 1: uni-directional prediction, frame 1
+ 2: uni-directional prediction, frame 2
+ 3: uni-directional prediction, frame 3
+ 4: bi-directional prediction, frame (0, 0)
+ 5: bi-directional prediction, frame (0, 1)
+ 6: bi-directional prediction, frame (1, 0)
+ 7: bi-directional prediction, frame (1, 1)
+ 8: exception, for uni-directional prediction, if combined list, reference frame index >= 4 (count from 0) is exception
+ if GPB (only list0 is used), reference frame index >= 2 (count from 0) is exception
+ for bi-directional prediction, reference frame index >= 2 (count from 0 ) is exception
+ */
+const UInt g_auiMI1TableEOnly1Ref[8] = {0,3,1,4,2,6,5,7};
+const UInt g_auiMI1TableDOnly1Ref[8] = {0,2,4,1,3,6,5,7};
+const UInt g_auiMI1TableEOnly1RefNoL1[8] = {0,2,3,4,1,6,5,7};
+const UInt g_auiMI1TableDOnly1RefNoL1[8] = {0,4,1,2,3,6,5,7};
+#endif
+#endif
+
+#if QC_LCEC_INTER_MODE
+const UInt g_auiInterModeTableE[4][7] = {{0,1,2,3,4,5,6},{0,1,2,3,4,5,6},{0,1,2,3,4,5,6},{6,0,1,2,3,4,5}};
+const UInt g_auiInterModeTableD[4][7] = {{0,1,2,3,4,5,6},{0,1,2,3,4,5,6},{0,1,2,3,4,5,6},{1,2,3,4,5,6,0}};
+#endif
+
+
+
+// Below table need to be optimized
+const UInt g_auiMITableVlcNum[15] = 
+{
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+
+const UInt g_auiLPTableE4[3][32] =
+{
+  {0,1,2,3,5,4,7,6,9,11,14,8,16,15,10,13,12,17,18,19,25,23,20,22,28,26,29,24,30,31,27,21},  //4x4I
+  {0,1,2,7,5,3,6,4,11,8,12,10,9,14,13,15,16,17,21,27,26,18,19,23,29,20,25,28,22,30,24,31},  //4x4P
+  {0,1,2,7,5,3,6,4,11,8,12,10,9,14,13,15,16,17,21,27,26,18,19,23,29,20,25,28,22,30,24,31}   //4x4B
+};
+
+const UInt g_auiLPTableD4[3][32] =
+{
+  {0,1,2,3,5,4,7,6,11,8,14,9,16,15,10,13,12,17,18,19,22,31,23,21,27,20,25,30,24,26,28,29},  //4x4I
+  {0,1,2,5,7,4,6,3,9,12,11,8,10,14,13,15,16,17,21,22,25,18,28,23,30,26,20,19,27,24,29,31},  //4x4P
+  {0,1,2,5,7,4,6,3,9,12,11,8,10,14,13,15,16,17,21,22,25,18,28,23,30,26,20,19,27,24,29,31}   //4x4B
+};
+
+#if !CAVLC_COEF_LRG_BLK
+const UInt g_auiLPTableE8[8][128] =
+{
+  {0,2,1,4,7,3,6,11,13,9,18,22,19,17,8,10,20,24,28,27,21,26,38,42,37,31,23,12,16,33,30,44,45,49,46,36,57,50,55,47,39,43,35,75,66,56,60,58,54,70,63,29,77,87,69,48,51,64,71,65,80,85,76,94,5,15,14,34,52,25,41,72,74,53,59,81,82,68,40,62,95,127,89,84,67,73,126,79,125,93,90,61,32,124,123,83,86,122,88,78,121,92,91,120,119,118,117,116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,100,99,98,97,96}, //U
+  {0,2,1,4,7,3,6,11,13,9,18,22,19,17,8,10,20,24,28,27,21,26,38,42,37,31,23,12,16,33,30,44,45,49,46,36,57,50,55,47,39,43,35,75,66,56,60,58,54,70,63,29,77,87,69,48,51,64,71,65,80,85,76,94,5,15,14,34,52,25,41,72,74,53,59,81,82,68,40,62,95,127,89,84,67,73,126,79,125,93,90,61,32,124,123,83,86,122,88,78,121,92,91,120,119,118,117,116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,100,99,98,97,96}, //V
+  
+  {0,1,2,6,7,3,5,12,11,10,8,17,20,22,9,13,32,21,14,25,16,29,62,59,42,28,15,18,19,26,35,36,30,48,56,39,91,72,63,37,38,44,23,27,41,47,40,58,77,83,52,65,57,33,53,60,54,69,89,45,34,51,46,49,4,31,24,71,88,70,92,103,119,93,55,95,122,127,106,123,125,76,66,126,108,112,117,107,124,111,68,97,85,114,113,121,116,115,79,82,105,120,110,118,109,102,100,84,101,90,104,94,96,78,86,99,81,75,87,98,80,73,74,67,64,61,43,50}, //8x8I
+  {0,1,2,7,5,3,11,16,6,8,14,18,13,19,9,15,21,22,24,25,20,31,44,36,37,30,23,10,4,26,28,33,39,45,49,40,55,56,59,43,42,32,12,17,38,48,50,60,74,79,75,47,51,27,35,53,65,73,76,66,46,80,77,83,29,71,69,88,92,81,90,106,97,86,85,116,127,115,93,101,114,126,113,102,87,84,104,125,124,123,122,82,34,103,121,120,107,112,94,41,68,105,111,119,110,95,61,57,96,109,118,108,52,54,100,117,99,62,78,98,91,58,64,89,67,72,63,70}, //8x8P
+  {0,1,2,7,5,3,11,16,6,8,14,18,13,19,9,15,21,22,24,25,20,31,44,36,37,30,23,10,4,26,28,33,39,45,49,40,55,56,59,43,42,32,12,17,38,48,50,60,74,79,75,47,51,27,35,53,65,73,76,66,46,80,77,83,29,71,69,88,92,81,90,106,97,86,85,116,127,115,93,101,114,126,113,102,87,84,104,125,124,123,122,82,34,103,121,120,107,112,94,41,68,105,111,119,110,95,61,57,96,109,118,108,52,54,100,117,99,62,78,98,91,58,64,89,67,72,63,70}, //8x8B
+  
+  {0,1,2,5,4,3,6,7,8,9,10,11,13,12,15,16,20,17,14,18,23,29,26,19,24,38,22,34,32,46,21,39,41,30,28,45,27,40,56,59,35,42,51,48,44,43,47,54,58,36,53,63,61,37,55,65,50,62,60,52,57,49,31,25,33,64,67,69,72,70,80,86,95,99,89,123,88,96,94,113,101,91,98,93,83,108,110,107,103,105,79,77,90,85,127,81,114,104,118,84,97,102,122,87,106,109,92,117,126,78,116,71,112,120,82,121,75,66,111,124,76,100,125,68,73,115,119,74}, //16x16I
+  {0,2,1,4,5,3,6,7,8,11,14,13,12,10,9,15,17,16,20,23,22,26,31,30,27,21,25,19,24,32,28,29,36,35,40,37,47,42,44,38,33,34,41,43,45,39,48,49,54,59,60,57,52,51,56,58,61,55,65,62,63,64,67,69,18,50,46,72,66,53,70,73,71,74,89,81,79,77,68,83,78,84,80,87,90,96,127,93,95,86,94,75,82,99,107,126,92,100,88,76,85,106,125,124,98,97,105,104,123,122,121,103,91,102,120,119,118,117,101,116,115,114,113,112,111,110,109,108}, //16x16P
+  {0,2,1,4,5,3,6,7,8,11,14,13,12,10,9,15,17,16,20,23,22,26,31,30,27,21,25,19,24,32,28,29,36,35,40,37,47,42,44,38,33,34,41,43,45,39,48,49,54,59,60,57,52,51,56,58,61,55,65,62,63,64,67,69,18,50,46,72,66,53,70,73,71,74,89,81,79,77,68,83,78,84,80,87,90,96,127,93,95,86,94,75,82,99,107,126,92,100,88,76,85,106,125,124,98,97,105,104,123,122,121,103,91,102,120,119,118,117,101,116,115,114,113,112,111,110,109,108}  //16x16B 
+};
+
+const UInt g_auiLPTableD8[8][128] =
+{
+  {0,2,1,5,3,64,6,4,14,9,15,7,27,8,66,65,28,13,10,12,16,20,11,26,17,69,21,19,18,51,30,25,92,29,67,42,35,24,22,40,78,70,23,41,31,32,34,39,55,33,37,56,68,73,48,38,45,36,47,74,46,91,79,50,57,59,44,84,77,54,49,58,71,85,72,43,62,52,99,87,60,75,76,95,83,61,96,53,98,82,90,102,101,89,63,80,127,126,125,124,123,122,121,120,119,118,117,116,115,114,113,112,111,110,109,108,107,106,105,104,103,100,97,94,93,88,86,81}, //U
+  {0,2,1,5,3,64,6,4,14,9,15,7,27,8,66,65,28,13,10,12,16,20,11,26,17,69,21,19,18,51,30,25,92,29,67,42,35,24,22,40,78,70,23,41,31,32,34,39,55,33,37,56,68,73,48,38,45,36,47,74,46,91,79,50,57,59,44,84,77,54,49,58,71,85,72,43,62,52,99,87,60,75,76,95,83,61,96,53,98,82,90,102,101,89,63,80,127,126,125,124,123,122,121,120,119,118,117,116,115,114,113,112,111,110,109,108,107,106,105,104,103,100,97,94,93,88,86,81}, //V 
+  
+  {0,1,2,5,64,6,3,4,10,14,9,8,7,15,18,26,20,11,27,28,12,17,13,42,66,19,29,43,25,21,32,65,16,53,60,30,31,39,40,35,46,44,24,126,41,59,62,45,33,63,127,61,50,54,56,74,34,52,47,23,55,125,22,38,124,51,82,123,90,57,69,67,37,121,122,117,81,48,113,98,120,116,99,49,107,92,114,118,68,58,109,36,70,73,111,75,112,91,119,115,106,108,105,71,110,100,78,87,84,104,102,89,85,94,93,97,96,86,103,72,101,95,76,79,88,80,83,77}, //8x8I
+  {0,1,2,5,28,4,8,3,9,14,27,6,42,12,10,15,7,43,11,13,20,16,17,26,18,19,29,53,30,64,25,21,41,31,92,54,23,24,44,32,35,99,40,39,22,33,60,51,45,34,46,52,112,55,113,36,37,107,121,38,47,106,117,126,122,56,59,124,100,66,127,65,125,57,48,50,58,62,118,49,61,69,91,63,85,74,73,84,67,123,70,120,68,78,98,105,108,72,119,116,114,79,83,93,86,101,71,96,111,109,104,102,97,82,80,77,75,115,110,103,95,94,90,89,88,87,81,76}, //8x8P
+  {0,1,2,5,28,4,8,3,9,14,27,6,42,12,10,15,7,43,11,13,20,16,17,26,18,19,29,53,30,64,25,21,41,31,92,54,23,24,44,32,35,99,40,39,22,33,60,51,45,34,46,52,112,55,113,36,37,107,121,38,47,106,117,126,122,56,59,124,100,66,127,65,125,57,48,50,58,62,118,49,61,69,91,63,85,74,73,84,67,123,70,120,68,78,98,105,108,72,119,116,114,79,83,93,86,101,71,96,111,109,104,102,97,82,80,77,75,115,110,103,95,94,90,89,88,87,81,76}, //8x8B
+  
+  {0,1,2,5,4,3,6,7,8,9,10,11,13,12,18,14,15,17,19,23,16,30,26,20,24,63,22,36,34,21,33,62,28,64,27,40,49,53,25,31,37,32,41,45,44,35,29,46,43,61,56,42,59,50,47,54,38,60,48,39,58,52,57,51,65,55,117,66,123,67,69,111,68,124,127,116,120,91,109,90,70,95,114,84,99,93,71,103,76,74,92,81,106,83,78,72,77,100,82,73,121,80,101,88,97,89,104,87,85,105,86,118,112,79,96,125,110,107,98,126,113,115,102,75,119,122,108,94}, //16x16I
+  {0,2,1,5,3,4,6,7,8,14,13,9,12,11,10,15,17,16,64,27,18,25,20,19,28,26,21,24,30,31,23,22,29,40,41,33,32,35,39,45,34,42,37,43,38,44,66,36,46,47,65,53,52,69,48,57,54,51,55,49,50,56,59,60,61,58,68,62,78,63,70,72,67,71,73,91,99,77,80,76,82,75,92,79,81,100,89,83,98,74,84,112,96,87,90,88,85,105,104,93,97,118,113,111,107,106,101,94,127,126,125,124,123,122,121,120,119,117,116,115,114,110,109,108,103,102,95,86}, //16x16P
+  {0,2,1,5,3,4,6,7,8,14,13,9,12,11,10,15,17,16,64,27,18,25,20,19,28,26,21,24,30,31,23,22,29,40,41,33,32,35,39,45,34,42,37,43,38,44,66,36,46,47,65,53,52,69,48,57,54,51,55,49,50,56,59,60,61,58,68,62,78,63,70,72,67,71,73,91,99,77,80,76,82,75,92,79,81,100,89,83,98,74,84,112,96,87,90,88,85,105,104,93,97,118,113,111,107,106,101,94,127,126,125,124,123,122,121,120,119,117,116,115,114,110,109,108,103,102,95,86}  //16x16B  
+};
+#endif
+
+#if LCEC_INTRA_MODE
+#if MTK_DCM_MPM
+
+const UInt  g_auiIntraModeTableD17[2][16]=
+{
+  {0, 15, 11, 10, 13,  7,  9, 4, 14,  2, 3, 6,  8, 5, 12, 1},
+  {14,10,  9,  0, 13,  7,  2, 8,  3, 12, 6, 4, 11, 1,  5, 0}  
+};
+const UInt  g_auiIntraModeTableE17[2][16]=
+{
+  {0, 15,  9, 10,  7, 13, 11, 5, 12, 6, 3,  2, 14, 4,  8, 1},
+  {3, 13,  6,  8, 11, 14, 10, 5,  7, 2, 1, 12,  9, 4,  0, 0}
+};
+const UInt  g_auiIntraModeTableD34[2][33]=
+{
+  {2, 0, 29, 30, 20,  1, 21, 28, 15,  7, 16,  8, 11, 31, 22, 19, 32, 10, 27, 14,  4, 18, 12, 23, 17, 24, 26,  6, 25,  5, 9, 3, 13},
+  {2, 1, 28,  0, 29, 20, 27, 19, 15, 21,  7, 14, 10, 11, 30, 31, 18, 16, 26,  8, 17,  4, 22,  9, 23,  6, 25, 13, 24, 12, 3, 5,  0}
+};
+const UInt  g_auiIntraModeTableE34[2][33]=
+{
+  {1, 5, 0, 31, 20, 29, 27,  9, 11, 30, 17, 12, 22, 32, 19, 8, 10, 24, 21, 15, 4, 6, 14, 23, 25, 28, 26, 18, 7, 2,  3, 13, 16},
+  {3, 1, 0, 30, 21, 31, 25, 10, 19, 23, 12, 13, 29, 27, 11, 8, 17, 20, 16,  7, 5, 9, 22, 24, 28, 26, 18,  6, 2, 4, 14, 15,  0}
+};
+
+#else
+const UInt  g_auiIntraModeTableD17[16]={15,0,11,7,14,10,13,4,9,2,3,1,8,6,12,5};
+const UInt  g_auiIntraModeTableE17[16]={1,11,9,10,7,15,13,3,12,8,5,2,14,6,4,0};
+
+const UInt  g_auiIntraModeTableD34[33]={0,29,1,2,30,20,28,15,32,21,27,11,10,7,19,14,16,23,22,8,4,18,31,26,17,9,25,6,3,12,13,24,5};
+const UInt  g_auiIntraModeTableE34[33]={0,2,3,28,20,32,27,13,19,25,12,11,29,30,15,7,16,24,21,14,5,9,18,17,31,26,23,10,6,1,4,22,8};
+#endif
+#endif
+
+const UInt g_auiLastPosVlcIndex[10] = {0,0,0,0,0,0,0,0,0,0};
+
+const UInt g_auiLastPosVlcNum[10][17] =
+{
+  {10,10,10,10, 2,2,2,7,9,9,9,9,9,4,4,4,4},
+  {10,10,10,10,10,2,9,9,9,9,9,9,9,4,4,4,4},
+#if CAVLC_COEF_LRG_BLK 
+  { 2, 2, 2, 2, 2, 7, 7, 7, 7, 7, 7, 7, 7, 7, 4, 4,13},
+  { 2, 2, 2, 2, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,13},
+  { 2, 2, 2, 2, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,13},
+  {10,10,10, 4, 4, 4, 4,12,12,12,12,12,12,12,12,12,12},
+  {10,10,10,10, 4, 4,12,12,12,12,12,12,12,12,12,12,12},
+  {10,10,10,10, 4, 4,12,12,12,12,12,12,12,12,12,12,12},
+#else
+  { 2, 2, 2, 2, 2,7,7,7,7,7,7,7,7,7,4,4,4},
+  { 2, 2, 2, 2, 7,7,7,7,7,7,7,7,7,7,7,7,4},
+  { 2, 2, 2, 2, 7,7,7,7,7,7,7,7,7,7,7,7,4},
+  {10, 1, 2, 2, 2,2,7,7,7,7,9,9,9,4,4,4,4},
+  {10,10, 2, 2, 7,7,7,7,7,7,7,7,4,4,4,4,4},
+  {10,10, 2, 2, 7,7,7,7,7,7,7,7,4,4,4,4,4},
+#endif
+  { 2, 2, 2, 2, 7,7,7,7,7,7,7,7,7,7,7,7,4},
+  { 2, 2, 2, 2, 7,7,7,7,7,7,7,7,7,7,7,7,4}
+};
+
+
+
+#if RUNLEVEL_TABLE_CUT
+const UInt g_auiLumaRun8x8[28][29] =
+{
+  {1,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {2,   1,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   3,   2,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {2,   1,   3,   4,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   5,   3,   2,   4,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   6,   5,   3,   4,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {2,   1,   3,   5,   4,   7,   6,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   5,   4,   2,   3,   6,   8,   7,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   3,   8,   7,   5,   2,   4,   9,   6,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   5,   9,   8,   7,   3,   4,  10,   6,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {2,   1,   3,   4,   7,   8,   5,   6,   9,  11,  10,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   4,   3,   2,   5,   7,   6,   8,  10,  11,  12,   9,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   6,   7,   5,   3,   4,   8,   9,  13,  11,  12,  10,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   4,   8,   9,   7,   6,   3,   5,  12,  14,  13,  11,  10,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   3,   5,   9,  10,   8,   7,   4,   6,  12,  15,  14,  13,  11,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   3,   4,   5,   8,  10,   7,   6,   9,  11,  13,  16,  14,  15,  12,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   3,   4,   2,   5,   6,  10,   9,   7,   8,  11,  12,  13,  15,  16,  17,  14,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   4,   7,   6,   3,   5,   8,   9,  10,  11,  17,  15,  13,  14,  16,  18,  12,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   5,   7,   9,  10,   6,   3,   4,   8,  11,  16,  19,  17,  15,  13,  14,  18,  12,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   3,   5,   7,   9,  14,  12,   8,   6,   2,   4,  15,  17,  19,  18,  16,  10,  11,  20,  13,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   2,   4,   6,   9,   8,  15,  14,  13,   7,   3,   5,  16,  18,  21,  19,  17,  10,  12,  20,  11,   0,  M1,  M1,  M1,  M1,  M1,  M1,  M1},
+  {2,   1,   3,   4,   5,   8,   9,  11,  13,  10,   6,   7,  12,  14,  19,  22,  21,  17,  15,  18,  20,  16,   0,  M1,  M1,  M1,  M1,  M1,  M1},
+  {1,   5,   4,   2,   3,   6,   8,   7,  11,  12,   9,  10,  13,  14,  15,  18,  22,  21,  17,  19,  20,  23,  16,   0,  M1,  M1,  M1,  M1,  M1},
+  {1,   4,   8,   6,   5,   2,   3,   7,   9,  12,  10,  11,  13,  16,  15,  14,  18,  20,  21,  19,  23,  22,  24,  17,   0,  M1,  M1,  M1,  M1},
+  {1,   3,   7,  12,  10,   6,   5,   2,   4,   8,   9,  11,  13,  16,  23,  20,  15,  14,  18,  19,  21,  24,  25,  22,  17,   0,  M1,  M1,  M1},
+  {1,   2,   5,   9,  13,  11,  10,   8,   6,   3,   4,   7,  12,  15,  18,  25,  22,  19,  16,  14,  17,  21,  26,  23,  24,  20,   0,  M1,  M1},
+  {1,   2,   4,   7,  11,  15,  12,   9,  10,   8,   5,   3,   6,  14,  16,  22,  23,  24,  20,  19,  13,  18,  26,  27,  25,  21,  17,   0,  M1},
+  {1,   2,   3,   5,   6,  10,  14,  13,  11,   9,  12,   7,   4,   8,  16,  18,  21,  23,  25,  20,  22,  15,  19,  27,  28,  26,  24,  17,   0}
+};
+#else
+const UInt g_auiLumaRun8x8[29][2][64] =
+{
+  /* 0 */
+  {
+    {
+      1,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      2, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 1 */
+  {
+    {
+      2,  1,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      4,  3, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 2 */
+  {
+    {
+      1,  3,  2,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      4,  6,  5, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 3 */
+  {
+    {
+      2,  1,  3,  4,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      6,  5,  7,  8, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 4 */
+  {
+    {
+      1,  5,  3,  2,  4,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      6, 10,  8,  7,  9, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 5 */
+  {
+    {
+      1,  2,  6,  5,  3,  4,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      7,  8, 11, 10,  9, 12, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 6 */
+  {
+    {
+      2,  1,  3,  5,  4,  7,  6,  0, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      9,  8, 10, 12, 11, 13, 14, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 7 */
+  {
+    {
+      1,  5,  4,  2,  3,  6,  8,  7,  0, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      9, 13, 12, 10, 11, 14, 15, 16, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 8 */
+  {
+    {
+      1,  3,  8,  7,  5,  2,  4,  9,  6,  0, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      10, 12, 16, 15, 14, 11, 13, 18, 17, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  /* 9 */
+  {
+    {
+      1,  2,  5, 10,  9,  7,  3,  4, 11,  6,  0, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      8, 12, 15, 17, 18, 16, 13, 14, 20, 19, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      2,  1,  3,  4,  7,  8,  5,  6,  9, 11, 10,  0, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      13, 12, 14, 15, 17, 18, 16, 19, 20, 22, 21, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  4,  3,  2,  5,  7,  6,  8, 10, 11, 12,  9,  0, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      13, 17, 15, 14, 16, 19, 18, 20, 22, 23, 24, 21, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  2,  6,  7,  5,  3,  4,  8,  9, 13, 11, 12, 10,  0, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      14, 16, 18, 21, 19, 15, 17, 20, 22, 26, 23, 24, 25, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  2,  4,  8,  9,  7,  6,  3,  5, 12, 14, 13, 11, 10,  0, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      15, 16, 19, 21, 23, 22, 20, 17, 18, 26, 28, 27, 24, 25, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  2,  3,  5,  9, 10,  8,  7,  4,  6, 13, 16, 15, 14, 12,  0,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      11, 17, 18, 20, 22, 24, 23, 26, 19, 21, 27, 30, 29, 25, 28, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  2,  3,  4,  5,  8, 10,  7,  6,  9, 11, 13, 18, 15, 16, 12,
+      0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      14, 17, 19, 20, 21, 23, 25, 24, 22, 26, 27, 29, 31, 28, 32, 30,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  3,  4,  2,  5,  6, 10,  9,  7,  8, 11, 12, 13, 16, 17, 18,
+      14,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      15, 19, 22, 20, 21, 24, 26, 25, 23, 27, 32, 29, 28, 30, 33, 34,
+      31, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  2,  4,  7,  6,  3,  5,  8,  9, 10, 11, 18, 15, 13, 14, 17,
+      19, 12,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      16, 21, 24, 25, 26, 20, 22, 27, 23, 28, 30, 35, 31, 29, 34, 33,
+      36, 32, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  2,  5,  7,  9, 10,  6,  3,  4,  8, 11, 17, 20, 18, 15, 13,
+      14, 19, 12,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      16, 21, 24, 25, 29, 28, 27, 23, 22, 26, 31, 36, 34, 37, 33, 32,
+      30, 38, 35, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  3,  5,  7,  9, 14, 12,  8,  6,  2,  4, 15, 18, 21, 20, 16,
+      10, 11, 22, 13,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      17, 23, 25, 27, 29, 31, 33, 30, 26, 19, 24, 35, 37, 39, 40, 36,
+      32, 28, 38, 34, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      0,  2,  4,  7, 10,  9, 16, 15, 14,  8,  3,  5, 17, 19, 22, 20,
+      18, 11, 13, 21, 12,  1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      6, 23, 25, 29, 27, 31, 30, 34, 38, 32, 24, 26, 36, 82, 39, 37,
+      83, 28, 33, 84, 35, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      2,  1,  3,  4,  5,  8,  9, 11, 13, 10,  6,  7, 12, 14, 21, 24,
+      23, 18, 15, 19, 22, 16,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      20, 17, 25, 26, 27, 28, 31, 34, 35, 30, 29, 32, 33, 36, 37, 43,
+      44, 38, 39, 40, 41, 42, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  5,  4,  2,  3,  6,  8,  7, 11, 12,  9, 10, 13, 14, 15, 18,
+      22, 21, 17, 19, 20, 25, 16,  0, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      26, 28, 27, 23, 24, 29, 31, 32, 38, 34, 30, 33, 35, 37, 36, 43,
+      44, 40, 41, 85, 42, 86, 39, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  4,  8,  6,  5,  2,  3,  7,  9, 12, 10, 11, 13, 16, 15, 14,
+      18, 20, 21, 19, 23, 22, 25, 17,  0, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      24, 28, 33, 29, 31, 26, 27, 34, 35, 36, 32, 30, 37, 40, 38, 42,
+      45, 47, 39, 43, 46, 41, 87, 44, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      0,  3,  7, 12, 10,  6,  5,  2,  4,  8,  9, 11, 13, 17, 24, 21,
+      16, 15, 19, 20, 22, 25, 26, 23, 18,  1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      14, 28, 34, 36, 33, 35, 31, 27, 30, 29, 32, 37, 40, 46, 38, 44,
+      39, 47, 48, 49, 45, 41, 42, 50, 43, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      0,  2,  5,  9, 13, 11, 10,  8,  6,  3,  4,  7, 12, 15, 19, 26,
+      23, 20, 16, 14, 18, 22, 27, 24, 25, 21,  1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      17, 28, 31, 36, 35, 39, 37, 34, 33, 30, 29, 32, 38, 43, 86, 87,
+      45, 46, 44, 41, 40, 88, 48, 89, 47, 42, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      1,  2,  4,  7, 11, 15, 12,  9, 10,  8,  5,  3,  6, 14, 16, 23,
+      24, 25, 21, 20, 13, 19, 27, 28, 26, 22, 17,  0, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      18, 29, 31, 33, 39, 36, 35, 38, 41, 40, 34, 30, 32, 43, 48, 53,
+      90, 49, 42, 50, 37, 44, 51, 47, 52, 45, 46, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      0,  2,  3,  5,  7, 11, 15, 14, 12, 10, 13,  8,  4,  9, 17, 19,
+      22, 24, 26, 21, 23, 16, 20, 29, 30, 28, 25, 18,  1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    },
+    {
+      6, 27, 31, 33, 34, 38, 39, 37, 40, 42, 41, 35, 32, 36, 44, 45,
+      87, 48, 88, 49, 46, 89, 43, 47, 90, 50, 51, 91, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1,
+      M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1
+    }
+  },
+  {
+    {
+      0,  1,  2,  3,  4,  5,  7,  9, 10, 13,  8, 12, 11,  6, 14, 15,
+      18, 20, 24, 31, 32, 30, 28, 26, 22, 25, 33, 37, 38, 17, 19, 21,
+      23, 29, 36, 34, 45, 40, 43, 42, 44, 39, 35, 46, 48, 53, 54, 51,
+      61, 62, 67, 66, 68, 65, 73, 74, 71, 69, 86, 82, 90, 88, 98, 94
+    },
+    {
+      16, 27, 41, 47, 50, 57, 58, 60, 59, 55, 52, 63, 56, 49, 64, 70,
+      72, 77, 76, 80, 84, 81, 79, 78, 75, 83, 85, 87, 91, 95, 92,104,
+      89, 93, 96, 99,100,102,101, 97,105,103,106,107,108,109,110,111,
+      112,113,114,115,116,117,118,119,120,121,122,123,124,125,126, M1
+    }
+  }
+};
+#endif
+
+#if  QC_MOD_LCEC
+const UInt g_auiLumaRunTr14x4[5][15]=
+{
+    {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0},
+    {2, 3, 4, 5, 6, 5, 6, 7, 7, 7, 7, 7, 6, 4, 2},
+    {2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 2, M1},
+    {2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, M1, M1},
+    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, M1, M1, M1}
+};
+const UInt g_auiLumaRunTr18x8[5][29]=
+{
+    {0, 1, 2, 2, 2, 2, 2, 4, 5, 5, 6, 6, 6, 6, 6, 6, 7, 8, 7, 8, 8, 9, 10, 10, 10, 12, 10, 9, 8},
+    {2, 4, 4, 6, 6, 8, 8, 10, 11, 13, 15, 13, 14, 15, 16, 18, 18, 21, 20, 21, 22, 23, 25, 25, 26, 27, 28, 29, 27},
+    {2, 3, 4, 5, 4, 5, 6, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 13, 14, 15, 16, 16, 17, 18, 19, 20, 19, 19},
+    {2, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13},
+    {2, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 8}
+};
+
+#if CAVLC_COEF_LRG_BLK
+const UInt *g_pLumaRunTr14x4[5] = { 
+  &g_auiLumaRunTr14x4[0][0], &g_auiLumaRunTr14x4[1][0], &g_auiLumaRunTr14x4[2][0], 
+  &g_auiLumaRunTr14x4[3][0], &g_auiLumaRunTr14x4[4][0]
+};
+
+const UInt *g_pLumaRunTr18x8[5] = { 
+  &g_auiLumaRunTr18x8[0][0], &g_auiLumaRunTr18x8[1][0], &g_auiLumaRunTr18x8[2][0], 
+  &g_auiLumaRunTr18x8[3][0], &g_auiLumaRunTr18x8[4][0]
+};
+#endif
+#endif
+
+#if QC_MOD_LCEC
+const UInt g_auiVlcTable8x8Inter[29] = {8,0,0,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,3};
+const UInt g_auiVlcTable8x8Intra[29] = {8,0,0,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,3};
+#if CAVLC_COEF_LRG_BLK
+const UInt g_auiVlcTable16x16Intra[29] = {8,0,0,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,1,1,1,1,1,1,1,1,1,1,2};
+const UInt g_auiVlcTable16x16Inter[29] = {8,0,1,1,1,1,2,2,2,2,2,2,2,6,6,6,6,6,6,3,3,3,3,3,3,3,3,3,3};
+#endif
+#else
+const UInt g_auiVlcTable8x8[28] = {8,0,0,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6};
+#endif
+
+#if LCEC_INTRA_MODE
+#if MTK_DCM_MPM
+const UInt huff17_2[2][17]=
+{
+  {1, 7, 6, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 3, 2, 1, 0},
+  {1, 0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 0},
+};
+const UInt lengthHuff17_2[2][17]=
+{
+  {1, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6},
+  {1, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0},
+};
+const UInt huff34_2[2][34]=
+{
+  {1, 0, 7, 6, 5, 4, 3, 2, 23, 22, 21, 20, 19, 18, 17, 16, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 127, 126, 125, 124 },
+  {1, 0, 5, 4, 3, 2, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51,50, 0 }
+};
+const UInt lengthHuff34_2[2][34]=
+{
+  {1, 4,  5,  5,  5,  5,  5,  5,  6,  6,  6,  6,  6,  6,  6,  6,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  8,  8,  8, 8 },
+  {1, 4,  5,  5,  5,  5,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7, 0 }
+};
+#else
+const UInt huff17_2[2][17]=
+{
+  {1, 7, 6, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 3, 2, 1, 0},
+  {3, 5, 9, 8, 7, 6, 5, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
+};
+const UInt lengthHuff17_2[2][17]=
+{
+  {1, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6},
+  {2, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}
+};
+const UInt huff34_2[2][34]=
+{
+  {1, 7, 13, 12, 11, 10, 9, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 0},
+  {3, 11, 10, 9, 17, 16, 15, 14, 13, 12, 11, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 0}
+};
+const UInt lengthHuff34_2[2][34]=
+{
+  {1, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8},
+  {2, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7}
+};
+#endif
+#endif
+
+#if RUNLEVEL_TABLE_CUT
+const UInt g_acstructLumaRun8x8[28][29] =
+{
+  {  1,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  {  2,  1,  0, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  {  3,  0,  2,  1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  {  4,  1,  0,  2,  3, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  {  5,  0,  3,  2,  4,  1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  {  6,  0,  1,  4,  5,  3,  2, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  {  7,  1,  0,  2,  4,  3,  6,  5, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  {  8,  0,  3,  4,  2,  1,  5,  7,  6, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  {  9,  0,  5,  1,  6,  4,  8,  3,  2,  7, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 10,  0,  1,  6,  7,  2,  9,  5,  4,  3,  8, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 11,  1,  0,  2,  3,  6,  7,  4,  5,  8, 10,  9, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 12,  0,  3,  2,  1,  4,  6,  5,  7, 11,  8,  9, 10, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 13,  0,  1,  5,  6,  4,  2,  3,  7,  8, 12, 10, 11,  9, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 14,  0,  1,  7,  2,  8,  6,  5,  3,  4, 13, 12,  9, 11, 10, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 15,  0,  1,  2,  8,  3,  9,  7,  6,  4,  5, 14, 10, 13, 12, 11, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 16,  0,  1,  2,  3,  4,  8,  7,  5,  9,  6, 10, 15, 11, 13, 14, 12, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 17,  0,  3,  1,  2,  4,  5,  8,  9,  7,  6, 10, 11, 12, 16, 13, 14, 15, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 18,  0,  1,  5,  2,  6,  4,  3,  7,  8,  9, 10, 17, 13, 14, 12, 15, 11, 16, M1, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 19,  0,  1,  7,  8,  2,  6,  3,  9,  4,  5, 10, 18, 15, 16, 14, 11, 13, 17, 12, M1, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 20,  0,  9,  1, 10,  2,  8,  3,  7,  4, 16, 17,  6, 19,  5, 11, 15, 12, 14, 13, 18, M1, M1, M1, M1, M1, M1, M1, M1},
+  { 21,  0,  1, 10,  2, 11,  3,  9,  5,  4, 17, 20, 18,  8,  7,  6, 12, 16, 13, 15, 19, 14, M1, M1, M1, M1, M1, M1, M1},
+  { 22,  1,  0,  2,  3,  4, 10, 11,  5,  6,  9,  7, 12,  8, 13, 18, 21, 17, 19, 14, 20, 16, 15, M1, M1, M1, M1, M1, M1},
+  { 23,  0,  3,  4,  2,  1,  5,  7,  6, 10, 11,  8,  9, 12, 13, 14, 22, 18, 15, 19, 20, 17, 16, 21, M1, M1, M1, M1, M1},
+  { 24,  0,  5,  6,  1,  4,  3,  7,  2,  8, 10, 11,  9, 12, 15, 14, 13, 23, 16, 19, 17, 18, 21, 20, 22, M1, M1, M1, M1},
+  { 25,  0,  7,  1,  8,  6,  5,  2,  9, 10,  4, 11,  3, 12, 17, 16, 13, 24, 18, 19, 15, 20, 23, 14, 21, 22, M1, M1, M1},
+  { 26,  0,  1,  9, 10,  2,  8, 11,  7,  3,  6,  5, 12,  4, 19, 13, 18, 20, 14, 17, 25, 21, 16, 23, 24, 15, 22, M1, M1},
+  { 27,  0,  1, 11,  2, 10, 12,  3,  9,  7,  8,  4,  6, 20, 13,  5, 14, 26, 21, 19, 18, 25, 15, 16, 17, 24, 22, 23, M1},
+  { 28,  0,  1,  2, 12,  3,  4, 11, 13,  9,  5,  8, 10,  7,  6, 21, 14, 27, 15, 22, 19, 16, 20, 17, 26, 18, 25, 23, 24}
+};
+#else
+const LastCoeffStruct g_acstructLumaRun8x8[29][127] =
+{
+  {
+    {0,1},{0,0},{1,0},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,2},{0,1},{0,0},{1,1},{1,0},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,3},{0,0},{0,2},{0,1},{1,0},{1,2},{1,1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,4},{0,1},{0,0},{0,2},{0,3},{1,1},{1,0},{1,2},{1,3},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,5},{0,0},{0,3},{0,2},{0,4},{0,1},{1,0},{1,3},{1,2},{1,4},{1,1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,6},{0,0},{0,1},{0,4},{0,5},{0,3},{0,2},{1,0},{1,1},{1,4},{1,3},{1,2},{1,5},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,7},{0,1},{0,0},{0,2},{0,4},{0,3},{0,6},{0,5},{1,1},{1,0},{1,2},{1,4},{1,3},{1,5},{1,6},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,8},{0,0},{0,3},{0,4},{0,2},{0,1},{0,5},{0,7},{0,6},{1,0},{1,3},{1,4},{1,2},{1,1},{1,5},{1,6},{1,7},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,9},{0,0},{0,5},{0,1},{0,6},{0,4},{0,8},{0,3},{0,2},{0,7},{1,0},{1,5},{1,1},{1,6},{1,4},{1,3},{1,2},{1,8},{1,7},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,10},{0,0},{0,1},{0,6},{0,7},{0,2},{0,9},{0,5},{1,0},{0,4},{0,3},{0,8},{1,1},{1,6},{1,7},{1,2},{1,5},{1,3},{1,4},{1,9},{1,8},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,11},{0,1},{0,0},{0,2},{0,3},{0,6},{0,7},{0,4},{0,5},{0,8},{0,10},{0,9},{1,1},{1,0},{1,2},{1,3},{1,6},{1,4},{1,5},{1,7},{1,8},{1,10},
+    {1,9},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,12},{0,0},{0,3},{0,2},{0,1},{0,4},{0,6},{0,5},{0,7},{0,11},{0,8},{0,9},{0,10},{1,0},{1,3},{1,2},{1,4},{1,1},{1,6},{1,5},{1,7},{1,11},
+    {1,8},{1,9},{1,10},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,13},{0,0},{0,1},{0,5},{0,6},{0,4},{0,2},{0,3},{0,7},{0,8},{0,12},{0,10},{0,11},{0,9},{1,0},{1,5},{1,1},{1,6},{1,2},{1,4},{1,7},{1,3},
+    {1,8},{1,10},{1,11},{1,12},{1,9},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,14},{0,0},{0,1},{0,7},{0,2},{0,8},{0,6},{0,5},{0,3},{0,4},{0,13},{0,12},{0,9},{0,11},{0,10},{1,0},{1,1},{1,7},{1,8},{1,2},{1,6},{1,3},
+    {1,5},{1,4},{1,12},{1,13},{1,9},{1,11},{1,10},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,15},{0,0},{0,1},{0,2},{0,8},{0,3},{0,9},{0,7},{0,6},{0,4},{0,5},{1,0},{0,14},{0,10},{0,13},{0,12},{0,11},{1,1},{1,2},{1,8},{1,3},{1,9},
+    {1,4},{1,6},{1,5},{1,13},{1,7},{1,10},{1,14},{1,12},{1,11},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1}
+  },
+  
+  {
+    {0,16},{0,0},{0,1},{0,2},{0,3},{0,4},{0,8},{0,7},{0,5},{0,9},{0,6},{0,10},{0,15},{0,11},{1,0},{0,13},{0,14},{1,1},{0,12},{1,2},{1,3},{1,4},
+    {1,8},{1,5},{1,7},{1,6},{1,9},{1,10},{1,13},{1,11},{1,15},{1,12},{1,14},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1}
+  },
+  
+  {
+    {0,17},{0,0},{0,3},{0,1},{0,2},{0,4},{0,5},{0,8},{0,9},{0,7},{0,6},{0,10},{0,11},{0,12},{0,16},{1,0},{0,13},{0,14},{0,15},{1,1},{1,3},
+    {1,4},{1,2},{1,8},{1,5},{1,7},{1,6},{1,9},{1,12},{1,11},{1,13},{1,16},{1,10},{1,14},{1,15},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1}
+  },
+  
+  {
+    {0,18},{0,0},{0,1},{0,5},{0,2},{0,6},{0,4},{0,3},{0,7},{0,8},{0,9},{0,10},{0,17},{0,13},{0,14},{0,12},{1,0},{0,15},{0,11},{0,16},{1,5},
+    {1,1},{1,6},{1,8},{1,2},{1,3},{1,4},{1,7},{1,9},{1,13},{1,10},{1,12},{1,17},{1,15},{1,14},{1,11},{1,16},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1}
+  },
+  
+  {
+    {0,19},{0,0},{0,1},{0,7},{0,8},{0,2},{0,6},{0,3},{0,9},{0,4},{0,5},{0,10},{0,18},{0,15},{0,16},{0,14},{1,0},{0,11},{0,13},{0,17},{0,12},
+    {1,1},{1,8},{1,7},{1,2},{1,3},{1,9},{1,6},{1,5},{1,4},{1,16},{1,10},{1,15},{1,14},{1,12},{1,18},{1,11},{1,13},{1,17},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1}
+  },
+  
+  {
+    {0,20},{0,0},{0,9},{0,1},{0,10},{0,2},{0,8},{0,3},{0,7},{0,4},{0,16},{0,17},{0,6},{0,19},{0,5},{0,11},{0,15},{1,0},{0,12},{1,9},{0,14},
+    {0,13},{0,18},{1,1},{1,10},{1,2},{1,8},{1,3},{1,17},{1,4},{1,7},{1,5},{1,16},{1,6},{1,19},{1,11},{1,15},{1,12},{1,18},{1,13},{1,14},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1}
+  },
+  
+  {
+    {0,0},{0,21},{0,1},{0,10},{0,2},{0,11},{1,0},{0,3},{0,9},{0,5},{0,4},{0,17},{0,20},{0,18},{0,8},{0,7},{0,6},{0,12},{0,16},{0,13},{0,15},
+    {0,19},{0,14},{1,1},{1,10},{1,2},{1,11},{1,4},{1,17},{1,3},{1,6},{1,5},{1,9},{1,18},{1,7},{1,20},{1,12},{1,15},{1,8},{1,14},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{1,13},{1,16},{1,19},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1}
+  },
+  
+  {
+    {0,22},{0,1},{0,0},{0,2},{0,3},{0,4},{0,10},{0,11},{0,5},{0,6},{0,9},{0,7},{0,12},{0,8},{0,13},{0,18},{0,21},{1,1},{0,17},{0,19},{1,0},
+    {0,14},{0,20},{0,16},{0,15},{1,2},{1,3},{1,4},{1,5},{1,10},{1,9},{1,6},{1,11},{1,12},{1,7},{1,8},{1,13},{1,14},{1,17},{1,18},{1,19},{1,20},
+    {1,21},{1,15},{1,16},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,23},{0,0},{0,3},{0,4},{0,2},{0,1},{0,5},{0,7},{0,6},{0,10},{0,11},{0,8},{0,9},{0,12},{0,13},{0,14},{0,22},{0,18},{0,15},{0,19},{0,20},
+    {0,17},{0,16},{1,3},{1,4},{0,21},{1,0},{1,2},{1,1},{1,5},{1,10},{1,6},{1,7},{1,11},{1,9},{1,12},{1,14},{1,13},{1,8},{1,22},{1,17},{1,18},
+    {1,20},{1,15},{1,16},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{1,19},{1,21},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,24},{0,0},{0,5},{0,6},{0,1},{0,4},{0,3},{0,7},{0,2},{0,8},{0,10},{0,11},{0,9},{0,12},{0,15},{0,14},{0,13},{0,23},{0,16},{0,19},{0,17},
+    {0,18},{0,21},{0,20},{1,0},{0,22},{1,5},{1,6},{1,1},{1,3},{1,11},{1,4},{1,10},{1,2},{1,7},{1,8},{1,9},{1,12},{1,14},{1,18},{1,13},{1,21},
+    {1,15},{1,19},{1,23},{1,16},{1,20},{1,17},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{1,22},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  {
+    {0,0},{0,25},{0,7},{0,1},{0,8},{0,6},{0,5},{0,2},{0,9},{0,10},{0,4},{0,11},{0,3},{0,12},{1,0},{0,17},{0,16},{0,13},{0,24},{0,18},{0,19},
+    {0,15},{0,20},{0,23},{0,14},{0,21},{0,22},{1,7},{1,1},{1,9},{1,8},{1,6},{1,10},{1,4},{1,2},{1,5},{1,3},{1,11},{1,14},{1,16},{1,12},{1,21},
+    {1,22},{1,24},{1,15},{1,20},{1,13},{1,17},{1,18},{1,19},{1,23},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  {
+    {0,0},{0,26},{0,1},{0,9},{0,10},{0,2},{0,8},{0,11},{0,7},{0,3},{0,6},{0,5},{0,12},{0,4},{0,19},{0,13},{0,18},{1,0},{0,20},{0,14},{0,17},
+    {0,25},{0,21},{0,16},{0,23},{0,24},{0,15},{0,22},{1,1},{1,10},{1,9},{1,2},{1,11},{1,8},{1,7},{1,4},{1,3},{1,6},{1,12},{1,5},{1,20},{1,19},
+    {1,25},{1,13},{1,18},{1,16},{1,17},{1,24},{1,22},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{1,14},{1,15},{1,21},{1,23},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  {
+    {0,27},{0,0},{0,1},{0,11},{0,2},{0,10},{0,12},{0,3},{0,9},{0,7},{0,8},{0,4},{0,6},{0,20},{0,13},{0,5},{0,14},{0,26},{1,0},{0,21},{0,19},
+    {0,18},{0,25},{0,15},{0,16},{0,17},{0,24},{0,22},{0,23},{1,1},{1,11},{1,2},{1,12},{1,3},{1,10},{1,6},{1,5},{1,20},{1,7},{1,4},{1,9},{1,8},
+    {1,18},{1,13},{1,21},{1,25},{1,26},{1,23},{1,14},{1,17},{1,19},{1,22},{1,24},{1,15},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{1,16},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,0},{0,28},{0,1},{0,2},{0,12},{0,3},{1,0},{0,4},{0,11},{0,13},{0,9},{0,5},{0,8},{0,10},{0,7},{0,6},{0,21},{0,14},{0,27},{0,15},{0,22},
+    {0,19},{0,16},{0,20},{0,17},{0,26},{0,18},{1,1},{0,25},{0,23},{0,24},{1,2},{1,12},{1,3},{1,4},{1,11},{1,13},{1,7},{1,5},{1,6},{1,8},{1,10},
+    {1,9},{1,22},{1,14},{1,15},{1,20},{1,23},{1,17},{1,19},{1,25},{1,26},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{1,16},{1,18},{1,21},{1,24},{1,27},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},
+    {M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1},{M1,M1}
+  },
+  
+  {
+    {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,13},{0,6},{0,10},{0,7},{0,8},{0,12},{0,11},{0,9},{0,14},{0,15},{1,0},{0,29},{0,16},{0,30},{0,17},
+    {0,31},{0,24},{0,32},{0,18},{0,25},{0,23},{1,1},{0,22},{0,33},{0,21},{0,19},{0,20},{0,26},{0,35},{0,42},{0,34},{0,27},{0,28},{0,41},{0,37},
+    {1,2},{0,39},{0,38},{0,40},{0,36},{0,43},{1,3},{0,44},{1,13},{1,4},{0,47},{1,10},{0,45},{0,46},{1,9},{1,12},{1,5},{1,6},{1,8},{1,7},{0,48},
+    {0,49},{1,11},{1,14},{0,53},{0,51},{0,50},{0,52},{0,57},{1,15},{0,56},{1,16},{0,54},{0,55},{1,24},{1,18},{1,17},{1,23},{1,22},{1,19},
+    {1,21},{0,59},{1,25},{1,20},{1,26},{0,58},{1,27},{0,61},{1,32},{0,60},{1,28},{1,30},{1,33},{0,63},{1,29},{1,34},{1,39},{0,62},{1,35},
+    {1,36},{1,38},{1,37},{1,41},{1,31},{1,40},{1,42},{1,43},{1,44},{1,45},{1,46},{1,47},{1,48},{1,49},{1,50},{1,51},{1,52},{1,53},{1,54},
+    {1,55},{1,56},{1,57},{1,58},{1,59},{1,60},{1,61},{1,62}
+  }
+};
+#endif
+
+// Mode-Dependent DCT/DST 
+#if INTRA_DST_TYPE_7
+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},
+};
+// Mapping each Unified Directional Intra prediction direction to DCT/DST transform 
+// 0 implies use DCT, 1 implies DST
+#if ADD_PLANAR_MODE
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE+8] =
+#elif HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE+4] =
+#else
+const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE] =
+#endif
+#else
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+const UChar g_aucDCTDSTMode_Vert[34+8] =
+#elif
+const UChar g_aucDCTDSTMode_Vert[34+4] =
+#else
+const UChar g_aucDCTDSTMode_Vert[34] =
+#endif
+#endif
+{ //0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
+  1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 ,0 
+#if ADD_PLANAR_MODE
+,1
+#endif
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+,0,0,0,0,0,0,0,0
+#elif HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+,0,0,0,0
+#endif
+};
+#if ADD_PLANAR_MODE
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE+8] =
+#elif HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE+4] =
+#else
+const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE] =
+#endif
+#else
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+const UChar g_aucDCTDSTMode_Hor[34+8] =
+#elif
+const UChar g_aucDCTDSTMode_Hor[34+4] =
+#else
+const UChar g_aucDCTDSTMode_Hor[34] =
+#endif
+#endif
+{ //0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
+  0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 ,1 
+#if ADD_PLANAR_MODE
+,1
+#endif
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+,0,0,0,0,0,0,0,0
+#elif HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+,0,0,0,0
+#endif
+};
+#endif  // for INTRA_DST_TYPE_7
+
+
+
+// ====================================================================================================================
+// 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
+#if SAMSUNG_FAST_UDI_MODESET==0
+const UChar g_aucIntraModeNumFast[7] =
+{
+  3,  //   2x2
+  9,  //   4x4
+  9,  //   8x8
+  4,  //  16x16   33
+  4,  //  32x32   33
+  5,  //  64x64   33
+  4   // 128x128  33
+};
+#else
+const UChar g_aucIntraModeNumFast[7] =
+{
+  3,  //   2x2
+  9,  //   4x4
+  9,  //   8x8
+  9,  //  16x16   33
+  9,  //  32x32   33
+  5,  //  64x64   33
+  4   // 128x128  33
+};
+#endif
+#endif // FAST_UDI_USE_MPM
+
+// chroma
+
+const UChar g_aucConvertTxtTypeToIdx[4] = { 0, 1, 1, 2 };
+
+// ====================================================================================================================
+// Angular Intra prediction
+// ====================================================================================================================
+
+// g_aucAngIntraModeOrder
+//   Indexing this array with the mode indicated in the bitstream
+//   gives a logical index used in the prediction functions.
+#if ADD_PLANAR_MODE
+const UChar g_aucAngIntraModeOrder[NUM_INTRA_MODE] =
+#else
+const UChar g_aucAngIntraModeOrder[34] =
+#endif
+{     //  ModeOrder LogicalOrderInPredFunctions
+  9,  //  0 VER     DC
+  25, //  1 HOR     VER-8 (diagonal from top-left to bottom-right = HOR-8)
+  0,  //  2 DC      VER-7
+  1,  //  3 VER-8   VER-6
+  5,  //  4 VER-4   VER-5
+  13, //  5 VER+4   VER-4
+  17, //  6 VER+8   VER-3
+  21, //  7 HOR-4   VER-2
+  29, //  8 HOR+4   VER-1
+  33, //  9 HOR+8   VER
+  3,  // 10 VER-6   VER+1
+  7,  // 11 VER-2   VER+2
+  11, // 12 VER+2   VER+3
+  15, // 13 VER+6   VER+4
+  19, // 14 HOR-6   VER+5
+  23, // 15 HOR-2   VER+6
+  27, // 16 HOR+2   VER+7
+  31, // 17 HOR+6   VER+8
+  2,  // 18 VER-7   HOR-7
+  4,  // 19 VER-5   HOR-6
+  6,  // 20 VER-3   HOR-5
+  8,  // 21 VER-1   HOR-4
+  10, // 22 VER+1   HOR-3
+  12, // 23 VER+3   HOR-2
+  14, // 24 VER+5   HOR-1
+  16, // 25 VER+7   HOR
+  18, // 26 HOR-7   HOR+1
+  20, // 27 HOR-5   HOR+2
+  22, // 28 HOR-3   HOR+3
+  24, // 29 HOR-1   HOR+4
+  26, // 30 HOR+1   HOR+5
+  28, // 31 HOR+3   HOR+6
+  30, // 32 HOR+5   HOR+7
+  32, // 33 HOR+7   HOR+8
+#if ADD_PLANAR_MODE
+  0, // PLANAR_IDX PLANAR PLANAR (add any other mode earlier; this mode is designed to be the last in the list)
+#endif
+};
+
+const UChar g_aucIntraModeNumAng[7] =
+{
+  3,  //   2x2
+  17,  //   4x4
+  34,  //   8x8
+  34,  //  16x16
+  34,  //  32x32
+  3,  //  64x64
+  5   // 128x128
+};
+
+const UChar g_aucIntraModeBitsAng[7] =
+{
+  2,  //   2x2     3   1+1
+  5,  //   4x4    17   4+1
+  6,  //   8x8    34   5+esc
+  6,  //  16x16   34   5+esc
+  6,  //  32x32   34   5+esc
+  2,  //  64x64    3   1+1
+  3   // 128x128   5   2+1
+};
+
+const UChar g_aucAngModeMapping[4][34] = // intra mode conversion for most probable
+{
+  {2,3,2,2,4, 4,4,0,0,0, 0,0,0,0,2, 2,2,2,2,2, 2,1,1,1,1, 1,1,1,1,1, 2,2,2,2},               // conversion to 5 modes
+  {2,3,3,2,4, 4,4,2,0,0, 0,2,5,5,5, 2,6,6,3,2, 7,7,7,2,1, 1,1,2,8,8, 8,2,2,2},               // conversion to 9 modes
+  {2,3,3,10,10, 4,11,11,0,0, 0,12,12,5,5, 13,13,6,14,14, 7,7,15,15,1, 1,1,16,16,8, 8,2,2,9}, // conversion to 17 modes
+  {2,2,2,2,2, 2,2,0,0,0, 0,0,0,0,2, 2,2,2,2,2, 2,1,1,1,1, 1,1,1,1,1, 2,2,2,2}                // conversion to 3 modes
+};
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+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  
+};
+
+const UChar g_aucIntraSizeIdxToWedgeSize[7] =
+{
+  2,
+  4,
+  8,
+  16,
+  32,
+  64,
+  128  
+};
+
+double g_dDeltaDCsQuantOffset = 0.0;
+#endif
+
+// ====================================================================================================================
+// 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
+
+// ====================================================================================================================
+// 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  ];
+#if QC_MDCS
+UInt* g_auiSigLastScan[3][ MAX_CU_DEPTH ];
+#endif //QC_MDCS
+
+#if PCP_SIGMAP_SIMPLE_LAST
+UInt g_uiCtxXYOffset[ MAX_CU_DEPTH ] =
+{
+  15, 15, 15, 8, 3, 0, 0
+};
+
+UInt g_uiCtxXY[ 31 ] =
+{
+  0, 1, 2, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10
+};
+#endif
+
+// scanning order to 8x8 context model mapping table
+UInt  g_auiAntiScan8  [64];
+
+#if E253
+// Rice parameters for absolute transform levels
+const UInt g_auiGoRiceRange[4] =
+{
+  7, 20, 42, 70
+};
+
+const UInt g_auiGoRicePrefixLen[4] =
+{
+  8, 10, 11, 8
+};
+
+const UInt g_aauiGoRiceUpdate[4][16] =
+{
+  {
+    0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3
+  },
+  {
+    1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3
+  },
+  {
+    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3
+  },
+  {
+    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
+  }
+};
+#endif
+
+// 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;
+  }
+  
+  // LTR_2D_CONTEXT_MAPPING
+  if (iWidth == 8 && iHeight == 8)
+  {
+    for( c = 0; c < iWidth*iHeight; c++)
+    {
+      g_auiAntiScan8[pBuff[c]] = c;
+    }
+  }
+}
+
+#if QC_MDCS
+Void initSigLastScan(UInt* pBuffZ, UInt* pBuffH, UInt* pBuffV, Int iWidth, Int iHeight, Int iDepth)
+{
+
+    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 ++;
+      }
+    }
+    
+}
+#endif //QC_MDCS
+
+#if CHROMA_CODEWORD_SWITCH 
+const UChar ChromaMapping[2][5] = 
+{
+  {0, 1, 3, 2, 4},
+  {0, 1, 2, 4, 3}
+};
+#endif
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+std::vector<std::vector<TComWedgelet> > g_aacWedgeLists;
+std::vector<std::vector<TComWedgeRef> > g_aacWedgeRefLists;
+
+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 );
+  }
+
+  return;
+}
+
+Void createWedgeList( UInt uiWidth, UInt uiHeight, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList, WedgeResolution eWedgeRes )
+{
+  assert( uiWidth == uiHeight );
+
+  UChar uhStartX, uhStartY, uhEndX, uhEndY;
+  Int    iStepStartX, iStepStartY, iStepEndX, iStepEndY;
+
+  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; }
+  }
+
+  Bool bValid;
+  TComWedgelet cTempWedgelet( uiWidth, uiHeight );
+  TComWedgeRef cTempWedgeRef;
+  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 );
+
+        bValid = cTempWedgelet.checkNotPlain();
+        if( bValid )
+        {
+          for( UInt uiPos = 0; uiPos < racWedgeList.size(); uiPos++ )
+          {
+           if( !cTempWedgelet.checkNotIdentical( racWedgeList[uiPos].getPattern() ) )
+           {
+             cTempWedgeRef.setWedgeRef( uhStartX + (iK*iStepStartX) , uhStartY + (iK*iStepStartY), uhEndX + (iL*iStepEndX), uhEndY + (iL*iStepEndY), uiPos );
+             racWedgeRefList.push_back( cTempWedgeRef );
+             bValid = false;
+             break;
+           }
+          }
+        }
+        if( bValid )
+        {
+          for( UInt uiPos = 0; uiPos < racWedgeList.size(); uiPos++ )
+          {
+            if( !cTempWedgelet.checkNotInvIdentical( racWedgeList[uiPos].getPattern() ) )
+            {
+              cTempWedgeRef.setWedgeRef( uhStartX + (iK*iStepStartX) , uhStartY + (iK*iStepStartY), uhEndX + (iL*iStepEndX), uhEndY + (iL*iStepEndY), uiPos );
+              racWedgeRefList.push_back( cTempWedgeRef );
+              bValid = false;
+              break;
+            }
+          }
+        }
+        if( bValid )
+        {
+          racWedgeList.push_back( cTempWedgelet );
+        }
+      }
+    }
+  }
+}
+#endif
Index: /tags/0.2r1/source/Lib/TLibCommon/TComRom.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComRom.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComRom.h	(revision 19)
@@ -0,0 +1,640 @@
+/* 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     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
+
+// ====================================================================================================================
+// 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 );
+#if QC_MDCS
+Void         initSigLastScan(UInt* pBuffZ, UInt* pBuffH, UInt* pBuffV, Int iWidth, Int iHeight, Int iDepth);
+#endif //QC_MDCS
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+Void initWedgeLists();
+Void createWedgeList( UInt uiWidth, UInt uiHeight, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList, WedgeResolution eWedgeRes );
+#endif
+
+// ====================================================================================================================
+// 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 ];
+
+Void         initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx );
+Void         initRasterToZscan ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth         );
+
+// conversion of partition index to picture pel position
+extern       UInt   g_auiRasterToPelX[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt   g_auiRasterToPelY[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+
+Void         initRasterToPelXY ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth );
+#if MTK_SAO
+Int  LevelRowCol2Idx(int level, int row, int col);
+void Idx2LevelRowCol(int idx, int *level, int *row, int *col);
+#endif
+
+// 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[4];
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+extern       std::vector<std::vector<TComWedgelet> > g_aacWedgeLists;
+extern       std::vector<std::vector<TComWedgeRef> > g_aacWedgeRefLists;
+#endif
+
+#if E243_CORE_TRANSFORMS
+#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 UInt g_auiQ[6];             // Q(QP%6)  
+extern UInt g_auiIQ[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];
+
+
+
+#endif
+
+// ====================================================================================================================
+// Quantization & DeQuantization
+// ====================================================================================================================
+
+extern       UInt   g_aiQuantCoef4      [6];
+extern       Int    g_aiDequantCoef4    [6];
+extern       UInt   g_aiQuantCoef       [6][16];
+extern       Int    g_aiDequantCoef     [6][16];
+extern       Int    g_aiDequantCoef64   [6][64];
+extern       UInt   g_aiQuantCoef64     [6][64];
+extern       UInt   g_aiQuantCoef256    [6][256];
+extern       UInt   g_aiDeQuantCoef256  [6][256];
+extern       UInt   g_aiQuantCoef1024   [6][1024];
+extern       UInt   g_aiDeQuantCoef1024 [6][1024];
+extern       UInt   g_aiQuantCoef4096   [6];
+extern       UInt   g_aiDeQuantCoef4096 [6];
+
+// ====================================================================================================================
+// 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_auiAntiScan8[64];                   // 2D context mapping for coefficients
+#if QC_MDCS
+extern       UInt*  g_auiSigLastScan[3][ MAX_CU_DEPTH ];  // raster index from scanning index (zigzag, hor, ver)
+#endif //QC_MDCS
+#if PCP_SIGMAP_SIMPLE_LAST
+extern       UInt   g_uiCtxXYOffset[ MAX_CU_DEPTH ];      //!< context offset for last pos coding
+extern       UInt   g_uiCtxXY      [ 31 ];                //!< context mapping for last pos coding
+#endif
+
+#if E253
+extern const UInt   g_auiGoRiceRange[4];                  //!< maximum value coded with Rice codes
+extern const UInt   g_auiGoRicePrefixLen[4];              //!< prefix length for each maximum value
+extern const UInt   g_aauiGoRiceUpdate[4][16];            //!< parameter update rules for Rice codes
+#endif
+
+// ====================================================================================================================
+// CAVLC table
+// ====================================================================================================================
+
+extern const UChar  g_aucCodeTable3[7][15];
+extern const UChar  g_aucLenTable3 [7][15];
+extern const UChar  g_aucCodeTableTZ4[3][4];
+extern const UChar  g_aucLenTableTZ4 [3][4];
+extern const UChar  g_aucCodeTableTZ16[15][16];
+extern const UChar  g_aucLenTableTZ16 [15][16];
+extern const UChar  g_aucCodeTableTO4[4][5];
+extern const UChar  g_aucLenTableTO4 [4][5];
+extern const UChar  g_aucACTab[6];
+extern const UChar  g_aucFrameBits[32];
+
+#if !CAVLC_COEF_LRG_BLK
+extern const UInt    g_auiLPTableE8[8][128];
+extern const UInt    g_auiLPTableD8[8][128];
+#endif
+extern const UInt    g_auiLPTableE4[3][32];
+extern const UInt    g_auiLPTableD4[3][32];
+extern const UInt    g_auiLastPosVlcIndex[10];
+extern const UInt    g_auiLastPosVlcNum[10][17];
+#if RUNLEVEL_TABLE_CUT
+extern const UInt    g_auiLumaRun8x8[28][29];
+#else
+extern const UInt    g_auiLumaRun8x8[29][2][64];
+#endif
+
+#if LCEC_INTRA_MODE
+#if MTK_DCM_MPM
+extern const UInt    g_auiIntraModeTableD17[2][16];
+extern const UInt    g_auiIntraModeTableE17[2][16];
+extern const UInt    g_auiIntraModeTableD34[2][33];
+extern const UInt    g_auiIntraModeTableE34[2][33];
+#else
+extern const UInt    g_auiIntraModeTableD17[16];
+extern const UInt    g_auiIntraModeTableE17[16];
+extern const UInt    g_auiIntraModeTableD34[33];
+extern const UInt    g_auiIntraModeTableE34[33];
+#endif
+#endif
+
+#if QC_MOD_LCEC
+extern const UInt    g_auiVlcTable8x8Inter[29];
+extern const UInt    g_auiVlcTable8x8Intra[29];
+#else
+extern const UInt    g_auiVlcTable8x8[28];
+#endif
+#if RUNLEVEL_TABLE_CUT 
+extern const UInt    g_acstructLumaRun8x8[28][29];
+#else
+extern const LastCoeffStruct g_acstructLumaRun8x8[29][127];
+#endif
+
+#if CAVLC_COEF_LRG_BLK
+extern const UInt   g_auiVlcTable16x16Intra[29];
+extern const UInt   g_auiVlcTable16x16Inter[29];
+#endif
+
+#if LCEC_INTRA_MODE
+extern const UInt huff17_2[2][17];
+extern const UInt lengthHuff17_2[2][17];
+extern const UInt huff34_2[2][34];
+extern const UInt lengthHuff34_2[2][34];
+#endif
+
+#if QC_MOD_LCEC
+#if CAVLC_COEF_LRG_BLK
+extern const UInt   *g_pLumaRunTr14x4[5]; 
+extern const UInt   *g_pLumaRunTr18x8[5]; 
+#else
+extern const UInt    g_auiLumaRunTr14x4[5][15];
+extern const UInt    g_auiLumaRunTr18x8[5][29];
+#endif
+#endif
+#if CAVLC_RQT_CBP
+extern const UInt    g_auiCBP_YUV_TableE[4][8];
+extern const UInt    g_auiCBP_YUV_TableD[4][8];
+extern const UInt    g_auiCBP_YS_TableE[2][4];
+extern const UInt    g_auiCBP_YS_TableD[2][4];
+extern const UInt    g_auiCBP_YCS_TableE[2][8];
+extern const UInt    g_auiCBP_YCS_TableD[2][8];
+extern const UInt    g_auiCBP_YCS_Table[2][8];
+extern const UInt    g_auiCBP_YCS_TableLen[2][8];
+extern const UInt    g_auiCBP_YC_TableE[2][4];
+extern const UInt    g_auiCBP_YC_TableD[2][4];
+extern const UInt    g_auiCBP_4Y_TableE[2][15];
+extern const UInt    g_auiCBP_4Y_TableD[2][15];
+extern const UInt    g_auiCBP_4Y_VlcNum[15];
+#else
+extern const UInt    g_auiCBPTableE[2][8];
+extern const UInt    g_auiCBPTableD[2][8];
+extern const UInt    g_auiBlkCBPTableE[2][15];
+extern const UInt    g_auiBlkCBPTableD[2][15];
+extern const UInt    g_auiBlkCbpVlcNum[15];
+#endif//
+extern const UInt    g_auiCbpVlcNum[2][8];
+
+#if UNIFY_INTER_TABLE
+extern const UInt g_auiComMI1TableE[9];
+extern const UInt g_auiComMI1TableD[9];
+#else
+extern const UInt g_auiMI1TableE[8];
+extern const UInt g_auiMI1TableD[8];
+extern const UInt g_auiMI2TableE[15];
+extern const UInt g_auiMI2TableD[15];
+extern const UInt g_auiMITableVlcNum[15];
+
+extern const UInt g_auiMI1TableENoL1[8];
+extern const UInt g_auiMI1TableDNoL1[8];
+extern const UInt g_auiMI2TableENoL1[15];
+extern const UInt g_auiMI2TableDNoL1[15];
+
+#if MS_LCEC_ONE_FRAME
+extern const UInt g_auiMI1TableEOnly1Ref[8];
+extern const UInt g_auiMI1TableDOnly1Ref[8];
+extern const UInt g_auiMI1TableEOnly1RefNoL1[8];
+extern const UInt g_auiMI1TableDOnly1RefNoL1[8];
+#endif
+#endif
+
+#if QC_LCEC_INTER_MODE
+extern const UInt g_auiInterModeTableE[4][7];
+extern const UInt g_auiInterModeTableD[4][7];
+#endif
+// ====================================================================================================================
+// 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_aucAngModeMapping[4][34];
+#if ADD_PLANAR_MODE
+extern const UChar g_aucAngIntraModeOrder[NUM_INTRA_MODE];
+#else
+extern const UChar g_aucAngIntraModeOrder[34];
+#endif
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+extern const UChar g_aucWedgeFullBitsListIdx[7];
+extern const UChar g_aucIntraSizeIdxToWedgeSize[7];
+extern const WedgeResolution g_aeWedgeResolutionList[5];
+extern       double g_dDeltaDCsQuantOffset;
+#endif
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+extern       UInt g_uiBitDepth;
+extern       UInt g_uiBitIncrement;
+extern       UInt g_uiIBDI_MAX;
+extern       UInt g_uiBASE_MAX;
+
+// ====================================================================================================================
+// Texture type to integer mapping
+// ====================================================================================================================
+
+extern const UChar g_aucConvertTxtTypeToIdx[4];
+
+// ==========================================
+// Mode-Dependent DST Matrices
+#if INTRA_DST_TYPE_7
+extern const short g_as_DST_MAT_4 [4][4];
+#if ADD_PLANAR_MODE
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+extern const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE+8];
+extern const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE+8];
+#elif HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+extern const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE+4];
+extern const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE+4];
+#else
+extern const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE];
+extern const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE];
+#endif
+#else
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+extern const UChar g_aucDCTDSTMode_Vert[34+8];
+extern const UChar g_aucDCTDSTMode_Hor[34+8];
+#elif HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+extern const UChar g_aucDCTDSTMode_Vert[34+4];
+extern const UChar g_aucDCTDSTMode_Hor[34+4];
+#else
+extern const UChar g_aucDCTDSTMode_Vert[34];
+extern const UChar g_aucDCTDSTMode_Hor[34];
+#endif
+#endif
+#endif
+// ==========================================
+
+// ====================================================================================================================
+// Misc.
+// ====================================================================================================================
+
+#if QC_MOD_LCEC
+__inline UInt xRunLevelInd(Int lev, Int run, Int maxrun, UInt lrg1Pos)
+{
+  UInt cn;
+
+  if ( lrg1Pos > 0 )
+  {
+    if ( lev == 0 )
+    {
+      if ( run < lrg1Pos )
+        cn = run;
+      else
+        cn = (run << 1) - lrg1Pos + 1;
+    }
+    else
+    {
+      if ( run > (maxrun - (Int)lrg1Pos + 1) )
+        cn = maxrun + run + 2 ;  
+      else
+        cn = lrg1Pos + (run << 1);
+    }
+  }
+  else
+  {
+    cn = (run << 1);
+    if ( lev == 0 && run <= maxrun )
+    { 
+      cn++;
+    }
+  }
+  return(cn);
+}
+
+#if RUNLEVEL_TABLE_CUT
+/** Function for deriving codeword index in CAVLC run-level coding 
+ * \param lev a value indicating coefficient level greater than one or not
+ * \param run length of run
+ * \param maxrun maximum length of run for a given coefficient location
+ * \returns the codeword index
+ * This function derives codeword index in CAVLC run-level coding .
+ */
+__inline UInt xRunLevelIndInter(Int lev, Int run, Int maxrun)
+{
+  UInt cn;
+  
+  if (maxrun < 28)
+  {
+    if (lev == 0)
+    {
+      cn = g_auiLumaRun8x8[maxrun][run];
+    }
+    else
+    {
+      cn = maxrun + g_auiLumaRun8x8[maxrun][run] + 1;  
+    }
+  }
+  else
+  {
+    if (lev == 0)
+    {
+      cn = run;
+    }
+    else
+    {
+      cn = maxrun + run + 2;
+    }
+  }
+
+  return(cn);
+}
+#endif
+#endif
+
+
+#if QC_MOD_LCEC_RDOQ
+__inline UInt xLeadingZeros(UInt uiCode)
+{
+  UInt uiCount = 0;
+  Int iDone = 0;
+  
+  if (uiCode)
+  {
+    while (!iDone)
+    {
+      uiCode >>= 1;
+      if (!uiCode) iDone = 1;
+      else uiCount++;
+    }
+  }
+  return uiCount;
+}
+#endif
+
+extern       Char   g_aucConvertToBit  [ MAX_CU_SIZE+1 ];   // from width to log2(width)-2
+
+#if CAVLC_COEF_LRG_BLK
+/** Function for deriving codeword index in coding last significant position and level information.
+ * \param lev a value indicating coefficient level greater than one or not
+ * \param last_pos last significant coefficient position
+ * \param N block size
+ * \returns the codeword index
+ * This function derives codeword index in coding last significant position and level information in CAVLC. 
+ */
+__inline UInt xLastLevelInd(Int lev, Int last_pos, Int N)
+{
+  UInt cx;
+  UInt uiConvBit = g_aucConvertToBit[N]+2;
+
+  if (lev==0)
+  {
+    cx = ((last_pos + (last_pos>>uiConvBit))>>uiConvBit)+last_pos;
+  }
+  else
+  {
+    if (last_pos<N)
+    {
+      cx = (last_pos+1)<<uiConvBit;
+    }
+    else
+    {
+      cx = (0x01<<(uiConvBit<<1)) + last_pos;
+    }
+  }
+  return(cx);
+}
+
+__inline void xLastLevelIndInv(Int& lev, Int& last_pos, Int N, UInt cx)
+{
+  UInt uiConvBit = g_aucConvertToBit[N]+2;
+  Int N2 = 0x01<<(uiConvBit<<1);
+
+  if(cx <= N2+N)
+  {
+    if(cx && (cx&(N-1))==0)
+    {
+      lev = 1;
+      last_pos = (cx>>uiConvBit)-1;
+    }
+    else
+    {
+      lev = 0;
+      last_pos = cx - (cx>>uiConvBit);
+    }
+  }
+  else
+  {
+    lev = 1;
+    last_pos = cx - N2;
+  }
+}
+#endif
+
+
+#if CHROMA_CODEWORD_SWITCH 
+extern const UChar ChromaMapping[2][5];
+#endif
+
+#if ADD_PLANAR_MODE
+__inline Void mapPlanartoDC( UChar& curDir ) { curDir = (curDir == PLANAR_IDX) ? 2 : curDir; }
+__inline Void mapPlanartoDC(  UInt& curDir ) { curDir = (curDir == PLANAR_IDX) ? 2 : curDir; }
+__inline Void mapPlanartoDC(   Int& curDir ) { curDir = (curDir == PLANAR_IDX) ? 2 : curDir; }
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+__inline Void mapDMMtoDC( UChar& curDir ) { curDir = (curDir > MAX_MODE_ID_INTRA_DIR) ? 2 : curDir; }
+__inline Void mapDMMtoDC(  UInt& curDir ) { curDir = (curDir > MAX_MODE_ID_INTRA_DIR) ? 2 : curDir; }
+__inline Void mapDMMtoDC(   Int& curDir ) { curDir = (curDir > MAX_MODE_ID_INTRA_DIR) ? 2 : curDir; }
+#endif
+
+
+#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_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_T(x)
+#define DTRACE_CABAC_X(x)
+#define DTRACE_CABAC_R( x,y )
+#define DTRACE_CABAC_N
+
+#endif
+#if CAVLC_COUNTER_ADAPT
+/** Function for codeword adaptation
+ * \param uiCodeIdx codeword index of the syntax element being coded
+ * \param pucTableCounter pointer to counter array
+ * \param rucTableCounterSum sum counter
+ * \param puiTableD pointer to table mapping codeword index to syntax element value
+ * \param puiTableE pointer to table mapping syntax element value to codeword index
+ * \param uiCounterNum number of counters
+ * \returns
+ * This function performs codeword adaptation.
+*/
+__inline Void adaptCodeword( UInt uiCodeIdx, UChar * pucTableCounter, UChar & rucTableCounterSum, UInt * puiTableD, UInt * puiTableE, UInt uiCounterNum )
+{
+  Bool bSwapping  = false;
+  UInt uiCodeword = puiTableD [uiCodeIdx];
+
+  UInt uiPrevCodeIdx   = (uiCodeIdx >= 1)? uiCodeIdx - 1 : 0;
+  UInt uiPrevCodeword  = puiTableD[uiPrevCodeIdx];
+
+  if ( uiCodeIdx < uiCounterNum ) 
+  {
+    pucTableCounter [uiCodeIdx] ++;
+
+    if (pucTableCounter[uiCodeIdx] >= pucTableCounter[uiPrevCodeIdx])
+    {
+      bSwapping = true;
+      UChar ucTempCounter             = pucTableCounter[uiCodeIdx];
+      pucTableCounter[uiCodeIdx]      = pucTableCounter[uiPrevCodeIdx];
+      pucTableCounter[uiPrevCodeIdx]  = ucTempCounter;
+    }
+
+    if ( rucTableCounterSum >= 15 )
+    {
+      rucTableCounterSum = 0;
+      for (UInt uiIdx = 0; uiIdx < uiCounterNum; uiIdx++)
+      {
+        pucTableCounter[uiIdx] >>= 1;
+      }
+    }
+    else
+    {
+      rucTableCounterSum ++;
+    }
+  }
+  else
+  {
+    bSwapping = true;
+  }
+
+  if ( bSwapping )
+  {
+    puiTableD[uiPrevCodeIdx] = uiCodeword;
+    puiTableD[uiCodeIdx    ] = uiPrevCodeword;
+
+    if  (puiTableE != NULL)
+    {
+      puiTableE[uiCodeword]     = uiPrevCodeIdx;
+      puiTableE[uiPrevCodeword] = uiCodeIdx;
+    }
+  }
+}
+#endif
+#endif  //__TCOMROM__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComSlice.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComSlice.cpp	(revision 19)
@@ -0,0 +1,766 @@
+/* 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     TComSlice.cpp
+    \brief    slice header and SPS class
+*/
+
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComPic.h"
+
+TComSlice::TComSlice()
+{
+  m_uiPPSId             = 0;
+  m_iPOC                = 0;
+  m_eSliceType          = I_SLICE;
+  m_iSliceQp            = 0;
+  m_iSymbolMode         = 1;
+  m_aiNumRefIdx[0]      = 0;
+  m_aiNumRefIdx[1]      = 0;
+  m_bLoopFilterDisable  = false;
+  
+  m_iSliceQpDelta       = 0;
+  
+  m_iDepth              = 0;
+  
+  m_pcPic               = NULL;
+  m_bRefenced           = false;
+#ifdef ROUNDING_CONTROL_BIPRED
+  m_bRounding           = false;
+#endif
+  m_uiColDir = 0;
+  
+  m_iViewIdx = 0 ;
+
+  initEqualRef();
+  m_bNoBackPredFlag = false;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  m_bRefIdxCombineCoding = false;
+#endif
+#if DCM_COMB_LIST 
+  m_bRefPicListCombinationFlag = false;
+  m_bRefPicListModificationFlagLC = false;
+#endif
+  m_uiSliceCurStartCUAddr        = 0;
+  m_uiEntropySliceCurStartCUAddr = 0;
+
+  ::memset( m_aaiCodedScale,  0x00, sizeof( m_aaiCodedScale  ) );
+  ::memset( m_aaiCodedOffset, 0x00, sizeof( m_aaiCodedOffset ) );
+  m_pcTexturePic = NULL;
+#ifdef WEIGHT_PRED
+  resetWpScaling(m_weightPredTable);
+  initWpAcDcParam();
+#endif
+}
+
+TComSlice::~TComSlice()
+{
+}
+
+
+Void TComSlice::initSlice()
+{
+  m_aiNumRefIdx[0]      = 0;
+  m_aiNumRefIdx[1]      = 0;
+  
+  m_uiColDir = 0;
+
+  ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+  ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+  m_pcTexturePic = NULL;
+  
+  initEqualRef();
+  m_bNoBackPredFlag = false;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  m_bRefIdxCombineCoding = false;
+#endif
+#if DCM_COMB_LIST 
+  m_bRefPicListCombinationFlag = false;
+  m_bRefPicListModificationFlagLC = false;
+#endif
+}
+
+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);
+  }
+}
+
+Void TComSlice::setRefPOCList       ()
+{
+  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();
+    }
+  }
+
+}
+
+#if DCM_COMB_LIST 
+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]->getViewIdx() == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getViewIdx() ))
+          {
+            m_iRefIdxOfL1FromRefIdxOfL0[iNumRefIdx] = m_iRefIdxFromIdxOfLC[iRefIdxLC];
+            m_iRefIdxOfL0FromRefIdxOfL1[m_iRefIdxFromIdxOfLC[iRefIdxLC]] = iNumRefIdx;
+            bTempRefIdxInL2 = false;
+            assert(m_eListIdFromIdxOfLC[iRefIdxLC]==REF_PIC_LIST_1);
+            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]->getViewIdx() == m_apcRefPicList[m_eListIdFromIdxOfLC[iRefIdxLC]][m_iRefIdxFromIdxOfLC[iRefIdxLC]]->getViewIdx() ))
+          {
+            m_iRefIdxOfL0FromRefIdxOfL1[iNumRefIdx] = m_iRefIdxFromIdxOfLC[iRefIdxLC];
+            m_iRefIdxOfL1FromRefIdxOfL0[m_iRefIdxFromIdxOfLC[iRefIdxLC]] = iNumRefIdx;
+            bTempRefIdxInL2 = false;
+            assert(m_eListIdFromIdxOfLC[iRefIdxLC]==REF_PIC_LIST_0);
+            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]++;
+        }
+      }
+    }
+  }
+}
+#endif
+
+Void TComSlice::setRefPicListFromGOPSTring( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& rapcSpatRefPics )
+{
+
+  if (m_eSliceType == I_SLICE)
+  {
+    ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+    ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+
+    return;
+  }
+
+  sortPicList(rcListPic);
+  assert( m_eSliceType != P_SLICE || m_pcPic->getNumRefs( REF_PIC_LIST_1 ) == 0 );
+  for(Int iRefList = 0; iRefList<2; iRefList++ )
+  {
+    RefPicList eRefList = (RefPicList) iRefList;
+    m_aiNumRefIdx[eRefList] = m_pcPic->getNumRefs( eRefList );
+    for( Int i =0; i<m_pcPic->getNumRefs(eRefList); i++ )
+    {
+      const int iRefPoc = m_pcPic->getRefPOC( eRefList, i );
+      const int iRefViewIdx = m_pcPic->getRefViewIdx( eRefList, i );
+      m_aiRefPOCList[eRefList][i] = iRefPoc;
+      m_aiRefViewList[eRefList][i] = iRefViewIdx;
+
+      TComPic* pcRefPic = NULL;
+      if( iRefViewIdx == m_iViewIdx )
+      {
+        // temporal prediction from current view
+        for( TComList<TComPic*>::iterator it = rcListPic.begin(); it!=rcListPic.end(); it++)
+        {
+          if((*it)->getPOC() == iRefPoc)
+          {
+            pcRefPic = *it;
+            break;
+          }
+        }
+        assert( pcRefPic );
+        if( pcRefPic == NULL && iRefPoc > m_iPOC )
+        {
+          const int iAltRefPoc = m_iPOC-(iRefPoc-m_iPOC) ;
+          m_aiRefPOCList[eRefList][i] = iAltRefPoc ;
+          for( TComList<TComPic*>::iterator it = rcListPic.begin(); it!=rcListPic.end(); it++)
+          {
+            if((*it)->getPOC() == iAltRefPoc)
+            {
+              pcRefPic = *it ;
+              break;
+            }
+          }
+        }
+      }
+      else
+      {
+        // inter-view prediction
+        assert( iRefPoc == m_iPOC );
+        assert( 0 <= iRefViewIdx && iRefViewIdx < rapcSpatRefPics.size() );
+        pcRefPic = rapcSpatRefPics[iRefViewIdx];
+      }
+      if( pcRefPic )
+      {
+        m_apcRefPicList[eRefList][i] = pcRefPic;
+        pcRefPic->getPicYuvRec()->extendPicBorder();
+      }
+      else
+      {
+        printf("\n inconsistence in gop string!") ; // gop string inconsistent
+        assert(0) ;
+      }
+    }
+  }
+}
+Void TComSlice::setRefPicListExplicitlyDecoderSided( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& rapcSpatRefPics )
+{
+  sortPicList(rcListPic);
+  TComPic*  pcRefPic = NULL;
+
+  for(Int iRefList = 0; iRefList<2; iRefList++)
+  {
+    RefPicList eRefList = (RefPicList) iRefList;
+    for( Int i=0; i<m_aiNumRefIdx[eRefList]; i++ )
+    {
+      const int iRefPoc = m_aiRefPOCList[ eRefList][i ];
+      const int iRefViewIdx = m_aiRefViewList[ eRefList][i ];
+      if( iRefViewIdx == m_iViewIdx )
+      {
+        for( TComList<TComPic*>::iterator it = rcListPic.begin(); it!=rcListPic.end(); it++)
+        {
+          if((*it)->getPOC() == iRefPoc)
+          {
+            pcRefPic = *it;
+            break;
+          }
+        }
+      }
+      else
+      {
+        // inter-view prediction
+        assert( iRefPoc == m_iPOC );
+        assert( 0 <= iRefViewIdx && iRefViewIdx < rapcSpatRefPics.size() );
+        pcRefPic = rapcSpatRefPics[iRefViewIdx];
+      }
+      if( pcRefPic )
+      {
+        m_apcRefPicList[eRefList][i] = pcRefPic;
+        pcRefPic->getPicYuvRec()->extendPicBorder();
+      }
+      else
+      {
+        printf("\n inconsistence in gop string!") ; // gop string inconsistent
+        assert(0) ;
+      }
+    }
+  }
+}
+
+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 DCM_DECODING_REFRESH
+/** Function for marking the reference pictures when an IDR and CDR is encountered.
+ * \param uiPOCCDR POC of the CDR 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 CDR case (non CDR 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 CDR picture (uiPOCCDR), 
+ *    mark all reference pictures except the latest CDR picture as "unused for reference" and set 
+ *    the bRefreshPending flag to false.
+ *    If the nal_unit_type is CDR, set the bRefreshPending flag to true and iPOCCDR 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(UInt& uiPOCCDR, Bool& bRefreshPending, TComList<TComPic*>& rcListPic)
+{
+  TComPic*                 rpcPic;
+  UInt uiPOCCurr = getPOC(); 
+
+  if (getNalUnitType() == 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 // CDR or No DR
+  {
+    if (bRefreshPending==true && uiPOCCurr > uiPOCCDR) // CDR reference marking pending 
+    {
+      TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+      while (iterPic != rcListPic.end())
+      {
+        rpcPic = *(iterPic);
+        if (rpcPic->getPOC() != uiPOCCurr && rpcPic->getPOC() != uiPOCCDR) rpcPic->getSlice(0)->setReferenced(false);
+        iterPic++;
+      }
+      bRefreshPending = false; 
+    }
+    if (getNalUnitType() == NAL_UNIT_CODED_SLICE_CDR) // CDR picture found
+    {
+      bRefreshPending = true; 
+      uiPOCCDR = uiPOCCurr;
+    }
+  }
+}
+#endif
+
+Void TComSlice::copySliceInfo(TComSlice *pSrc)
+{
+  assert( pSrc != NULL );
+
+  Int i, j, k;
+
+  m_iPOC                 = pSrc->m_iPOC;
+  m_iViewIdx             = pSrc->m_iViewIdx;
+#if DCM_DECODING_REFRESH
+  m_eNalUnitType         = pSrc->m_eNalUnitType;
+#endif  
+  m_eSliceType           = pSrc->m_eSliceType;
+  m_iSliceQp             = pSrc->m_iSliceQp;
+  m_iSymbolMode          = pSrc->m_iSymbolMode;
+  m_bLoopFilterDisable   = pSrc->m_bLoopFilterDisable;
+  
+#if DCM_COMB_LIST  
+  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;
+#else
+  for (i = 0; i < 2; i++)
+  {
+    m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
+  }
+#endif  
+
+  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_aiRefViewList[i][j]  = pSrc->m_aiRefViewList[i][j];
+    }
+  }  
+  m_iDepth               = pSrc->m_iDepth;
+
+  // referenced slice
+  m_bRefenced            = pSrc->m_bRefenced;
+#ifdef ROUNDING_CONTROL_BIPRED
+  m_bRounding            = pSrc->m_bRounding;
+#endif
+
+  // access channel
+  m_pcSPS                = pSrc->m_pcSPS;
+  m_pcPPS                = pSrc->m_pcPPS;
+  m_uiPPSId              = pSrc->m_uiPPSId;
+  m_pcPic                = pSrc->m_pcPic;
+
+  m_uiColDir             = pSrc->m_uiColDir;
+  m_dLambda              = pSrc->m_dLambda;
+  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;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  m_bRefIdxCombineCoding = pSrc->m_bRefIdxCombineCoding;
+#endif
+  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;
+#ifdef WEIGHT_PRED
+  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 );
+#endif
+}
+
+#ifdef WEIGHT_PRED
+Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, wpScalingParam *&wp )
+{
+  wp = m_weightPredTable[e][iRefIdx];
+}
+
+Void  TComSlice::displayWpScaling()
+{
+  Bool  bFound = false;
+  for ( int e=0 ; e<2 ; e++ ) {
+    for ( int i=0 ; i<MAX_NUM_REF ; i++ )
+    for ( int yuv=0 ; yuv<3 ; yuv++ )
+      if ( m_weightPredTable[e][i][yuv].bPresentFlag ) {
+        if ( !bFound ) {
+          printf("\tluma_log2_weight_denom = %d\n",   m_weightPredTable[0][0][0].uiLog2WeightDenom);
+          printf("\tchroma_log2_weight_denom = %d\n", m_weightPredTable[0][0][1].uiLog2WeightDenom);
+          bFound = true;
+        }
+        Double  weight = (Double)m_weightPredTable[e][i][yuv].iWeight / (Double)(1<<m_weightPredTable[0][0][0].uiLog2WeightDenom);
+        if ( yuv == 0 ) {
+          printf("\tluma_weight_l%d_flag = 1\n", e);
+          printf("\t luma_weight_l%d[%d] = %d => w = %g\n", e, i, m_weightPredTable[e][i][yuv].iWeight, weight);
+          printf("\t luma_offset_l%d[%d] = %d\n", e, i, m_weightPredTable[e][i][yuv].iOffset);
+        }
+        else {
+          if ( yuv == 1 ) printf("\tchroma_weight_l%d_flag = 1\n", e);
+          printf("\t chroma_weight_l%d[%d][%d] = %d => w = %g\n", e, i, yuv-1, m_weightPredTable[e][i][yuv].iWeight, weight);
+          printf("\t chroma_offset_l%d[%d][%d] = %d\n", e, i, yuv-1, m_weightPredTable[e][i][yuv].iOffset);
+        }
+      }
+  }
+}
+
+// Default WP values settings : no weight. 
+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;
+      }
+  }
+}
+
+Void  TComSlice::initWpScaling()
+{
+  initWpScaling(m_weightPredTable);
+}
+
+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);
+      }
+  }
+}
+#endif
+
+#ifdef WEIGHT_PRED
+Void  TComSlice::getWpAcDcParam(wpACDCParam *&wp)
+{
+  wp = m_weightACDCParam;
+}
+
+Void  TComSlice::initWpAcDcParam()
+{
+  for(Int iComp = 0; iComp < 3; iComp++ )
+  {
+    m_weightACDCParam[iComp].iAC = 0;
+    m_weightACDCParam[iComp].iDC = 0;
+  }
+}
+#endif
+
+// ------------------------------------------------------------------------------------------------
+// Sequence parameter set (SPS)
+// ------------------------------------------------------------------------------------------------
+
+TComSPS::TComSPS()
+{
+  // Structure
+  m_uiSPSId       = 0;
+  m_uiWidth       = 352;
+  m_uiHeight      = 288;
+  m_uiMaxCUWidth  = 32;
+  m_uiMaxCUHeight = 32;
+  m_uiMaxCUDepth  = 3;
+  m_uiMinTrDepth  = 0;
+  m_uiMaxTrDepth  = 1;
+  m_uiMaxTrSize   = 32;
+  
+  // Tool list
+  m_bUseALF       = false;
+  m_bUseDQP       = false;
+  
+  m_bUseMRG      = false; // SOPH:
+#if HHI_MPI
+  m_bUseMVI = false;
+#endif
+  
+  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 HHI_INTER_VIEW_MOTION_PRED
+  m_uiMultiviewMvPredMode    = 0;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_uiMultiviewResPredMode   = 0;
+#endif
+
+  // AMVP parameter
+  ::memset( m_aeAMVPMode, 0, sizeof( m_aeAMVPMode ) );
+  m_bUseDMM = false;
+}
+
+TComSPS::~TComSPS()
+{
+}
+
+TComPPS::TComPPS()
+{
+#if CONSTRAINED_INTRA_PRED
+  m_bConstrainedIntraPred = false;
+#endif
+  m_uiSPSId = 0;
+  m_uiPPSId = 0;
+}
+
+TComPPS::~TComPPS()
+{
+}
+
+Void
+TComSPS::initMultiviewSPS( UInt uiViewId, Int iViewOrderIdx, UInt uiCamParPrecision, Bool bCamParSlice, Int** aaiScale, Int** aaiOffset )
+{
+  AOT( uiViewId == 0 && iViewOrderIdx != 0 );
+  AOT( uiViewId != 0 && iViewOrderIdx == 0 );
+  AOT( uiViewId != 0 && !bCamParSlice && ( aaiScale == 0 || aaiOffset == 0 ) );
+
+  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( !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 ];
+    }
+  }
+}
+
+Void
+TComSPS::initMultiviewSPSDepth( UInt uiViewId, Int iViewOrderIdx )
+{
+  AOT( uiViewId == 0 && iViewOrderIdx != 0 );
+  AOT( uiViewId != 0 && iViewOrderIdx == 0 );
+
+  m_uiViewId              = uiViewId;
+  m_iViewOrderIdx         = iViewOrderIdx;
+  m_bDepth                = true;
+  m_uiCamParPrecision     = 0;
+  m_bCamParInSliceHeader  = false;
+  ::memset( m_aaiCodedScale,  0x00, sizeof( m_aaiCodedScale  ) );
+  ::memset( m_aaiCodedOffset, 0x00, sizeof( m_aaiCodedOffset ) );
+}
+
+
+#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 HHI_INTER_VIEW_MOTION_PRED
+  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
Index: /tags/0.2r1/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComSlice.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComSlice.h	(revision 19)
@@ -0,0 +1,621 @@
+/* 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     TComSlice.h
+    \brief    slice header and SPS class (header)
+*/
+
+#ifndef __TCOMSLICE__
+#define __TCOMSLICE__
+
+
+#include "CommonDef.h"
+#ifdef WEIGHT_PRED
+  #include <string.h>	// To avoid compilation failure with some g++ linux compilators...
+#endif
+#include "TComList.h"
+#include <math.h>
+
+class TComPic;
+#if DEPTH_MAP_GENERATION
+class TComDepthMapGenerator;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+class TComResidualGenerator;
+#endif
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// SPS class
+class TComSPS
+{
+private:
+  // Structure
+  UInt        m_uiSPSId;
+  UInt        m_uiWidth;
+  UInt        m_uiHeight;
+  Int         m_aiPad[2];
+  UInt        m_uiMaxCUWidth;
+  UInt        m_uiMaxCUHeight;
+  UInt        m_uiMaxCUDepth;
+  UInt        m_uiMinTrDepth;
+  UInt        m_uiMaxTrDepth;
+
+  UInt        m_uiViewId;
+  Int         m_iViewOrderIdx;
+  Bool        m_bDepth;
+  UInt        m_uiCamParPrecision;
+  Bool        m_bCamParInSliceHeader;
+  Int         m_aaiCodedScale [2][MAX_NUMBER_VIEWS];
+  Int         m_aaiCodedOffset[2][MAX_NUMBER_VIEWS];
+
+  // Tool list
+  UInt        m_uiQuadtreeTULog2MaxSize;
+  UInt        m_uiQuadtreeTULog2MinSize;
+  UInt        m_uiQuadtreeTUMaxDepthInter;
+  UInt        m_uiQuadtreeTUMaxDepthIntra;
+  Bool        m_bUseALF;
+  Bool        m_bUseDQP;
+#if !HHI_NO_LowDelayCoding
+  Bool        m_bUseLDC;
+#endif
+  Bool        m_bUsePAD;
+  Bool        m_bUseMRG; // SOPH:
+
+#if LM_CHROMA
+  Bool        m_bUseLMChroma; // JL:
+#endif
+
+#if DCM_COMB_LIST
+  Bool        m_bUseLComb;
+  Bool        m_bLCMod;
+#endif
+
+#if HHI_RMP_SWITCH
+  Bool        m_bUseRMP;
+#endif
+  // Parameter
+  AMVP_MODE   m_aeAMVPMode[MAX_CU_DEPTH];
+  UInt        m_uiBitDepth;
+  UInt        m_uiBitIncrement;
+
+  // Max physical transform size
+  UInt        m_uiMaxTrSize;
+
+  Int m_iAMPAcc[MAX_CU_DEPTH];
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  Bool        m_bLFCrossSliceBoundaryFlag;
+#endif
+#if MTK_SAO
+  Bool        m_bUseSAO;
+#endif
+#if HHI_MPI
+  Bool        m_bUseMVI;
+#endif
+
+  UInt m_uiCodedPictureBufferSize ;
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool  m_bUseDMM;
+#endif
+
+#if DEPTH_MAP_GENERATION
+  UInt  m_uiPredDepthMapGeneration;
+  UInt  m_uiPdmPrecision;
+  Int   m_aiPdmScaleNomDelta[MAX_NUMBER_VIEWS];
+  Int   m_aiPdmOffset       [MAX_NUMBER_VIEWS];
+#endif
+#if HHI_INTER_VIEW_MOTION_PRED
+  UInt  m_uiMultiviewMvPredMode;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  UInt  m_uiMultiviewResPredMode;
+#endif
+
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator* m_pcDepthMapGenerator;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  TComResidualGenerator* m_pcResidualGenerator;
+#endif
+
+public:
+  TComSPS();
+  virtual ~TComSPS();
+
+  // structure
+  Void setSPSId       ( UInt u ) { m_uiSPSId = u;           }
+  UInt getSPSId       ()         { return m_uiSPSId;        }
+  Void setWidth       ( UInt u ) { m_uiWidth = u;           }
+  UInt getWidth       ()         { return  m_uiWidth;       }
+  Void setHeight      ( UInt u ) { m_uiHeight = u;          }
+  UInt getHeight      ()         { return  m_uiHeight;      }
+  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 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 setPad         (Int iPad[2]) { m_aiPad[0] = iPad[0]; m_aiPad[1] = iPad[1]; }
+  Void setPadX        ( Int  u ) { m_aiPad[0] = u; }
+  Void setPadY        ( Int  u ) { m_aiPad[1] = u; }
+  Int  getPad         ( Int  u ) { assert(u < 2); return m_aiPad[u];}
+  Int* getPad         ( )        { return m_aiPad; }
+
+  Void        initMultiviewSPS      ( UInt uiViewId, Int iViewOrderIdx = 0, UInt uiCamParPrecision = 0, Bool bCamParSlice = false, Int** aaiScale = 0, Int** aaiOffset = 0 );
+  Void        initMultiviewSPSDepth ( UInt uiViewId, Int iViewOrderIdx );
+
+  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]; }
+
+  // physical transform
+  Void setMaxTrSize   ( UInt u ) { m_uiMaxTrSize = u;       }
+  UInt getMaxTrSize   ()         { return  m_uiMaxTrSize;   }
+
+  // Tool list
+  Bool getUseALF      ()         { return m_bUseALF;        }
+  Bool getUseDQP      ()         { return m_bUseDQP;        }
+
+#if !HHI_NO_LowDelayCoding
+  Bool getUseLDC      ()         { return m_bUseLDC;        }
+#endif
+  Bool getUsePAD      ()         { return m_bUsePAD;        }
+  Bool getUseMRG      ()         { return m_bUseMRG;        } // SOPH:
+
+  Void setUseALF      ( Bool b ) { m_bUseALF  = b;          }
+  Void setUseDQP      ( Bool b ) { m_bUseDQP   = b;         }
+
+#if !HHI_NO_LowDelayCoding
+  Void setUseLDC      ( Bool b ) { m_bUseLDC   = b;         }
+#endif
+  Void setUsePAD      ( Bool b ) { m_bUsePAD   = b;         }
+  Void setUseMRG      ( Bool b ) { m_bUseMRG  = b;          } // SOPH:
+  
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool getUseDMM()         { return m_bUseDMM; }
+  Void setUseDMM( Bool b ) { m_bUseDMM = b;    }
+#endif
+
+
+#if DCM_COMB_LIST
+  Void setUseLComb    (Bool b)   { m_bUseLComb = b;         }
+  Bool getUseLComb    ()         { return m_bUseLComb;      }
+  Void setLCMod       (Bool b)   { m_bLCMod = b;     }
+  Bool getLCMod       ()         { return m_bLCMod;  }
+#endif
+
+#if HHI_RMP_SWITCH
+  Bool getUseRMP     ()         { return m_bUseRMP; }
+  Void setUseRMP     ( Bool b ) { m_bUseRMP = b;    }
+#endif
+
+#if LM_CHROMA
+  Bool getUseLMChroma ()         { return m_bUseLMChroma;        }
+  Void setUseLMChroma ( Bool b ) { m_bUseLMChroma  = b;          }
+#endif
+
+  // 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; }
+
+  // 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;    }
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  Void      setLFCrossSliceBoundaryFlag     ( Bool   bValue  )    { m_bLFCrossSliceBoundaryFlag = bValue; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                    { return m_bLFCrossSliceBoundaryFlag;   }
+#endif
+
+#if MTK_SAO
+  Void setUseSAO                  (Bool bVal)  {m_bUseSAO = bVal;}
+  Bool getUseSAO                  ()           {return m_bUseSAO;}
+#endif
+
+#if HHI_MPI
+  Void setUseMVI                  (Bool bVal)  {m_bUseMVI = bVal;}
+  Bool getUseMVI                  ()           {return m_bUseMVI;}
+#endif
+
+  Void      setCodedPictureBufferSize( UInt u ) { m_uiCodedPictureBufferSize = u ;}
+  UInt      getCodedPictureBufferSize( )        { return m_uiCodedPictureBufferSize ;}
+
+#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 HHI_INTER_VIEW_RESIDUAL_PRED
+  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 HHI_INTER_VIEW_MOTION_PRED
+  UInt  getMultiviewMvPredMode   ()          { return m_uiMultiviewMvPredMode;    }
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  UInt  getMultiviewResPredMode  ()          { return m_uiMultiviewResPredMode;   }
+#endif
+
+#if DEPTH_MAP_GENERATION
+  Void                    setDepthMapGenerator( TComDepthMapGenerator* pcDepthMapGenerator )  { m_pcDepthMapGenerator = pcDepthMapGenerator; }
+  TComDepthMapGenerator*  getDepthMapGenerator()                                              { return m_pcDepthMapGenerator; }
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Void                    setResidualGenerator( TComResidualGenerator* pcResidualGenerator )  { m_pcResidualGenerator = pcResidualGenerator; }
+  TComResidualGenerator*  getResidualGenerator()                                              { return m_pcResidualGenerator; }
+#endif
+};
+
+/// PPS class
+class TComPPS
+{
+private:
+#if CONSTRAINED_INTRA_PRED
+  Bool        m_bConstrainedIntraPred;    //  constrained_intra_pred_flag
+#endif
+#ifdef WEIGHT_PRED
+  Bool        m_bUseWeightPred;           // Use of Weighting Prediction (P_SLICE)
+  UInt        m_uiBiPredIdc;              // Use of Weighting Bi-Prediction (B_SLICE)
+#endif
+  UInt        m_uiPPSId;
+  UInt        m_uiSPSId;
+
+public:
+  TComPPS();
+  virtual ~TComPPS();
+
+  Void      setPPSId                ( UInt u ) { m_uiPPSId = u; }
+  UInt      getPPSId                ()         { return m_uiPPSId; }
+  Void      setSPSId                ( UInt u ) { m_uiSPSId = u; }
+  UInt      getSPSId                ()         { return m_uiSPSId; }
+#if CONSTRAINED_INTRA_PRED
+  Bool      getConstrainedIntraPred ()         { return  m_bConstrainedIntraPred; }
+  Void      setConstrainedIntraPred ( Bool b ) { m_bConstrainedIntraPred = b;     }
+#endif
+
+#ifdef WEIGHT_PRED
+  Bool getUseWP                     ()          { return m_bUseWeightPred;      }
+  UInt getWPBiPredIdc               ()          { return m_uiBiPredIdc;         }
+
+  Void setUseWP                     ( Bool b )  { m_bUseWeightPred = b;       }
+  Void setWPBiPredIdc               ( UInt u )  { m_uiBiPredIdc = u;          }
+#endif
+};
+
+#ifdef WEIGHT_PRED
+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;
+#endif
+
+/// slice header class
+class TComSlice
+{
+
+private:
+  //  Bitstream writing
+  UInt        m_uiPPSId;
+  Int         m_iPOC;
+#if DCM_DECODING_REFRESH
+  NalUnitType m_eNalUnitType;         ///< Nal unit type for the slice
+#endif
+  SliceType   m_eSliceType;
+  Int         m_iSliceQp;
+  Int         m_iSymbolMode;
+  Bool        m_bLoopFilterDisable;
+
+#if DCM_COMB_LIST
+  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;
+#else
+  Int         m_aiNumRefIdx   [2];    //  for multiple reference of current slice
+#endif
+
+  //  Data
+  Int         m_iSliceQpDelta;
+  TComPic*    m_apcRefPicList [2][MAX_NUM_REF];
+  Int         m_aiRefPOCList  [2][MAX_NUM_REF];
+  Int         m_iDepth;
+  TComPic*    m_pcTexturePic;
+
+  // referenced slice?
+  Bool        m_bRefenced;
+#ifdef ROUNDING_CONTROL_BIPRED
+  Bool        m_bRounding;
+#endif
+
+  // access channel
+  TComSPS*    m_pcSPS;
+  TComPPS*    m_pcPPS;
+  TComPic*    m_pcPic;
+
+  UInt        m_uiColDir;  // direction to get colocated CUs
+
+  Double      m_dLambda;
+
+  Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
+
+  Int         m_iViewIdx;
+  Int         m_aiRefViewList[2][MAX_INPUT_VIEW_NUM];
+
+  Bool        m_bNoBackPredFlag;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  Bool        m_bRefIdxCombineCoding;
+#endif
+
+  Int         m_aaiCodedScale [2][MAX_NUMBER_VIEWS];
+  Int         m_aaiCodedOffset[2][MAX_NUMBER_VIEWS];
+
+  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;
+
+#ifdef WEIGHT_PRED
+  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]
+#endif
+
+public:
+  TComSlice();
+  virtual ~TComSlice();
+
+  Void      initSlice       ();
+
+  Void      setSPS          ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
+  TComSPS*  getSPS          () { return m_pcSPS; }
+
+  Void      setPPS          ( TComPPS* pcPPS ) { m_pcPPS = pcPPS; }
+  TComPPS*  getPPS          () { return m_pcPPS; }
+
+  UInt      getPPSId        ()                          { return  m_uiPPSId;            }
+  SliceType getSliceType    ()                          { return  m_eSliceType;         }
+  Int       getPOC          ()                          { return  m_iPOC;           }
+  Int       getSliceQp      ()                          { return  m_iSliceQp;           }
+  Int       getSliceQpDelta ()                          { return  m_iSliceQpDelta;      }
+  Int       getSymbolMode   ()                          { return  m_iSymbolMode;        }
+  Bool      getLoopFilterDisable()                      { return  m_bLoopFilterDisable; }
+  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       getDepth            ()                              { return  m_iDepth;                     }
+  UInt      getColDir           ()                              { return  m_uiColDir;                   }
+
+#if DCM_COMB_LIST
+  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;}
+#endif
+
+  Void      setReferenced(Bool b)                               { m_bRefenced = b; }
+  Bool      isReferenced()                                      { return m_bRefenced; }
+#ifdef ROUNDING_CONTROL_BIPRED
+  Void      setRounding(Bool bRound)                            { m_bRounding = bRound; }
+  Bool      isRounding()                                        { return m_bRounding; }
+#endif
+
+  Void      setPPSId            ( UInt u )                      { m_uiPPSId           = u;      }
+  Void      setPOC              ( Int i )                       { m_iPOC              = i;      }
+#if DCM_DECODING_REFRESH
+  Void      setNalUnitType      ( NalUnitType e )               { m_eNalUnitType      = e;      }
+  NalUnitType getNalUnitType    ()                              { return m_eNalUnitType;        }
+  Void      decodingRefreshMarking(UInt& uiPOCCDR, Bool& bRefreshPending, TComList<TComPic*>& rcListPic);
+#endif
+  Void      setSliceType        ( SliceType e )                 { m_eSliceType        = e;      }
+  Void      setSliceQp          ( Int i )                       { m_iSliceQp          = i;      }
+  Void      setSliceQpDelta     ( Int i )                       { m_iSliceQpDelta     = i;      }
+  Void      setSymbolMode       ( Int b  )                      { m_iSymbolMode       = b;      }
+  Void      setLoopFilterDisable( Bool b )                      { m_bLoopFilterDisable= b;      }
+
+  Void      setRefPic           ( TComPic* p, RefPicList e, Int iRefIdx ) { m_apcRefPicList[e][iRefIdx] = p; }
+  Void      setRefPOC           ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefPOCList[e][iRefIdx] = i; }
+  Void      setNumRefIdx        ( RefPicList e, Int i )         { m_aiNumRefIdx[e]    = i;      }
+  Void      setPic              ( TComPic* p )                  { m_pcPic             = p;      }
+  Void      setDepth            ( Int iDepth )                  { m_iDepth            = iDepth; }
+
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic );
+  Void      setRefPOCList       ();
+  Void      setColDir           ( UInt uiDir ) { m_uiColDir = uiDir; }
+
+  Void      setRefPicListFromGOPSTring( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& rapcSpatRefPics );
+  Void      setRefPicListExplicitlyDecoderSided( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& rapcSpatRefPics );
+
+  Bool      isIntra         ()                          { return  m_eSliceType == I_SLICE;  }
+  Bool      isInterB        ()                          { return  m_eSliceType == B_SLICE;  }
+  Bool      isInterP        ()                          { return  m_eSliceType == P_SLICE;  }
+
+  Void      setLambda( Double d ) { m_dLambda = d; }
+  Double    getLambda() { return m_dLambda;        }
+
+  Void      setViewIdx(Int i)                           { m_iViewIdx = i; }
+  Int       getViewIdx()                                { return m_iViewIdx; }
+
+  Void      setRefViewIdx       ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefViewList[e][iRefIdx] = i; }
+  Int       getRefViewIdx       ( RefPicList e, Int iRefIdx)    { return  m_aiRefViewList[e][iRefIdx]; }
+
+  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; }
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  Bool getRefIdxCombineCoding() { return m_bRefIdxCombineCoding; }
+  Void setRefIdxCombineCoding( Bool b ) { m_bRefIdxCombineCoding = b; }
+#endif
+#if DCM_COMB_LIST
+  Void      generateCombinedList       ();
+#endif
+  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      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]; }
+
+  Void setTexturePic( TComPic *pcTexturePic ) { m_pcTexturePic = pcTexturePic; }
+  TComPic *getTexturePic() const { return m_pcTexturePic; }
+
+#ifdef WEIGHT_PRED
+  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  displayWpScaling();
+  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();
+#endif
+
+protected:
+#if 0
+  TComPic*  xGetRefPic  (TComList<TComPic*>& rcListPic,
+                         Bool                bDRBFlag,
+                         ERBIndex            eERBIndex,
+                         UInt                uiPOCCurr,
+                         RefPicList          eRefPicList,
+                         UInt                uiNthRefPic );
+#endif
+
+};// END CLASS DEFINITION TComSlice
+
+
+#endif // __TCOMSLICE__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 19)
@@ -0,0 +1,6387 @@
+/* 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     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"
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define RDOQ_CHROMA                 1           ///< use of RDOQ in chroma
+
+#define DQ_BITS                     6
+#define Q_BITS_8                    16
+#define SIGN_BITS                   1
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// RDOQ parameter
+Int entropyBits[128]=
+{
+  895,    943,    994,   1048,   1105,   1165,   1228,   1294,
+  1364,   1439,   1517,   1599,   1686,   1778,   1875,   1978,
+  2086,   2200,   2321,   2448,   2583,   2725,   2876,   3034,
+  3202,   3380,   3568,   3767,   3977,   4199,   4435,   4684,
+  4948,   5228,   5525,   5840,   6173,   6527,   6903,   7303,
+  7727,   8178,   8658,   9169,   9714,  10294,  10914,  11575,
+  12282,  13038,  13849,  14717,  15650,  16653,  17734,  18899,
+  20159,  21523,  23005,  24617,  26378,  28306,  30426,  32768,
+  32768,  35232,  37696,  40159,  42623,  45087,  47551,  50015,
+  52479,  54942,  57406,  59870,  62334,  64798,  67262,  69725,
+  72189,  74653,  77117,  79581,  82044,  84508,  86972,  89436,
+  91900,  94363,  96827,  99291, 101755, 104219, 106683, 109146,
+  111610, 114074, 116538, 119002, 121465, 123929, 126393, 128857,
+  131321, 133785, 136248, 138712, 141176, 143640, 146104, 148568,
+  151031, 153495, 155959, 158423, 160887, 163351, 165814, 168278,
+  170742, 173207, 175669, 178134, 180598, 183061, 185525, 187989
+};
+
+static const Int estErr4x4[6][4][4]=
+{
+  {
+    {25600, 27040, 25600, 27040},
+    {27040, 25600, 27040, 25600},
+    {25600, 27040, 25600, 27040},
+    {27040, 25600, 27040, 25600}
+  },
+  {
+    {30976, 31360, 30976, 31360},
+    {31360, 32400, 31360, 32400},
+    {30976, 31360, 30976, 31360},
+    {31360, 32400, 31360, 32400}
+  },
+  {
+    {43264, 40960, 43264, 40960},
+    {40960, 40000, 40960, 40000},
+    {43264, 40960, 43264, 40960},
+    {40960, 40000, 40960, 40000}
+  },
+  {
+    {50176, 51840, 50176, 51840},
+    {51840, 52900, 51840, 52900},
+    {50176, 51840, 50176, 51840},
+    {51840, 52900, 51840, 52900}
+  },
+  {
+    {65536, 64000, 65536, 64000},
+    {64000, 62500, 64000, 62500},
+    {65536, 64000, 65536, 64000},
+    {64000, 62500, 64000, 62500}
+  },
+  {
+    {82944, 84640, 82944, 84640},
+    {84640, 84100, 84640, 84100},
+    {82944, 84640, 82944, 84640},
+    {84640, 84100, 84640, 84100}
+  }
+};
+
+static const Int estErr8x8[6][8][8]={
+  {
+    {6553600, 6677056, 6400000, 6677056, 6553600, 6677056, 6400000, 6677056},
+    {6677056, 6765201, 6658560, 6765201, 6677056, 6765201, 6658560, 6765201},
+    {6400000, 6658560, 6553600, 6658560, 6400000, 6658560, 6553600, 6658560},
+    {6677056, 6765201, 6658560, 6765201, 6677056, 6765201, 6658560, 6765201},
+    {6553600, 6677056, 6400000, 6677056, 6553600, 6677056, 6400000, 6677056},
+    {6677056, 6765201, 6658560, 6765201, 6677056, 6765201, 6658560, 6765201},
+    {6400000, 6658560, 6553600, 6658560, 6400000, 6658560, 6553600, 6658560},
+    {6677056, 6765201, 6658560, 6765201, 6677056, 6765201, 6658560, 6765201}
+  },
+  {
+    {7929856, 8156736, 8028160, 8156736, 7929856, 8156736, 8028160, 8156736},
+    {8156736, 7537770, 7814560, 7537770, 8156736, 7537770, 7814560, 7537770},
+    {8028160, 7814560, 7840000, 7814560, 8028160, 7814560, 7840000, 7814560},
+    {8156736, 7537770, 7814560, 7537770, 8156736, 7537770, 7814560, 7537770},
+    {7929856, 8156736, 8028160, 8156736, 7929856, 8156736, 8028160, 8156736},
+    {8156736, 7537770, 7814560, 7537770, 8156736, 7537770, 7814560, 7537770},
+    {8028160, 7814560, 7840000, 7814560, 8028160, 7814560, 7840000, 7814560},
+    {8156736, 7537770, 7814560, 7537770, 8156736, 7537770, 7814560, 7537770}
+  },
+  {
+    {11075584, 10653696, 11151360, 10653696, 11075584, 10653696, 11151360, 10653696},
+    {10653696, 11045652, 11109160, 11045652, 10653696, 11045652, 11109160, 11045652},
+    {11151360, 11109160, 11289600, 11109160, 11151360, 11109160, 11289600, 11109160},
+    {10653696, 11045652, 11109160, 11045652, 10653696, 11045652, 11109160, 11045652},
+    {11075584, 10653696, 11151360, 10653696, 11075584, 10653696, 11151360, 10653696},
+    {10653696, 11045652, 11109160, 11045652, 10653696, 11045652, 11109160, 11045652},
+    {11151360, 11109160, 11289600, 11109160, 11151360, 11109160, 11289600, 11109160},
+    {10653696, 11045652, 11109160, 11045652, 10653696, 11045652, 11109160, 11045652}
+  },
+  {
+    {12845056, 12503296, 12544000, 12503296, 12845056, 12503296, 12544000, 12503296},
+    {12503296, 13050156, 12588840, 13050156, 12503296, 13050156, 12588840, 13050156},
+    {12544000, 12588840, 12960000, 12588840, 12544000, 12588840, 12960000, 12588840},
+    {12503296, 13050156, 12588840, 13050156, 12503296, 13050156, 12588840, 13050156},
+    {12845056, 12503296, 12544000, 12503296, 12845056, 12503296, 12544000, 12503296},
+    {12503296, 13050156, 12588840, 13050156, 12503296, 13050156, 12588840, 13050156},
+    {12544000, 12588840, 12960000, 12588840, 12544000, 12588840, 12960000, 12588840},
+    {12503296, 13050156, 12588840, 13050156, 12503296, 13050156, 12588840, 13050156}
+  },
+  {
+    {16777216, 16646400, 16384000, 16646400, 16777216, 16646400, 16384000, 16646400},
+    {16646400, 16370116, 16692640, 16370116, 16646400, 16370116, 16692640, 16370116},
+    {16384000, 16692640, 16646400, 16692640, 16384000, 16692640, 16646400, 16692640},
+    {16646400, 16370116, 16692640, 16370116, 16646400, 16370116, 16692640, 16370116},
+    {16777216, 16646400, 16384000, 16646400, 16777216, 16646400, 16384000, 16646400},
+    {16646400, 16370116, 16692640, 16370116, 16646400, 16370116, 16692640, 16370116},
+    {16384000, 16692640, 16646400, 16692640, 16384000, 16692640, 16646400, 16692640},
+    {16646400, 16370116, 16692640, 16370116, 16646400, 16370116, 16692640, 16370116}
+  },
+  {
+    {21233664, 21381376, 21667840, 21381376, 21233664, 21381376, 21667840, 21381376},
+    {21381376, 21381376, 21374440, 21381376, 21381376, 21381376, 21374440, 21381376},
+    {21667840, 21374440, 21529600, 21374440, 21667840, 21374440, 21529600, 21374440},
+    {21381376, 21381376, 21374440, 21381376, 21381376, 21381376, 21374440, 21381376},
+    {21233664, 21381376, 21667840, 21381376, 21233664, 21381376, 21667840, 21381376},
+    {21381376, 21381376, 21374440, 21381376, 21381376, 21381376, 21374440, 21381376},
+    {21667840, 21374440, 21529600, 21374440, 21667840, 21374440, 21529600, 21374440},
+    {21381376, 21381376, 21374440, 21381376, 21381376, 21381376, 21374440, 21381376}
+  }
+};
+
+#if QC_MOD_LCEC
+#if CAVLC_COEF_LRG_BLK
+  static const int VLClength[14][128] = {
+#else
+  static const int VLClength[13][128] = {
+#endif
+    { 1, 2, 3, 4, 5, 6, 7, 9, 9,11,11,11,11,13,13,13,13,13,13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19},
+    { 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,10,10,10,10,12,12,12,12,12,12,12,12,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18},
+    { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,11,11,11,11,11,11,11,11,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17},
+    { 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16},
+    { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13},
+    { 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,43,43,44,44,45,45,46,46,47,47,48,48,49,49,50,50,51,51,52,52,53,53,54,54,55,55,56,56,57,57,58,58,59,59,60,60,61,61,62,62,63,63,64,64,65,65},
+    { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,14,15,15,15,15,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,22,22,22,22,23,23,23,23,24,24,24,24,25,25,25,25,26,26,26,26,27,27,27,27,28,28,28,28,29,29,29,29,30,30,30,30,31,31,31,31,32,32,32,32,33,33,33,33,34,34,34,34},
+    { 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19},
+    { 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+    { 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13},
+    { 1, 3, 3, 5, 5, 5, 5, 7, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,15},
+
+    { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
+    { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}
+#if CAVLC_COEF_LRG_BLK
+    ,{ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}
+#endif
+  };
+#endif
+static const Int estErr16x16[6] = { 25329, 30580, 42563, 49296, 64244, 82293 };
+static const Int estErr32x32[6] = { 25351, 30674, 42843, 49687, 64898, 82136 };
+
+// ====================================================================================================================
+// Qp class member functions
+// ====================================================================================================================
+
+QpParam::QpParam()
+{
+}
+
+Void QpParam::initOffsetParam( Int iStartQP, Int iEndQP )
+{
+  Int iDefaultOffset;
+  Int iDefaultOffset_LTR;
+  
+  Int iPer;
+  
+  for (Int iQP = iStartQP; iQP <= iEndQP; iQP++)
+  {
+    for (UInt uiSliceType = 0; uiSliceType < 3; uiSliceType++)
+    {
+      Int k =  (iQP + 6*g_uiBitIncrement)/6;
+#if FULL_NBIT
+      k += g_uiBitDepth - 8;
+#endif
+      
+      Bool bLowPass = (uiSliceType == 0);
+      iDefaultOffset = (bLowPass? 10922 : 5462);
+      
+      bLowPass = (uiSliceType == 0);
+      iDefaultOffset_LTR = (bLowPass? 170 : 86);
+      
+      iPer = QP_BITS + k - QOFFSET_BITS;
+      m_aiAdd2x2[iQP][uiSliceType] = iDefaultOffset << iPer;
+      m_aiAdd4x4[iQP][uiSliceType] = iDefaultOffset << iPer;
+      
+      iPer = QP_BITS + 1 + k - QOFFSET_BITS;
+      m_aiAdd8x8[iQP][uiSliceType] = iDefaultOffset << iPer;
+      
+      iPer = ECore16Shift + k - QOFFSET_BITS_LTR;
+      m_aiAdd16x16[iQP][uiSliceType] = iDefaultOffset_LTR << iPer;
+      
+      iPer = ECore32Shift + k - QOFFSET_BITS_LTR;
+      m_aiAdd32x32[iQP][uiSliceType] = iDefaultOffset_LTR << iPer;
+    }
+  }
+}
+
+// ====================================================================================================================
+// TComTrQuant class member functions
+// ====================================================================================================================
+
+TComTrQuant::TComTrQuant()
+{
+  m_cQP.clear();
+  
+  // allocate temporary buffers
+  m_plTempCoeff  = new Long[ MAX_CU_SIZE*MAX_CU_SIZE ];
+  
+  // allocate bit estimation class  (for RDOQ)
+  m_pcEstBitsSbac = new estBitsSbacStruct;
+}
+
+TComTrQuant::~TComTrQuant()
+{
+  // delete temporary buffers
+  if ( m_plTempCoeff )
+  {
+    delete [] m_plTempCoeff;
+    m_plTempCoeff = NULL;
+  }
+  
+  // delete bit estimation class
+  if ( m_pcEstBitsSbac ) delete m_pcEstBitsSbac;
+}
+
+/// Including Chroma QP Parameter setting
+Void TComTrQuant::setQPforQuant( Int iQP, Bool bLowpass, SliceType eSliceType, TextType eTxtType)
+{
+  iQP = Max( Min( iQP, 51 ), 0 );
+  
+  if(eTxtType != TEXT_LUMA) //Chroma
+  {
+    iQP  = g_aucChromaScale[ iQP ];
+  }
+  
+  m_cQP.setQpParam( iQP, bLowpass, eSliceType, m_bEnc );
+}
+
+#if E243_CORE_TRANSFORMS
+
+#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
+ */
+#if INTRA_DST_TYPE_7
+void xTr(Pel *block, Long *coeff, UInt uiStride, UInt uiTrSize, UInt uiMode)
+#else
+void xTr(Pel *block, Long *coeff, UInt uiStride, UInt uiTrSize)
+#endif
+{
+  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 INTRA_DST_TYPE_7
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode])
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+  }
+#endif
+  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 INTRA_DST_TYPE_7
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode])
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+    else
+    {
+      iT  = g_aiT4[0];
+    }
+  }
+ #endif
+  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
+ */
+#if INTRA_DST_TYPE_7
+void xITr(Long *coeff, Pel *block, UInt uiStride, UInt uiTrSize, UInt uiMode)
+#else
+void xITr(Long *coeff, Pel *block, UInt uiStride, UInt uiTrSize)
+#endif
+{
+  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);
+  }
+  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 INTRA_DST_TYPE_7
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode] ) // Check for DCT or DST
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+  }
+#endif
+  /* 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] = (iSum + add_1st)>>shift_1st;
+    }
+  }   
+#if INTRA_DST_TYPE_7
+  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];
+    }
+  }
+#endif
+  /* 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] = (iSum + add_2nd)>>shift_2nd;
+    }
+  }
+}
+
+#else //MATRIX_MULT
+
+/** 4x4 forward transform implemented using partial butterfly structure (1D)
+ *  \param block input data (residual)
+ *  \param coeff output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ */
+void partialButterfly4(short block[4][4],short coeff[4][4],int shift)
+{
+  int j;  
+  int E[2],O[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<4; j++)
+  {    
+    /* E and O */
+    E[0] = block[j][0] + block[j][3];
+    O[0] = block[j][0] - block[j][3];
+    E[1] = block[j][1] + block[j][2];
+    O[1] = block[j][1] - block[j][2];
+
+    coeff[0][j] = (g_aiT4[0][0]*E[0] + g_aiT4[0][1]*E[1] + add)>>shift;
+    coeff[2][j] = (g_aiT4[2][0]*E[0] + g_aiT4[2][1]*E[1] + add)>>shift;
+    coeff[1][j] = (g_aiT4[1][0]*O[0] + g_aiT4[1][1]*O[1] + add)>>shift;
+    coeff[3][j] = (g_aiT4[3][0]*O[0] + g_aiT4[3][1]*O[1] + add)>>shift;
+  }
+}
+
+#if INTRA_DST_TYPE_7
+// Fast DST Algorithm. Full matrix multiplication for DST and Fast DST algorithm 
+// give identical results
+void fastForwardDst(short block[4][4],short coeff[4][4],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[i][0] + block[i][3];
+    c[1] = block[i][1] + block[i][3];
+    c[2] = block[i][0] - block[i][1];
+    c[3] = 74* block[i][2];
+    
+    coeff[0][i] =  ( 29 * c[0] + 55 * c[1]         + c[3]               + rnd_factor ) >> shift;
+    coeff[1][i] =  ( 74 * (block[i][0]+ block[i][1] - block[i][3])      + rnd_factor ) >> shift;
+    coeff[2][i] =  ( 29 * c[2] + 55 * c[0]         - c[3]               + rnd_factor ) >> shift;
+    coeff[3][i] =  ( 55 * c[2] - 29 * c[1]         + c[3]               + rnd_factor ) >> shift;
+  }
+}
+void fastInverseDst(short tmp[4][4],short block[4][4],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[0][i] + tmp[2][i];
+    c[1] = tmp[2][i] + tmp[3][i];
+    c[2] = tmp[0][i] - tmp[3][i];
+    c[3] = 74* tmp[1][i];
+
+    block[i][0] =  ( 29 * c[0] + 55 * c[1]     + c[3]               + rnd_factor ) >> shift;
+    block[i][1] =  ( 55 * c[2] - 29 * c[1]     + c[3]               + rnd_factor ) >> shift;
+    block[i][2] =  ( 74 * (tmp[0][i] - tmp[2][i]  + tmp[3][i])      + rnd_factor ) >> shift;
+    block[i][3] =  ( 55 * c[0] + 29 * c[2]     - c[3]               + rnd_factor ) >> shift;
+  }
+}
+#endif 
+/** 4x4 forward transform (2D)
+ *  \param block input data (residual)
+ *  \param coeff output data (transform coefficients)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+#if INTRA_DST_TYPE_7
+void xTr4(short block[4][4],short coeff[4][4],UInt uiMode)
+#else
+void xTr4(short block[4][4],short coeff[4][4])
+#endif
+{
+#if FULL_NBIT
+  int shift_1st = 1 + g_uiBitDepth - 8; // log2(4) - 1 + g_uiBitDepth - 8
+#else
+  int shift_1st = 1 + g_uiBitIncrement; // log2(4) - 1 + g_uiBitIncrement
+#endif
+  int shift_2nd = 8;                    // log2(4) + 6
+  short tmp[4][4]; 
+#if INTRA_DST_TYPE_7
+  if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode])// 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);
+  }
+#else
+  partialButterfly4(block,tmp,shift_1st);
+#endif
+
+#if INTRA_DST_TYPE_7
+  if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode] )   // 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);
+  }   
+#else
+  partialButterfly4(tmp,coeff,shift_2nd);
+#endif
+}
+
+/** 4x4 inverse transform implemented using partial butterfly structure (1D)
+ *  \param coeff input data (transform coefficients)
+ *  \param block output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ */
+void partialButterflyInverse4(short tmp[4][4],short block[4][4],int shift)
+{
+  int j;    
+  int E[2],O[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<4; j++)
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */    
+    O[0] = g_aiT4[1][0]*tmp[1][j] + g_aiT4[3][0]*tmp[3][j];
+    O[1] = g_aiT4[1][1]*tmp[1][j] + g_aiT4[3][1]*tmp[3][j];
+    E[0] = g_aiT4[0][0]*tmp[0][j] + g_aiT4[2][0]*tmp[2][j];
+    E[1] = g_aiT4[0][1]*tmp[0][j] + g_aiT4[2][1]*tmp[2][j];
+    
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */ 
+    block[j][0] = (E[0] + O[0] + add)>>shift;
+    block[j][1] = (E[1] + O[1] + add)>>shift;
+    block[j][2] = (E[1] - O[1] + add)>>shift;
+    block[j][3] = (E[0] - O[0] + add)>>shift;
+  }
+}
+
+/** 4x4 inverse transform (2D)
+ *  \param coeff input data (transform coefficients)
+ *  \param block output data (residual)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+#if INTRA_DST_TYPE_7
+void xITr4(short coeff[4][4],short block[4][4], UInt uiMode)
+#else
+void xITr4(short coeff[4][4],short block[4][4])
+#endif
+{
+  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[4][4];
+  
+#if INTRA_DST_TYPE_7
+  if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode] )    // 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);    
+  } 
+#else
+  partialButterflyInverse4(coeff,tmp,shift_1st);
+#endif
+#if INTRA_DST_TYPE_7
+  if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode] )    // 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);
+  }   
+#else
+   partialButterflyInverse4(tmp,block,shift_2nd);
+#endif
+}
+
+/** 8x8 forward transform implemented using partial butterfly structure (1D)
+ *  \param block input data (residual)
+ *  \param coeff output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ */
+void partialButterfly8(short block[8][8],short coeff[8][8],int shift)
+{
+  int j,k;  
+  int E[4],O[4];
+  int EE[2],EO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<8; j++)
+  {    
+    /* E and O*/
+    for (k=0;k<4;k++)
+    {
+      E[k] = block[j][k] + block[j][7-k];
+      O[k] = block[j][k] - block[j][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];
+
+    coeff[0][j] = (g_aiT8[0][0]*EE[0] + g_aiT8[0][1]*EE[1] + add)>>shift;
+    coeff[4][j] = (g_aiT8[4][0]*EE[0] + g_aiT8[4][1]*EE[1] + add)>>shift; 
+    coeff[2][j] = (g_aiT8[2][0]*EO[0] + g_aiT8[2][1]*EO[1] + add)>>shift;
+    coeff[6][j] = (g_aiT8[6][0]*EO[0] + g_aiT8[6][1]*EO[1] + add)>>shift; 
+
+    coeff[1][j] = (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;
+    coeff[3][j] = (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;
+    coeff[5][j] = (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;
+    coeff[7][j] = (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;
+  }
+}
+
+/** 8x8 forward transform (2D)
+ *  \param block input data (residual)
+ *  \param coeff  output data (transform coefficients)
+ */
+void xTr8(short block[8][8],short coeff[8][8])
+{
+#if FULL_NBIT
+  int shift_1st = 2 + g_uiBitDepth - 8; // log2(8) - 1 + g_uiBitDepth - 8
+#else
+  int shift_1st = 2 + g_uiBitIncrement; // log2(8) - 1 + g_uiBitIncrement
+#endif
+  int shift_2nd = 9;                    // log2(8) + 6
+  short tmp[8][8]; 
+
+  partialButterfly8(block,tmp,shift_1st);
+  partialButterfly8(tmp,coeff,shift_2nd);
+}
+
+/** 8x8 inverse transform implemented using partial butterfly structure (1D)
+ *  \param coeff input data (transform coefficients)
+ *  \param block output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ */
+void partialButterflyInverse8(short tmp[8][8],short block[8][8],int shift)
+{
+  int j,k;    
+  int E[4],O[4];
+  int EE[2],EO[2];
+  int add = 1<<(shift-1);
+
+  for (j=0; j<8; 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]*tmp[ 1][j] + g_aiT8[ 3][k]*tmp[ 3][j] + g_aiT8[ 5][k]*tmp[ 5][j] + g_aiT8[ 7][k]*tmp[ 7][j];
+    }
+   
+    EO[0] = g_aiT8[2][0]*tmp[2][j] + g_aiT8[6][0]*tmp[6][j];
+    EO[1] = g_aiT8[2][1]*tmp[2][j] + g_aiT8[6][1]*tmp[6][j];
+    EE[0] = g_aiT8[0][0]*tmp[0][j] + g_aiT8[4][0]*tmp[4][j];
+    EE[1] = g_aiT8[0][1]*tmp[0][j] + g_aiT8[4][1]*tmp[4][j];
+
+    /* 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++)
+    {
+      block[j][k] = (E[k] + O[k] + add)>>shift;
+      block[j][k+4] = (E[3-k] - O[3-k] + add)>>shift;
+    }        
+  }
+}
+
+/** 8x8 inverse transform (2D)
+ *  \param coeff input data (transform coefficients)
+ *  \param block output data (residual)
+ */
+void xITr8(short coeff[8][8],short block[8][8])
+{
+  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[8][8];
+  
+  partialButterflyInverse8(coeff,tmp,shift_1st);
+  partialButterflyInverse8(tmp,block,shift_2nd);
+}
+
+/** 16x16 forward transform implemented using partial butterfly structure (1D)
+ *  \param block input data (residual)
+ *  \param coeff output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ */
+void partialButterfly16(short block[16][16],short coeff[16][16],int shift)
+{
+  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<16; j++)
+  {    
+    /* E and O*/
+    for (k=0;k<8;k++)
+    {
+      E[k] = block[j][k] + block[j][15-k];
+      O[k] = block[j][k] - block[j][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];
+
+    coeff[ 0][j] = (g_aiT16[ 0][0]*EEE[0] + g_aiT16[ 0][1]*EEE[1] + add)>>shift;        
+    coeff[ 8][j] = (g_aiT16[ 8][0]*EEE[0] + g_aiT16[ 8][1]*EEE[1] + add)>>shift;    
+    coeff[ 4][j] = (g_aiT16[ 4][0]*EEO[0] + g_aiT16[ 4][1]*EEO[1] + add)>>shift;        
+    coeff[12][j] = (g_aiT16[12][0]*EEO[0] + g_aiT16[12][1]*EEO[1] + add)>>shift;
+
+    for (k=2;k<16;k+=4)
+    {
+      coeff[k][j] = (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)
+    {
+      coeff[k][j] = (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;
+    }
+
+  }
+}
+
+/** 16x16 forward transform (2D)
+ *  \param block input data (residual)
+ *  \param coeff output data (transform coefficients)
+ */
+void xTr16(short block[16][16],short coeff[16][16])
+{
+ #if FULL_NBIT
+  int shift_1st = 3 + g_uiBitDepth - 8; // log2(16) - 1 + g_uiBitDepth - 8
+#else
+  int shift_1st = 3 + g_uiBitIncrement; // log2(16) - 1 + g_uiBitIncrement
+#endif
+  int shift_2nd = 10;                   // log2(16) + 6
+  short tmp[16][16]; 
+
+  partialButterfly16(block,tmp,shift_1st);
+  partialButterfly16(tmp,coeff,shift_2nd);
+}
+
+/** 16x16 inverse transform implemented using partial butterfly structure (1D)
+ *  \param coeff input data (transform coefficients)
+ *  \param block output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ */
+void partialButterflyInverse16(short tmp[16][16],short block[16][16],int shift)
+{
+  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<16; 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]*tmp[ 1][j] + g_aiT16[ 3][k]*tmp[ 3][j] + g_aiT16[ 5][k]*tmp[ 5][j] + g_aiT16[ 7][k]*tmp[ 7][j] + 
+             g_aiT16[ 9][k]*tmp[ 9][j] + g_aiT16[11][k]*tmp[11][j] + g_aiT16[13][k]*tmp[13][j] + g_aiT16[15][k]*tmp[15][j];
+    }
+    for (k=0;k<4;k++)
+    {
+      EO[k] = g_aiT16[ 2][k]*tmp[ 2][j] + g_aiT16[ 6][k]*tmp[ 6][j] + g_aiT16[10][k]*tmp[10][j] + g_aiT16[14][k]*tmp[14][j];
+    }
+    EEO[0] = g_aiT16[4][0]*tmp[4][j] + g_aiT16[12][0]*tmp[12][j];
+    EEE[0] = g_aiT16[0][0]*tmp[0][j] + g_aiT16[ 8][0]*tmp[ 8][j];
+    EEO[1] = g_aiT16[4][1]*tmp[4][j] + g_aiT16[12][1]*tmp[12][j];
+    EEE[1] = g_aiT16[0][1]*tmp[0][j] + g_aiT16[ 8][1]*tmp[ 8][j];
+
+    /* 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++)
+    {
+      block[j][k] = (E[k] + O[k] + add)>>shift;
+      block[j][k+8] = (E[7-k] - O[7-k] + add)>>shift;
+    }        
+  }
+}
+
+/** 16x16 inverse transform (2D)
+ *  \param coeff input data (transform coefficients)
+ *  \param block output data (residual)
+ */
+void xITr16(short coeff[16][16],short block[16][16])
+{
+  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[16][16];
+  
+  partialButterflyInverse16(coeff,tmp,shift_1st);
+  partialButterflyInverse16(tmp,block,shift_2nd);
+}
+
+/** 32x32 forward transform implemented using partial butterfly structure (1D)
+ *  \param block input data (residual)
+ *  \param coeff output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ */
+void partialButterfly32(short block[32][32],short coeff[32][32],int shift)
+{
+  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<32; j++)
+  {    
+    /* E and O*/
+    for (k=0;k<16;k++)
+    {
+      E[k] = block[j][k] + block[j][31-k];
+      O[k] = block[j][k] - block[j][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];
+
+    coeff[ 0][j] = (g_aiT32[ 0][0]*EEEE[0] + g_aiT32[ 0][1]*EEEE[1] + add)>>shift;
+    coeff[16][j] = (g_aiT32[16][0]*EEEE[0] + g_aiT32[16][1]*EEEE[1] + add)>>shift;
+    coeff[ 8][j] = (g_aiT32[ 8][0]*EEEO[0] + g_aiT32[ 8][1]*EEEO[1] + add)>>shift; 
+    coeff[24][j] = (g_aiT32[24][0]*EEEO[0] + g_aiT32[24][1]*EEEO[1] + add)>>shift;
+    for (k=4;k<32;k+=8)
+    {
+      coeff[k][j] = (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)
+    {
+      coeff[k][j] = (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)
+    {
+      coeff[k][j] = (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;
+    }
+  }
+}
+
+/** 32x32 forward transform (2D)
+ *  \param block input data (residual)
+ *  \param coeff output data (transform coefficients)
+ */
+void xTr32(short block[32][32],short coeff[32][32])
+{
+ #if FULL_NBIT
+  int shift_1st = 4 + g_uiBitDepth - 8; // log2(32) - 1 + g_uiBitDepth - 8
+#else
+  int shift_1st = 4 + g_uiBitIncrement; // log2(32) - 1 + g_uiBitIncrement
+#endif
+  int shift_2nd = 11;                   // log2(32) + 6
+  short tmp[32][32]; 
+
+  partialButterfly32(block,tmp,shift_1st);
+  partialButterfly32(tmp,coeff,shift_2nd);
+}
+
+/** 32x32 inverse transform implemented using partial butterfly structure (1D)
+ *  \param coeff input data (transform coefficients)
+ *  \param block output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ */
+void partialButterflyInverse32(short tmp[32][32],short block[32][32],int shift)
+{
+  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<32; 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]*tmp[ 1][j] + g_aiT32[ 3][k]*tmp[ 3][j] + g_aiT32[ 5][k]*tmp[ 5][j] + g_aiT32[ 7][k]*tmp[ 7][j] + 
+             g_aiT32[ 9][k]*tmp[ 9][j] + g_aiT32[11][k]*tmp[11][j] + g_aiT32[13][k]*tmp[13][j] + g_aiT32[15][k]*tmp[15][j] + 
+             g_aiT32[17][k]*tmp[17][j] + g_aiT32[19][k]*tmp[19][j] + g_aiT32[21][k]*tmp[21][j] + g_aiT32[23][k]*tmp[23][j] + 
+             g_aiT32[25][k]*tmp[25][j] + g_aiT32[27][k]*tmp[27][j] + g_aiT32[29][k]*tmp[29][j] + g_aiT32[31][k]*tmp[31][j];
+    }
+    for (k=0;k<8;k++)
+    {
+      EO[k] = g_aiT32[ 2][k]*tmp[ 2][j] + g_aiT32[ 6][k]*tmp[ 6][j] + g_aiT32[10][k]*tmp[10][j] + g_aiT32[14][k]*tmp[14][j] + 
+              g_aiT32[18][k]*tmp[18][j] + g_aiT32[22][k]*tmp[22][j] + g_aiT32[26][k]*tmp[26][j] + g_aiT32[30][k]*tmp[30][j];
+    }
+    for (k=0;k<4;k++)
+    {
+      EEO[k] = g_aiT32[4][k]*tmp[4][j] + g_aiT32[12][k]*tmp[12][j] + g_aiT32[20][k]*tmp[20][j] + g_aiT32[28][k]*tmp[28][j];
+    }
+    EEEO[0] = g_aiT32[8][0]*tmp[8][j] + g_aiT32[24][0]*tmp[24][j];
+    EEEO[1] = g_aiT32[8][1]*tmp[8][j] + g_aiT32[24][1]*tmp[24][j];
+    EEEE[0] = g_aiT32[0][0]*tmp[0][j] + g_aiT32[16][0]*tmp[16][j];    
+    EEEE[1] = g_aiT32[0][1]*tmp[0][j] + g_aiT32[16][1]*tmp[16][j];
+
+    /* 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++)
+    {
+      block[j][k] = (E[k] + O[k] + add)>>shift;
+      block[j][k+16] = (E[15-k] - O[15-k] + add)>>shift;
+    }        
+  }
+}
+
+/** 32x32 inverse transform (2D)
+ *  \param coeff input data (transform coefficients)
+ *  \param block output data (residual)
+ */
+void xITr32(short coeff[32][32],short block[32][32])
+{
+  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[32][32];
+  
+  partialButterflyInverse32(coeff,tmp,shift_1st);
+  partialButterflyInverse32(tmp,block,shift_2nd);
+}
+#endif //MATRIX_MULT
+#else //E243_CORE_TRANSFORMS
+
+Void TComTrQuant::xT32( Pel* pSrc, UInt uiStride, Long* pDes )
+{
+  Int x, y;
+  Long aaiTemp[32][32];
+  
+  Long A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23, A24, A25, A26, A27, A28, A29, A30, A31;
+  Long B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15, B20, B21, B22, B23, B24, B25, B26, B27;
+  Long C0, C1, C2, C3, C4, C5, C6, C7, C10, C11, C12, C13, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30, C31;
+  Long D0, D1, D2, D3, D5, D6, D8, D9, D10, D11, D12, D13, D14, D15, D18, D19, D20, D21, D26, D27, D28, D29;
+  Long E4, E5, E6, E7, E9, E10, E13, E14, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31;
+  Long F8, F9, F10, F11, F12, F13, F14, F15, F17, F18, F21, F22, F25, F26, F29, F30;
+  Long G16, G17, G18, G19, G20, G21, G22, G23, G24, G25, G26, G27, G28, G29, G30, G31;
+#ifdef TRANS_PRECISION_EXT
+  Int uiBitDepthIncrease=g_iShift32x32-g_uiBitIncrement;
+  Int offset = (uiBitDepthIncrease==0)? 0:(1<<(uiBitDepthIncrease-1));
+#endif
+  //--Butterfly
+  for( y=0 ; y<32 ; y++ )
+  {
+#ifdef TRANS_PRECISION_EXT
+    A0  = (pSrc[0] + pSrc[31])<<uiBitDepthIncrease;
+    A31 = (pSrc[0] - pSrc[31])<<uiBitDepthIncrease;
+    A1  = (pSrc[1] + pSrc[30])<<uiBitDepthIncrease;
+    A30 = (pSrc[1] - pSrc[30])<<uiBitDepthIncrease;
+    A2  = (pSrc[2] + pSrc[29])<<uiBitDepthIncrease;
+    A29 = (pSrc[2] - pSrc[29])<<uiBitDepthIncrease;
+    A3  = (pSrc[3] + pSrc[28])<<uiBitDepthIncrease;
+    A28 = (pSrc[3] - pSrc[28])<<uiBitDepthIncrease;
+    A4  = (pSrc[4] + pSrc[27])<<uiBitDepthIncrease;
+    A27 = (pSrc[4] - pSrc[27])<<uiBitDepthIncrease;
+    A5  = (pSrc[5] + pSrc[26])<<uiBitDepthIncrease;
+    A26 = (pSrc[5] - pSrc[26])<<uiBitDepthIncrease;
+    A6  = (pSrc[6] + pSrc[25])<<uiBitDepthIncrease;
+    A25 = (pSrc[6] - pSrc[25])<<uiBitDepthIncrease;
+    A7  = (pSrc[7] + pSrc[24])<<uiBitDepthIncrease;
+    A24 = (pSrc[7] - pSrc[24])<<uiBitDepthIncrease;
+    A8  = (pSrc[8] + pSrc[23])<<uiBitDepthIncrease;
+    A23 = (pSrc[8] - pSrc[23])<<uiBitDepthIncrease;
+    A9  = (pSrc[9] + pSrc[22])<<uiBitDepthIncrease;
+    A22 = (pSrc[9] - pSrc[22])<<uiBitDepthIncrease;
+    A10 = (pSrc[10] + pSrc[21])<<uiBitDepthIncrease;
+    A21 = (pSrc[10] - pSrc[21])<<uiBitDepthIncrease;
+    A11 = (pSrc[11] + pSrc[20])<<uiBitDepthIncrease;
+    A20 = (pSrc[11] - pSrc[20])<<uiBitDepthIncrease;
+    A12 = (pSrc[12] + pSrc[19])<<uiBitDepthIncrease;
+    A19 = (pSrc[12] - pSrc[19])<<uiBitDepthIncrease;
+    A13 = (pSrc[13] + pSrc[18])<<uiBitDepthIncrease;
+    A18 = (pSrc[13] - pSrc[18])<<uiBitDepthIncrease;
+    A14 = (pSrc[14] + pSrc[17])<<uiBitDepthIncrease;
+    A17 = (pSrc[14] - pSrc[17])<<uiBitDepthIncrease;
+    A15 = (pSrc[15] + pSrc[16])<<uiBitDepthIncrease;
+    A16 = (pSrc[15] - pSrc[16])<<uiBitDepthIncrease;
+#else
+    A0 = pSrc[0] + pSrc[31];
+    A31 = pSrc[0] - pSrc[31];
+    A1 = pSrc[1] + pSrc[30];
+    A30 = pSrc[1] - pSrc[30];
+    A2 = pSrc[2] + pSrc[29];
+    A29 = pSrc[2] - pSrc[29];
+    A3 = pSrc[3] + pSrc[28];
+    A28 = pSrc[3] - pSrc[28];
+    A4 = pSrc[4] + pSrc[27];
+    A27 = pSrc[4] - pSrc[27];
+    A5 = pSrc[5] + pSrc[26];
+    A26 = pSrc[5] - pSrc[26];
+    A6 = pSrc[6] + pSrc[25];
+    A25 = pSrc[6] - pSrc[25];
+    A7 = pSrc[7] + pSrc[24];
+    A24 = pSrc[7] - pSrc[24];
+    A8 = pSrc[8] + pSrc[23];
+    A23 = pSrc[8] - pSrc[23];
+    A9 = pSrc[9] + pSrc[22];
+    A22 = pSrc[9] - pSrc[22];
+    A10 = pSrc[10] + pSrc[21];
+    A21 = pSrc[10] - pSrc[21];
+    A11 = pSrc[11] + pSrc[20];
+    A20 = pSrc[11] - pSrc[20];
+    A12 = pSrc[12] + pSrc[19];
+    A19 = pSrc[12] - pSrc[19];
+    A13 = pSrc[13] + pSrc[18];
+    A18 = pSrc[13] - pSrc[18];
+    A14 = pSrc[14] + pSrc[17];
+    A17 = pSrc[14] - pSrc[17];
+    A15 = pSrc[15] + pSrc[16];
+    A16 = pSrc[15] - pSrc[16];
+#endif
+    B0 = A0 + A15;
+    B15 = A0 - A15;
+    B1 = A1 + A14;
+    B14 = A1 - A14;
+    B2 = A2 + A13;
+    B13 = A2 - A13;
+    B3 = A3 + A12;
+    B12 = A3 - A12;
+    B4 = A4 + A11;
+    B11 = A4 - A11;
+    B5 = A5 + A10;
+    B10 = A5 - A10;
+    B6 = A6 + A9;
+    B9 = A6 - A9;
+    B7 = A7 + A8;
+    B8 = A7 - A8;
+    B20 = xTrRound( 181 * ( A27 - A20 ) , DenShift32);
+    B27 = xTrRound( 181 * ( A27 + A20 ) , DenShift32);
+    B21 = xTrRound( 181 * ( A26 - A21 ) , DenShift32);
+    B26 = xTrRound( 181 * ( A26 + A21 ) , DenShift32);
+    B22 = xTrRound( 181 * ( A25 - A22 ) , DenShift32);
+    B25 = xTrRound( 181 * ( A25 + A22 ) , DenShift32);
+    B23 = xTrRound( 181 * ( A24 - A23 ) , DenShift32);
+    B24 = xTrRound( 181 * ( A24 + A23 ) , DenShift32);;
+    
+    C0 = B0 + B7;
+    C7 = B0 - B7;
+    C1 = B1 + B6;
+    C6 = B1 - B6;
+    C2 = B2 + B5;
+    C5 = B2 - B5;
+    C3 = B3 + B4;
+    C4 = B3 - B4;
+    C10 = xTrRound( 181 * ( B13 - B10 ) , DenShift32);
+    C13 = xTrRound( 181 * ( B13 + B10 ) , DenShift32);
+    C11 = xTrRound( 181 * ( B12 - B11 ) , DenShift32);
+    C12 = xTrRound( 181 * ( B12 + B11 ) , DenShift32);
+    C16 = A16 + B23;
+    C23 = A16 - B23;
+    C24 = A31 - B24;
+    C31 = A31 + B24;
+    C17 = A17 + B22;
+    C22 = A17 - B22;
+    C25 = A30 - B25;
+    C30 = A30 + B25;
+    C18 = A18 + B21;
+    C21 = A18 - B21;
+    C26 = A29 - B26;
+    C29 = A29 + B26;
+    C19 = A19 + B20;
+    C20 = A19 - B20;
+    C27 = A28 - B27;
+    C28 = A28 + B27;
+    
+    D0 = C0 + C3;
+    D3 = C0 - C3;
+    D8 = B8 + C11;
+    D11 = B8 - C11;
+    D12 = B15 - C12;
+    D15 = B15 + C12;
+    D1 = C1 + C2;
+    D2 = C1 - C2;
+    D9 = B9 + C10;
+    D10 = B9 - C10;
+    D13 = B14 - C13;
+    D14 = B14 + C13;
+    D5 = xTrRound( 181 * ( C6 - C5 ) , DenShift32);
+    D6 = xTrRound( 181 * ( C6 + C5 ) , DenShift32);
+    D18 = xTrRound( 97 * C29 - 236 * C18 , DenShift32);
+    D20 = xTrRound(  - 236 * C27 - 97 * C20 , DenShift32);
+    D26 = xTrRound(  - 236 * C21 + 97 * C26 , DenShift32);
+    D28 = xTrRound( 97 * C19 + 236 * C28 , DenShift32);
+    D19 = xTrRound( 97 * C28 - 236 * C19 , DenShift32);
+    D21 = xTrRound(  - 236 * C26 - 97 * C21 , DenShift32);
+    D27 = xTrRound(  - 236 * C20 + 97 * C27 , DenShift32);
+    D29 = xTrRound( 97 * C18 + 236 * C29 , DenShift32);;
+    
+    aaiTemp[0][y] = xTrRound( 181 * ( D0 + D1 ) , DenShift32);
+    aaiTemp[16][y] = xTrRound( 181 * ( D0 - D1 ) , DenShift32);
+    aaiTemp[8][y] = xTrRound( 236 * D3 + 97 * D2 , DenShift32);
+    aaiTemp[24][y] = xTrRound( 97 * D3 - 236 * D2 , DenShift32);
+    E4 = C4 + D5;
+    E5 = C4 - D5;
+    E6 = C7 - D6;
+    E7 = C7 + D6;
+    E9 = xTrRound( 97 * D14 - 236 * D9 , DenShift32);
+    E10 = xTrRound(  - 236 * D13 - 97 * D10 , DenShift32);
+    E13 = xTrRound( 97 * D13 - 236 * D10 , DenShift32);
+    E14 = xTrRound( 236 * D14 + 97 * D9 , DenShift32);
+    E16 = C16 + D19;
+    E19 = C16 - D19;
+    E20 = C23 - D20;
+    E23 = C23 + D20;
+    E24 = C24 + D27;
+    E27 = C24 - D27;
+    E28 = C31 - D28;
+    E31 = C31 + D28;
+    E17 = C17 + D18;
+    E18 = C17 - D18;
+    E21 = C22 - D21;
+    E22 = C22 + D21;
+    E25 = C25 + D26;
+    E26 = C25 - D26;
+    E29 = C30 - D29;
+    E30 = C30 + D29;
+    
+    aaiTemp[4][y] = xTrRound( 49 * E4 + 251 * E7 , DenShift32);
+    aaiTemp[20][y] = xTrRound( 212 * E5 + 142 * E6 , DenShift32);
+    aaiTemp[12][y] = xTrRound( 212 * E6 - 142 * E5 , DenShift32);
+    aaiTemp[28][y] = xTrRound( 49 * E7 - 251 * E4 , DenShift32);
+    F8 = D8 + E9;
+    F9 = D8 - E9;
+    F10 = D11 - E10;
+    F11 = D11 + E10;
+    F12 = D12 + E13;
+    F13 = D12 - E13;
+    F14 = D15 - E14;
+    F15 = D15 + E14;
+    F17 = xTrRound( 49 * E30 - 251 * E17 , DenShift32);
+    F18 = xTrRound(  - 251 * E29 - 49 * E18 , DenShift32);
+    F21 = xTrRound( 212 * E26 - 142 * E21 , DenShift32);
+    F22 = xTrRound(  - 142 * E25 - 212 * E22 , DenShift32);
+    F25 = xTrRound( 212 * E25 - 142 * E22 , DenShift32);
+    F26 = xTrRound( 142 * E26 + 212 * E21 , DenShift32);
+    F29 = xTrRound( 49 * E29 - 251 * E18 , DenShift32);
+    F30 = xTrRound( 251 * E30 + 49 * E17 , DenShift32);;
+    
+    aaiTemp[2][y] = xTrRound( 25 * F8 + 254 * F15 , DenShift32);
+    aaiTemp[18][y] = xTrRound( 197 * F9 + 162 * F14 , DenShift32);
+    aaiTemp[10][y] = xTrRound( 120 * F10 + 225 * F13 , DenShift32);
+    aaiTemp[26][y] = xTrRound( 244 * F11 + 74 * F12 , DenShift32);
+    aaiTemp[6][y] = xTrRound( 244 * F12 - 74 * F11 , DenShift32);
+    aaiTemp[22][y] = xTrRound( 120 * F13 - 225 * F10 , DenShift32);
+    aaiTemp[14][y] = xTrRound( 197 * F14 - 162 * F9 , DenShift32);
+    aaiTemp[30][y] = xTrRound( 25 * F15 - 254 * F8 , DenShift32);
+    G16 = E16 + F17;
+    G17 = E16 - F17;
+    G18 = E19 - F18;
+    G19 = E19 + F18;
+    G20 = E20 + F21;
+    G21 = E20 - F21;
+    G22 = E23 - F22;
+    G23 = E23 + F22;
+    G24 = E24 + F25;
+    G25 = E24 - F25;
+    G26 = E27 - F26;
+    G27 = E27 + F26;
+    G28 = E28 + F29;
+    G29 = E28 - F29;
+    G30 = E31 - F30;
+    G31 = E31 + F30;
+    
+    aaiTemp[1][y] = xTrRound( 12 * G16 + 255 * G31 , DenShift32);
+    aaiTemp[17][y] = xTrRound( 189 * G17 + 171 * G30 , DenShift32);
+    aaiTemp[9][y] = xTrRound( 109 * G18 + 231 * G29 , DenShift32);
+    aaiTemp[25][y] = xTrRound( 241 * G19 + 86 * G28 , DenShift32);
+    aaiTemp[5][y] = xTrRound( 62 * G20 + 248 * G27 , DenShift32);
+    aaiTemp[21][y] = xTrRound( 219 * G21 + 131 * G26 , DenShift32);
+    aaiTemp[13][y] = xTrRound( 152 * G22 + 205 * G25 , DenShift32);
+    aaiTemp[29][y] = xTrRound( 253 * G23 + 37 * G24 , DenShift32);
+    aaiTemp[3][y] = xTrRound( 253 * G24 - 37 * G23 , DenShift32);
+    aaiTemp[19][y] = xTrRound( 152 * G25 - 205 * G22 , DenShift32);
+    aaiTemp[11][y] = xTrRound( 219 * G26 - 131 * G21 , DenShift32);
+    aaiTemp[27][y] = xTrRound( 62 * G27 - 248 * G20 , DenShift32);
+    aaiTemp[7][y] = xTrRound( 241 * G28 - 86 * G19 , DenShift32);
+    aaiTemp[23][y] = xTrRound( 109 * G29 - 231 * G18 , DenShift32);
+    aaiTemp[15][y] = xTrRound( 189 * G30 - 171 * G17 , DenShift32);
+    aaiTemp[31][y] = xTrRound( 12 * G31 - 255 * G16 , DenShift32);
+    
+    pSrc += uiStride;
+  }
+  
+  for( x=0 ; x<32 ; x++, pDes++ )
+  {
+    A0 = aaiTemp[x][0] + aaiTemp[x][31];
+    A31 = aaiTemp[x][0] - aaiTemp[x][31];
+    A1 = aaiTemp[x][1] + aaiTemp[x][30];
+    A30 = aaiTemp[x][1] - aaiTemp[x][30];
+    A2 = aaiTemp[x][2] + aaiTemp[x][29];
+    A29 = aaiTemp[x][2] - aaiTemp[x][29];
+    A3 = aaiTemp[x][3] + aaiTemp[x][28];
+    A28 = aaiTemp[x][3] - aaiTemp[x][28];
+    A4 = aaiTemp[x][4] + aaiTemp[x][27];
+    A27 = aaiTemp[x][4] - aaiTemp[x][27];
+    A5 = aaiTemp[x][5] + aaiTemp[x][26];
+    A26 = aaiTemp[x][5] - aaiTemp[x][26];
+    A6 = aaiTemp[x][6] + aaiTemp[x][25];
+    A25 = aaiTemp[x][6] - aaiTemp[x][25];
+    A7 = aaiTemp[x][7] + aaiTemp[x][24];
+    A24 = aaiTemp[x][7] - aaiTemp[x][24];
+    A8 = aaiTemp[x][8] + aaiTemp[x][23];
+    A23 = aaiTemp[x][8] - aaiTemp[x][23];
+    A9 = aaiTemp[x][9] + aaiTemp[x][22];
+    A22 = aaiTemp[x][9] - aaiTemp[x][22];
+    A10 = aaiTemp[x][10] + aaiTemp[x][21];
+    A21 = aaiTemp[x][10] - aaiTemp[x][21];
+    A11 = aaiTemp[x][11] + aaiTemp[x][20];
+    A20 = aaiTemp[x][11] - aaiTemp[x][20];
+    A12 = aaiTemp[x][12] + aaiTemp[x][19];
+    A19 = aaiTemp[x][12] - aaiTemp[x][19];
+    A13 = aaiTemp[x][13] + aaiTemp[x][18];
+    A18 = aaiTemp[x][13] - aaiTemp[x][18];
+    A14 = aaiTemp[x][14] + aaiTemp[x][17];
+    A17 = aaiTemp[x][14] - aaiTemp[x][17];
+    A15 = aaiTemp[x][15] + aaiTemp[x][16];
+    A16 = aaiTemp[x][15] - aaiTemp[x][16];
+    
+    B0 = A0 + A15;
+    B15 = A0 - A15;
+    B1 = A1 + A14;
+    B14 = A1 - A14;
+    B2 = A2 + A13;
+    B13 = A2 - A13;
+    B3 = A3 + A12;
+    B12 = A3 - A12;
+    B4 = A4 + A11;
+    B11 = A4 - A11;
+    B5 = A5 + A10;
+    B10 = A5 - A10;
+    B6 = A6 + A9;
+    B9 = A6 - A9;
+    B7 = A7 + A8;
+    B8 = A7 - A8;
+    B20 = xTrRound( 181 * ( A27 - A20 ) , DenShift32);
+    B27 = xTrRound( 181 * ( A27 + A20 ) , DenShift32);
+    B21 = xTrRound( 181 * ( A26 - A21 ) , DenShift32);
+    B26 = xTrRound( 181 * ( A26 + A21 ) , DenShift32);
+    B22 = xTrRound( 181 * ( A25 - A22 ) , DenShift32);
+    B25 = xTrRound( 181 * ( A25 + A22 ) , DenShift32);
+    B23 = xTrRound( 181 * ( A24 - A23 ) , DenShift32);
+    B24 = xTrRound( 181 * ( A24 + A23 ) , DenShift32);;
+    
+    C0 = B0 + B7;
+    C7 = B0 - B7;
+    C1 = B1 + B6;
+    C6 = B1 - B6;
+    C2 = B2 + B5;
+    C5 = B2 - B5;
+    C3 = B3 + B4;
+    C4 = B3 - B4;
+    C10 = xTrRound( 181 * ( B13 - B10 ) , DenShift32);
+    C13 = xTrRound( 181 * ( B13 + B10 ) , DenShift32);
+    C11 = xTrRound( 181 * ( B12 - B11 ) , DenShift32);
+    C12 = xTrRound( 181 * ( B12 + B11 ) , DenShift32);
+    C16 = A16 + B23;
+    C23 = A16 - B23;
+    C24 = A31 - B24;
+    C31 = A31 + B24;
+    C17 = A17 + B22;
+    C22 = A17 - B22;
+    C25 = A30 - B25;
+    C30 = A30 + B25;
+    C18 = A18 + B21;
+    C21 = A18 - B21;
+    C26 = A29 - B26;
+    C29 = A29 + B26;
+    C19 = A19 + B20;
+    C20 = A19 - B20;
+    C27 = A28 - B27;
+    C28 = A28 + B27;
+    
+    D0 = C0 + C3;
+    D3 = C0 - C3;
+    D8 = B8 + C11;
+    D11 = B8 - C11;
+    D12 = B15 - C12;
+    D15 = B15 + C12;
+    D1 = C1 + C2;
+    D2 = C1 - C2;
+    D9 = B9 + C10;
+    D10 = B9 - C10;
+    D13 = B14 - C13;
+    D14 = B14 + C13;
+    D5 = xTrRound( 181 * ( C6 - C5 ) , DenShift32);
+    D6 = xTrRound( 181 * ( C6 + C5 ) , DenShift32);
+    D18 = xTrRound( 97 * C29 - 236 * C18 , DenShift32);
+    D20 = xTrRound(  - 236 * C27 - 97 * C20 , DenShift32);
+    D26 = xTrRound(  - 236 * C21 + 97 * C26 , DenShift32);
+    D28 = xTrRound( 97 * C19 + 236 * C28 , DenShift32);
+    D19 = xTrRound( 97 * C28 - 236 * C19 , DenShift32);
+    D21 = xTrRound(  - 236 * C26 - 97 * C21 , DenShift32);
+    D27 = xTrRound(  - 236 * C20 + 97 * C27 , DenShift32);
+    D29 = xTrRound( 97 * C18 + 236 * C29 , DenShift32);;
+    
+    pDes[0] = xTrRound( 181 * ( D0 + D1 ) , DenShift32);
+    pDes[512] = xTrRound( 181 * ( D0 - D1 ) , DenShift32);
+    pDes[256] = xTrRound( 236 * D3 + 97 * D2 , DenShift32);
+    pDes[768] = xTrRound( 97 * D3 - 236 * D2 , DenShift32);
+#ifdef TRANS_PRECISION_EXT
+    pDes[0]   = (pDes[0]  +offset)>>uiBitDepthIncrease;
+    pDes[512] = (pDes[512]+offset)>>uiBitDepthIncrease;
+    pDes[256] = (pDes[256]+offset)>>uiBitDepthIncrease;
+    pDes[768] = (pDes[768]+offset)>>uiBitDepthIncrease;
+#endif
+    E4 = C4 + D5;
+    E5 = C4 - D5;
+    E6 = C7 - D6;
+    E7 = C7 + D6;
+    E9 = xTrRound( 97 * D14 - 236 * D9 , DenShift32);
+    E10 = xTrRound(  - 236 * D13 - 97 * D10 , DenShift32);
+    E13 = xTrRound( 97 * D13 - 236 * D10 , DenShift32);
+    E14 = xTrRound( 236 * D14 + 97 * D9 , DenShift32);
+    E16 = C16 + D19;
+    E19 = C16 - D19;
+    E20 = C23 - D20;
+    E23 = C23 + D20;
+    E24 = C24 + D27;
+    E27 = C24 - D27;
+    E28 = C31 - D28;
+    E31 = C31 + D28;
+    E17 = C17 + D18;
+    E18 = C17 - D18;
+    E21 = C22 - D21;
+    E22 = C22 + D21;
+    E25 = C25 + D26;
+    E26 = C25 - D26;
+    E29 = C30 - D29;
+    E30 = C30 + D29;
+    
+    pDes[128] = xTrRound( 49 * E4 + 251 * E7 , DenShift32);
+    pDes[640] = xTrRound( 212 * E5 + 142 * E6 , DenShift32);
+    pDes[384] = xTrRound( 212 * E6 - 142 * E5 , DenShift32);
+    pDes[896] = xTrRound( 49 * E7 - 251 * E4 , DenShift32);
+#ifdef TRANS_PRECISION_EXT
+    pDes[128] = (pDes[128]+offset)>>uiBitDepthIncrease;
+    pDes[640] = (pDes[640]+offset)>>uiBitDepthIncrease;
+    pDes[384] = (pDes[384]+offset)>>uiBitDepthIncrease;
+    pDes[896] = (pDes[896]+offset)>>uiBitDepthIncrease;
+#endif
+    F8 = D8 + E9;
+    F9 = D8 - E9;
+    F10 = D11 - E10;
+    F11 = D11 + E10;
+    F12 = D12 + E13;
+    F13 = D12 - E13;
+    F14 = D15 - E14;
+    F15 = D15 + E14;
+    F17 = xTrRound( 49 * E30 - 251 * E17 , DenShift32);
+    F18 = xTrRound(  - 251 * E29 - 49 * E18 , DenShift32);
+    F21 = xTrRound( 212 * E26 - 142 * E21 , DenShift32);
+    F22 = xTrRound(  - 142 * E25 - 212 * E22 , DenShift32);
+    F25 = xTrRound( 212 * E25 - 142 * E22 , DenShift32);
+    F26 = xTrRound( 142 * E26 + 212 * E21 , DenShift32);
+    F29 = xTrRound( 49 * E29 - 251 * E18 , DenShift32);
+    F30 = xTrRound( 251 * E30 + 49 * E17 , DenShift32);;
+    
+    pDes[64] = xTrRound( 25 * F8 + 254 * F15 , DenShift32);
+    pDes[576] = xTrRound( 197 * F9 + 162 * F14 , DenShift32);
+    pDes[320] = xTrRound( 120 * F10 + 225 * F13 , DenShift32);
+    pDes[832] = xTrRound( 244 * F11 + 74 * F12 , DenShift32);
+    pDes[192] = xTrRound( 244 * F12 - 74 * F11 , DenShift32);
+    pDes[704] = xTrRound( 120 * F13 - 225 * F10 , DenShift32);
+    pDes[448] = xTrRound( 197 * F14 - 162 * F9 , DenShift32);
+    pDes[960] = xTrRound( 25 * F15 - 254 * F8 , DenShift32);
+#ifdef TRANS_PRECISION_EXT
+    pDes[64]  = (pDes[64] +offset)>>uiBitDepthIncrease;
+    pDes[576] = (pDes[576]+offset)>>uiBitDepthIncrease;
+    pDes[320] = (pDes[320]+offset)>>uiBitDepthIncrease;
+    pDes[832] = (pDes[832]+offset)>>uiBitDepthIncrease;
+    pDes[192] = (pDes[192]+offset)>>uiBitDepthIncrease;
+    pDes[704] = (pDes[704]+offset)>>uiBitDepthIncrease;
+    pDes[448] = (pDes[448]+offset)>>uiBitDepthIncrease;
+    pDes[960] = (pDes[960]+offset)>>uiBitDepthIncrease;
+#endif
+    G16 = E16 + F17;
+    G17 = E16 - F17;
+    G18 = E19 - F18;
+    G19 = E19 + F18;
+    G20 = E20 + F21;
+    G21 = E20 - F21;
+    G22 = E23 - F22;
+    G23 = E23 + F22;
+    G24 = E24 + F25;
+    G25 = E24 - F25;
+    G26 = E27 - F26;
+    G27 = E27 + F26;
+    G28 = E28 + F29;
+    G29 = E28 - F29;
+    G30 = E31 - F30;
+    G31 = E31 + F30;
+    
+    pDes[32] = xTrRound( 12 * G16 + 255 * G31 , DenShift32);
+    pDes[544] = xTrRound( 189 * G17 + 171 * G30 , DenShift32);
+    pDes[288] = xTrRound( 109 * G18 + 231 * G29 , DenShift32);
+    pDes[800] = xTrRound( 241 * G19 + 86 * G28 , DenShift32);
+    pDes[160] = xTrRound( 62 * G20 + 248 * G27 , DenShift32);
+    pDes[672] = xTrRound( 219 * G21 + 131 * G26 , DenShift32);
+    pDes[416] = xTrRound( 152 * G22 + 205 * G25 , DenShift32);
+    pDes[928] = xTrRound( 253 * G23 + 37 * G24 , DenShift32);
+    pDes[96] = xTrRound( 253 * G24 - 37 * G23 , DenShift32);
+    pDes[608] = xTrRound( 152 * G25 - 205 * G22 , DenShift32);
+    pDes[352] = xTrRound( 219 * G26 - 131 * G21 , DenShift32);
+    pDes[864] = xTrRound( 62 * G27 - 248 * G20 , DenShift32);
+    pDes[224] = xTrRound( 241 * G28 - 86 * G19 , DenShift32);
+    pDes[736] = xTrRound( 109 * G29 - 231 * G18 , DenShift32);
+    pDes[480] = xTrRound( 189 * G30 - 171 * G17 , DenShift32);
+    pDes[992] = xTrRound( 12 * G31 - 255 * G16 , DenShift32);
+#ifdef TRANS_PRECISION_EXT
+    pDes[32]  = (pDes[32] +offset)>>uiBitDepthIncrease;
+    pDes[544] = (pDes[544]+offset)>>uiBitDepthIncrease;
+    pDes[288] = (pDes[288]+offset)>>uiBitDepthIncrease;
+    pDes[800] = (pDes[800]+offset)>>uiBitDepthIncrease;
+    pDes[160] = (pDes[160]+offset)>>uiBitDepthIncrease;
+    pDes[672] = (pDes[672]+offset)>>uiBitDepthIncrease;
+    pDes[416] = (pDes[416]+offset)>>uiBitDepthIncrease;
+    pDes[928] = (pDes[928]+offset)>>uiBitDepthIncrease;
+    pDes[96]  = (pDes[96] +offset)>>uiBitDepthIncrease;
+    pDes[608] = (pDes[608]+offset)>>uiBitDepthIncrease;
+    pDes[352] = (pDes[352]+offset)>>uiBitDepthIncrease;
+    pDes[864] = (pDes[864]+offset)>>uiBitDepthIncrease;
+    pDes[224] = (pDes[224]+offset)>>uiBitDepthIncrease;
+    pDes[736] = (pDes[736]+offset)>>uiBitDepthIncrease;
+    pDes[480] = (pDes[480]+offset)>>uiBitDepthIncrease;
+    pDes[992] = (pDes[992]+offset)>>uiBitDepthIncrease;
+#endif
+  }
+}
+
+Void TComTrQuant::xT16( Pel* pSrc, UInt uiStride, Long* pDes )
+{
+  Int x, y;
+  
+  Long aaiTemp[16][16];
+  Long B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15;
+  Long C0, C1, C2, C3, C4, C5, C6, C7, C10, C11, C12, C13;
+  Long D0, D1, D2, D3, D5, D6, D8, D9, D10, D11, D12, D13, D14, D15;
+  Long E4, E5, E6, E7, E9, E10, E13, E14;
+  Long F8, F9, F10, F11, F12, F13, F14, F15;
+#ifdef TRANS_PRECISION_EXT
+  Int uiBitDepthIncrease=g_iShift16x16-g_uiBitIncrement;
+  Int offset = (uiBitDepthIncrease==0)? 0:(1<<(uiBitDepthIncrease-1));
+#endif
+  
+  //--Butterfly
+  for( y=0 ; y<16 ; y++ )
+  {
+#ifdef TRANS_PRECISION_EXT
+    B0  = (pSrc[0] + pSrc[15])<<uiBitDepthIncrease;
+    B15 = (pSrc[0] - pSrc[15])<<uiBitDepthIncrease;
+    B1  = (pSrc[1] + pSrc[14])<<uiBitDepthIncrease;
+    B14 = (pSrc[1] - pSrc[14])<<uiBitDepthIncrease;
+    B2  = (pSrc[2] + pSrc[13])<<uiBitDepthIncrease;
+    B13 = (pSrc[2] - pSrc[13])<<uiBitDepthIncrease;
+    B3  = (pSrc[3] + pSrc[12])<<uiBitDepthIncrease;
+    B12 = (pSrc[3] - pSrc[12])<<uiBitDepthIncrease;
+    B4  = (pSrc[4] + pSrc[11])<<uiBitDepthIncrease;
+    B11 = (pSrc[4] - pSrc[11])<<uiBitDepthIncrease;
+    B5  = (pSrc[5] + pSrc[10])<<uiBitDepthIncrease;
+    B10 = (pSrc[5] - pSrc[10])<<uiBitDepthIncrease;
+    B6  = (pSrc[6] + pSrc[9])<<uiBitDepthIncrease;
+    B9  = (pSrc[6] - pSrc[9])<<uiBitDepthIncrease;
+    B7  = (pSrc[7] + pSrc[8])<<uiBitDepthIncrease;
+    B8  = (pSrc[7] - pSrc[8])<<uiBitDepthIncrease;
+#else
+    B0 = pSrc[0] + pSrc[15];
+    B15 = pSrc[0] - pSrc[15];
+    B1 = pSrc[1] + pSrc[14];
+    B14 = pSrc[1] - pSrc[14];
+    B2 = pSrc[2] + pSrc[13];
+    B13 = pSrc[2] - pSrc[13];
+    B3 = pSrc[3] + pSrc[12];
+    B12 = pSrc[3] - pSrc[12];
+    B4 = pSrc[4] + pSrc[11];
+    B11 = pSrc[4] - pSrc[11];
+    B5 = pSrc[5] + pSrc[10];
+    B10 = pSrc[5] - pSrc[10];
+    B6 = pSrc[6] + pSrc[9];
+    B9 = pSrc[6] - pSrc[9];
+    B7 = pSrc[7] + pSrc[8];
+    B8 = pSrc[7] - pSrc[8];
+#endif
+    C0 = B0 + B7;
+    C7 = B0 - B7;
+    C1 = B1 + B6;
+    C6 = B1 - B6;
+    C2 = B2 + B5;
+    C5 = B2 - B5;
+    C3 = B3 + B4;
+    C4 = B3 - B4;
+    C10 = xTrRound( 45 * ( B13 - B10 ) , DenShift16);
+    C13 = xTrRound( 45 * ( B13 + B10 ) , DenShift16);
+    C11 = xTrRound( 45 * ( B12 - B11 ) , DenShift16);
+    C12 = xTrRound( 45 * ( B12 + B11 ) , DenShift16);
+    
+    D0 = C0 + C3;
+    D3 = C0 - C3;
+    D8 = B8 + C11;
+    D11 = B8 - C11;
+    D12 = B15 - C12;
+    D15 = B15 + C12;
+    D1 = C1 + C2;
+    D2 = C1 - C2;
+    D9 = B9 + C10;
+    D10 = B9 - C10;
+    D13 = B14 - C13;
+    D14 = B14 + C13;
+    D5 = xTrRound( 45 * ( C6 - C5 ) , DenShift16);
+    D6 = xTrRound( 45 * ( C6 + C5 ) , DenShift16);
+    
+    aaiTemp[0][y] = xTrRound( 45 * ( D0 + D1 ) , DenShift16);
+    aaiTemp[8][y] = xTrRound( 45 * ( D0 - D1 ) , DenShift16);
+    aaiTemp[4][y] = xTrRound( 59 * D3 + 24 * D2 , DenShift16);
+    aaiTemp[12][y] = xTrRound( 24 * D3 - 59 * D2 , DenShift16);
+    E4 = C4 + D5;
+    E5 = C4 - D5;
+    E6 = C7 - D6;
+    E7 = C7 + D6;
+    E9 = xTrRound( 24 * D14 - 59 * D9 , DenShift16);
+    E10 = xTrRound(  -59 * D13 - 24 * D10 , DenShift16);
+    E13 = xTrRound( 24 * D13 - 59 * D10 , DenShift16);
+    E14 = xTrRound( 59 * D14 + 24 * D9 , DenShift16);
+    
+    aaiTemp[2][y] = xTrRound( 12 * E4 + 62 * E7 , DenShift16);
+    aaiTemp[10][y] = xTrRound( 53 * E5 + 35 * E6 , DenShift16);
+    aaiTemp[6][y] = xTrRound( 53 * E6 - 35 * E5 , DenShift16);
+    aaiTemp[14][y] = xTrRound( 12 * E7 - 62 * E4 , DenShift16);
+    F8 = D8 + E9;
+    F9 = D8 - E9;
+    F10 = D11 - E10;
+    F11 = D11 + E10;
+    F12 = D12 + E13;
+    F13 = D12 - E13;
+    F14 = D15 - E14;
+    F15 = D15 + E14;
+    
+    aaiTemp[1][y] = xTrRound( 6 * F8 + 63 * F15 , DenShift16);
+    aaiTemp[9][y] = xTrRound( 49 * F9 + 40 * F14 , DenShift16);
+    aaiTemp[5][y] = xTrRound( 30 * F10 + 56 * F13 , DenShift16);
+    aaiTemp[13][y] = xTrRound( 61 * F11 + 18 * F12 , DenShift16);
+    aaiTemp[3][y] = xTrRound( 61 * F12 - 18 * F11 , DenShift16);
+    aaiTemp[11][y] = xTrRound( 30 * F13 - 56 * F10 , DenShift16);
+    aaiTemp[7][y] = xTrRound( 49 * F14 - 40 * F9 , DenShift16);
+    aaiTemp[15][y] = xTrRound( 6 * F15 - 63 * F8 , DenShift16);
+    
+    pSrc += uiStride;
+  }
+  
+  for( x=0 ; x<16 ; x++, pDes++ )
+  {
+    B0 = aaiTemp[x][0] + aaiTemp[x][15];
+    B15 = aaiTemp[x][0] - aaiTemp[x][15];
+    B1 = aaiTemp[x][1] + aaiTemp[x][14];
+    B14 = aaiTemp[x][1] - aaiTemp[x][14];
+    B2 = aaiTemp[x][2] + aaiTemp[x][13];
+    B13 = aaiTemp[x][2] - aaiTemp[x][13];
+    B3 = aaiTemp[x][3] + aaiTemp[x][12];
+    B12 = aaiTemp[x][3] - aaiTemp[x][12];
+    B4 = aaiTemp[x][4] + aaiTemp[x][11];
+    B11 = aaiTemp[x][4] - aaiTemp[x][11];
+    B5 = aaiTemp[x][5] + aaiTemp[x][10];
+    B10 = aaiTemp[x][5] - aaiTemp[x][10];
+    B6 = aaiTemp[x][6] + aaiTemp[x][9];
+    B9 = aaiTemp[x][6] - aaiTemp[x][9];
+    B7 = aaiTemp[x][7] + aaiTemp[x][8];
+    B8 = aaiTemp[x][7] - aaiTemp[x][8];
+    
+    C0 = B0 + B7;
+    C7 = B0 - B7;
+    C1 = B1 + B6;
+    C6 = B1 - B6;
+    C2 = B2 + B5;
+    C5 = B2 - B5;
+    C3 = B3 + B4;
+    C4 = B3 - B4;
+    C10 = xTrRound( 45 * ( B13 - B10 ) , DenShift16);
+    C13 = xTrRound( 45 * ( B13 + B10 ) , DenShift16);
+    C11 = xTrRound( 45 * ( B12 - B11 ) , DenShift16);
+    C12 = xTrRound( 45 * ( B12 + B11 ) , DenShift16);
+    
+    D0 = C0 + C3;
+    D3 = C0 - C3;
+    D8 = B8 + C11;
+    D11 = B8 - C11;
+    D12 = B15 - C12;
+    D15 = B15 + C12;
+    D1 = C1 + C2;
+    D2 = C1 - C2;
+    D9 = B9 + C10;
+    D10 = B9 - C10;
+    D13 = B14 - C13;
+    D14 = B14 + C13;
+    D5 = xTrRound( 45 * ( C6 - C5 ) , DenShift16);
+    D6 = xTrRound( 45 * ( C6 + C5 ) , DenShift16);
+    
+    pDes[0] = xTrRound( 45 * ( D0 + D1 ) , DenShift16);
+    pDes[128] = xTrRound( 45 * ( D0 - D1 ) , DenShift16);
+    pDes[64] = xTrRound( 59 * D3 + 24 * D2 , DenShift16);
+    pDes[192] = xTrRound( 24 * D3 - 59 * D2 , DenShift16);
+#ifdef TRANS_PRECISION_EXT
+    pDes[0  ] = (pDes[0  ]+offset)>>uiBitDepthIncrease;
+    pDes[128] = (pDes[128]+offset)>>uiBitDepthIncrease;
+    pDes[64 ] = (pDes[64 ]+offset)>>uiBitDepthIncrease;
+    pDes[192] = (pDes[192]+offset)>>uiBitDepthIncrease;
+#endif
+    E4 = C4 + D5;
+    E5 = C4 - D5;
+    E6 = C7 - D6;
+    E7 = C7 + D6;
+    E9 = xTrRound( 24 * D14 - 59 * D9 , DenShift16);
+    E10 = xTrRound(  -59 * D13 - 24 * D10 , DenShift16);
+    E13 = xTrRound( 24 * D13 - 59 * D10 , DenShift16);
+    E14 = xTrRound( 59 * D14 + 24 * D9 , DenShift16);
+    
+    pDes[32] = xTrRound( 12 * E4 + 62 * E7 , DenShift16);
+    pDes[160] = xTrRound( 53 * E5 + 35 * E6 , DenShift16);
+    pDes[96] = xTrRound( 53 * E6 - 35 * E5 , DenShift16);
+    pDes[224] = xTrRound( 12 * E7 - 62 * E4 , DenShift16);
+#ifdef TRANS_PRECISION_EXT
+    pDes[32]  = (pDes[32] +offset)>>uiBitDepthIncrease;
+    pDes[160] = (pDes[160]+offset)>>uiBitDepthIncrease;
+    pDes[96]  = (pDes[96] +offset)>>uiBitDepthIncrease;
+    pDes[224] = (pDes[224]+offset)>>uiBitDepthIncrease;
+#endif
+    F8 = D8 + E9;
+    F9 = D8 - E9;
+    F10 = D11 - E10;
+    F11 = D11 + E10;
+    F12 = D12 + E13;
+    F13 = D12 - E13;
+    F14 = D15 - E14;
+    F15 = D15 + E14;
+    
+    pDes[16] = xTrRound( 6 * F8 + 63 * F15 , DenShift16);
+    pDes[144] = xTrRound( 49 * F9 + 40 * F14 , DenShift16);
+    pDes[80] = xTrRound( 30 * F10 + 56 * F13 , DenShift16);
+    pDes[208] = xTrRound( 61 * F11 + 18 * F12 , DenShift16);
+    pDes[48] = xTrRound( 61 * F12 - 18 * F11 , DenShift16);
+    pDes[176] = xTrRound( 30 * F13 - 56 * F10 , DenShift16);
+    pDes[112] = xTrRound( 49 * F14 - 40 * F9 , DenShift16);
+    pDes[240] = xTrRound( 6 * F15 - 63 * F8 , DenShift16);
+#ifdef TRANS_PRECISION_EXT
+    pDes[16]  = (pDes[16] +offset)>>uiBitDepthIncrease;
+    pDes[144] = (pDes[144]+offset)>>uiBitDepthIncrease;
+    pDes[80]  = (pDes[80] +offset)>>uiBitDepthIncrease;
+    pDes[208] = (pDes[208]+offset)>>uiBitDepthIncrease;
+    pDes[48]  = (pDes[48] +offset)>>uiBitDepthIncrease;
+    pDes[176] = (pDes[176]+offset)>>uiBitDepthIncrease;
+    pDes[112] = (pDes[112]+offset)>>uiBitDepthIncrease;
+    pDes[240] = (pDes[240]+offset)>>uiBitDepthIncrease;
+#endif
+  }
+}
+#endif //E243_CORE_TRANSFORMS
+
+#if QC_MOD_LCEC_RDOQ
+UInt TComTrQuant::xCountVlcBits(UInt uiTableNumber, UInt uiCodeNumber)
+{
+  UInt uiLength = 0;
+  UInt uiCode = 0;
+
+  if ( uiCodeNumber < 128 )
+  {
+    uiLength=VLClength[uiTableNumber][uiCodeNumber];
+  }
+  else
+  {
+    if ( uiTableNumber < 10 )
+    {
+      if ( uiTableNumber < 5 )
+      {
+        uiCode = uiCodeNumber - (6 * (1 << uiTableNumber)) + (1 << uiTableNumber);
+        uiLength = ( 6 - uiTableNumber ) + 1 + 2 * xLeadingZeros(uiCode);
+      }
+      else if ( uiTableNumber < 8 )
+      {
+        uiLength = 1 + (uiTableNumber - 4) + (uiCodeNumber >> (uiTableNumber - 4));
+      }
+      else if ( uiTableNumber == 9 )
+      {
+        uiLength = 5 + ((uiCodeNumber + 5) >> 4);
+      }
+    }
+    else
+    {
+      if ( uiTableNumber == 10 )
+      {
+        uiCode = uiCodeNumber + 1;
+        uiLength = 1 + 2 * xLeadingZeros(uiCode);
+      }
+#if CAVLC_COEF_LRG_BLK
+      else if (uiTableNumber == 12)
+      {
+        uiLength = 7+(uiCodeNumber>>6);
+      }
+      else if(uiTableNumber == 13)
+      {
+        uiLength = 5+(uiCodeNumber>>4);
+      }
+#endif
+    }
+  }
+  return uiLength;
+}
+
+
+#if CAVLC_COEF_LRG_BLK
+Int TComTrQuant::bitCountRDOQ(Int coeff, Int pos, Int nTab, Int lastCoeffFlag,Int levelMode,Int run, Int maxrun, Int vlc_adaptive, Int N, 
+                              UInt uiTr1, Int iSum_big_coef, Int iBlockType, TComDataCU* pcCU, const UInt **pLumaRunTr1)
+#else
+Int TComTrQuant::bitCountRDOQ(Int coeff, Int pos, Int nTab, Int lastCoeffFlag,Int levelMode,Int run, Int maxrun, Int vlc_adaptive, Int N, 
+                              UInt uiTr1, Int iSum_big_coef, Int iBlockType, TComDataCU* pcCU)
+#endif
+{
+  UInt cn, n, level, lev;
+  Int vlc,x,cx,vlcNum,bits;
+  static const int vlcTable4[3] = {2,2,2};             // Y4x4I,Y4x4P,Y4x4B,
+
+  Int sign = coeff < 0 ? 1 : 0;
+
+  if ( N==4 )
+  {
+    n = Max(0, nTab - 2);
+  }
+  else
+  {
+    n = nTab;
+  }
+
+  UInt uiModZeroCoding = 0;
+  const UInt *uiVlcTableTemp;
+
+#if CAVLC_COEF_LRG_BLK
+  uiModZeroCoding = (m_uiRDOQOffset==1 || N>8)? 1:0;
+  int tmprun = Min(maxrun,28);
+
+  if( N<=8 )
+  {
+    uiVlcTableTemp = (nTab==2 || nTab==5)? g_auiVlcTable8x8Intra:g_auiVlcTable8x8Inter;
+  }
+  else
+  {
+    uiVlcTableTemp = (nTab==5)? g_auiVlcTable16x16Intra:g_auiVlcTable16x16Inter;
+  }
+#else
+  if( nTab == 2 || nTab == 5 ){
+    uiVlcTableTemp = g_auiVlcTable8x8Intra;
+  }
+  else
+  {
+    uiVlcTableTemp = g_auiVlcTable8x8Inter;
+  }
+#endif
+
+  level = abs(coeff);
+  lev = (level == 1) ? 0 : 1;
+
+  if ( level )
+  {
+    if ( lastCoeffFlag == 1 )
+    {     
+      x = pos + (level == 1 ? 0 : N * N);
+      if( N == 4 )
+      {
+        cx = m_uiLPTableE4[(n << 5) + x];
+        vlcNum = vlcTable4[n];
+      }
+      else{
+#if CAVLC_COEF_LRG_BLK
+        cx = xLastLevelInd(lev, pos, N);
+#else
+        cx = m_uiLPTableE8[(n << 7) + x];
+#endif
+        vlcNum = g_auiLastPosVlcNum[n][Min(16,m_uiLastPosVlcIndex[n])];
+      }
+      bits=xCountVlcBits( vlcNum, cx );
+
+      if ( level > 1 )
+      {
+        bits += xCountVlcBits( 0, 2 * (level - 2) + sign );
+      }
+      else
+      {
+        bits++;
+      }
+
+    }
+    else{ // Level !=0  && lastCoeffFlag==0
+
+      if ( !levelMode ){   
+#if CAVLC_COEF_LRG_BLK
+          if(nTab == 2 || nTab == 5)
+          {
+            cn = xRunLevelInd(lev, run, maxrun, pLumaRunTr1[uiTr1][tmprun]);
+          }
+          else
+          {
+            cn = xRunLevelIndInter(lev, run, maxrun);
+          }
+          vlc = uiVlcTableTemp[tmprun];
+#else
+        if ( N == 4 ){
+          // 4x4
+          if ( nTab == 2 ){
+            cn = xRunLevelInd(lev, run, maxrun, g_auiLumaRunTr14x4[uiTr1][maxrun]);
+          }
+          else{
+#if RUNLEVEL_TABLE_CUT
+            cn = xRunLevelIndInter(lev, run, maxrun);
+#else
+            cn = g_auiLumaRun8x8[maxrun][lev][run];
+#endif
+          }
+          vlc = uiVlcTableTemp[maxrun];
+        }
+        else {
+          // 8x8
+          if(nTab == 2 || nTab == 5)
+          {
+            cn = xRunLevelInd(lev, run, maxrun, g_auiLumaRunTr18x8[uiTr1][Min(maxrun,28)]);
+          }
+          else
+          {
+#if RUNLEVEL_TABLE_CUT
+            cn = xRunLevelIndInter(lev, run, maxrun);
+#else
+            cn = g_auiLumaRun8x8[Min(maxrun,28)][lev][run];
+#endif
+          }
+          vlc = uiVlcTableTemp[Min(maxrun,28)];
+        }
+#endif
+        bits = xCountVlcBits( vlc, cn );
+        if ( level > 1 ){
+          bits += xCountVlcBits( 0, 2 * (level - 2) + sign );
+        }
+        else{
+          bits++;
+        } 
+
+      }
+      else{ // Level !=0  && lastCoeffFlag==0 && levelMode
+        bits = (xCountVlcBits( vlc_adaptive, level ) + 1);
+      }
+    }
+  }
+  else{
+
+    if (levelMode){
+      bits=xCountVlcBits( vlc_adaptive, level );
+    }
+    else{                        
+      if ( pos == 0 && lastCoeffFlag == 0){  
+
+#if CAVLC_COEF_LRG_BLK
+        vlc = uiVlcTableTemp[tmprun];
+        if(nTab == 2 || nTab == 5)
+        {
+          cn = xRunLevelInd(0, run + 1, maxrun, pLumaRunTr1[uiTr1][tmprun]);
+        }
+        else
+        {
+          cn = xRunLevelIndInter(0, run + 1, maxrun);
+        }
+#else
+        if ( N == 4 ){
+          // 4x4
+          vlc = uiVlcTableTemp[maxrun];
+          if ( nTab == 2 ){
+            cn = xRunLevelInd(0, run + 1, maxrun, g_auiLumaRunTr14x4[uiTr1][maxrun]);
+          }
+          else{
+#if RUNLEVEL_TABLE_CUT
+            cn = xRunLevelIndInter(0, run+1, maxrun);
+#else
+            cn = g_auiLumaRun8x8[maxrun][0][run + 1];
+#endif
+          }
+        }
+        else{
+          // 8x8
+          vlc = uiVlcTableTemp[Min(maxrun, 28)];
+          if(nTab == 2 || nTab == 5){
+            cn = xRunLevelInd(0, run + 1, maxrun, g_auiLumaRunTr18x8[uiTr1][Min(maxrun, 28)]);
+          }
+          else{
+#if RUNLEVEL_TABLE_CUT
+            cn = xRunLevelIndInter(0, run+1, maxrun);
+#else
+            cn = g_auiLumaRun8x8[Min(maxrun, 28)][0][run + 1];
+#endif
+          }
+        }
+#endif
+        bits=xCountVlcBits( vlc, cn );
+      }
+      else{
+        bits = 0;
+
+        if ( pos > 0 && uiModZeroCoding == 1 ){
+
+          Int iSum_big_coefTemp, levelModeTemp, maxrunTemp;
+          UInt uiTr1Temp;
+
+          if ( lastCoeffFlag == 0 ){
+
+#if CAVLC_COEF_LRG_BLK
+            vlc = uiVlcTableTemp[tmprun];
+            if(nTab == 2 || nTab == 5)
+            {
+              cn = xRunLevelInd(0, run + 1, maxrun, pLumaRunTr1[uiTr1][tmprun]);
+            }
+            else
+            {
+              cn = xRunLevelIndInter(0, run + 1, maxrun);
+            }
+#else
+            if ( N == 4 ){
+              // 4x4
+              vlc = uiVlcTableTemp[maxrun];
+              if ( nTab == 2 ){
+                cn = xRunLevelInd(0, run + 1, maxrun, g_auiLumaRunTr14x4[uiTr1][maxrun]);
+              }
+              else{
+#if RUNLEVEL_TABLE_CUT
+                cn = xRunLevelIndInter(0, run+1, maxrun);
+#else
+                cn = g_auiLumaRun8x8[maxrun][0][run + 1];
+#endif
+              }
+            }
+            else{
+              // 8x8
+              vlc = uiVlcTableTemp[Min(maxrun, 28)];
+              if(nTab == 2 || nTab == 5){
+                cn = xRunLevelInd(0, run + 1, maxrun, g_auiLumaRunTr18x8[uiTr1][Min(maxrun, 28)]);
+              }
+              else{
+#if RUNLEVEL_TABLE_CUT
+                cn = xRunLevelIndInter(0, run+1, maxrun);
+#else
+                cn = g_auiLumaRun8x8[Min(maxrun,28)][0][run + 1];
+#endif
+              }
+            }
+#endif
+          }
+          else{
+
+            x = (pos - 1);
+            if( N == 4 )
+            {
+              cn = m_uiLPTableE4[(n << 5) + x];
+              vlc = vlcTable4[n];
+            }
+            else{
+#if CAVLC_COEF_LRG_BLK
+              cn = xLastLevelInd(lev, pos, N);
+#else
+              cn = m_uiLPTableE8[(n << 7) + x];
+#endif
+              vlc = g_auiLastPosVlcNum[n][Min(16, m_uiLastPosVlcIndex[n])];
+            }
+          }
+          bits+=xCountVlcBits( vlc, cn );
+
+          // Next coeff is 1 with run=0
+
+          iSum_big_coefTemp = iSum_big_coef;
+          levelModeTemp = levelMode;
+          Int switch_thr[10] = {49,49,0,49,49,0,49,49,49,49};
+
+          if ( N > 4 ){ 
+            if ( level > 1 ){
+              iSum_big_coefTemp += level;
+              if ((N * N - pos - 1) > switch_thr[iBlockType] || iSum_big_coefTemp > 2) levelModeTemp = 1;
+            }
+          }
+          else{
+            if ( level > 1 ) levelModeTemp = 1;
+          }
+
+          if ( levelModeTemp == 1 ){
+            bits-=xCountVlcBits( vlc_adaptive, 1);
+          }
+          else{
+            maxrunTemp = pos - 1;
+            uiTr1Temp = uiTr1;
+
+            if ( uiTr1Temp > 0 && level < 2 ){
+              uiTr1Temp++;
+              uiTr1Temp = Min(MAX_TR1, uiTr1Temp);
+            }
+            else{
+              uiTr1Temp=0;
+            }
+
+#if CAVLC_COEF_LRG_BLK
+            vlc = uiVlcTableTemp[Min(maxrunTemp,28)];
+            if(nTab == 2 || nTab == 5)
+            {
+              cn = xRunLevelInd(0, 0, maxrunTemp, pLumaRunTr1[uiTr1Temp][Min(maxrunTemp,28)]);
+            }
+            else
+            {
+              cn = xRunLevelIndInter(0, 0, maxrunTemp);
+            }
+#else
+            if ( N == 4 ){
+              // 4x4
+              vlc = uiVlcTableTemp[maxrunTemp];
+              if ( nTab == 2 ){
+                cn = xRunLevelInd(0, 0, maxrunTemp, g_auiLumaRunTr14x4[uiTr1Temp][maxrunTemp]);
+              }
+              else{
+#if RUNLEVEL_TABLE_CUT
+                cn = xRunLevelIndInter(0, 0, maxrunTemp);
+#else
+                cn = g_auiLumaRun8x8[maxrunTemp][0][0];
+#endif
+              }
+            }
+            else{
+              // 8x8
+              vlc = uiVlcTableTemp[Min(maxrunTemp,28)];
+              if(nTab == 2 || nTab == 5){
+                cn = xRunLevelInd(0, 0, maxrunTemp, g_auiLumaRunTr18x8[uiTr1Temp][Min(maxrunTemp,28)]);
+              }
+              else{
+#if RUNLEVEL_TABLE_CUT
+                cn = xRunLevelIndInter(0, 0, maxrunTemp);
+#else
+                cn = g_auiLumaRun8x8[Min(maxrunTemp,28)][0][0];
+#endif
+              }
+            }
+#endif
+            bits -= xCountVlcBits( vlc, cn );
+          }
+        } // if ( pos > 0 && uiModZeroCoding == 1 ){
+
+      } 
+    }
+  }
+  return bits;
+}
+
+Int TComTrQuant::xCodeCoeffCountBitsLast(TCoeff* scoeff, levelDataStruct* levelData, Int nTab, UInt N)
+{
+  Int i, prevCoeffInd, lastPosMin, iRate;
+  Int done,last_pos;
+#if CAVLC_COEF_LRG_BLK
+  Int run_done, maxrun,run, bitsLast[1024], bitsRun[1024], bitsLastPrev;
+  quantLevelStruct quantCoeffInfo[1024];
+#else
+  Int run_done, maxrun,run, bitsLast[256], bitsRun[256], bitsLastPrev;
+  quantLevelStruct quantCoeffInfo[256];
+#endif
+  UInt last_pos_init, bitsLevel, sign, lev, cn, vlc, uiBitShift=15, uiNoCoeff=N*N, absLevel;
+  Int n;
+  double lagrMin, lagr, lagrPrev;
+  UInt uiLumaRunNoTr14x4[15]={2, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2};
+  UInt uiLumaRunNoTr18x8[29]={2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 13};
+
+
+  if ( N == 4 ){
+    n = Max(0, nTab - 2);
+  }
+  else
+  {
+    n = nTab;
+  }
+
+  /* Do the last coefficient first */
+  i = uiNoCoeff - 1;
+  done = 0;
+
+  while ( !done && i >= 0 )
+  {
+    if (scoeff[i])
+    {
+      done = 1;
+    }
+    else
+    {
+      i--;
+    }
+  }
+  if (i == -1)
+  {
+    return(-1);
+  }
+
+  last_pos = last_pos_init = i;
+  prevCoeffInd = i;
+
+  i--;
+
+  if ( i >= 0 ){
+
+    /* Go into run mode */
+    run_done = 0;
+    while ( !run_done )
+    {
+      maxrun = i;
+
+      run = 0;
+      done = 0;
+      while ( !done )
+      {
+        if ( !scoeff[i] )
+        {
+          run++;
+        }
+        else
+        {
+          quantCoeffInfo[prevCoeffInd].run=run;
+          quantCoeffInfo[prevCoeffInd].maxrun=maxrun;
+          quantCoeffInfo[prevCoeffInd].nextLev=(abs(scoeff[i]) == 1) ? 0 : 1;
+          quantCoeffInfo[prevCoeffInd].nexLevelVal=scoeff[i];
+
+          prevCoeffInd = i;
+
+          run = 0;
+          done = 1;
+        }
+        if (i == 0)
+        {
+          quantCoeffInfo[prevCoeffInd].run=run;
+          quantCoeffInfo[prevCoeffInd].maxrun=maxrun;
+          quantCoeffInfo[prevCoeffInd].nextLev=0;
+          quantCoeffInfo[prevCoeffInd].nexLevelVal=0;
+
+          done = 1;
+          run_done = 1;
+        }
+        i--;
+      }
+    }
+  }
+
+#if CAVLC_COEF_LRG_BLK
+  const UInt *vlcTableIntra = (N<=8)? g_auiVlcTable8x8Intra:g_auiVlcTable16x16Intra;
+  const UInt *vlcTableInter = (N<=8)? g_auiVlcTable8x8Inter:g_auiVlcTable16x16Inter;
+  const UInt *pLumaRunTr1 = (N==4)? uiLumaRunNoTr14x4:uiLumaRunNoTr18x8;
+#endif
+  for (i = last_pos_init; i >= 0; i--){
+
+    if (scoeff[i]){
+
+      bitsLast[i] = bitsRun[i] = 0; 
+
+      last_pos = i;
+      {
+        int x,cx,vlcNum;
+        int vlcTable[3] = {2,2,2};
+
+        bitsLevel=0;
+        absLevel = abs(scoeff[i]);
+        sign = (scoeff[i] < 0) ? 1 : 0;
+        lev = (absLevel == 1) ? 0 : 1;
+
+        if (absLevel > 1)
+        {
+          bitsLevel=xCountVlcBits( 0, 2*(absLevel-2)+sign );
+        }
+        else
+        {
+          bitsLevel++;
+        }
+
+        x = uiNoCoeff*lev + last_pos;
+
+        if ( uiNoCoeff == 16 ){
+          cx = m_uiLPTableE4[n * 32 + x];
+          vlcNum = vlcTable[n];
+        }
+        else {
+#if CAVLC_COEF_LRG_BLK
+          cx = xLastLevelInd(lev, last_pos, N);
+#else
+          cx = m_uiLPTableE8[n * 128 + x];
+#endif
+          vlcNum = g_auiLastPosVlcNum[n][Min(16,m_uiLastPosVlcIndex[n])];
+        }
+        bitsLast[i]=bitsLevel + xCountVlcBits( vlcNum, cx);
+      }
+
+      bitsRun[i]=0;
+
+      if ( i > 0 )
+      {
+        bitsLevel = 0;
+        if ( quantCoeffInfo[i].nexLevelVal != 0 ){
+          absLevel = abs(quantCoeffInfo[i].nexLevelVal);
+          sign = (quantCoeffInfo[i].nexLevelVal < 0) ? 1 : 0;
+          lev = (absLevel == 1) ? 0 : 1;
+
+          if (absLevel > 1)
+          {
+            bitsLevel = xCountVlcBits( 0, 2 * (absLevel - 2) + sign );
+          }
+          else
+          {
+            bitsLevel++;
+          }
+        }
+
+        bitsRun[i] = bitsLevel;
+        run = quantCoeffInfo[i].run;
+        maxrun = quantCoeffInfo[i].maxrun;
+
+#if CAVLC_COEF_LRG_BLK 
+        Int tmprun = Min(maxrun,28);
+        if(nTab == 2 || nTab == 5)
+        {
+          vlc = vlcTableIntra[tmprun]; 
+          cn = xRunLevelInd(quantCoeffInfo[i].nextLev, run, maxrun, pLumaRunTr1[tmprun]);
+        }
+        else
+        {
+          vlc = vlcTableInter[tmprun]; 
+          cn = xRunLevelIndInter(quantCoeffInfo[i].nextLev, run, maxrun);
+        }
+        bitsRun[i] += xCountVlcBits( vlc, cn );
+#else
+        if ( uiNoCoeff == 16 )
+        {
+          if ( nTab == 2 ){
+            vlc = g_auiVlcTable8x8Intra[maxrun];        
+            cn = xRunLevelInd(quantCoeffInfo[i].nextLev, run, maxrun, uiLumaRunNoTr14x4[maxrun]);
+          }
+          else{
+            vlc = g_auiVlcTable8x8Inter[maxrun];           
+#if RUNLEVEL_TABLE_CUT
+            cn = xRunLevelIndInter(quantCoeffInfo[i].nextLev, run, maxrun);
+#else
+            cn = g_auiLumaRun8x8[maxrun][quantCoeffInfo[i].nextLev][run];
+#endif
+          }
+          bitsRun[i] += xCountVlcBits( vlc, cn );
+        }
+        else
+        {
+          if(nTab == 2 || nTab == 5){
+            vlc = g_auiVlcTable8x8Intra[Min(maxrun,28)];          
+            cn = xRunLevelInd(quantCoeffInfo[i].nextLev, run, maxrun, uiLumaRunNoTr18x8[min(maxrun,28)]);
+          }
+          else{
+            vlc = g_auiVlcTable8x8Inter[Min(maxrun,28)];           
+#if RUNLEVEL_TABLE_CUT
+            cn = xRunLevelIndInter(quantCoeffInfo[i].nextLev, run, maxrun); 
+#else
+            cn = g_auiLumaRun8x8[min(maxrun,28)][quantCoeffInfo[i].nextLev][run];
+#endif
+          }
+          bitsRun[i] += xCountVlcBits( vlc, cn );
+        }
+#endif
+      }
+    }
+  }
+
+  lagrMin=0; lastPosMin=-1; 
+  for (i=0; i<uiNoCoeff; i++){
+    if ( scoeff[i] != 0 ){
+      lagrMin += levelData[i].errLevel[0];
+    }
+  }
+
+  UInt first=1; 
+
+  bitsLastPrev=0; lagrPrev=lagrMin;
+  for (i=0; i<uiNoCoeff; i++){
+    if (scoeff[i]){
+      iRate = (bitsRun[i] + bitsLast[i] - bitsLastPrev) << uiBitShift;
+      lagr = lagrPrev-levelData[i].errLevel[0] + levelData[i].errLevel[levelData[i].quantInd] + m_dLambda*iRate;
+      bitsLastPrev = bitsLast[i];
+      lagrPrev = lagr;
+
+      if ( lagr < lagrMin || abs(scoeff[i]) > 1 || first == 1){
+        lagrMin = lagr;
+        lastPosMin =i;
+        first = 0;
+      }
+    }
+  }
+
+  return(lastPosMin);
+}    
+#else
+#if QC_MOD_LCEC
+Int TComTrQuant::bitCount_LCEC(Int k,Int pos,Int nTab, Int lpflag,Int levelMode,Int run, Int maxrun, Int vlc_adaptive, Int N, UInt uiTr1)
+#else
+Int TComTrQuant::bitCount_LCEC(Int k,Int pos,Int n,Int lpflag,Int levelMode,Int run,Int maxrun,Int vlc_adaptive,Int N)
+#endif
+{
+  UInt cn;
+  int vlc,x,cx,vlcNum,bits,temp;
+#if QC_MOD_LCEC == 0
+  static const int vlctable_8x8[28] = {8,0,0,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6};
+  static const int vlcTable8[8] = {10,10,3,3,3,4,4,4}; // U,V,Y8x8I,Y8x8P,Y8x8B,Y16x16I,Y16x16P,Y16x16B
+#endif
+  static const int vlcTable4[3] = {2,2,2};             // Y4x4I,Y4x4P,Y4x4B,
+#if QC_MOD_LCEC == 0
+  static const int VLClength[11][128] =
+  {
+    { 1, 2, 3, 4, 5, 6, 7, 9, 9,11,11,11,11,13,13,13,13,13,13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19},
+    { 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,10,10,10,10,12,12,12,12,12,12,12,12,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18},
+    { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,11,11,11,11,11,11,11,11,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17},
+    { 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16},
+    { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13},
+    { 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,43,43,44,44,45,45,46,46,47,47,48,48,49,49,50,50,51,51,52,52,53,53,54,54,55,55,56,56,57,57,58,58,59,59,60,60,61,61,62,62,63,63,64,64,65,65},
+    { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,14,15,15,15,15,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,22,22,22,22,23,23,23,23,24,24,24,24,25,25,25,25,26,26,26,26,27,27,27,27,28,28,28,28,29,29,29,29,30,30,30,30,31,31,31,31,32,32,32,32,33,33,33,33,34,34,34,34},
+    { 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19},
+    { 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+    { 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13},
+    { 1, 3, 3, 5, 5, 5, 5, 7, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,15}
+  };
+#endif
+  int sign = k<0 ? 1 : 0;
+  
+  k = abs(k);
+#if QC_MOD_LCEC
+  Int n;
+  Int lev = (k>1 ? 1 : 0);
+  if (N==4)
+    n=max(0,nTab-2);
+  else
+    n=nTab;
+#endif
+  if (N != 4 && N!= 8)
+  {
+    FATAL_ERROR_0("unsupported block size in bitCount_LCEC()" , -1 );
+  }
+  if (k)
+  {
+    if (lpflag==1)
+    {                       
+      x = pos + (k==1 ? 0 : N*N);
+      if (N==8)
+      {
+        cx = m_uiLPTableE8[n*128+x];
+#if QC_MOD_LCEC
+        vlcNum = g_auiLastPosVlcNum[n][Min(16,m_uiLastPosVlcIndex[n])];
+#else
+        vlcNum = vlcTable8[n];
+#endif
+      }
+      else // (N==4)
+      {
+        cx = m_uiLPTableE4[n*32+x];
+        vlcNum = vlcTable4[n];
+      }
+      bits = VLClength[vlcNum][cx];
+      if (k>1)
+      {
+        temp = 2*(k-2)+sign;
+        if(temp > 127)
+          temp = 127;
+        bits += VLClength[0][temp];
+      }
+      else
+        bits += 1;                                     
+    }
+    else
+    {
+      if (!levelMode)
+      {                                                    
+#if QC_MOD_LCEC
+        const UInt *p_auiLumaRunTr1 = g_auiLumaRunTr14x4[uiTr1];
+        UInt ui_maxrun = maxrun;
+        if (N==8)
+        { 
+          p_auiLumaRunTr1 = g_auiLumaRunTr18x8[uiTr1];
+          ui_maxrun =min(maxrun,28);
+        }
+        if(nTab == 2 || nTab == 5)
+        {
+          cn = xRunLevelInd(lev, run, maxrun, p_auiLumaRunTr1[ui_maxrun]);
+          vlc = g_auiVlcTable8x8Intra[ui_maxrun];
+        }
+        else
+        {
+          cn = g_auiLumaRun8x8[ui_maxrun][lev][run];
+          vlc = g_auiVlcTable8x8Inter[ui_maxrun];
+        }
+#else                                      
+        if (maxrun > 27)
+        {
+          cn = g_auiLumaRun8x8[28][k>1 ? 1 : 0][run];
+        }
+        else
+        {
+          cn = g_auiLumaRun8x8[maxrun][k>1 ? 1 : 0][run];
+        }
+        vlc = (maxrun>27) ? 3 : vlctable_8x8[maxrun];
+#endif
+        bits = VLClength[vlc][cn];
+        if (k>1)
+        {
+          temp = 2*(k-2)+sign;
+          if(temp > 127)
+            temp = 127;
+          bits += VLClength[0][temp];
+        }
+        else
+          bits += 1;  
+        
+      }
+      else
+      {
+        if(k > 127)
+          k = 127;
+        bits = VLClength[vlc_adaptive][k] + 1;
+      }
+    }
+  }
+  else
+  {
+    if (levelMode)
+      bits = VLClength[vlc_adaptive][k];
+    else
+    {                        
+      if (pos==0 && lpflag==0)
+      {  
+#if QC_MOD_LCEC
+        const UInt *p_auiLumaRunTr1 = g_auiLumaRunTr14x4[uiTr1];
+        UInt ui_maxrun = maxrun;
+        if (N==8)
+        { 
+           p_auiLumaRunTr1 = g_auiLumaRunTr18x8[uiTr1];
+           ui_maxrun =min(maxrun,28);
+        }
+        if(nTab == 2 || nTab == 5)
+        {
+          cn = xRunLevelInd(0, run+1, maxrun, p_auiLumaRunTr1[ui_maxrun]);
+          vlc = g_auiVlcTable8x8Intra[ui_maxrun];
+        }
+        else
+        {
+          cn = g_auiLumaRun8x8[ui_maxrun][0][run+1];
+          vlc = g_auiVlcTable8x8Inter[ui_maxrun];
+        }
+#else   
+        if (maxrun > 27)
+        {
+          cn = g_auiLumaRun8x8[28][0][run+1];
+        }
+        else
+        {
+          cn = g_auiLumaRun8x8[maxrun][0][run+1];
+        }
+        vlc = (maxrun>27) ? 3 : vlctable_8x8[maxrun];
+#endif
+        bits = VLClength[vlc][cn];
+      }
+      else
+        bits = 0;
+    }
+  }
+  return bits;
+}
+#endif
+#if QC_MOD_LCEC_RDOQ
+static levelDataStruct slevelData  [ MAX_CU_SIZE*MAX_CU_SIZE ];
+Void TComTrQuant::xRateDistOptQuant_LCEC(TComDataCU* pcCU, Long* pSrcCoeff, TCoeff*& pDstCoeff, UInt uiWidth, UInt uiHeight, UInt& uiAbsSum, TextType eTType, 
+                                         UInt uiAbsPartIdx )
+{
+  Int     i, j;
+  Int     iShift = 0;
+  Int     qp_rem, q_bits;
+  Double  err, lagr, lagrMin;
+  Double  normFact = 0.0;
+  Double  OneOverNormFact = 0.0;
+  Double  fTemp = 0.0;
+  Int     iQuantCoeff;
+  
+#if E243_CORE_TRANSFORMS
+  Int     iShiftQBits, iSign, iRate, lastPosMin, iBlockType;
+  UInt    uiBitShift = SCALE_BITS, uiScanPos, levelInd;
+  Int     levelBest, iLevel;
+#else
+  Bool    bExt8x8Flag = false;
+  Int     iShiftQBits, iSign, iRate, lastPosMin, iBlockType;
+  UInt    uiBitShift = 15, uiScanPos, levelInd;
+  Int     levelBest, iLevel, iAdd;
+#endif
+
+  levelDataStruct* levelData = &slevelData[0];
+
+  Int     iPos, iScanning;
+
+#if CAVLC_COEF_LRG_BLK
+  static TCoeff sQuantCoeff[1024];
+#else
+  static TCoeff sQuantCoeff[256];
+#endif
+
+  qp_rem    = m_cQP.m_iRem;
+  q_bits    = m_cQP.m_iBits;
+
+  UInt noCoeff=(uiWidth < 8 ? 16 : 64);
+#if CAVLC_COEF_LRG_BLK
+  UInt maxBlSize = (eTType==TEXT_LUMA)? 32:8;
+  UInt uiBlSize = Min(uiWidth,maxBlSize);
+  noCoeff = uiBlSize*uiBlSize;
+#endif
+
+#if E243_CORE_TRANSFORMS 
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiWidth ] + 2;
+  UInt uiQ = g_auiQ[m_cQP.rem()];
+
+#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
+  double dErrScale = (double)(1<<uiBitShift);                              // Compensate for scaling of bitcount in Lagrange cost function
+  dErrScale = dErrScale*pow(2.0,-2.0*iTransformShift);                     // Compensate for scaling through forward transform
+  dErrScale = dErrScale/(double)(uiQ*uiQ);                                 // Compensate for qp-dependent multiplier applied before calculating the Lagrange cost function
+  dErrScale = dErrScale/(double)(1<<(2*g_uiBitIncrement));                   // Compensate for Lagrange multiplier that is tuned towards 8-bit input
+
+  q_bits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+
+  iShift = uiLog2TrSize;
+  if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+  {
+    iBlockType = eTType-2;
+  }
+  else
+  {
+    iBlockType = (uiWidth < 16 ? 2 : 5) + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() ); 
+  }
+#else
+  if ( uiWidth == 4 && uiHeight == 4 )
+  {
+    normFact = pow(2., (2 * DQ_BITS + 19));
+    if ( g_uiBitIncrement ) normFact *= 1 << (2 * g_uiBitIncrement);
+    m_puiQuantMtx = &g_aiQuantCoef  [m_cQP.m_iRem][0];
+    iShift = 2;
+    iAdd = m_cQP.m_iAdd4x4;
+
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+  }
+  else
+    if ( uiWidth == 8 && uiHeight == 8 )
+    {
+      q_bits++;
+      normFact = pow(2., (2 * Q_BITS_8 + 9));
+      if ( g_uiBitIncrement ) normFact *= 1<<(2*g_uiBitIncrement);
+      m_puiQuantMtx = &g_aiQuantCoef64[m_cQP.m_iRem][0];
+      iShift = 3;
+      iAdd = m_cQP.m_iAdd8x8;
+
+      if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V) 
+        iBlockType = eTType-2;
+      else
+        iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() ); 
+    }
+    else
+      if ( uiWidth == 16 && uiHeight == 16 )
+      {
+        q_bits = ECore16Shift + m_cQP.per();
+        normFact = pow(2., 21);
+        if ( g_uiBitIncrement ) normFact *= 1 << (2 * g_uiBitIncrement);
+        fTemp = estErr16x16[qp_rem] / normFact;
+
+        m_puiQuantMtx = ( &g_aiQuantCoef256[m_cQP.m_iRem][0] );
+        iShift = 4;
+        iAdd = m_cQP.m_iAdd16x16;
+        bExt8x8Flag = true;
+
+        if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V) 
+          iBlockType = eTType-2;
+        else
+          iBlockType = 5 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() ); 
+      }
+      else
+        if ( uiWidth == 32 && uiHeight == 32 )
+        {
+          q_bits = ECore32Shift + m_cQP.per();
+          normFact = pow(2., 21);
+          if ( g_uiBitIncrement ) normFact *= 1<<(2*g_uiBitIncrement);
+          fTemp = estErr32x32[qp_rem]/normFact;
+
+          m_puiQuantMtx = ( &g_aiQuantCoef1024[m_cQP.m_iRem][0] );
+          iShift = 5;
+          iAdd = m_cQP.m_iAdd32x32;
+          bExt8x8Flag = true;
+
+          if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V) 
+            iBlockType = eTType-2;
+          else
+            iBlockType = 5 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() ); 
+        }
+        else
+        {
+          iBlockType =0;
+
+          assert(0);
+        }
+#endif //E243_CORE_TRANSFORMS
+        memset(&pDstCoeff[0],0,uiWidth*uiHeight*sizeof(TCoeff)); 
+
+        iShiftQBits = (1 <<( q_bits - 1));
+
+
+#if QC_MDCS
+#if CAVLC_COEF_LRG_BLK
+        UInt uiLog2BlkSize = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : uiBlSize   ] + 2;
+#else
+        UInt uiLog2BlkSize = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : Min(8,uiWidth)    ] + 2;
+#endif
+        const UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+#else
+        const UInt* pucScan;
+        if( !pcCU->isIntra(uiAbsPartIdx )){
+#if CAVLC_COEF_LRG_BLK
+          pucScan = g_auiFrameScanXY[ g_aucConvertToBit[ uiBlSize ] + 1];
+#else
+          pucScan = g_auiFrameScanXY[ g_aucConvertToBit[ Min(uiWidth, 8) ] + 1];
+#endif
+        }
+        else{
+          pucScan = g_auiFrameScanXY[ g_aucConvertToBit[ uiWidth ] + 1];
+        }
+#endif //QC_MDCS
+
+
+
+        OneOverNormFact = 1.0 / normFact;
+
+        UInt uiShift_local = iShift;
+        UInt uiRes_local = (uiWidth - 1);
+        UInt uiWidth_local = uiShift_local;
+
+#if CAVLC_COEF_LRG_BLK
+        if(!pcCU->isIntra(uiAbsPartIdx) && uiWidth > maxBlSize)
+        {
+          uiShift_local = g_aucConvertToBit[ maxBlSize ] + 2;;
+          uiRes_local = maxBlSize - 1; 
+        }
+#else
+        if( !pcCU->isIntra(uiAbsPartIdx) && uiWidth >= 16 )
+        {
+          uiShift_local = 3;
+          uiRes_local = 7; 
+        }
+#endif
+
+        Int iAddRDOQ = 0;
+#if E243_CORE_TRANSFORMS
+        /* Code below is consistent with JCTVC-E243 but could preferably be replaced with iAddRDOQ = 171 << (q_bits-9); */
+        if (q_bits>=15)
+        {
+          iAddRDOQ = (uiWidth<16 ? 10922 : 10880) << (q_bits-15);
+        }
+        else
+        {
+          iAddRDOQ = (uiWidth<16 ? 10922 : 10880) >> (15-q_bits);
+        }
+#else
+        {
+          UInt uiSliceType = 0;
+
+          Int iQP=pcCU->getSlice()->getSliceQp();
+          if( eTType != TEXT_LUMA ) //Chroma
+          {
+            iQP  = g_aucChromaScale[ iQP ];
+          }
+
+          Int iDefaultOffset;
+          Int iDefaultOffset_LTR;
+          Int iPer;
+          Int k =  (iQP + 6 * g_uiBitIncrement) / 6;
+#if FULL_NBIT
+          k += g_uiBitDepth - 8;
+#endif
+          Bool bLowPass = (uiSliceType == 0);
+          iDefaultOffset = (bLowPass ? 10922 : 5462);
+
+          bLowPass = (uiSliceType == 0);
+          iDefaultOffset_LTR = (bLowPass? 170 : 86);
+
+          if ( uiWidth == 4 && uiWidth == 4 ){
+            iPer = QP_BITS + k - QOFFSET_BITS;
+            iAddRDOQ = iDefaultOffset << iPer;
+          }
+          else if ( uiWidth == 8 && uiWidth == 8){
+            iPer = QP_BITS + k + 1 - QOFFSET_BITS;
+            iAddRDOQ = iDefaultOffset << iPer;
+          }
+          else if ( uiWidth == 16 && uiHeight == 16 ){
+            iPer = ECore16Shift + k - QOFFSET_BITS_LTR;
+            iAddRDOQ = iDefaultOffset_LTR << iPer;
+          }
+          else if ( uiWidth == 32 && uiHeight == 32 ){
+            iPer = ECore32Shift + k - QOFFSET_BITS_LTR;
+            iAddRDOQ = iDefaultOffset_LTR << iPer;
+          }
+        }
+#endif
+        if (m_uiRDOQOffset==1)
+          iAddRDOQ=iShiftQBits;
+
+        for (iScanning=noCoeff-1; iScanning>=0; iScanning--) 
+        {
+#if QC_MDCS
+          iPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][iScanning];
+#else
+          iPos = pucScan[iScanning];
+#endif //QC_MDCS
+          j = iPos >> uiShift_local;
+          i = iPos &  uiRes_local;
+          iPos = (j << uiWidth_local) + i;
+
+          levelDataStruct *psLevelData = &levelData[iScanning];
+#if E243_CORE_TRANSFORMS
+          psLevelData->levelDouble = abs(pSrcCoeff[iPos]) * uiQ;          
+          iQuantCoeff = (Int)((psLevelData->levelDouble + iAddRDOQ) >> q_bits);
+
+          psLevelData->levelQ   = (Long)( psLevelData->levelDouble >> q_bits );
+          psLevelData->lowerInt = ( ( psLevelData->levelDouble - (psLevelData->levelQ << q_bits) ) < iShiftQBits ) ? true : false;
+
+          iSign = pSrcCoeff[iPos] < 0 ? -1 : 1;
+          sQuantCoeff[iScanning] = iQuantCoeff*iSign;
+
+          fTemp = dErrScale;
+#else
+          psLevelData->levelDouble = abs( pSrcCoeff[iPos] * (Long) m_puiQuantMtx[iPos]);
+          iQuantCoeff=(Int)((psLevelData->levelDouble +iAddRDOQ) >> q_bits);
+
+          psLevelData->levelQ   = ( psLevelData->levelDouble >> q_bits );
+          psLevelData->lowerInt = ( ( psLevelData->levelDouble - (psLevelData->levelQ << q_bits) ) < iShiftQBits ) ? true : false;
+
+          iSign = pSrcCoeff[iPos] < 0 ? -1 : 1;
+          sQuantCoeff[iScanning] = iQuantCoeff*iSign;
+
+          if      ( uiWidth == 4 ) fTemp = estErr4x4[qp_rem][i][j] * OneOverNormFact;
+          else if ( uiWidth == 8 ) fTemp = estErr8x8[qp_rem][i][j] * OneOverNormFact;
+#endif
+          psLevelData->level[0] = 0;
+          err = (Double)(psLevelData->levelDouble);
+          psLevelData->errLevel[0] = err * err * fTemp;
+
+          if ( !psLevelData->levelQ )
+          {
+            if ( psLevelData->lowerInt )
+            {
+              psLevelData->noLevels = 1;
+            }
+            else
+            {
+              psLevelData->level[1] = 1;
+              psLevelData->noLevels = 2;
+            }
+            if (iQuantCoeff==0)
+              psLevelData->quantInd=0;
+            else
+              psLevelData->quantInd=1;
+
+          }
+          else if ( psLevelData->lowerInt )
+          {
+            psLevelData->level[1] = psLevelData->levelQ;
+            psLevelData->noLevels = 2;
+
+            if ( psLevelData->levelQ > 1 ){
+              psLevelData->noLevels++;
+              psLevelData->level[2] = 1;
+            }
+
+            psLevelData->quantInd = 1;
+          }
+          else
+          {
+            psLevelData->level[1] = psLevelData->levelQ;
+            psLevelData->level[2] = psLevelData->levelQ + 1;
+            psLevelData->noLevels = 3;
+
+            if ( psLevelData->levelQ > 1 ){
+              psLevelData->noLevels++;
+              psLevelData->level[3] = 1;
+            }
+            if ( iQuantCoeff == psLevelData->level[1] )
+              psLevelData->quantInd = 1;
+            else
+              psLevelData->quantInd = 2;
+          }
+
+          for ( levelInd = 1; levelInd < psLevelData->noLevels; levelInd++ ){
+            err = (Double)((psLevelData->level[levelInd] << q_bits) - psLevelData->levelDouble);
+            psLevelData->errLevel[levelInd] = err * err * fTemp;
+            psLevelData->level[levelInd] *= iSign;
+          }
+        }
+
+#if CAVLC_COEF_LRG_BLK==0
+        UInt uiNum;
+        if ( uiWidth == 4 )
+          uiNum = 4;
+        else
+          uiNum = 8;
+#endif
+
+        // Last Position
+#if CAVLC_COEF_LRG_BLK
+        lastPosMin = xCodeCoeffCountBitsLast(sQuantCoeff, levelData, iBlockType, uiBlSize);
+#else
+        lastPosMin = xCodeCoeffCountBitsLast(sQuantCoeff, levelData, iBlockType, uiNum);
+#endif
+        memset(&sQuantCoeff[lastPosMin+1],0,sizeof(TCoeff) * (noCoeff - (lastPosMin + 1)));
+
+
+        Int  iLpFlag = 1; 
+        Int  iLevelMode = 0;
+        Int  iRun = 0;
+        Int  iVlc_adaptive = 0;
+        Int  iMaxrun = 0;
+        Int  iSum_big_coef = 0;
+
+
+        UInt uiTr1=0;
+        UInt absBestLevel;
+
+        Int atable[5] = {4,6,14,28,0xfffffff};
+        Int switch_thr[10] = {49,49,0,49,49,0,49,49,49,49};
+
+        Int levelIndBest, iRateMin=0, levelStart;
+        Double lagrCoded=0, lagrNotCoded=0;
+#if CAVLC_COEF_LRG_BLK
+        const UInt **pLumaRunTr1 = (uiWidth==4)? g_pLumaRunTr14x4:g_pLumaRunTr18x8;
+        UInt coeffBlkSize = (uiWidth==4)? 4:(noCoeff==64)? 8:(noCoeff==256)? 16:32;
+#endif
+
+        for (iScanning = lastPosMin; iScanning>=0; iScanning--){
+          uiScanPos = iScanning;
+          levelStart = (iScanning == lastPosMin) ? 1 : 0;
+
+          sQuantCoeff[uiScanPos] = levelBest = 0;
+          levelDataStruct *psLevelData = &levelData[uiScanPos];
+          if ( psLevelData->noLevels >1 || iScanning == 0 ){
+
+            lagrMin = 0; iRateMin = 0;
+            for (levelInd = levelStart; levelInd < psLevelData->noLevels; levelInd++){
+
+              lagr = psLevelData->errLevel[levelInd];
+              iLevel=psLevelData->level[levelInd];
+
+#if CAVLC_COEF_LRG_BLK
+              iRate = bitCountRDOQ(iLevel,uiScanPos,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,
+                coeffBlkSize,uiTr1, iSum_big_coef, iBlockType, pcCU, pLumaRunTr1)<<uiBitShift;
+#else
+              if ( uiWidth == 4 ){
+                iRate = bitCountRDOQ(iLevel,uiScanPos,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,4,uiTr1, 
+                  iSum_big_coef,iBlockType, pcCU)<<uiBitShift;
+              }
+              else{
+                iRate = bitCountRDOQ(iLevel,uiScanPos,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,8,uiTr1, 
+                  iSum_big_coef, iBlockType, pcCU) << uiBitShift;
+              }
+#endif
+              lagr += m_dLambda * iRate; 
+
+              if ( lagr < lagrMin || levelInd == levelStart){
+                lagrMin = lagr;
+                iRateMin = iRate;
+                levelBest = iLevel;
+                levelIndBest = levelInd;
+              }
+            }
+          }
+
+          if ( levelBest != 0 ){
+            lagrCoded += lagrMin;
+            lagrNotCoded += psLevelData->errLevel[0];
+          }
+          if ( uiScanPos == 0 && levelBest == 0 ){
+            lagrCoded += m_dLambda * iRateMin;
+          }
+
+          sQuantCoeff[uiScanPos] = levelBest;
+
+          absBestLevel = abs(levelBest);
+          if ( levelBest != 0 ){  
+
+            if ( uiWidth > 4 ){ 
+              if ( !iLpFlag && absBestLevel > 1 ){
+                iSum_big_coef += absBestLevel;
+                if ((noCoeff - uiScanPos - 1) > switch_thr[iBlockType] || iSum_big_coef > 2) iLevelMode = 1; 
+              }
+            }
+            else{
+              if ( absBestLevel > 1 ) iLevelMode = 1;
+            }
+
+            if ( iLpFlag == 1 )
+            {
+              uiTr1 = (absBestLevel > 1) ? 0 : 1;
+            }
+            else
+            {
+              if ( uiTr1 == 0 || absBestLevel >= 2 )
+              { 
+                uiTr1 = 0;
+              }
+              else if ( uiTr1 < MAX_TR1 )
+              {
+                uiTr1++;
+              }
+            }
+            iMaxrun = iScanning - 1;
+            iLpFlag = 0;
+            iRun = 0;
+            if ( iLevelMode && (absBestLevel > atable[iVlc_adaptive])) iVlc_adaptive++;        
+          }
+          else
+          {
+            iRun += 1;         
+          }
+        }
+
+        if (lastPosMin >= 0 && lagrCoded > lagrNotCoded){
+          for (iScanning = lastPosMin; iScanning>=0; iScanning--){
+            sQuantCoeff[iScanning] = 0;
+          }
+        }
+
+#if CAVLC_COEF_LRG_BLK 
+        if ((!pcCU->isIntra(uiAbsPartIdx) && uiWidth > maxBlSize))
+        {
+          for (iScanning=noCoeff-1; iScanning>=0; iScanning--) 
+          {
+#if QC_MDCS
+            iPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][iScanning];
+#else
+            iPos = pucScan[iScanning];
+#endif //QC_MDCS
+            j = iPos >>  (g_aucConvertToBit[ maxBlSize ] + 2);
+            i = iPos & (maxBlSize-1);
+            iPos = (j<<(g_aucConvertToBit[ uiWidth ] + 2))+i;
+            pDstCoeff[iPos] = sQuantCoeff[iScanning];
+            uiAbsSum += abs(sQuantCoeff[iScanning]);
+          }
+        }
+#else
+        if ((!pcCU->isIntra(uiAbsPartIdx) && uiWidth >= 16))
+        {
+          for (iScanning = noCoeff - 1; iScanning >= 0; iScanning--) 
+          {
+#if QC_MDCS
+            iPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][iScanning];
+#else
+            iPos = pucScan[iScanning];
+#endif //QC_MDCS
+            j = iPos >> 3;
+            i = iPos & 0x7;
+            iPos = uiWidth * j + i;
+            pDstCoeff[iPos] = sQuantCoeff[iScanning];
+            uiAbsSum += abs(sQuantCoeff[iScanning]);
+          }
+        }
+#endif
+        else
+        {
+          for (iScanning = noCoeff - 1; iScanning >= 0; iScanning--) 
+          {
+#if QC_MDCS
+            iPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][iScanning];
+#else
+            iPos = pucScan[iScanning];
+#endif //QC_MDCS
+            pDstCoeff[iPos] = sQuantCoeff[iScanning];
+            uiAbsSum += abs(sQuantCoeff[iScanning]);
+          }
+        }
+}
+#else
+Void TComTrQuant::xRateDistOptQuant_LCEC             ( TComDataCU*                     pcCU,
+                                                      Long*                           plSrcCoeff,
+                                                      TCoeff*&                        piDstCoeff,
+                                                      UInt                            uiWidth,
+                                                      UInt                            uiHeight,
+                                                      UInt&                           uiAbsSum,
+                                                      TextType                        eTType,
+                                                      UInt                            uiAbsPartIdx )
+{
+  Int iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,iSum_big_coef,iSign;
+  Int atable[5] = {4,6,14,28,0xfffffff};
+  Int switch_thr[8] = {49,49,0,49,49,0,49,49};
+  
+  const UInt* pucScan;
+  UInt* piQuantCoef = NULL;
+  UInt uiBlkPos,uiPosY,uiPosX,uiLog2BlkSize,uiConvBit,uiLevel,uiMaxLevel,uiMinLevel,uiAbsLevel,uiBestAbsLevel,uiBitShift;
+  Int iScanning,iQpRem,iBlockType,iRate;
+  Int  iQBits      = m_cQP.m_iBits;
+  Int64 lLevelDouble;
+  Double dErr,dTemp=0,dNormFactor,rd64UncodedCost,rd64CodedCost,dCurrCost;
+  
+  uiBitShift = 15;
+  iQpRem = m_cQP.m_iRem;
+  
+  Bool bExt8x8Flag = false;
+  uiLog2BlkSize = g_aucConvertToBit[ uiWidth ] + 2; 
+  uiConvBit = g_aucConvertToBit[ uiWidth ];
+  
+#if QC_MDCS
+  const UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+#endif //QC_MDCS
+  
+  if (uiWidth == 4)
+  {
+#if QC_MOD_LCEC
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+#else
+    iBlockType = 0 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() ); 
+#endif
+    iQBits = m_cQP.m_iBits;                 
+    dNormFactor = pow(2., (2*DQ_BITS+19));
+    if ( g_uiBitIncrement ) dNormFactor *= 1<<(2*g_uiBitIncrement);
+    piQuantCoef = ( g_aiQuantCoef[m_cQP.rem()] );
+  }
+  else if (uiWidth == 8)
+  {
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V) 
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() ); 
+    iQBits = m_cQP.m_iBits + 1;                 
+    dNormFactor = pow(2., (2*Q_BITS_8+9)); 
+    if ( g_uiBitIncrement ) dNormFactor *= 1<<(2*g_uiBitIncrement);
+    piQuantCoef = ( g_aiQuantCoef64[m_cQP.rem()] );
+  }
+  else
+  {
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V) 
+      iBlockType = eTType-2;
+    else
+      iBlockType = 5 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() ); 
+    
+    if(!pcCU->isIntra(uiAbsPartIdx))
+    {
+      uiLog2BlkSize = g_aucConvertToBit[ 8 ] + 2; 
+      uiConvBit = g_aucConvertToBit[ 8 ];
+    }
+    dNormFactor = pow(2., 21);
+    if ( g_uiBitIncrement ) dNormFactor *= 1<<(2*g_uiBitIncrement);
+    
+    bExt8x8Flag = true;
+    
+    if ( uiWidth == 16)
+    {
+      piQuantCoef = ( g_aiQuantCoef256[m_cQP.rem()] );
+      iQBits = ECore16Shift + m_cQP.per();     
+      dTemp = estErr16x16[iQpRem]/dNormFactor;
+    }
+    else if ( uiWidth == 32)
+    {
+      piQuantCoef = ( g_aiQuantCoef1024[m_cQP.rem()] );
+      iQBits = ECore32Shift + m_cQP.per();
+      dTemp = estErr32x32[iQpRem]/dNormFactor;
+    }
+    else
+    {
+      assert(0);
+    }
+    memset(&piDstCoeff[0],0,uiWidth*uiHeight*sizeof(TCoeff)); 
+  }
+  
+  pucScan = g_auiFrameScanXY [ uiConvBit + 1 ];
+  
+  iLpFlag = 1;  // shawn note: last position flag
+  iLevelMode = 0;
+  iRun = 0;
+  iVlc_adaptive = 0;
+  iMaxrun = 0;
+  iSum_big_coef = 0;
+#if QC_MOD_LCEC
+  UInt uiTr1=0;
+#endif
+  
+  for (iScanning=(uiWidth<8 ? 15 : 63); iScanning>=0; iScanning--) 
+  {            
+#if QC_MDCS
+    uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][iScanning];
+#else
+    uiBlkPos = pucScan[iScanning];
+#endif //QC_MDCS
+    uiPosY   = uiBlkPos >> uiLog2BlkSize;
+    uiPosX   = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+    
+    if (uiWidth==4)
+      dTemp = estErr4x4[ iQpRem ][ uiPosX ][ uiPosY ] / dNormFactor; 
+    else if(uiWidth==8)
+      dTemp = estErr8x8[ iQpRem ][ uiPosX ][ uiPosY ] / dNormFactor;
+    else if(!pcCU->isIntra(uiAbsPartIdx))
+      uiBlkPos = uiWidth*uiPosY+uiPosX;
+    
+    lLevelDouble = abs(plSrcCoeff[uiBlkPos]);
+    
+    lLevelDouble = lLevelDouble * (Int64) ( uiWidth == 64? piQuantCoef[m_cQP.rem()]: piQuantCoef[uiBlkPos] );
+    
+    iSign = plSrcCoeff[uiBlkPos]<0 ? -1 : 1;
+    
+    
+    uiLevel = (UInt)(lLevelDouble  >> iQBits);      
+    uiMaxLevel = uiLevel + 1;
+    uiMinLevel = Max(1,(Int)uiLevel - 2);
+    
+    uiBestAbsLevel = 0;
+#if QC_MOD_LCEC
+    if (uiWidth==4)
+      iRate = bitCount_LCEC(0,iScanning,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,4,uiTr1)<<uiBitShift; 
+    else 
+      iRate = bitCount_LCEC(0,iScanning,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,8,uiTr1)<<uiBitShift; 
+#else
+    if (uiWidth==4)
+      iRate = bitCount_LCEC(0,iScanning,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,4)<<uiBitShift; 
+    else 
+      iRate = bitCount_LCEC(0,iScanning,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,8)<<uiBitShift; 
+#endif
+    
+    dErr = Double( lLevelDouble );
+    rd64UncodedCost = dErr * dErr * dTemp;
+    rd64CodedCost   = rd64UncodedCost + xGetICost( iRate ); 
+    for(uiAbsLevel = uiMinLevel; uiAbsLevel <= uiMaxLevel ; uiAbsLevel++ ) 
+    {
+#if QC_MOD_LCEC
+      if (uiWidth==4)
+        iRate = bitCount_LCEC(iSign*uiAbsLevel,iScanning,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,4,uiTr1)<<uiBitShift; 
+      else 
+        iRate = bitCount_LCEC(iSign*uiAbsLevel,iScanning,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,8,uiTr1)<<uiBitShift; 
+#else
+      if (uiWidth==4)
+        iRate = bitCount_LCEC(iSign*uiAbsLevel,iScanning,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,4)<<uiBitShift; 
+      else 
+        iRate = bitCount_LCEC(iSign*uiAbsLevel,iScanning,iBlockType,iLpFlag,iLevelMode,iRun,iMaxrun,iVlc_adaptive,8)<<uiBitShift; 
+#endif
+      dErr = Double( lLevelDouble  - (((Int64)uiAbsLevel) << iQBits ) );
+      rd64UncodedCost = dErr * dErr * dTemp;
+      dCurrCost = rd64UncodedCost + xGetICost( iRate ); 
+      if( dCurrCost < rd64CodedCost )
+      {         
+        uiBestAbsLevel  = uiAbsLevel;
+        rd64CodedCost   = dCurrCost;
+      }
+    }
+    
+    
+    if (uiBestAbsLevel)
+    {                  
+      if (uiWidth>4)
+      { 
+        if (!iLpFlag && uiBestAbsLevel > 1)
+        {
+          iSum_big_coef += uiBestAbsLevel;
+          if ((63-iScanning) > switch_thr[iBlockType] || iSum_big_coef > 2)
+            iLevelMode = 1;
+        }
+      }
+      else
+      {
+        if (uiBestAbsLevel>1)
+          iLevelMode = 1;
+      }
+#if QC_MOD_LCEC
+      if (iLpFlag==1){
+        if (uiBestAbsLevel>1){
+          uiTr1=0;
+        }
+        else{
+          uiTr1=1;
+        }
+      }
+      else{
+        if (uiTr1>0 && uiBestAbsLevel<2){
+          uiTr1++;
+          uiTr1=Min(MAX_TR1,uiTr1);
+        }
+        else{
+          uiTr1=0;
+        }
+      }
+#endif
+      iMaxrun = iScanning-1;
+      iLpFlag = 0;
+      iRun = 0;
+      if (iLevelMode && (uiBestAbsLevel > atable[iVlc_adaptive]))
+        iVlc_adaptive++;                    
+    }
+    else
+    {
+      iRun += 1;         
+    }
+    
+    uiAbsSum += uiBestAbsLevel;
+    piDstCoeff[uiBlkPos] = iSign*uiBestAbsLevel;
+  } // for uiScanning
+} 
+#endif
+
+Void TComTrQuant::xQuantLTR  (TComDataCU* pcCU, Long* pSrc, TCoeff*& pDes, Int iWidth, Int iHeight, UInt& uiAcSum, TextType eTType, UInt uiAbsPartIdx )
+{
+  Long*   piCoef    = pSrc;
+  TCoeff* piQCoef   = pDes;
+  Int   iAdd = 0;
+  
+#if E243_CORE_TRANSFORMS
+  if ( m_bUseRDOQ && (eTType == TEXT_LUMA || RDOQ_CHROMA) )
+  {
+    if ( m_iSymbolMode == 0)
+      xRateDistOptQuant_LCEC(pcCU, piCoef, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+    else
+      xRateDistOptQuant( pcCU, piCoef, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+  }
+  else
+  {
+    const UInt*  pucScan;
+    UInt uiConvBit = g_aucConvertToBit[ iWidth ];
+    pucScan        = g_auiFrameScanXY [ uiConvBit + 1 ];
+
+    UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
+    UInt uiQ = g_auiQ[m_cQP.rem()];
+
+#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);
+
+    for( Int n = 0; n < iWidth*iHeight; n++ )
+    {
+      Long iLevel;
+      Int  iSign;
+      UInt uiBlockPos = pucScan[n]; 
+      iLevel  = (Long) piCoef[uiBlockPos];
+      iSign   = (iLevel < 0 ? -1: 1);      
+
+      iLevel = (abs(iLevel) * uiQ + iAdd ) >> iQBits;
+#if CAVLC_COEF_LRG_BLK
+      if (m_iSymbolMode == 0 && n>=64 && eTType != TEXT_LUMA)
+      {
+        iLevel = 0;
+      }
+#else
+      if (m_iSymbolMode == 0 && iWidth>8)
+      {
+        /* Two methods of limiting number of encoded coefficients to 8x8 for intra and inter respectively */
+        if (pcCU->isIntra( uiAbsPartIdx ))
+        {
+          if(n>=64) iLevel = 0;
+        }
+        else
+        {
+          if ((uiBlockPos%iWidth)>=8 || (uiBlockPos/iWidth)>=8) iLevel = 0;
+        }
+      }
+#endif
+      uiAcSum += iLevel;
+      iLevel *= iSign;        
+      piQCoef[uiBlockPos] = iLevel;
+    } // for n
+  } //if RDOQ
+  //return;
+
+#else //E243_CORE_TRANSFORMS
+
+  UInt* piQuantCoef = NULL;
+  Int   iNewBits    = 0;
+  switch(iWidth)
+  {
+    case 2:
+    {
+      m_puiQuantMtx = &g_aiQuantCoef4[m_cQP.m_iRem];
+      xQuant2x2(piCoef, piQCoef, uiAcSum );
+      return;
+    }
+    case 4:
+    {
+      m_puiQuantMtx = &g_aiQuantCoef[m_cQP.m_iRem][0];
+      xQuant4x4(pcCU, piCoef, piQCoef, uiAcSum, eTType, uiAbsPartIdx );
+      return;
+    }
+    case 8:
+    {
+      m_puiQuantMtx = &g_aiQuantCoef64[m_cQP.m_iRem][0];
+      xQuant8x8(pcCU, piCoef, piQCoef, uiAcSum, eTType, uiAbsPartIdx );
+      return;
+    }
+    case 16:
+    {
+      piQuantCoef = ( g_aiQuantCoef256[m_cQP.rem()] );
+      iNewBits = ECore16Shift + m_cQP.per();
+      iAdd = m_cQP.m_iAdd16x16;
+      break;
+    }
+    case 32:
+    {
+      piQuantCoef = ( g_aiQuantCoef1024[m_cQP.rem()] );
+      iNewBits = ECore32Shift + m_cQP.per();
+      iAdd = m_cQP.m_iAdd32x32;
+      break;
+    }
+    default:
+      assert(0);
+      break;
+  }
+  
+  if ( m_bUseRDOQ && (eTType == TEXT_LUMA || RDOQ_CHROMA) )
+  {
+    if ( m_iSymbolMode == 0)
+      xRateDistOptQuant_LCEC(pcCU, piCoef, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+    else
+      xRateDistOptQuant( pcCU, piCoef, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+  }
+  else
+  {
+    UInt uiAcSum_init = uiAcSum;
+    for( Int n = 0; n < iWidth*iHeight; n++ )
+    {
+      Long iLevel;
+      Int  iSign;
+      iLevel  = (Long) piCoef[n];
+      iSign   = (iLevel < 0 ? -1: 1);
+      if ( iWidth == 64 ) iLevel = abs( iLevel ) * piQuantCoef[m_cQP.rem()];
+      else                iLevel = abs( iLevel ) * piQuantCoef[n];
+      
+      if (!pcCU->isIntra( uiAbsPartIdx ) && (m_iSymbolMode == 0) && ((n%iWidth)>=8 || (n/iWidth)>=8))
+        iLevel = 0;
+      else
+        iLevel = ( iLevel + iAdd ) >> iNewBits;
+      
+      if( 0 != iLevel )
+      {
+        uiAcSum += iLevel;
+        iLevel    *= iSign;
+        piQCoef[n] = iLevel;
+      }
+      else
+      {
+        piQCoef[n] = 0;
+      }
+    }
+    
+    const UInt*  pucScan;
+    if(pcCU->isIntra( uiAbsPartIdx ) && m_iSymbolMode == 0 && iWidth >= 16)
+    {
+      UInt uiConvBit = g_aucConvertToBit[ iWidth ];
+      pucScan        = g_auiFrameScanXY [ uiConvBit + 1 ];
+#if CAVLC_COEF_LRG_BLK
+      UInt noCoeff = (eTType == TEXT_LUMA)? (iWidth*iHeight):64;
+
+      for( Int n = noCoeff; n < iWidth*iHeight; n++ )
+      {
+        piQCoef[ pucScan[ n ] ] = 0;
+      }
+      uiAcSum = uiAcSum_init;
+      for( Int n = 0; n < noCoeff; n++ )
+      {
+        uiAcSum += abs(piQCoef[ pucScan[ n ] ]);
+      }
+#else
+      for( Int n = 64; n < iWidth*iHeight; n++ )
+      {
+        piQCoef[ pucScan[ n ] ] = 0;
+      }
+      
+      uiAcSum = uiAcSum_init;
+      
+      for( Int n = 0; n < 64; n++ )
+      {
+        uiAcSum += abs(piQCoef[ pucScan[ n ] ]);
+      }
+#endif
+    }
+  }
+#endif
+}
+
+Void TComTrQuant::xDeQuantLTR( TCoeff* pSrc, Long*& pDes, Int iWidth, Int iHeight )
+{
+  
+  TCoeff* piQCoef   = pSrc;
+  Long*   piCoef    = pDes;
+  
+  if ( iWidth > (Int)m_uiMaxTrSize )
+  {
+    iWidth  = m_uiMaxTrSize;
+    iHeight = m_uiMaxTrSize;
+  }
+  
+#if E243_CORE_TRANSFORMS
+  Int iShift,iAdd,iCoeffQ;
+  UInt uiQ;
+  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;
+  iAdd = 1 << (iShift-1);
+  uiQ = g_auiIQ[m_cQP.m_iRem];
+
+  for( Int n = 0; n < iWidth*iHeight; n++ )
+  {
+    iCoeffQ = ((piQCoef[n]*(Int)uiQ << m_cQP.m_iPer)+iAdd)>>iShift;
+    piCoef[n] = Clip3(-32768,32767,iCoeffQ);
+  } 
+#else
+  UInt* piDeQuantCoef = NULL;
+  switch(iWidth)
+  {
+    case 2:
+    {
+      xDeQuant2x2( piQCoef, piCoef );
+      return;
+    }
+    case 4:
+    {
+      xDeQuant4x4( piQCoef, piCoef );
+      return;
+    }
+    case 8:
+    {
+      xDeQuant8x8( piQCoef, piCoef );
+      return;
+    }
+    case 16:
+    {
+      piDeQuantCoef = ( g_aiDeQuantCoef256[m_cQP.rem()] );
+      break;
+    }
+    case 32:
+    {
+      piDeQuantCoef = ( g_aiDeQuantCoef1024[m_cQP.rem()] );
+      break;
+    }
+    case 64:
+    {
+      piDeQuantCoef = ( g_aiDeQuantCoef4096 ); // To save the memory for g_aiDeQuantCoef4096
+      break;
+    }
+  }
+  
+  Int iLevel;
+  Int iDeScale;
+  
+  for( Int n = 0; n < iWidth*iHeight; n++ )
+  {
+    iLevel  = piQCoef[n];
+    
+    if( 0 != iLevel )
+    {
+      if ( iWidth == 64 ) iDeScale = piDeQuantCoef[m_cQP.rem()];
+      else                iDeScale = piDeQuantCoef[n];
+      piCoef[n] = (Long) (iLevel*iDeScale) << m_cQP.per();
+    }
+    else
+    {
+      piCoef [n] = 0;
+    }
+  }
+#endif
+}
+#if !E243_CORE_TRANSFORMS
+Void TComTrQuant::xIT16( Long* pSrc, Pel* pDes, UInt uiStride )
+{
+  Int x, y;
+  Long aaiTemp[16][16];
+  
+  Long B0, B1, B2, B3, B4, B5, B6, B7, B10, B11, B12, B13;
+  Long C0, C1, C2, C3, C5, C6, C8, C9, C10, C11, C12, C13, C14, C15;
+  Long D0, D1, D2, D3, D4, D5, D6, D7, D9, D10, D13, D14;
+  Long E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15;
+  Long F8, F9, F10, F11, F12, F13, F14, F15;
+  
+  UInt uiStride2  = uiStride<<1;
+  UInt uiStride3  = uiStride2  + uiStride;
+  UInt uiStride4  = uiStride3  + uiStride;
+  UInt uiStride5  = uiStride4  + uiStride;
+  UInt uiStride6  = uiStride5  + uiStride;
+  UInt uiStride7  = uiStride6  + uiStride;
+  UInt uiStride8  = uiStride7  + uiStride;
+  UInt uiStride9  = uiStride8  + uiStride;
+  UInt uiStride10 = uiStride9  + uiStride;
+  UInt uiStride11 = uiStride10 + uiStride;
+  UInt uiStride12 = uiStride11 + uiStride;
+  UInt uiStride13 = uiStride12 + uiStride;
+  UInt uiStride14 = uiStride13 + uiStride;
+  UInt uiStride15 = uiStride14 + uiStride;
+#ifdef TRANS_PRECISION_EXT
+#if FULL_NBIT
+  Int uiBitDepthIncrease=g_iShift16x16-g_uiBitIncrement-g_uiBitDepth+8;
+#else
+  Int uiBitDepthIncrease=g_iShift16x16-g_uiBitIncrement;
+#endif
+  Int offset = (uiBitDepthIncrease==0)? 0:(1<<(uiBitDepthIncrease-1));
+#endif
+  //--Butterfly
+  for( y=0 ; y<16 ; y++ )
+  {
+#ifdef TRANS_PRECISION_EXT
+    Long     ai0[16];
+    ai0[0] =  pSrc[0]<<uiBitDepthIncrease;
+    ai0[1] =  pSrc[1]<<uiBitDepthIncrease;
+    ai0[2] =  pSrc[2]<<uiBitDepthIncrease;
+    ai0[3] =  pSrc[3]<<uiBitDepthIncrease;
+    ai0[4] =  pSrc[4]<<uiBitDepthIncrease;
+    ai0[5] =  pSrc[5]<<uiBitDepthIncrease;
+    ai0[6] =  pSrc[6]<<uiBitDepthIncrease;
+    ai0[7] =  pSrc[7]<<uiBitDepthIncrease;
+    ai0[8 ] =  pSrc[8 ]<<uiBitDepthIncrease;
+    ai0[9 ] =  pSrc[9 ]<<uiBitDepthIncrease;
+    ai0[10] =  pSrc[10]<<uiBitDepthIncrease;
+    ai0[11] =  pSrc[11]<<uiBitDepthIncrease;
+    ai0[12] =  pSrc[12]<<uiBitDepthIncrease;
+    ai0[13] =  pSrc[13]<<uiBitDepthIncrease;
+    ai0[14] =  pSrc[14]<<uiBitDepthIncrease;
+    ai0[15] =  pSrc[15]<<uiBitDepthIncrease;
+    F8 = xTrRound( 6 * ai0[1] - 63 * ai0[15] , DenShift16);
+    F9 = xTrRound( 49 * ai0[9] - 40 * ai0[7] , DenShift16);
+    F10 = xTrRound( 30 * ai0[5] - 56 * ai0[11] , DenShift16);
+    F11 = xTrRound( 61 * ai0[13] - 18 * ai0[3] , DenShift16);
+    F12 = xTrRound( 61 * ai0[3] + 18 * ai0[13] , DenShift16);
+    F13 = xTrRound( 30 * ai0[11] + 56 * ai0[5] , DenShift16);
+    F14 = xTrRound( 49 * ai0[7] + 40 * ai0[9] , DenShift16);
+    F15 = xTrRound( 6 * ai0[15] + 63 * ai0[1] , DenShift16);
+    
+    E4 = xTrRound( 12 * ai0[2] - 62 * ai0[14] , DenShift16);
+    E5 = xTrRound( 53 * ai0[10] - 35 * ai0[6] , DenShift16);
+    E6 = xTrRound( 53 * ai0[6] + 35 * ai0[10] , DenShift16);
+    E7 = xTrRound( 12 * ai0[14] + 62 * ai0[2] , DenShift16);
+#else
+    F8 = xTrRound( 6 * pSrc[1] - 63 * pSrc[15] , DenShift16);
+    F9 = xTrRound( 49 * pSrc[9] - 40 * pSrc[7] , DenShift16);
+    F10 = xTrRound( 30 * pSrc[5] - 56 * pSrc[11] , DenShift16);
+    F11 = xTrRound( 61 * pSrc[13] - 18 * pSrc[3] , DenShift16);
+    F12 = xTrRound( 61 * pSrc[3] + 18 * pSrc[13] , DenShift16);
+    F13 = xTrRound( 30 * pSrc[11] + 56 * pSrc[5] , DenShift16);
+    F14 = xTrRound( 49 * pSrc[7] + 40 * pSrc[9] , DenShift16);
+    F15 = xTrRound( 6 * pSrc[15] + 63 * pSrc[1] , DenShift16);
+    
+    E4 = xTrRound( 12 * pSrc[2] - 62 * pSrc[14] , DenShift16);
+    E5 = xTrRound( 53 * pSrc[10] - 35 * pSrc[6] , DenShift16);
+    E6 = xTrRound( 53 * pSrc[6] + 35 * pSrc[10] , DenShift16);
+    E7 = xTrRound( 12 * pSrc[14] + 62 * pSrc[2] , DenShift16);
+#endif
+    E8 = F8 + F9;
+    E9 = F8 - F9;
+    E10 = F11 - F10;
+    E11 = F11 + F10;
+    E12 = F12 + F13;
+    E13 = F12 - F13;
+    E14 = F15 - F14;
+    E15 = F15 + F14;
+#ifdef TRANS_PRECISION_EXT
+    D0 = xTrRound( 45 * ( ai0[0] + ai0[8] ) , DenShift16);
+    D1 = xTrRound( 45 * ( ai0[0] - ai0[8] ) , DenShift16);
+    D2 = xTrRound( 24 * ai0[4] - 59 * ai0[12] , DenShift16);
+    D3 = xTrRound( 59 * ai0[4] + 24 * ai0[12] , DenShift16);
+#else
+    D0 = xTrRound( 45 * ( pSrc[0] + pSrc[8] ) , DenShift16);
+    D1 = xTrRound( 45 * ( pSrc[0] - pSrc[8] ) , DenShift16);
+    D2 = xTrRound( 24 * pSrc[4] - 59 * pSrc[12] , DenShift16);
+    D3 = xTrRound( 59 * pSrc[4] + 24 * pSrc[12] , DenShift16);
+#endif
+    D4 = E4 + E5;
+    D5 = E4 - E5;
+    D6 = E7 - E6;
+    D7 = E7 + E6;
+    D9 = xTrRound( 24 * E14 - 59 * E9 , DenShift16);
+    D10 = xTrRound(  - 59 * E13 - 24 * E10 , DenShift16);
+    D13 = xTrRound( 24 * E13 - 59 * E10 , DenShift16);
+    D14 = xTrRound( 59 * E14 + 24 * E9 , DenShift16);
+    
+    C0 = D0 + D3;
+    C3 = D0 - D3;
+    C8 = E8 + E11;
+    C11 = E8 - E11;
+    C12 = E15 - E12;
+    C15 = E15 + E12;
+    C1 = D1 + D2;
+    C2 = D1 - D2;
+    C9 = D9 + D10;
+    C10 = D9 - D10;
+    C13 = D14 - D13;
+    C14 = D14 + D13;
+    C5 = xTrRound( 45 * ( D6 - D5 ) , DenShift16);
+    C6 = xTrRound( 45 * ( D6 + D5 ) , DenShift16);
+    
+    B0 = C0 + D7;
+    B7 = C0 - D7;
+    B1 = C1 + C6;
+    B6 = C1 - C6;
+    B2 = C2 + C5;
+    B5 = C2 - C5;
+    B3 = C3 + D4;
+    B4 = C3 - D4;
+    B10 = xTrRound( 45 * ( C13 - C10 ) , DenShift16);
+    B13 = xTrRound( 45 * ( C13 + C10 ) , DenShift16);
+    B11 = xTrRound( 45 * ( C12 - C11 ) , DenShift16);
+    B12 = xTrRound( 45 * ( C12 + C11 ) , DenShift16);
+    
+    aaiTemp[0][y] = B0 + C15;
+    aaiTemp[15][y] = B0 - C15;
+    aaiTemp[1][y] = B1 + C14;
+    aaiTemp[14][y] = B1 - C14;
+    aaiTemp[2][y] = B2 + B13;
+    aaiTemp[13][y] = B2 - B13;
+    aaiTemp[3][y] = B3 + B12;
+    aaiTemp[12][y] = B3 - B12;
+    aaiTemp[4][y] = B4 + B11;
+    aaiTemp[11][y] = B4 - B11;
+    aaiTemp[5][y] = B5 + B10;
+    aaiTemp[10][y] = B5 - B10;
+    aaiTemp[6][y] = B6 + C9;
+    aaiTemp[9][y] = B6 - C9;
+    aaiTemp[7][y] = B7 + C8;
+    aaiTemp[8][y] = B7 - C8;
+    
+    pSrc += 16;
+  }
+  
+  for( x=0 ; x<16 ; x++, pDes++ )
+  {
+    F8 = xTrRound( 6 * aaiTemp[x][1] - 63 * aaiTemp[x][15] , DenShift16);
+    F9 = xTrRound( 49 * aaiTemp[x][9] - 40 * aaiTemp[x][7] , DenShift16);
+    F10 = xTrRound( 30 * aaiTemp[x][5] - 56 * aaiTemp[x][11] , DenShift16);
+    F11 = xTrRound( 61 * aaiTemp[x][13] - 18 * aaiTemp[x][3] , DenShift16);
+    F12 = xTrRound( 61 * aaiTemp[x][3] + 18 * aaiTemp[x][13] , DenShift16);
+    F13 = xTrRound( 30 * aaiTemp[x][11] + 56 * aaiTemp[x][5] , DenShift16);
+    F14 = xTrRound( 49 * aaiTemp[x][7] + 40 * aaiTemp[x][9] , DenShift16);
+    F15 = xTrRound( 6 * aaiTemp[x][15] + 63 * aaiTemp[x][1] , DenShift16);
+    
+    E4 = xTrRound( 12 * aaiTemp[x][2] - 62 * aaiTemp[x][14] , DenShift16);
+    E5 = xTrRound( 53 * aaiTemp[x][10] - 35 * aaiTemp[x][6] , DenShift16);
+    E6 = xTrRound( 53 * aaiTemp[x][6] + 35 * aaiTemp[x][10] , DenShift16);
+    E7 = xTrRound( 12 * aaiTemp[x][14] + 62 * aaiTemp[x][2] , DenShift16);
+    E8 = F8 + F9;
+    E9 = F8 - F9;
+    E10 = F11 - F10;
+    E11 = F11 + F10;
+    E12 = F12 + F13;
+    E13 = F12 - F13;
+    E14 = F15 - F14;
+    E15 = F15 + F14;
+    
+    D0 = xTrRound( 45 * ( aaiTemp[x][0] + aaiTemp[x][8] ) , DenShift16);
+    D1 = xTrRound( 45 * ( aaiTemp[x][0] - aaiTemp[x][8] ) , DenShift16);
+    D2 = xTrRound( 24 * aaiTemp[x][4] - 59 * aaiTemp[x][12] , DenShift16);
+    D3 = xTrRound( 59 * aaiTemp[x][4] + 24 * aaiTemp[x][12] , DenShift16);
+    D4 = E4 + E5;
+    D5 = E4 - E5;
+    D6 = E7 - E6;
+    D7 = E7 + E6;
+    D9 = xTrRound( 24 * E14 - 59 * E9 , DenShift16);
+    D10 = xTrRound(  - 59 * E13 - 24 * E10 , DenShift16);
+    D13 = xTrRound( 24 * E13 - 59 * E10 , DenShift16);
+    D14 = xTrRound( 59 * E14 + 24 * E9 , DenShift16);
+    
+    C0 = D0 + D3;
+    C3 = D0 - D3;
+    C8 = E8 + E11;
+    C11 = E8 - E11;
+    C12 = E15 - E12;
+    C15 = E15 + E12;
+    C1 = D1 + D2;
+    C2 = D1 - D2;
+    C9 = D9 + D10;
+    C10 = D9 - D10;
+    C13 = D14 - D13;
+    C14 = D14 + D13;
+    C5 = xTrRound( 45 * ( D6 - D5 ) , DenShift16);
+    C6 = xTrRound( 45 * ( D6 + D5 ) , DenShift16);
+    
+    B0 = C0 + D7;
+    B7 = C0 - D7;
+    B1 = C1 + C6;
+    B6 = C1 - C6;
+    B2 = C2 + C5;
+    B5 = C2 - C5;
+    B3 = C3 + D4;
+    B4 = C3 - D4;
+    B10 = xTrRound( 45 * ( C13 - C10 ) , DenShift16);
+    B13 = xTrRound( 45 * ( C13 + C10 ) , DenShift16);
+    B11 = xTrRound( 45 * ( C12 - C11 ) , DenShift16);
+    B12 = xTrRound( 45 * ( C12 + C11 ) , DenShift16);
+    
+    pDes[          0] = (Pel)xTrRound(B0 + C15, DCore16Shift);
+    pDes[uiStride15] = (Pel)xTrRound(B0 - C15, DCore16Shift);
+    pDes[uiStride  ] = (Pel)xTrRound(B1 + C14, DCore16Shift);
+    pDes[uiStride14] = (Pel)xTrRound(B1 - C14, DCore16Shift);
+    pDes[uiStride2 ] = (Pel)xTrRound(B2 + B13, DCore16Shift);
+    pDes[uiStride13] = (Pel)xTrRound(B2 - B13, DCore16Shift);
+    pDes[uiStride3 ] = (Pel)xTrRound(B3 + B12, DCore16Shift);
+    pDes[uiStride12] = (Pel)xTrRound(B3 - B12, DCore16Shift);
+    pDes[uiStride4 ] = (Pel)xTrRound(B4 + B11, DCore16Shift);
+    pDes[uiStride11] = (Pel)xTrRound(B4 - B11, DCore16Shift);
+    pDes[uiStride5 ] = (Pel)xTrRound(B5 + B10, DCore16Shift);
+    pDes[uiStride10] = (Pel)xTrRound(B5 - B10, DCore16Shift);
+    pDes[uiStride6 ] = (Pel)xTrRound(B6 + C9, DCore16Shift);
+    pDes[uiStride9 ] = (Pel)xTrRound(B6 - C9, DCore16Shift);
+    pDes[uiStride7 ] = (Pel)xTrRound(B7 + C8, DCore16Shift);
+    pDes[uiStride8 ] = (Pel)xTrRound(B7 - C8, DCore16Shift);
+#ifdef TRANS_PRECISION_EXT
+    pDes[        0 ] =  (pDes[        0 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride  ] =  (pDes[uiStride  ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride2 ] =  (pDes[uiStride2 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride3 ] =  (pDes[uiStride3 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride4 ] =  (pDes[uiStride4 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride5 ] =  (pDes[uiStride5 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride6 ] =  (pDes[uiStride6 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride7 ] =  (pDes[uiStride7 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride8 ] =  (pDes[uiStride8 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride9 ] =  (pDes[uiStride9 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride10] =  (pDes[uiStride10]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride11] =  (pDes[uiStride11]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride12] =  (pDes[uiStride12]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride13] =  (pDes[uiStride13]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride14] =  (pDes[uiStride14]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride15] =  (pDes[uiStride15]+offset)>>uiBitDepthIncrease;
+#endif
+    
+  }
+}
+
+Void TComTrQuant::xIT32( Long* pSrc, Pel* pDes, UInt uiStride )
+{
+  Int x, y;
+  Long aaiTemp[32][32];
+  
+  Long A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A20, A21, A22, A23, A24, A25, A26, A27;
+  Long B0, B1, B2, B3, B4, B5, B6, B7, B10, B11, B12, B13, B16, B17, B18, B19, B20, B21, B22, B23, B24, B25, B26, B27, B28, B29, B30, B31;
+  Long C0, C1, C2, C3, C5, C6, C8, C9, C10, C11, C12, C13, C14, C15, C18, C19, C20, C21, C26, C27, C28, C29;
+  Long D0, D1, D2, D3, D4, D5, D6, D7, D9, D10, D13, D14, D16, D17, D18, D19, D20, D21, D22, D23, D24, D25, D26, D27, D28, D29, D30, D31;
+  Long E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E17, E18, E21, E22, E25, E26, E29, E30;
+  Long F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, F25, F26, F27, F28, F29, F30, F31;
+  Long G16, G17, G18, G19, G20, G21, G22, G23, G24, G25, G26, G27, G28, G29, G30, G31;
+  
+  UInt uiStride2  = uiStride<<1;
+  UInt uiStride3  = uiStride2  + uiStride;
+  UInt uiStride4  = uiStride3  + uiStride;
+  UInt uiStride5  = uiStride4  + uiStride;
+  UInt uiStride6  = uiStride5  + uiStride;
+  UInt uiStride7  = uiStride6  + uiStride;
+  UInt uiStride8  = uiStride7  + uiStride;
+  UInt uiStride9  = uiStride8  + uiStride;
+  UInt uiStride10 = uiStride9  + uiStride;
+  UInt uiStride11 = uiStride10 + uiStride;
+  UInt uiStride12 = uiStride11 + uiStride;
+  UInt uiStride13 = uiStride12 + uiStride;
+  UInt uiStride14 = uiStride13 + uiStride;
+  UInt uiStride15 = uiStride14 + uiStride;
+  UInt uiStride16 = uiStride15 + uiStride;
+  UInt uiStride17 = uiStride16 + uiStride;
+  UInt uiStride18 = uiStride17 + uiStride;
+  UInt uiStride19 = uiStride18 + uiStride;
+  UInt uiStride20 = uiStride19 + uiStride;
+  UInt uiStride21 = uiStride20 + uiStride;
+  UInt uiStride22 = uiStride21 + uiStride;
+  UInt uiStride23 = uiStride22 + uiStride;
+  UInt uiStride24 = uiStride23 + uiStride;
+  UInt uiStride25 = uiStride24 + uiStride;
+  UInt uiStride26 = uiStride25 + uiStride;
+  UInt uiStride27 = uiStride26 + uiStride;
+  UInt uiStride28 = uiStride27 + uiStride;
+  UInt uiStride29 = uiStride28 + uiStride;
+  UInt uiStride30 = uiStride29 + uiStride;
+  UInt uiStride31 = uiStride30 + uiStride;
+#ifdef TRANS_PRECISION_EXT
+#if FULL_NBIT
+  Int uiBitDepthIncrease=g_iShift32x32-g_uiBitIncrement-g_uiBitDepth+8;
+#else
+  Int uiBitDepthIncrease=g_iShift32x32-g_uiBitIncrement;
+#endif
+  Int offset = (uiBitDepthIncrease==0)? 0:(1<<(uiBitDepthIncrease-1));
+#endif
+  //--Butterfly
+  for( y=0 ; y<32 ; y++ )
+  {
+#ifdef TRANS_PRECISION_EXT
+    Long     ai0[32];
+    ai0[0] =  pSrc[0]<<uiBitDepthIncrease;
+    ai0[1] =  pSrc[1]<<uiBitDepthIncrease;
+    ai0[2] =  pSrc[2]<<uiBitDepthIncrease;
+    ai0[3] =  pSrc[3]<<uiBitDepthIncrease;
+    ai0[4] =  pSrc[4]<<uiBitDepthIncrease;
+    ai0[5] =  pSrc[5]<<uiBitDepthIncrease;
+    ai0[6] =  pSrc[6]<<uiBitDepthIncrease;
+    ai0[7] =  pSrc[7]<<uiBitDepthIncrease;
+    ai0[8 ] =  pSrc[8 ]<<uiBitDepthIncrease;
+    ai0[9 ] =  pSrc[9 ]<<uiBitDepthIncrease;
+    ai0[10] =  pSrc[10]<<uiBitDepthIncrease;
+    ai0[11] =  pSrc[11]<<uiBitDepthIncrease;
+    ai0[12] =  pSrc[12]<<uiBitDepthIncrease;
+    ai0[13] =  pSrc[13]<<uiBitDepthIncrease;
+    ai0[14] =  pSrc[14]<<uiBitDepthIncrease;
+    ai0[15] =  pSrc[15]<<uiBitDepthIncrease;
+    ai0[16] =  pSrc[16]<<uiBitDepthIncrease;
+    ai0[17] =  pSrc[17]<<uiBitDepthIncrease;
+    ai0[18] =  pSrc[18]<<uiBitDepthIncrease;
+    ai0[19] =  pSrc[19]<<uiBitDepthIncrease;
+    ai0[20] =  pSrc[20]<<uiBitDepthIncrease;
+    ai0[21] =  pSrc[21]<<uiBitDepthIncrease;
+    ai0[22] =  pSrc[22]<<uiBitDepthIncrease;
+    ai0[23] =  pSrc[23]<<uiBitDepthIncrease;
+    ai0[24] =  pSrc[24]<<uiBitDepthIncrease;
+    ai0[25] =  pSrc[25]<<uiBitDepthIncrease;
+    ai0[26] =  pSrc[26]<<uiBitDepthIncrease;
+    ai0[27] =  pSrc[27]<<uiBitDepthIncrease;
+    ai0[28] =  pSrc[28]<<uiBitDepthIncrease;
+    ai0[29] =  pSrc[29]<<uiBitDepthIncrease;
+    ai0[30] =  pSrc[30]<<uiBitDepthIncrease;
+    ai0[31] =  pSrc[31]<<uiBitDepthIncrease;
+    G16 = xTrRound(  12 * ai0[1]  - 255 * ai0[31], DenShift32);
+    G17 = xTrRound( 189 * ai0[17] - 171 * ai0[15], DenShift32);
+    G18 = xTrRound( 109 * ai0[9]  - 231 * ai0[23], DenShift32);
+    G19 = xTrRound( 241 * ai0[25] -  86 * ai0[7], DenShift32);
+    G20 = xTrRound(  62 * ai0[5]  - 248 * ai0[27], DenShift32);
+    G21 = xTrRound( 219 * ai0[21] - 131 * ai0[11], DenShift32);
+    G22 = xTrRound( 152 * ai0[13] - 205 * ai0[19], DenShift32);
+    G23 = xTrRound( 253 * ai0[29] -  37 * ai0[3], DenShift32);
+    G24 = xTrRound( 253 * ai0[3]  +  37 * ai0[29], DenShift32);
+    G25 = xTrRound( 152 * ai0[19] + 205 * ai0[13], DenShift32);
+    G26 = xTrRound( 219 * ai0[11] + 131 * ai0[21], DenShift32);
+    G27 = xTrRound(  62 * ai0[27] + 248 * ai0[5], DenShift32);
+    G28 = xTrRound( 241 * ai0[7]  +  86 * ai0[25], DenShift32);
+    G29 = xTrRound( 109 * ai0[23] + 231 * ai0[9], DenShift32);
+    G30 = xTrRound( 189 * ai0[15] + 171 * ai0[17], DenShift32);
+    G31 = xTrRound(  12 * ai0[31] + 255 * ai0[1], DenShift32);
+    
+    F8  = xTrRound(  25 * ai0[2]  - 254 * ai0[30], DenShift32);
+    F9  = xTrRound( 197 * ai0[18] - 162 * ai0[14], DenShift32);
+    F10 = xTrRound( 120 * ai0[10] - 225 * ai0[22], DenShift32);
+    F11 = xTrRound( 244 * ai0[26] -  74 * ai0[6], DenShift32);
+    F12 = xTrRound( 244 * ai0[6]  +  74 * ai0[26], DenShift32);
+    F13 = xTrRound( 120 * ai0[22] + 225 * ai0[10], DenShift32);
+    F14 = xTrRound( 197 * ai0[14] + 162 * ai0[18], DenShift32);
+    F15 = xTrRound(  25 * ai0[30] + 254 * ai0[2], DenShift32);
+#else
+    G16 = xTrRound( 12 * pSrc[1] - 255 * pSrc[31], DenShift32);
+    G17 = xTrRound( 189 * pSrc[17] - 171 * pSrc[15], DenShift32);
+    G18 = xTrRound( 109 * pSrc[9] - 231 * pSrc[23], DenShift32);
+    G19 = xTrRound( 241 * pSrc[25] - 86 * pSrc[7], DenShift32);
+    G20 = xTrRound( 62 * pSrc[5] - 248 * pSrc[27], DenShift32);
+    G21 = xTrRound( 219 * pSrc[21] - 131 * pSrc[11], DenShift32);
+    G22 = xTrRound( 152 * pSrc[13] - 205 * pSrc[19], DenShift32);
+    G23 = xTrRound( 253 * pSrc[29] - 37 * pSrc[3], DenShift32);
+    G24 = xTrRound( 253 * pSrc[3] + 37 * pSrc[29], DenShift32);
+    G25 = xTrRound( 152 * pSrc[19] + 205 * pSrc[13], DenShift32);
+    G26 = xTrRound( 219 * pSrc[11] + 131 * pSrc[21], DenShift32);
+    G27 = xTrRound( 62 * pSrc[27] + 248 * pSrc[5], DenShift32);
+    G28 = xTrRound( 241 * pSrc[7] + 86 * pSrc[25], DenShift32);
+    G29 = xTrRound( 109 * pSrc[23] + 231 * pSrc[9], DenShift32);
+    G30 = xTrRound( 189 * pSrc[15] + 171 * pSrc[17], DenShift32);
+    G31 = xTrRound( 12 * pSrc[31] + 255 * pSrc[1], DenShift32);
+    
+    F8 = xTrRound( 25 * pSrc[2] - 254 * pSrc[30], DenShift32);
+    F9 = xTrRound( 197 * pSrc[18] - 162 * pSrc[14], DenShift32);
+    F10 = xTrRound( 120 * pSrc[10] - 225 * pSrc[22], DenShift32);
+    F11 = xTrRound( 244 * pSrc[26] - 74 * pSrc[6], DenShift32);
+    F12 = xTrRound( 244 * pSrc[6] + 74 * pSrc[26], DenShift32);
+    F13 = xTrRound( 120 * pSrc[22] + 225 * pSrc[10], DenShift32);
+    F14 = xTrRound( 197 * pSrc[14] + 162 * pSrc[18], DenShift32);
+    F15 = xTrRound( 25 * pSrc[30] + 254 * pSrc[2], DenShift32);
+#endif
+    F16 = G16 + G17;
+    F17 = G16 - G17;
+    F18 = G19 - G18;
+    F19 = G19 + G18;
+    F20 = G20 + G21;
+    F21 = G20 - G21;
+    F22 = G23 - G22;
+    F23 = G23 + G22;
+    F24 = G24 + G25;
+    F25 = G24 - G25;
+    F26 = G27 - G26;
+    F27 = G27 + G26;
+    F28 = G28 + G29;
+    F29 = G28 - G29;
+    F30 = G31 - G30;
+    F31 = G31 + G30;
+#ifdef TRANS_PRECISION_EXT
+    E4 = xTrRound( 49 * ai0[4] - 251 * ai0[28], DenShift32);
+    E5 = xTrRound( 212 * ai0[20] - 142 * ai0[12], DenShift32);
+    E6 = xTrRound( 212 * ai0[12] + 142 * ai0[20], DenShift32);
+    E7 = xTrRound( 49 * ai0[28] + 251 * ai0[4], DenShift32);
+#else
+    E4 = xTrRound( 49 * pSrc[4] - 251 * pSrc[28], DenShift32);
+    E5 = xTrRound( 212 * pSrc[20] - 142 * pSrc[12], DenShift32);
+    E6 = xTrRound( 212 * pSrc[12] + 142 * pSrc[20], DenShift32);
+    E7 = xTrRound( 49 * pSrc[28] + 251 * pSrc[4], DenShift32);
+#endif
+    E8 = F8 + F9;
+    E9 = F8 - F9;
+    E10 = F11 - F10;
+    E11 = F11 + F10;
+    E12 = F12 + F13;
+    E13 = F12 - F13;
+    E14 = F15 - F14;
+    E15 = F15 + F14;
+    E17 = xTrRound( 49 * F30 - 251 * F17, DenShift32);
+    E18 = xTrRound(  - 251 * F29 - 49 * F18, DenShift32);
+    E21 = xTrRound( 212 * F26 - 142 * F21, DenShift32);
+    E22 = xTrRound(  - 142 * F25 - 212 * F22, DenShift32);
+    E25 = xTrRound( 212 * F25 - 142 * F22, DenShift32);
+    E26 = xTrRound( 142 * F26 + 212 * F21, DenShift32);
+    E29 = xTrRound( 49 * F29 - 251 * F18, DenShift32);
+    E30 = xTrRound( 251 * F30 + 49 * F17, DenShift32);
+#ifdef TRANS_PRECISION_EXT
+    D0 = xTrRound( 181 * ( ai0[0] + ai0[16] ), DenShift32);
+    D1 = xTrRound( 181 * ( ai0[0] - ai0[16] ), DenShift32);
+    D2 = xTrRound( 97 * ai0[8] - 236 * ai0[24], DenShift32);
+    D3 = xTrRound( 236 * ai0[8] + 97 * ai0[24], DenShift32);
+#else
+    D0 = xTrRound( 181 * ( pSrc[0] + pSrc[16] ), DenShift32);
+    D1 = xTrRound( 181 * ( pSrc[0] - pSrc[16] ), DenShift32);
+    D2 = xTrRound( 97 * pSrc[8] - 236 * pSrc[24], DenShift32);
+    D3 = xTrRound( 236 * pSrc[8] + 97 * pSrc[24], DenShift32);
+#endif
+    D4 = E4 + E5;
+    D5 = E4 - E5;
+    D6 = E7 - E6;
+    D7 = E7 + E6;
+    D9 = xTrRound( 97 * E14 - 236 * E9, DenShift32);
+    D10 = xTrRound(  - 236 * E13 - 97 * E10, DenShift32);
+    D13 = xTrRound( 97 * E13 - 236 * E10, DenShift32);
+    D14 = xTrRound( 236 * E14 + 97 * E9, DenShift32);
+    D16 = F16 + F19;
+    D19 = F16 - F19;
+    D20 = F23 - F20;
+    D23 = F23 + F20;
+    D24 = F24 + F27;
+    D27 = F24 - F27;
+    D28 = F31 - F28;
+    D31 = F31 + F28;
+    D17 = E17 + E18;
+    D18 = E17 - E18;
+    D21 = E22 - E21;
+    D22 = E22 + E21;
+    D25 = E25 + E26;
+    D26 = E25 - E26;
+    D29 = E30 - E29;
+    D30 = E30 + E29;
+    
+    C0 = D0 + D3;
+    C3 = D0 - D3;
+    C8 = E8 + E11;
+    C11 = E8 - E11;
+    C12 = E15 - E12;
+    C15 = E15 + E12;
+    C1 = D1 + D2;
+    C2 = D1 - D2;
+    C9 = D9 + D10;
+    C10 = D9 - D10;
+    C13 = D14 - D13;
+    C14 = D14 + D13;
+    C5 = xTrRound( 181 * ( D6 - D5 ), DenShift32);
+    C6 = xTrRound( 181 * ( D6 + D5 ), DenShift32);
+    C18 = xTrRound( 97 * D29 - 236 * D18, DenShift32);
+    C20 = xTrRound(  - 236 * D27 - 97 * D20, DenShift32);
+    C26 = xTrRound(  - 236 * D21 + 97 * D26, DenShift32);
+    C28 = xTrRound( 97 * D19 + 236 * D28, DenShift32);
+    C19 = xTrRound( 97 * D28 - 236 * D19, DenShift32);
+    C21 = xTrRound(  - 236 * D26 - 97 * D21, DenShift32);
+    C27 = xTrRound(  - 236 * D20 + 97 * D27, DenShift32);
+    C29 = xTrRound( 97 * D18 + 236 * D29, DenShift32);
+    
+    B0 = C0 + D7;
+    B7 = C0 - D7;
+    B1 = C1 + C6;
+    B6 = C1 - C6;
+    B2 = C2 + C5;
+    B5 = C2 - C5;
+    B3 = C3 + D4;
+    B4 = C3 - D4;
+    B10 = xTrRound( 181 * ( C13 - C10 ), DenShift32);
+    B13 = xTrRound( 181 * ( C13 + C10 ), DenShift32);
+    B11 = xTrRound( 181 * ( C12 - C11 ), DenShift32);
+    B12 = xTrRound( 181 * ( C12 + C11 ), DenShift32);
+    B16 = D16 + D23;
+    B23 = D16 - D23;
+    B24 = D31 - D24;
+    B31 = D31 + D24;
+    B17 = D17 + D22;
+    B22 = D17 - D22;
+    B25 = D30 - D25;
+    B30 = D30 + D25;
+    B18 = C18 + C21;
+    B21 = C18 - C21;
+    B26 = C29 - C26;
+    B29 = C29 + C26;
+    B19 = C19 + C20;
+    B20 = C19 - C20;
+    B27 = C28 - C27;
+    B28 = C28 + C27;
+    
+    A0 = B0 + C15;
+    A15 = B0 - C15;
+    A1 = B1 + C14;
+    A14 = B1 - C14;
+    A2 = B2 + B13;
+    A13 = B2 - B13;
+    A3 = B3 + B12;
+    A12 = B3 - B12;
+    A4 = B4 + B11;
+    A11 = B4 - B11;
+    A5 = B5 + B10;
+    A10 = B5 - B10;
+    A6 = B6 + C9;
+    A9 = B6 - C9;
+    A7 = B7 + C8;
+    A8 = B7 - C8;
+    A20 = xTrRound( 181 * ( B27 - B20 ), DenShift32);
+    A27 = xTrRound( 181 * ( B27 + B20 ), DenShift32);
+    A21 = xTrRound( 181 * ( B26 - B21 ), DenShift32);
+    A26 = xTrRound( 181 * ( B26 + B21 ), DenShift32);
+    A22 = xTrRound( 181 * ( B25 - B22 ), DenShift32);
+    A25 = xTrRound( 181 * ( B25 + B22 ), DenShift32);
+    A23 = xTrRound( 181 * ( B24 - B23 ), DenShift32);
+    A24 = xTrRound( 181 * ( B24 + B23 ), DenShift32);
+    
+    aaiTemp[0][y] = A0 + B31;
+    aaiTemp[31][y] = A0 - B31;
+    aaiTemp[1][y] = A1 + B30;
+    aaiTemp[30][y] = A1 - B30;
+    aaiTemp[2][y] = A2 + B29;
+    aaiTemp[29][y] = A2 - B29;
+    aaiTemp[3][y] = A3 + B28;
+    aaiTemp[28][y] = A3 - B28;
+    aaiTemp[4][y] = A4 + A27;
+    aaiTemp[27][y] = A4 - A27;
+    aaiTemp[5][y] = A5 + A26;
+    aaiTemp[26][y] = A5 - A26;
+    aaiTemp[6][y] = A6 + A25;
+    aaiTemp[25][y] = A6 - A25;
+    aaiTemp[7][y] = A7 + A24;
+    aaiTemp[24][y] = A7 - A24;
+    aaiTemp[8][y] = A8 + A23;
+    aaiTemp[23][y] = A8 - A23;
+    aaiTemp[9][y] = A9 + A22;
+    aaiTemp[22][y] = A9 - A22;
+    aaiTemp[10][y] = A10 + A21;
+    aaiTemp[21][y] = A10 - A21;
+    aaiTemp[11][y] = A11 + A20;
+    aaiTemp[20][y] = A11 - A20;
+    aaiTemp[12][y] = A12 + B19;
+    aaiTemp[19][y] = A12 - B19;
+    aaiTemp[13][y] = A13 + B18;
+    aaiTemp[18][y] = A13 - B18;
+    aaiTemp[14][y] = A14 + B17;
+    aaiTemp[17][y] = A14 - B17;
+    aaiTemp[15][y] = A15 + B16;
+    aaiTemp[16][y] = A15 - B16;
+    
+    pSrc += 32;
+  }
+  
+  for( x=0 ; x<32 ; x++, pDes++ )
+  {
+    G16 = xTrRound( 12 * aaiTemp[x][1] - 255 * aaiTemp[x][31], DenShift32);
+    G17 = xTrRound( 189 * aaiTemp[x][17] - 171 * aaiTemp[x][15], DenShift32);
+    G18 = xTrRound( 109 * aaiTemp[x][9] - 231 * aaiTemp[x][23], DenShift32);
+    G19 = xTrRound( 241 * aaiTemp[x][25] - 86 * aaiTemp[x][7], DenShift32);
+    G20 = xTrRound( 62 * aaiTemp[x][5] - 248 * aaiTemp[x][27], DenShift32);
+    G21 = xTrRound( 219 * aaiTemp[x][21] - 131 * aaiTemp[x][11], DenShift32);
+    G22 = xTrRound( 152 * aaiTemp[x][13] - 205 * aaiTemp[x][19], DenShift32);
+    G23 = xTrRound( 253 * aaiTemp[x][29] - 37 * aaiTemp[x][3], DenShift32);
+    G24 = xTrRound( 253 * aaiTemp[x][3] + 37 * aaiTemp[x][29], DenShift32);
+    G25 = xTrRound( 152 * aaiTemp[x][19] + 205 * aaiTemp[x][13], DenShift32);
+    G26 = xTrRound( 219 * aaiTemp[x][11] + 131 * aaiTemp[x][21], DenShift32);
+    G27 = xTrRound( 62 * aaiTemp[x][27] + 248 * aaiTemp[x][5], DenShift32);
+    G28 = xTrRound( 241 * aaiTemp[x][7] + 86 * aaiTemp[x][25], DenShift32);
+    G29 = xTrRound( 109 * aaiTemp[x][23] + 231 * aaiTemp[x][9], DenShift32);
+    G30 = xTrRound( 189 * aaiTemp[x][15] + 171 * aaiTemp[x][17], DenShift32);
+    G31 = xTrRound( 12 * aaiTemp[x][31] + 255 * aaiTemp[x][1], DenShift32);
+    
+    F8 = xTrRound( 25 * aaiTemp[x][2] - 254 * aaiTemp[x][30], DenShift32);
+    F9 = xTrRound( 197 * aaiTemp[x][18] - 162 * aaiTemp[x][14], DenShift32);
+    F10 = xTrRound( 120 * aaiTemp[x][10] - 225 * aaiTemp[x][22], DenShift32);
+    F11 = xTrRound( 244 * aaiTemp[x][26] - 74 * aaiTemp[x][6], DenShift32);
+    F12 = xTrRound( 244 * aaiTemp[x][6] + 74 * aaiTemp[x][26], DenShift32);
+    F13 = xTrRound( 120 * aaiTemp[x][22] + 225 * aaiTemp[x][10], DenShift32);
+    F14 = xTrRound( 197 * aaiTemp[x][14] + 162 * aaiTemp[x][18], DenShift32);
+    F15 = xTrRound( 25 * aaiTemp[x][30] + 254 * aaiTemp[x][2], DenShift32);
+    F16 = G16 + G17;
+    F17 = G16 - G17;
+    F18 = G19 - G18;
+    F19 = G19 + G18;
+    F20 = G20 + G21;
+    F21 = G20 - G21;
+    F22 = G23 - G22;
+    F23 = G23 + G22;
+    F24 = G24 + G25;
+    F25 = G24 - G25;
+    F26 = G27 - G26;
+    F27 = G27 + G26;
+    F28 = G28 + G29;
+    F29 = G28 - G29;
+    F30 = G31 - G30;
+    F31 = G31 + G30;
+    
+    E4 = xTrRound( 49 * aaiTemp[x][4] - 251 * aaiTemp[x][28], DenShift32);
+    E5 = xTrRound( 212 * aaiTemp[x][20] - 142 * aaiTemp[x][12], DenShift32);
+    E6 = xTrRound( 212 * aaiTemp[x][12] + 142 * aaiTemp[x][20], DenShift32);
+    E7 = xTrRound( 49 * aaiTemp[x][28] + 251 * aaiTemp[x][4], DenShift32);
+    E8 = F8 + F9;
+    E9 = F8 - F9;
+    E10 = F11 - F10;
+    E11 = F11 + F10;
+    E12 = F12 + F13;
+    E13 = F12 - F13;
+    E14 = F15 - F14;
+    E15 = F15 + F14;
+    E17 = xTrRound( 49 * F30 - 251 * F17, DenShift32);
+    E18 = xTrRound(  - 251 * F29 - 49 * F18, DenShift32);
+    E21 = xTrRound( 212 * F26 - 142 * F21, DenShift32);
+    E22 = xTrRound(  - 142 * F25 - 212 * F22, DenShift32);
+    E25 = xTrRound( 212 * F25 - 142 * F22, DenShift32);
+    E26 = xTrRound( 142 * F26 + 212 * F21, DenShift32);
+    E29 = xTrRound( 49 * F29 - 251 * F18, DenShift32);
+    E30 = xTrRound( 251 * F30 + 49 * F17, DenShift32);
+    
+    D0 = xTrRound( 181 * ( aaiTemp[x][0] + aaiTemp[x][16] ), DenShift32);
+    D1 = xTrRound( 181 * ( aaiTemp[x][0] - aaiTemp[x][16] ), DenShift32);
+    D2 = xTrRound( 97 * aaiTemp[x][8] - 236 * aaiTemp[x][24], DenShift32);
+    D3 = xTrRound( 236 * aaiTemp[x][8] + 97 * aaiTemp[x][24], DenShift32);
+    D4 = E4 + E5;
+    D5 = E4 - E5;
+    D6 = E7 - E6;
+    D7 = E7 + E6;
+    D9 = xTrRound( 97 * E14 - 236 * E9, DenShift32);
+    D10 = xTrRound(  - 236 * E13 - 97 * E10, DenShift32);
+    D13 = xTrRound( 97 * E13 - 236 * E10, DenShift32);
+    D14 = xTrRound( 236 * E14 + 97 * E9, DenShift32);
+    D16 = F16 + F19;
+    D19 = F16 - F19;
+    D20 = F23 - F20;
+    D23 = F23 + F20;
+    D24 = F24 + F27;
+    D27 = F24 - F27;
+    D28 = F31 - F28;
+    D31 = F31 + F28;
+    D17 = E17 + E18;
+    D18 = E17 - E18;
+    D21 = E22 - E21;
+    D22 = E22 + E21;
+    D25 = E25 + E26;
+    D26 = E25 - E26;
+    D29 = E30 - E29;
+    D30 = E30 + E29;
+    
+    C0 = D0 + D3;
+    C3 = D0 - D3;
+    C8 = E8 + E11;
+    C11 = E8 - E11;
+    C12 = E15 - E12;
+    C15 = E15 + E12;
+    C1 = D1 + D2;
+    C2 = D1 - D2;
+    C9 = D9 + D10;
+    C10 = D9 - D10;
+    C13 = D14 - D13;
+    C14 = D14 + D13;
+    C5 = xTrRound( 181 * ( D6 - D5 ), DenShift32);
+    C6 = xTrRound( 181 * ( D6 + D5 ), DenShift32);
+    C18 = xTrRound( 97 * D29 - 236 * D18, DenShift32);
+    C20 = xTrRound(  - 236 * D27 - 97 * D20, DenShift32);
+    C26 = xTrRound(  - 236 * D21 + 97 * D26, DenShift32);
+    C28 = xTrRound( 97 * D19 + 236 * D28, DenShift32);
+    C19 = xTrRound( 97 * D28 - 236 * D19, DenShift32);
+    C21 = xTrRound(  - 236 * D26 - 97 * D21, DenShift32);
+    C27 = xTrRound(  - 236 * D20 + 97 * D27, DenShift32);
+    C29 = xTrRound( 97 * D18 + 236 * D29, DenShift32);
+    
+    B0 = C0 + D7;
+    B7 = C0 - D7;
+    B1 = C1 + C6;
+    B6 = C1 - C6;
+    B2 = C2 + C5;
+    B5 = C2 - C5;
+    B3 = C3 + D4;
+    B4 = C3 - D4;
+    B10 = xTrRound( 181 * ( C13 - C10 ), DenShift32);
+    B13 = xTrRound( 181 * ( C13 + C10 ), DenShift32);
+    B11 = xTrRound( 181 * ( C12 - C11 ), DenShift32);
+    B12 = xTrRound( 181 * ( C12 + C11 ), DenShift32);
+    B16 = D16 + D23;
+    B23 = D16 - D23;
+    B24 = D31 - D24;
+    B31 = D31 + D24;
+    B17 = D17 + D22;
+    B22 = D17 - D22;
+    B25 = D30 - D25;
+    B30 = D30 + D25;
+    B18 = C18 + C21;
+    B21 = C18 - C21;
+    B26 = C29 - C26;
+    B29 = C29 + C26;
+    B19 = C19 + C20;
+    B20 = C19 - C20;
+    B27 = C28 - C27;
+    B28 = C28 + C27;
+    
+    A0 = B0 + C15;
+    A15 = B0 - C15;
+    A1 = B1 + C14;
+    A14 = B1 - C14;
+    A2 = B2 + B13;
+    A13 = B2 - B13;
+    A3 = B3 + B12;
+    A12 = B3 - B12;
+    A4 = B4 + B11;
+    A11 = B4 - B11;
+    A5 = B5 + B10;
+    A10 = B5 - B10;
+    A6 = B6 + C9;
+    A9 = B6 - C9;
+    A7 = B7 + C8;
+    A8 = B7 - C8;
+    A20 = xTrRound( 181 * ( B27 - B20 ), DenShift32);
+    A27 = xTrRound( 181 * ( B27 + B20 ), DenShift32);
+    A21 = xTrRound( 181 * ( B26 - B21 ), DenShift32);
+    A26 = xTrRound( 181 * ( B26 + B21 ), DenShift32);
+    A22 = xTrRound( 181 * ( B25 - B22 ), DenShift32);
+    A25 = xTrRound( 181 * ( B25 + B22 ), DenShift32);
+    A23 = xTrRound( 181 * ( B24 - B23 ), DenShift32);
+    A24 = xTrRound( 181 * ( B24 + B23 ), DenShift32);
+    
+    pDes[         0] = (Pel)xTrRound( A0 + B31 , DCore32Shift);
+    pDes[uiStride31] = (Pel)xTrRound( A0 - B31 , DCore32Shift);
+    pDes[uiStride  ] = (Pel)xTrRound( A1 + B30 , DCore32Shift);
+    pDes[uiStride30] = (Pel)xTrRound( A1 - B30 , DCore32Shift);
+    pDes[uiStride2 ] = (Pel)xTrRound( A2 + B29 , DCore32Shift);
+    pDes[uiStride29] = (Pel)xTrRound( A2 - B29 , DCore32Shift);
+    pDes[uiStride3 ] = (Pel)xTrRound( A3 + B28 , DCore32Shift);
+    pDes[uiStride28] = (Pel)xTrRound( A3 - B28 , DCore32Shift);
+    pDes[uiStride4 ] = (Pel)xTrRound( A4 + A27 , DCore32Shift);
+    pDes[uiStride27] = (Pel)xTrRound( A4 - A27 , DCore32Shift);
+    pDes[uiStride5 ] = (Pel)xTrRound( A5 + A26 , DCore32Shift);
+    pDes[uiStride26] = (Pel)xTrRound( A5 - A26 , DCore32Shift);
+    pDes[uiStride6 ] = (Pel)xTrRound( A6 + A25 , DCore32Shift);
+    pDes[uiStride25] = (Pel)xTrRound( A6 - A25 , DCore32Shift);
+    pDes[uiStride7 ] = (Pel)xTrRound( A7 + A24 , DCore32Shift);
+    pDes[uiStride24] = (Pel)xTrRound( A7 - A24 , DCore32Shift);
+    pDes[uiStride8 ] = (Pel)xTrRound( A8 + A23 , DCore32Shift);
+    pDes[uiStride23] = (Pel)xTrRound( A8 - A23 , DCore32Shift);
+    pDes[uiStride9 ] = (Pel)xTrRound( A9 + A22 , DCore32Shift);
+    pDes[uiStride22] = (Pel)xTrRound( A9 - A22 , DCore32Shift);
+    pDes[uiStride10] = (Pel)xTrRound( A10 + A21 , DCore32Shift);
+    pDes[uiStride21] = (Pel)xTrRound( A10 - A21 , DCore32Shift);
+    pDes[uiStride11] = (Pel)xTrRound( A11 + A20 , DCore32Shift);
+    pDes[uiStride20] = (Pel)xTrRound( A11 - A20 , DCore32Shift);
+    pDes[uiStride12] = (Pel)xTrRound( A12 + B19 , DCore32Shift);
+    pDes[uiStride19] = (Pel)xTrRound( A12 - B19 , DCore32Shift);
+    pDes[uiStride13] = (Pel)xTrRound( A13 + B18 , DCore32Shift);
+    pDes[uiStride18] = (Pel)xTrRound( A13 - B18 , DCore32Shift);
+    pDes[uiStride14] = (Pel)xTrRound( A14 + B17 , DCore32Shift);
+    pDes[uiStride17] = (Pel)xTrRound( A14 - B17 , DCore32Shift);
+    pDes[uiStride15] = (Pel)xTrRound( A15 + B16 , DCore32Shift);
+    pDes[uiStride16] = (Pel)xTrRound( A15 - B16 , DCore32Shift);
+    
+#ifdef TRANS_PRECISION_EXT
+    pDes[        0 ] =  (pDes[        0 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride  ] =  (pDes[uiStride  ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride2 ] =  (pDes[uiStride2 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride3 ] =  (pDes[uiStride3 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride4 ] =  (pDes[uiStride4 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride5 ] =  (pDes[uiStride5 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride6 ] =  (pDes[uiStride6 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride7 ] =  (pDes[uiStride7 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride8 ] =  (pDes[uiStride8 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride9 ] =  (pDes[uiStride9 ]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride10] =  (pDes[uiStride10]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride11] =  (pDes[uiStride11]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride12] =  (pDes[uiStride12]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride13] =  (pDes[uiStride13]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride14] =  (pDes[uiStride14]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride15] =  (pDes[uiStride15]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride16] =  (pDes[uiStride16]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride17] =  (pDes[uiStride17]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride18] =  (pDes[uiStride18]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride19] =  (pDes[uiStride19]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride20] =  (pDes[uiStride20]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride21] =  (pDes[uiStride21]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride22] =  (pDes[uiStride22]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride23] =  (pDes[uiStride23]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride24] =  (pDes[uiStride24]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride25] =  (pDes[uiStride25]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride26] =  (pDes[uiStride26]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride27] =  (pDes[uiStride27]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride28] =  (pDes[uiStride28]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride29] =  (pDes[uiStride29]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride30] =  (pDes[uiStride30]+offset)>>uiBitDepthIncrease;
+    pDes[uiStride31] =  (pDes[uiStride31]+offset)>>uiBitDepthIncrease;
+#endif
+  }
+}
+#endif //!E243_CORE_TRANSFORMS
+#if QC_MOD_LCEC
+Void TComTrQuant::init( UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxTrSize, Int iSymbolMode, UInt *aTableLP4, UInt *aTableLP8, UInt *aTableLastPosVlcIndex,
+                       Bool bUseRDOQ,  Bool bEnc )
+#else 
+Void TComTrQuant::init( UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxTrSize, Int iSymbolMode, UInt *aTableLP4, UInt *aTableLP8, Bool bUseRDOQ,  Bool bEnc )
+#endif
+{
+  m_uiMaxTrSize  = uiMaxTrSize;
+  m_bEnc         = bEnc;
+  m_bUseRDOQ     = bUseRDOQ;
+  m_uiLPTableE8 = aTableLP8;
+  m_uiLPTableE4 = aTableLP4;
+#if QC_MOD_LCEC
+  m_uiLastPosVlcIndex=aTableLastPosVlcIndex;
+#endif
+  m_iSymbolMode = iSymbolMode;
+  
+  if ( m_bEnc )
+  {
+    m_cQP.initOffsetParam( MIN_QP, MAX_QP );
+  }
+}
+
+Void TComTrQuant::xQuant( TComDataCU* pcCU, Long* pSrc, TCoeff*& pDes, Int iWidth, Int iHeight, UInt& uiAcSum, TextType eTType, UInt uiAbsPartIdx )
+{
+  xQuantLTR(pcCU, pSrc, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+}
+
+Void TComTrQuant::xDeQuant( TCoeff* pSrc, Long*& pDes, Int iWidth, Int iHeight )
+{
+  xDeQuantLTR( pSrc, pDes, iWidth, iHeight );
+}
+
+#if INTRA_DST_TYPE_7
+Void TComTrQuant::transformNxN( TComDataCU* pcCU, Pel* pcResidual, UInt uiStride, TCoeff*& rpcCoeff, UInt uiWidth, UInt uiHeight, UInt& uiAbsSum, TextType eTType, UInt uiAbsPartIdx )
+{
+  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 );
+  xQuant( pcCU, m_plTempCoeff, rpcCoeff, uiWidth, uiHeight, uiAbsSum, eTType, uiAbsPartIdx );
+}
+#else
+Void TComTrQuant::transformNxN( TComDataCU* pcCU, Pel* pcResidual, UInt uiStride, TCoeff*& rpcCoeff, UInt uiWidth, UInt uiHeight, UInt& uiAbsSum, TextType eTType, UInt uiAbsPartIdx )
+{
+  uiAbsSum = 0;
+  
+  assert( (pcCU->getSlice()->getSPS()->getMaxTrSize() >= uiWidth) );
+  
+  xT( pcResidual, uiStride, m_plTempCoeff, uiWidth );
+  xQuant( pcCU, m_plTempCoeff, rpcCoeff, uiWidth, uiHeight, uiAbsSum, eTType, uiAbsPartIdx );
+}
+#endif
+
+
+#if INTRA_DST_TYPE_7
+Void TComTrQuant::invtransformNxN( TextType eText,UInt uiMode, Pel*& rpcResidual, UInt uiStride, TCoeff* pcCoeff, UInt uiWidth, UInt uiHeight )
+{
+  xDeQuant( pcCoeff, m_plTempCoeff, uiWidth, uiHeight);
+  xIT( uiMode, m_plTempCoeff, rpcResidual, uiStride, uiWidth);
+}
+#else
+Void TComTrQuant::invtransformNxN( Pel*& rpcResidual, UInt uiStride, TCoeff* pcCoeff, UInt uiWidth, UInt uiHeight )
+{
+  xDeQuant( pcCoeff, m_plTempCoeff, uiWidth, uiHeight);
+  xIT( m_plTempCoeff, rpcResidual, uiStride, uiWidth );
+}
+#endif
+
+#if !E243_CORE_TRANSFORMS
+Void TComTrQuant::xT2( Pel* piBlkResi, UInt uiStride, Long* psCoeff )
+{
+  Int itmp1, itmp2;
+  
+  itmp1 = piBlkResi[0] + piBlkResi[uiStride  ];
+  itmp2 = piBlkResi[1] + piBlkResi[uiStride+1];
+  
+  psCoeff[0] = itmp1 + itmp2;
+  psCoeff[1] = itmp1 - itmp2;
+  
+  itmp1 = piBlkResi[0] - piBlkResi[uiStride  ];
+  itmp2 = piBlkResi[1] - piBlkResi[uiStride+1];
+  
+  psCoeff[2] = itmp1 + itmp2;
+  psCoeff[3] = itmp1 - itmp2;
+}
+
+Void TComTrQuant::xT4( Pel* piBlkResi, UInt uiStride, Long* psCoeff )
+{
+  Int aai[4][4];
+  Int tmp1, tmp2;
+  
+  for( Int y = 0; y < 4; y++ )
+  {
+    tmp1 = piBlkResi[0] + piBlkResi[3];
+    tmp2 = piBlkResi[1] + piBlkResi[2];
+    
+    aai[0][y] = tmp1 + tmp2;
+    aai[2][y] = tmp1 - tmp2;
+    
+    tmp1 = piBlkResi[0] - piBlkResi[3];
+    tmp2 = piBlkResi[1] - piBlkResi[2];
+    
+    aai[1][y] = tmp1 * 2 + tmp2 ;
+    aai[3][y] = tmp1  - tmp2 * 2;
+    piBlkResi += uiStride;
+  }
+  
+  for( Int x = 0; x < 4; x++, psCoeff++ )
+  {
+    tmp1 = aai[x][0] + aai[x][3];
+    tmp2 = aai[x][1] + aai[x][2];
+    
+    psCoeff[0] = tmp1 + tmp2;
+    psCoeff[8] = tmp1 - tmp2;
+    
+    tmp1 = aai[x][0] - aai[x][3];
+    tmp2 = aai[x][1] - aai[x][2];
+    
+    psCoeff[4]  = tmp1 * 2 + tmp2;
+    psCoeff[12] = tmp1 - tmp2 * 2;
+  }
+}
+
+Void TComTrQuant::xT8( Pel* piBlkResi, UInt uiStride, Long* psCoeff )
+{
+  Int aai[8][8];
+#ifdef TRANS_PRECISION_EXT
+  Int uiBitDepthIncrease=g_iShift8x8-g_uiBitIncrement;
+  Int offset = (uiBitDepthIncrease==0)? 0:(1<<(uiBitDepthIncrease-1));
+#endif
+  for( Int i = 0; i < 8; i++, piBlkResi += uiStride )
+  {
+    Int ai1 [8];
+    Int ai2 [8];
+#ifdef TRANS_PRECISION_EXT
+    ai1[0] = (piBlkResi[0] + piBlkResi[7])<<uiBitDepthIncrease;
+    ai1[1] = (piBlkResi[1] + piBlkResi[6])<<uiBitDepthIncrease;
+    ai1[2] = (piBlkResi[2] + piBlkResi[5])<<uiBitDepthIncrease;
+    ai1[3] = (piBlkResi[3] + piBlkResi[4])<<uiBitDepthIncrease;
+    
+    ai1[4] = (piBlkResi[0] - piBlkResi[7])<<uiBitDepthIncrease;
+    ai1[5] = (piBlkResi[1] - piBlkResi[6])<<uiBitDepthIncrease;
+    ai1[6] = (piBlkResi[2] - piBlkResi[5])<<uiBitDepthIncrease;
+    ai1[7] = (piBlkResi[3] - piBlkResi[4])<<uiBitDepthIncrease;
+#else
+    ai1[0] = piBlkResi[0] + piBlkResi[7];
+    ai1[1] = piBlkResi[1] + piBlkResi[6];
+    ai1[2] = piBlkResi[2] + piBlkResi[5];
+    ai1[3] = piBlkResi[3] + piBlkResi[4];
+    
+    ai1[4] = piBlkResi[0] - piBlkResi[7];
+    ai1[5] = piBlkResi[1] - piBlkResi[6];
+    ai1[6] = piBlkResi[2] - piBlkResi[5];
+    ai1[7] = piBlkResi[3] - piBlkResi[4];
+#endif
+    ai2[0] = ai1[0] + ai1[3];
+    ai2[1] = ai1[1] + ai1[2];
+    ai2[2] = ai1[0] - ai1[3];
+    ai2[3] = ai1[1] - ai1[2];
+    ai2[4] = ai1[5] + ai1[6] + ((ai1[4]>>1) + ai1[4]);
+    ai2[5] = ai1[4] - ai1[7] - ((ai1[6]>>1) + ai1[6]);
+    ai2[6] = ai1[4] + ai1[7] - ((ai1[5]>>1) + ai1[5]);
+    ai2[7] = ai1[5] - ai1[6] + ((ai1[7]>>1) + ai1[7]);
+    
+    aai[0][i] =  ai2[0]     +  ai2[1];
+    aai[2][i] =  ai2[2]     + (ai2[3]>>1);
+    aai[4][i] =  ai2[0]     -  ai2[1];
+    aai[6][i] = (ai2[2]>>1) -  ai2[3];
+    
+    aai[1][i] =  ai2[4]     + (ai2[7]>>2);
+    aai[3][i] =  ai2[5]     + (ai2[6]>>2);
+    aai[5][i] =  ai2[6]     - (ai2[5]>>2);
+    aai[7][i] = (ai2[4]>>2) -  ai2[7];
+  }
+  
+  // vertical transform
+  for( Int n = 0; n < 8; n++, psCoeff++)
+  {
+    Int ai1[8];
+    Int ai2[8];
+    
+    ai1[0] = aai[n][0] + aai[n][7];
+    ai1[1] = aai[n][1] + aai[n][6];
+    ai1[2] = aai[n][2] + aai[n][5];
+    ai1[3] = aai[n][3] + aai[n][4];
+    ai1[4] = aai[n][0] - aai[n][7];
+    ai1[5] = aai[n][1] - aai[n][6];
+    ai1[6] = aai[n][2] - aai[n][5];
+    ai1[7] = aai[n][3] - aai[n][4];
+    
+    ai2[0] = ai1[0] + ai1[3];
+    ai2[1] = ai1[1] + ai1[2];
+    ai2[2] = ai1[0] - ai1[3];
+    ai2[3] = ai1[1] - ai1[2];
+    ai2[4] = ai1[5] + ai1[6] + ((ai1[4]>>1) + ai1[4]);
+    ai2[5] = ai1[4] - ai1[7] - ((ai1[6]>>1) + ai1[6]);
+    ai2[6] = ai1[4] + ai1[7] - ((ai1[5]>>1) + ai1[5]);
+    ai2[7] = ai1[5] - ai1[6] + ((ai1[7]>>1) + ai1[7]);
+    
+    psCoeff[ 0] =  ai2[0]     +  ai2[1];
+    psCoeff[16] =  ai2[2]     + (ai2[3]>>1);
+    psCoeff[32] =  ai2[0]     -  ai2[1];
+    psCoeff[48] = (ai2[2]>>1) -  ai2[3];
+    
+    psCoeff[ 8] =  ai2[4]     + (ai2[7]>>2);
+    psCoeff[24] =  ai2[5]     + (ai2[6]>>2);
+    psCoeff[40] =  ai2[6]     - (ai2[5]>>2);
+    psCoeff[56] = (ai2[4]>>2) -  ai2[7];
+#ifdef TRANS_PRECISION_EXT
+    psCoeff[ 0] =  (psCoeff[ 0]+offset)>>uiBitDepthIncrease;
+    psCoeff[16] =  (psCoeff[16]+offset)>>uiBitDepthIncrease;
+    psCoeff[32] =  (psCoeff[32]+offset)>>uiBitDepthIncrease;
+    psCoeff[48] =  (psCoeff[48]+offset)>>uiBitDepthIncrease;
+    
+    psCoeff[ 8] =  (psCoeff[ 8]+offset)>>uiBitDepthIncrease;
+    psCoeff[24] =  (psCoeff[24]+offset)>>uiBitDepthIncrease;
+    psCoeff[40] =  (psCoeff[40]+offset)>>uiBitDepthIncrease;
+    psCoeff[56] =  (psCoeff[56]+offset)>>uiBitDepthIncrease;
+#endif
+  }
+}
+
+Void TComTrQuant::xQuant2x2( Long* plSrcCoef, TCoeff*& pDstCoef, UInt& uiAbsSum )
+{
+  Int iLevel;
+  Int iSign;
+  Int iOffset = 1<<(6+m_cQP.per());
+  Int iBits   = m_cQP.per()+7;
+  
+  iSign       = plSrcCoef[0]>>31;
+  iLevel      = abs(plSrcCoef[0]);
+  iLevel     *= m_puiQuantMtx[0];
+  iLevel      = (iLevel + iOffset)>>iBits;
+  
+  if( iLevel != 0)
+  {
+    uiAbsSum   += iLevel;
+    iLevel     ^= iSign;
+    iLevel     -= iSign;
+    pDstCoef[0] = iLevel;
+  }
+  else
+  {
+    pDstCoef[0] = 0;
+  }
+  
+  iSign       = plSrcCoef[1]>>31;
+  iLevel      = abs(plSrcCoef[1]);
+  iLevel     *= m_puiQuantMtx[0];
+  iLevel      = (iLevel + iOffset)>>iBits;
+  
+  if( iLevel != 0)
+  {
+    uiAbsSum   += iLevel;
+    iLevel     ^= iSign;
+    iLevel     -= iSign;
+    pDstCoef[1] = iLevel;
+  }
+  else
+  {
+    pDstCoef[1] = 0;
+  }
+  
+  iSign       = plSrcCoef[2]>>31;
+  iLevel      = abs(plSrcCoef[2]);
+  iLevel     *= m_puiQuantMtx[0];
+  iLevel      = (iLevel + iOffset)>>iBits;
+  
+  if( iLevel != 0)
+  {
+    uiAbsSum   += iLevel;
+    iLevel     ^= iSign;
+    iLevel     -= iSign;
+    pDstCoef[2] = iLevel;
+  }
+  else
+  {
+    pDstCoef[2] = 0;
+  }
+  
+  iSign       = plSrcCoef[3]>>31;
+  iLevel      = abs(plSrcCoef[3]);
+  iLevel     *= m_puiQuantMtx[0];
+  iLevel      = (iLevel + iOffset)>>iBits;
+  
+  if( iLevel != 0)
+  {
+    uiAbsSum   += iLevel;
+    iLevel     ^= iSign;
+    iLevel     -= iSign;
+    pDstCoef[3] = iLevel;
+  }
+  else
+  {
+    pDstCoef[3] = 0;
+  }
+}
+
+Void TComTrQuant::xQuant4x4( TComDataCU* pcCU, Long* plSrcCoef, TCoeff*& pDstCoef, UInt& uiAbsSum, TextType eTType, UInt uiAbsPartIdx )
+{
+  if ( m_bUseRDOQ && (eTType == TEXT_LUMA || RDOQ_CHROMA) )
+  {
+    if ( m_iSymbolMode == 0)
+      xRateDistOptQuant_LCEC(pcCU, plSrcCoef, pDstCoef, 4, 4, uiAbsSum, eTType, uiAbsPartIdx );
+    else
+      xRateDistOptQuant(pcCU, plSrcCoef, pDstCoef, 4, 4, uiAbsSum, eTType, uiAbsPartIdx );
+  }
+  else
+  {
+    for( Int n = 0; n < 16; n++ )
+    {
+      Int iLevel, iSign;
+      iLevel  = plSrcCoef[n];
+      iSign   = iLevel;
+      iLevel  = abs( iLevel ) * m_puiQuantMtx[n];
+      
+      iLevel      = ( iLevel + m_cQP.m_iAdd4x4 ) >> m_cQP.m_iBits;
+      
+      if( 0 != iLevel )
+      {
+        iSign     >>= 31;
+        uiAbsSum   += iLevel;
+        iLevel     ^= iSign;
+        iLevel     -= iSign;
+        pDstCoef[n] = iLevel;
+      }
+      else
+      {
+        pDstCoef [n] = 0;
+      }
+    }
+  }
+}
+
+Void TComTrQuant::xQuant8x8( TComDataCU* pcCU, Long* plSrcCoef, TCoeff*& pDstCoef, UInt& uiAbsSum, TextType eTType, UInt uiAbsPartIdx )
+{
+  Int iBit = m_cQP.m_iBits + 1;
+  
+  if ( m_bUseRDOQ && (eTType == TEXT_LUMA || RDOQ_CHROMA) )
+  {
+    if ( m_iSymbolMode == 0)
+      xRateDistOptQuant_LCEC(pcCU, plSrcCoef, pDstCoef, 8, 8, uiAbsSum, eTType, uiAbsPartIdx );
+    else
+      xRateDistOptQuant(pcCU, plSrcCoef, pDstCoef, 8, 8, uiAbsSum, eTType, uiAbsPartIdx );
+  }
+  else
+  {
+    for( Int n = 0; n < 64; n++ )
+    {
+      Int iLevel, iSign;
+      
+      iLevel  = plSrcCoef[n];
+      iSign   = iLevel;
+      iLevel  = abs( iLevel ) * m_puiQuantMtx[n];
+      
+      iLevel      = ( iLevel + m_cQP.m_iAdd8x8 ) >> iBit;
+      
+      if( 0 != iLevel )
+      {
+        iSign     >>= 31;
+        uiAbsSum   += iLevel;
+        iLevel     ^= iSign;
+        iLevel     -= iSign;
+        pDstCoef[n] = iLevel;
+      }
+      else
+      {
+        pDstCoef [n] = 0;
+      }
+    }
+  }
+}
+
+Void TComTrQuant::xIT2( Long* plCoef, Pel* pResidual, UInt uiStride )
+{
+  Int itemp, itmp1, itmp2;
+  Int iSign;
+  UInt uiBits = 5;
+  UInt uiOffset = 1<<(uiBits-1);
+  
+  itmp1 = plCoef[0] + plCoef[2];
+  itmp2 = plCoef[1] + plCoef[3];
+  
+  itemp = itmp1 + itmp2;
+  iSign = itemp>>31;
+  pResidual[0] = (abs(itemp) + uiOffset)>>uiBits;
+  pResidual[0] ^= iSign;
+  pResidual[0] -= iSign;
+  
+  itemp = itmp1 - itmp2;
+  iSign = itemp>>31;
+  pResidual[1] = (abs(itemp) + uiOffset)>>uiBits;
+  pResidual[1] ^= iSign;
+  pResidual[1] -= iSign;
+  
+  itmp1 = plCoef[0] - plCoef[2];
+  itmp2 = plCoef[1] - plCoef[3];
+  
+  itemp = itmp1 + itmp2;
+  iSign = itemp>>31;
+  pResidual[uiStride] = (abs(itemp) + uiOffset)>>uiBits;
+  pResidual[uiStride] ^= iSign;
+  pResidual[uiStride] -= iSign;
+  
+  itemp = itmp1 - itmp2;
+  iSign = itemp>>31;
+  pResidual[uiStride+1] = (abs(itemp) + uiOffset)>>uiBits;
+  pResidual[uiStride+1] ^= iSign;
+  pResidual[uiStride+1] -= iSign;
+}
+
+Void TComTrQuant::xIT4( Long* plCoef, Pel* pResidual, UInt uiStride )
+{
+  Int aai[4][4];
+  Int tmp1, tmp2;
+  Int x, y;
+  Int uiStride2=(uiStride<<1);
+  Int uiStride3=uiStride2 + uiStride;
+  
+  for( x = 0; x < 4; x++, plCoef+=4 )
+  {
+    tmp1 = plCoef[0] + plCoef[2];
+    tmp2 = (plCoef[3]>>1) + plCoef[1];
+    
+    aai[0][x] = tmp1 + tmp2;
+    aai[3][x] = tmp1 - tmp2;
+    
+    tmp1 = plCoef[0] - plCoef[2];
+    tmp2 = (plCoef[1]>>1) - plCoef[3];
+    
+    aai[1][x] = tmp1 + tmp2;
+    aai[2][x] = tmp1 - tmp2;
+  }
+  
+  for( y = 0; y < 4; y++, pResidual ++ )
+  {
+    tmp1 =  aai[y][0] + aai[y][2];
+    tmp2 = (aai[y][3]>>1) + aai[y][1];
+    
+    pResidual[0]         =  xRound( tmp1 + tmp2);
+    pResidual[uiStride3] =  xRound( tmp1 - tmp2);
+    
+    tmp1 =  aai[y][0] - aai[y][2];
+    tmp2 = (aai[y][1]>>1) - aai[y][3];
+    
+    pResidual[uiStride]  =  xRound( tmp1 + tmp2);
+    pResidual[uiStride2] =  xRound( tmp1 - tmp2);
+  }
+}
+
+Void TComTrQuant::xIT8( Long* plCoef, Pel* pResidual, UInt uiStride )
+{
+  Long aai[8][8];
+  Int n;
+#ifdef TRANS_PRECISION_EXT
+#if FULL_NBIT
+  Int uiBitDepthIncrease=g_iShift8x8-g_uiBitIncrement-g_uiBitDepth+8;
+#else
+  Int uiBitDepthIncrease=g_iShift8x8-g_uiBitIncrement;
+#endif
+  Int offset = (uiBitDepthIncrease==0)? 0:(1<<(uiBitDepthIncrease-1));
+#endif
+  UInt uiStride2 = uiStride<<1;
+  UInt uiStride3 = uiStride2 + uiStride;
+  UInt uiStride4 = uiStride3 + uiStride;
+  UInt uiStride5 = uiStride4 + uiStride;
+  UInt uiStride6 = uiStride5 + uiStride;
+  UInt uiStride7 = uiStride6 + uiStride;
+  
+  for( n = 0; n < 8; n++ )
+  {
+    Long* pi = plCoef + (n<<3);
+    Long     ai1[8];
+    Long     ai2[8];
+#ifdef TRANS_PRECISION_EXT
+    Long     ai0[8];
+    ai0[0] =  pi[0]<<uiBitDepthIncrease;
+    ai0[1] =  pi[1]<<uiBitDepthIncrease;
+    ai0[2] =  pi[2]<<uiBitDepthIncrease;
+    ai0[3] =  pi[3]<<uiBitDepthIncrease;
+    ai0[4] =  pi[4]<<uiBitDepthIncrease;
+    ai0[5] =  pi[5]<<uiBitDepthIncrease;
+    ai0[6] =  pi[6]<<uiBitDepthIncrease;
+    ai0[7] =  pi[7]<<uiBitDepthIncrease;
+    ai1[0] = ai0[0] + ai0[4];
+    ai1[2] = ai0[0] - ai0[4];
+    
+    ai1[4] = (ai0[2]>>1) -  ai0[6];
+    ai1[6] =  ai0[2]     + (ai0[6]>>1);
+    
+    ai1[1] = ai0[5] - ai0[3] - ai0[7] - (ai0[7]>>1);
+    ai1[3] = ai0[1] + ai0[7] - ai0[3] - (ai0[3]>>1);;
+    ai1[5] = ai0[7] - ai0[1] + ai0[5] + (ai0[5]>>1);
+    ai1[7] = ai0[3] + ai0[5] + ai0[1] + (ai0[1]>>1);
+#else
+    ai1[0] = pi[0] + pi[4];
+    ai1[2] = pi[0] - pi[4];
+    
+    ai1[4] = (pi[2]>>1) -  pi[6];
+    ai1[6] =  pi[2]     + (pi[6]>>1);
+    
+    ai1[1] = pi[5] - pi[3] - pi[7] - (pi[7]>>1);
+    ai1[3] = pi[1] + pi[7] - pi[3] - (pi[3]>>1);;
+    ai1[5] = pi[7] - pi[1] + pi[5] + (pi[5]>>1);
+    ai1[7] = pi[3] + pi[5] + pi[1] + (pi[1]>>1);
+#endif
+    ai2[0] = ai1[0] + ai1[6];
+    ai2[6] = ai1[0] - ai1[6];
+    
+    ai2[2] = ai1[2] + ai1[4];
+    ai2[4] = ai1[2] - ai1[4];
+    
+    ai2[1] = ai1[1] + (ai1[7]>>2);
+    ai2[7] = ai1[7] - (ai1[1]>>2);
+    
+    ai2[3] =  ai1[3]     + (ai1[5]>>2);
+    ai2[5] = (ai1[3]>>2) -  ai1[5];
+    
+    aai[n][0] = ai2[0] + ai2[7];
+    aai[n][1] = ai2[2] + ai2[5];
+    aai[n][2] = ai2[4] + ai2[3];
+    aai[n][3] = ai2[6] + ai2[1];
+    aai[n][4] = ai2[6] - ai2[1];
+    aai[n][5] = ai2[4] - ai2[3];
+    aai[n][6] = ai2[2] - ai2[5];
+    aai[n][7] = ai2[0] - ai2[7];
+  }
+  
+  for( n = 0; n < 8; n++, pResidual++ )
+  {
+    Int ai1[8];
+    Int ai2[8];
+    
+    ai1[0] =  aai[0][n]     +  aai[4][n];
+    ai1[1] =  aai[5][n]     -  aai[3][n]     - aai[7][n] - (aai[7][n]>>1);
+    ai1[2] =  aai[0][n]     -  aai[4][n];
+    ai1[3] =  aai[1][n]     +  aai[7][n]     - aai[3][n] - (aai[3][n]>>1);
+    ai1[4] = (aai[2][n]>>1) -  aai[6][n];
+    ai1[5] =  aai[7][n]     -  aai[1][n]     + aai[5][n] + (aai[5][n]>>1);
+    ai1[6] =  aai[2][n]     + (aai[6][n]>>1);
+    ai1[7] =  aai[3][n]     +  aai[5][n]     + aai[1][n] + (aai[1][n]>>1);
+    
+    ai2[2] = ai1[2] + ai1[4];
+    ai2[4] = ai1[2] - ai1[4];
+    
+    ai2[0] = ai1[0] + ai1[6];
+    ai2[6] = ai1[0] - ai1[6];
+    
+    ai2[1] = ai1[1] + (ai1[7]>>2);
+    ai2[7] = ai1[7] - (ai1[1]>>2);
+    
+    ai2[3] =  ai1[3]     + (ai1[5]>>2);
+    ai2[5] = (ai1[3]>>2) -  ai1[5];
+    
+    pResidual[        0] = xRound( ai2[0] + ai2[7] );
+    pResidual[uiStride ] = xRound( ai2[2] + ai2[5] );
+    pResidual[uiStride2] = xRound( ai2[4] + ai2[3] );
+    pResidual[uiStride3] = xRound( ai2[6] + ai2[1] );
+    pResidual[uiStride4] = xRound( ai2[6] - ai2[1] );
+    pResidual[uiStride5] = xRound( ai2[4] - ai2[3] );
+    pResidual[uiStride6] = xRound( ai2[2] - ai2[5] );
+    pResidual[uiStride7] = xRound( ai2[0] - ai2[7] );
+    
+#ifdef TRANS_PRECISION_EXT
+    pResidual[        0] =  (pResidual[        0]+offset)>>uiBitDepthIncrease;
+    pResidual[uiStride ] =  (pResidual[uiStride ]+offset)>>uiBitDepthIncrease;
+    pResidual[uiStride2] =  (pResidual[uiStride2]+offset)>>uiBitDepthIncrease;
+    pResidual[uiStride3] =  (pResidual[uiStride3]+offset)>>uiBitDepthIncrease;
+    pResidual[uiStride4] =  (pResidual[uiStride4]+offset)>>uiBitDepthIncrease;
+    pResidual[uiStride5] =  (pResidual[uiStride5]+offset)>>uiBitDepthIncrease;
+    pResidual[uiStride6] =  (pResidual[uiStride6]+offset)>>uiBitDepthIncrease;
+    pResidual[uiStride7] =  (pResidual[uiStride7]+offset)>>uiBitDepthIncrease;
+#endif
+  }
+}
+
+Void TComTrQuant::xDeQuant2x2( TCoeff* pSrcCoef, Long*& rplDstCoef )
+{
+  Int iDeScale = g_aiDequantCoef4[m_cQP.m_iRem];
+  
+  if( pSrcCoef[0] != 0 )
+  {
+    rplDstCoef[0] = pSrcCoef[0]*iDeScale<<m_cQP.per();
+  }
+  else
+  {
+    rplDstCoef[0] = 0;
+  }
+  
+  if( pSrcCoef[1] != 0 )
+  {
+    rplDstCoef[1] = pSrcCoef[1]*iDeScale<<m_cQP.per();
+  }
+  else
+  {
+    rplDstCoef[1] = 0;
+  }
+  
+  if( pSrcCoef[2] != 0 )
+  {
+    rplDstCoef[2] = pSrcCoef[2]*iDeScale<<m_cQP.per();
+  }
+  else
+  {
+    rplDstCoef[2] = 0;
+  }
+  
+  if( pSrcCoef[3] != 0 )
+  {
+    rplDstCoef[3] = pSrcCoef[3]*iDeScale<<m_cQP.per();
+  }
+  else
+  {
+    rplDstCoef[3] = 0;
+  }
+}
+
+Void TComTrQuant::xDeQuant4x4( TCoeff* pSrcCoef, Long*& rplDstCoef )
+{
+  Int iLevel;
+  Int iDeScale;
+  
+  for( Int n = 0; n < 16; n++ )
+  {
+    iLevel  = pSrcCoef[n];
+    
+    if( 0 != iLevel )
+    {
+      iDeScale = g_aiDequantCoef[m_cQP.m_iRem][n];
+      
+      rplDstCoef[n] = iLevel*iDeScale << m_cQP.m_iPer;
+    }
+    else
+    {
+      rplDstCoef[n] = 0;
+    }
+  }
+}
+
+Void TComTrQuant::xDeQuant8x8( TCoeff* pSrcCoef, Long*& rplDstCoef )
+{
+  Int iLevel;
+  Int iDeScale;
+  
+  Int iAdd = ( 1 << 5 ) >> m_cQP.m_iPer;
+  
+  for( Int n = 0; n < 64; n++ )
+  {
+    iLevel  = pSrcCoef[n];
+    
+    if( 0 != iLevel )
+    {
+      iDeScale = g_aiDequantCoef64[m_cQP.m_iRem][n];
+      rplDstCoef[n]   = ( (iLevel*iDeScale*16 + iAdd) << m_cQP.m_iPer ) >> 6;
+    }
+    else
+    {
+      rplDstCoef[n] = 0;
+    }
+  }
+}
+#endif //!E243_CORE_TRANSFORMS
+
+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;
+  
+  assert(1); // as long as quadtrees are not used for residual transform
+  
+  if( uiTrMode == uiStopTrMode )
+  {
+    UInt uiDepth      = pcCU->getDepth( uiAbsPartIdx ) + uiTrMode;
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+    if( eTxt != TEXT_LUMA && uiLog2TrSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      uiWidth  <<= 1;
+      uiHeight <<= 1;
+    }
+    Pel* pResi = rpcResidual + uiAddr;
+#if INTRA_DST_TYPE_7
+    invtransformNxN( eTxt, REG_DCT, pResi, uiStride, rpcCoeff, uiWidth, uiHeight );
+#else
+    invtransformNxN( pResi, uiStride, rpcCoeff, uiWidth, uiHeight );
+#endif
+  }
+  else
+  {
+    uiTrMode++;
+    uiWidth  >>= 1;
+    uiHeight >>= 1;
+    UInt uiAddrOffset = uiHeight * uiStride;
+    UInt uiCoefOffset = uiWidth * uiHeight;
+    UInt uiPartOffset = pcCU->getTotalNumPart() >> (uiTrMode<<1);
+    invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr                         , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+    invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + uiWidth               , 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 + uiWidth, uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff );
+  }
+}
+
+// ------------------------------------------------------------------------------------------------
+// Logical transform
+// ------------------------------------------------------------------------------------------------
+
+#if E243_CORE_TRANSFORMS
+/** 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
+ */
+#if INTRA_DST_TYPE_7
+Void TComTrQuant::xT( UInt uiMode, Pel* piBlkResi, UInt uiStride, Long* psCoeff, Int iSize )
+#else
+Void TComTrQuant::xT( Pel* piBlkResi, UInt uiStride, Long* psCoeff, Int iSize )
+#endif
+{
+#if MATRIX_MULT  
+#if INTRA_DST_TYPE_7
+  xTr(piBlkResi,psCoeff,uiStride,(UInt)iSize,uiMode);
+#else
+  xTr(piBlkResi,psCoeff,uiStride,(UInt)iSize);
+#endif
+#else
+  Int j,k;
+  if (iSize==4)
+  {   
+    short block[4][4];   
+    short coeff[4][4];
+    for (j=0; j<4; j++)
+    {    
+      memcpy(block[j],piBlkResi+j*uiStride,4*sizeof(short));      
+    }
+#if INTRA_DST_TYPE_7
+    xTr4(block,coeff,uiMode);
+#else
+    xTr4(block,coeff);     
+#endif
+    for (j=0; j<4; j++)
+    {    
+      for (k=0; k<4; k++)
+      {        
+        psCoeff[j*4+k] = coeff[j][k];
+      }    
+    }    
+  }
+  else if (iSize==8)
+  {
+    short block[8][8];
+    short coeff[8][8];
+
+    for (j=0; j<8; j++)
+    {    
+      memcpy(block[j],piBlkResi+j*uiStride,8*sizeof(short));
+    }
+
+    xTr8(block,coeff);       
+    for (j=0; j<8; j++)
+    {    
+      for (k=0; k<8; k++)
+      {        
+        psCoeff[j*8+k] = coeff[j][k];
+      }    
+    }
+  }
+  else if (iSize==16)
+  {   
+    short block[16][16];
+    short coeff[16][16];
+
+    for (j=0; j<16; j++)
+    {    
+      memcpy(block[j],piBlkResi+j*uiStride,16*sizeof(short));
+    }
+    xTr16(block,coeff);       
+    for (j=0; j<16; j++)
+    {    
+      for (k=0; k<16; k++)
+      {        
+        psCoeff[j*16+k] = coeff[j][k];
+      }    
+    }
+  }
+  else if (iSize==32)
+  {   
+    short block[32][32];
+    short coeff[32][32];
+
+    for (j=0; j<32; j++)
+    {    
+      memcpy(block[j],piBlkResi+j*uiStride,32*sizeof(short));
+    }
+    xTr32(block,coeff);       
+    for (j=0; j<32; j++)
+    {    
+      for (k=0; k<32; k++)
+      {        
+        psCoeff[j*32+k] = coeff[j][k];
+      }    
+    }
+  }
+#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
+ */
+#if INTRA_DST_TYPE_7
+Void TComTrQuant::xIT( UInt uiMode, Long* plCoef, Pel* pResidual, UInt uiStride, Int iSize )
+#else
+Void TComTrQuant::xIT( Long* plCoef, Pel* pResidual, UInt uiStride, Int iSize )
+#endif
+{
+#if MATRIX_MULT  
+#if INTRA_DST_TYPE_7
+  xITr(plCoef,pResidual,uiStride,(UInt)iSize,uiMode);
+#else
+  xITr(plCoef,pResidual,uiStride,(UInt)iSize);
+#endif
+#else
+  Int j,k;
+  if (iSize==4)
+  {    
+    short block[4][4];
+    short coeff[4][4];
+
+    for (j=0; j<4; j++)
+    {    
+      for (k=0; k<4; k++)
+      {        
+        coeff[j][k] = (short)plCoef[j*4+k];
+      }    
+    }
+#if INTRA_DST_TYPE_7
+    xITr4(coeff,block,uiMode);
+#else
+    xITr4(coeff,block);       
+#endif
+    for (j=0; j<4; j++)
+    {    
+      memcpy(pResidual+j*uiStride,block[j],4*sizeof(short));
+    }    
+  }
+  else if (iSize==8)
+  {
+    short block[8][8];
+    short coeff[8][8];
+
+    for (j=0; j<8; j++)
+    {    
+      for (k=0; k<8; k++)
+      {        
+        coeff[j][k] = (short)plCoef[j*8+k];
+      }    
+    }
+    xITr8(coeff,block);       
+    for (j=0; j<8; j++)
+    {    
+      memcpy(pResidual+j*uiStride,block[j],8*sizeof(short));
+    }
+  }
+  else if (iSize==16)
+  {
+    short block[16][16];
+    short coeff[16][16];
+
+    for (j=0; j<16; j++)
+    {    
+      for (k=0; k<16; k++)
+      {        
+        coeff[j][k] = (short)plCoef[j*16+k];
+      }    
+    }
+    xITr16(coeff,block);       
+    for (j=0; j<16; j++)
+    {    
+      memcpy(pResidual+j*uiStride,block[j],16*sizeof(short));
+    }
+  }
+
+  else if (iSize==32)
+  {
+    short block[32][32];
+    short coeff[32][32];
+
+    for (j=0; j<32; j++)
+    {    
+      for (k=0; k<32; k++)
+      {        
+        coeff[j][k] = (short)plCoef[j*32+k];
+      }    
+    }
+    xITr32(coeff,block);       
+    for (j=0; j<32; j++)
+    {    
+      memcpy(pResidual+j*uiStride,block[j],32*sizeof(short));
+    }   
+  }
+#endif  
+}
+#else
+
+Void TComTrQuant::xT( Pel* piBlkResi, UInt uiStride, Long* psCoeff, Int iSize )
+{
+  switch( iSize )
+  {
+    case  2: xT2 ( piBlkResi, uiStride, psCoeff ); break;
+    case  4: xT4 ( piBlkResi, uiStride, psCoeff ); break;
+    case  8: xT8 ( piBlkResi, uiStride, psCoeff ); break;
+    case 16: xT16( piBlkResi, uiStride, psCoeff ); break;
+    case 32: xT32( piBlkResi, uiStride, psCoeff ); break;
+    default: assert(0); break;
+  }
+}
+
+Void TComTrQuant::xIT( Long* plCoef, Pel* pResidual, UInt uiStride, Int iSize )
+{
+  switch( iSize )
+  {
+    case  2: xIT2 ( plCoef, pResidual, uiStride ); break;
+    case  4: xIT4 ( plCoef, pResidual, uiStride ); break;
+    case  8: xIT8 ( plCoef, pResidual, uiStride ); break;
+    case 16: xIT16( plCoef, pResidual, uiStride ); break;
+    case 32: xIT32( plCoef, pResidual, uiStride ); break;
+    default: assert(0); break;
+  }
+}
+#endif //E243_CORE_TRANSFORMS
+#if QC_MDCS
+UInt TComTrQuant::getCurrLineNum(UInt uiScanIdx, UInt uiPosX, UInt uiPosY)
+{
+      UInt uiLineNum = 0;
+
+      switch (uiScanIdx)
+      {
+        case SCAN_ZIGZAG:
+          uiLineNum = uiPosY + uiPosX;
+          break;
+        case SCAN_HOR:
+          uiLineNum = uiPosY;
+          break;
+        case SCAN_VER:
+          uiLineNum = uiPosX;
+          break;
+      }
+
+      return uiLineNum;
+}
+#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,
+                                                      Long*                           plSrcCoeff,
+                                                      TCoeff*&                        piDstCoeff,
+                                                      UInt                            uiWidth,
+                                                      UInt                            uiHeight,
+                                                      UInt&                           uiAbsSum,
+                                                      TextType                        eTType,
+                                                      UInt                            uiAbsPartIdx )
+{
+  Int    iQBits      = m_cQP.m_iBits;
+  Double dTemp       = 0;
+  
+#if E243_CORE_TRANSFORMS
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiWidth ] + 2;
+  UInt uiQ = g_auiQ[m_cQP.rem()];
+
+#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
+  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
+  dErrScale = dErrScale/(double)(uiQ*uiQ);                                 // Compensate for qp-dependent multiplier applied before calculating the Lagrange cost function
+  dErrScale = dErrScale/(double)(1<<(2*g_uiBitIncrement));                   // Compensate for Lagrange multiplier that is tuned towards 8-bit input
+
+  iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+#else
+  Bool   b64Flag     = false;
+  Int    iQuantCoeff = 0;
+  Int    iQpRem      = m_cQP.m_iRem;
+  Bool   bExt8x8Flag = false;
+  Double dNormFactor = 0;
+  if( uiWidth == 4 && uiHeight == 4 )
+  {
+    dNormFactor = pow( 2., ( 2 * DQ_BITS + 19 ) );
+    if( g_uiBitIncrement )
+    {
+      dNormFactor *=  1 << ( 2 * g_uiBitIncrement );
+    }
+    m_puiQuantMtx = &g_aiQuantCoef[ m_cQP.m_iRem ][ 0 ];
+  }
+  else if( uiWidth == 8 && uiHeight == 8 )
+  {
+    iQBits++;
+    dNormFactor = pow( 2., ( 2 * Q_BITS_8 + 9 ) );
+    if( g_uiBitIncrement )
+    {
+      dNormFactor *= 1 << ( 2 * g_uiBitIncrement );
+    }
+    m_puiQuantMtx = &g_aiQuantCoef64[ m_cQP.m_iRem ][ 0 ];
+  }
+  else if( uiWidth == 16 && uiHeight == 16 )
+  {
+    iQBits = ECore16Shift + m_cQP.per();
+    dNormFactor = pow( 2., 21 );
+    if( g_uiBitIncrement )
+    {
+      dNormFactor *=  1 << ( 2 * g_uiBitIncrement );
+    }
+    dTemp = estErr16x16[ iQpRem ] / dNormFactor;
+    m_puiQuantMtx = ( &g_aiQuantCoef256[ m_cQP.m_iRem ][ 0 ] );
+    bExt8x8Flag = true;
+  }
+  else if ( uiWidth == 32 && uiHeight == 32 )
+  {
+    iQBits = ECore32Shift + m_cQP.per();
+    dNormFactor = pow( 2., 21 );
+    if( g_uiBitIncrement )
+    {
+      dNormFactor *= 1 << ( 2 * g_uiBitIncrement );
+    }
+    dTemp = estErr32x32[ iQpRem ] / dNormFactor;
+    m_puiQuantMtx = ( &g_aiQuantCoef1024[ m_cQP.m_iRem ][ 0 ] );
+    bExt8x8Flag = true;
+  }
+  else
+  {
+    assert( 0 );
+  }
+#endif
+
+#if E253
+  UInt       uiGoRiceParam       = 0;
+#endif
+#if PCP_SIGMAP_SIMPLE_LAST
+  UInt       uiLastScanPos       = 0;
+#else
+  UInt       uiMaxLineNum        = 0;
+#endif
+  Double     d64BlockUncodedCost = 0;
+  const UInt uiLog2BlkSize       = g_aucConvertToBit[ uiWidth ] + 2;
+  const UInt uiMaxNumCoeff       = 1 << ( uiLog2BlkSize << 1 );
+  const UInt uiNum4x4Blk         = max<UInt>( 1, uiMaxNumCoeff >> 4 );
+#if QC_MDCS
+  const UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+#endif //QC_MDCS
+  
+  Int  piCoeff      [ MAX_CU_SIZE * MAX_CU_SIZE ];
+  Long plLevelDouble[ MAX_CU_SIZE * MAX_CU_SIZE ];
+#if E253
+  UInt puiEstParams [ 16384 ];
+
+  ::memset( piDstCoeff,    0, sizeof(TCoeff) *   uiMaxNumCoeff        );
+  ::memset( piCoeff,       0, sizeof(Int)    *   uiMaxNumCoeff        );
+  ::memset( plLevelDouble, 0, sizeof(Long)   *   uiMaxNumCoeff        );
+  ::memset( puiEstParams,  0, sizeof(UInt)   * ( uiMaxNumCoeff << 2 ) );
+
+  UInt *puiOneCtx    = puiEstParams;
+  UInt *puiAbsCtx    = puiEstParams +   uiMaxNumCoeff;
+  UInt *puiAbsGoRice = puiEstParams + ( uiMaxNumCoeff << 1 );
+  UInt *puiBaseCtx   = puiEstParams + ( uiMaxNumCoeff << 1 ) + uiMaxNumCoeff;
+#else
+  UInt puiOneCtx    [ MAX_CU_SIZE * MAX_CU_SIZE ];
+  UInt puiAbsCtx    [ MAX_CU_SIZE * MAX_CU_SIZE ];
+  UInt puiBaseCtx   [ ( MAX_CU_SIZE * MAX_CU_SIZE ) >> 4 ];
+  
+  
+  ::memset( piDstCoeff,    0, sizeof(TCoeff) *   uiMaxNumCoeff        );
+  ::memset( piCoeff,       0, sizeof(Int)    *   uiMaxNumCoeff        );
+  ::memset( plLevelDouble, 0, sizeof(Long)   *   uiMaxNumCoeff        );
+  ::memset( puiOneCtx,     0, sizeof(UInt)   *   uiMaxNumCoeff        );
+  ::memset( puiAbsCtx,     0, sizeof(UInt)   *   uiMaxNumCoeff        );
+  ::memset( puiBaseCtx,    0, sizeof(UInt)   * ( uiMaxNumCoeff >> 4 ) );
+#endif
+
+  //===== quantization =====
+  for( UInt uiScanPos = 0; uiScanPos < uiMaxNumCoeff; uiScanPos++ )
+  {
+#if PCP_SIGMAP_SIMPLE_LAST
+    UInt    uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanPos];  
+#else
+    UInt    uiBlkPos = g_auiFrameScanXY[ uiLog2BlkSize-1 ][ uiScanPos ];
+#endif
+
+    Long lLevelDouble = plSrcCoeff[ uiBlkPos ];
+
+#if E243_CORE_TRANSFORMS
+    dTemp = dErrScale;  
+    lLevelDouble = abs(lLevelDouble * (Long)uiQ);   
+#else 
+    UInt    uiPosY   = uiBlkPos >> uiLog2BlkSize;
+    UInt    uiPosX   = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+    if      ( uiWidth == 4 ) dTemp = estErr4x4[ iQpRem ][ uiPosX ][ uiPosY ] / dNormFactor;
+    else if ( uiWidth == 8 ) dTemp = estErr8x8[ iQpRem ][ uiPosX ][ uiPosY ] / dNormFactor;
+    
+    lLevelDouble = abs( lLevelDouble * ( Long )( b64Flag ? iQuantCoeff : m_puiQuantMtx[ uiBlkPos ] ) );
+#endif    
+    plLevelDouble[ uiBlkPos ] = lLevelDouble;
+    UInt uiMaxAbsLevel = lLevelDouble >> iQBits;
+    Bool bLowerInt     = ( ( lLevelDouble - Long( uiMaxAbsLevel << iQBits ) ) < Long( 1 << ( iQBits - 1 ) ) ) ? true : false;
+    
+    if( !bLowerInt )
+    {
+      uiMaxAbsLevel++;
+    }
+    
+    Double dErr          = Double( lLevelDouble );
+    d64BlockUncodedCost += dErr * dErr * dTemp;
+    
+    piCoeff[ uiBlkPos ] = plSrcCoeff[ uiBlkPos ] > 0 ? uiMaxAbsLevel : -Int( uiMaxAbsLevel );
+    
+    if ( uiMaxAbsLevel > 0 )
+    {
+#if PCP_SIGMAP_SIMPLE_LAST
+      uiLastScanPos = uiScanPos;
+#else
+#if QC_MDCS
+      UInt uiLineNum = getCurrLineNum(uiScanIdx, uiPosX, uiPosY);
+#else
+      UInt uiLineNum = uiPosY + uiPosX;
+#endif //QC_MDCS
+      
+      if( uiLineNum > uiMaxLineNum )
+      {
+        uiMaxLineNum = uiLineNum;
+      }
+#endif
+    }    
+  }
+  
+#if PCP_SIGMAP_SIMPLE_LAST
+  uiLastScanPos++;
+#endif
+
+  //===== estimate context models =====
+  if ( uiNum4x4Blk > 1 )
+  {
+    Bool bFirstBlock  = true;
+    UInt uiNumOne = 0;
+    
+    for( UInt uiSubBlk = 0; uiSubBlk < uiNum4x4Blk; uiSubBlk++ )
+    {
+      UInt uiCtxSet    = 0;
+      UInt uiSubNumSig = 0;
+      UInt uiSubPosX   = 0;
+      UInt uiSubPosY   = 0;
+#if E253
+      uiGoRiceParam    = 0;
+#endif
+
+      uiSubPosX = g_auiFrameScanX[ g_aucConvertToBit[ uiWidth ] - 1 ][ uiSubBlk ] << 2;
+      uiSubPosY = g_auiFrameScanY[ g_aucConvertToBit[ uiWidth ] - 1 ][ uiSubBlk ] << 2;
+      
+      Int* piCurr = &piCoeff[ uiSubPosX + uiSubPosY * uiWidth ];
+      
+      for( UInt uiY = 0; uiY < 4; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < 4; uiX++ )
+        {
+          if( piCurr[ uiX ] )
+          {
+            uiSubNumSig++;
+          }
+        }
+        piCurr += uiWidth;
+      }
+      
+      if( uiSubNumSig > 0 )
+      {
+        Int c1 = 1;
+        Int c2 = 0;
+        UInt uiAbs  = 0;
+        UInt uiSign = 0;
+        
+        if( bFirstBlock )
+        {
+          bFirstBlock = false;
+          uiCtxSet = 5;
+        }
+        else
+        {
+          uiCtxSet = ( uiNumOne >> 2 ) + 1;
+          uiNumOne = 0;
+        }
+        
+        puiBaseCtx[ ( uiSubPosX >> 2 ) + ( uiSubPosY >> 2 ) * ( uiWidth >> 2 ) ] = uiCtxSet;
+        
+        for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+        {
+          UInt  uiBlkPos  = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+          UInt  uiPosY    = uiBlkPos >> 2;
+          UInt  uiPosX    = uiBlkPos - ( uiPosY << 2 );
+          UInt  uiIndex   = (uiSubPosY + uiPosY) * uiWidth + uiSubPosX + uiPosX;
+          
+          puiOneCtx[ uiIndex ] = min<UInt>( c1, 4 );
+          puiAbsCtx[ uiIndex ] = min<UInt>( c2, 4 );
+#if E253
+          puiAbsGoRice[ uiIndex ] = uiGoRiceParam;
+#endif
+          
+          if( piCoeff[ uiIndex ]  )
+          {
+            if( piCoeff[ uiIndex ] > 0) { uiAbs = static_cast<UInt>(  piCoeff[ uiIndex ] );  uiSign = 0; }
+            else                        { uiAbs = static_cast<UInt>( -piCoeff[ uiIndex ] );  uiSign = 1; }
+            
+            UInt uiSymbol = uiAbs > 1 ? 1 : 0;
+            
+            if( uiSymbol )
+            {
+              c1 = 0; c2++;
+              uiNumOne++;
+#if E253
+              if( uiAbs > 3 )
+              {
+                uiAbs -= 4;
+                uiAbs  = min<UInt>( uiAbs, 15 );
+                uiGoRiceParam = g_aauiGoRiceUpdate[ uiGoRiceParam ][ uiAbs ];
+              }
+#endif
+            }
+            else if( c1 )
+            {
+              c1++;
+            }
+          }
+        }
+      }
+    }
+  }
+  else
+  {
+    Int c1 = 1;
+    Int c2 = 0;
+    UInt uiAbs  = 0;
+    UInt uiSign = 0;
+    
+    for ( UInt uiScanPos = 0; uiScanPos < uiWidth*uiHeight; uiScanPos++ )
+    {
+      UInt uiIndex = g_auiFrameScanXY[ (int)g_aucConvertToBit[ uiWidth ] + 1 ][ uiWidth * uiHeight - uiScanPos - 1 ];
+      
+      puiOneCtx[ uiIndex ] = min<UInt>( c1, 4 );
+      puiAbsCtx[ uiIndex ] = min<UInt>( c2, 4 );
+#if E253
+      puiAbsGoRice[ uiIndex ] = uiGoRiceParam;
+#endif
+
+      if( piCoeff[ uiIndex ]  )
+      {
+        if( piCoeff[ uiIndex ] > 0) { uiAbs = static_cast<UInt>(  piCoeff[ uiIndex ] );  uiSign = 0; }
+        else                        { uiAbs = static_cast<UInt>( -piCoeff[ uiIndex ] );  uiSign = 1; }
+        
+        UInt uiSymbol = uiAbs > 1 ? 1 : 0;
+        
+        if( uiSymbol )
+        {
+          c1 = 0; c2++;
+#if E253
+          if( uiAbs > 3 )
+          {
+            uiAbs -= 4;
+            uiAbs  = min<UInt>( uiAbs, 15 );
+            uiGoRiceParam = g_aauiGoRiceUpdate[ uiGoRiceParam ][ uiAbs ];
+          }
+#endif
+        }
+        else if( c1 )
+        {
+          c1++;
+        }
+      }
+    }
+  }
+  
+  Int     ui16CtxCbf        = 0;
+  UInt    uiBestLastIdxP1   = 0;
+  Double  d64BestCost       = 0;
+  Double  d64BaseCost       = 0;
+  Double  d64CodedCost      = 0;
+  Double  d64UncodedCost    = 0;
+
+  if( !pcCU->isIntra( uiAbsPartIdx ) && eTType == TEXT_LUMA && pcCU->getTransformIdx( uiAbsPartIdx ) == 0 )
+  {
+    ui16CtxCbf  = pcCU->getCtxQtRootCbf( uiAbsPartIdx );
+    d64BestCost = d64BlockUncodedCost + xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 0 ] );
+    d64BaseCost = d64BestCost - xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 0 ] ) + xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 1 ] );
+  }
+  else
+  {
+    ui16CtxCbf  = pcCU->getCtxQtCbf( uiAbsPartIdx, eTType, pcCU->getTransformIdx( uiAbsPartIdx ) );
+    ui16CtxCbf  = ( eTType ? eTType - 1 : eTType ) * NUM_QT_CBF_CTX + ui16CtxCbf;
+    d64BestCost = d64BlockUncodedCost + xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 0 ] );
+    d64BaseCost = d64BestCost - xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 0 ] ) + xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 1 ] );
+  }
+  
+#if PCP_SIGMAP_SIMPLE_LAST
+  Double  d64CostLast        = 0;
+  TCoeff  iLastCoeffLevel    = 0;
+  UInt    uiBestNonZeroLevel = 0;
+  UInt    uiBestLastBlkPos   = 0;
+
+  for( UInt uiScanPos = 0; uiScanPos < uiLastScanPos; uiScanPos++ )
+  {
+    UInt   uiBlkPos     = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanPos];  
+    UInt   uiPosY       = uiBlkPos >> uiLog2BlkSize;
+    UInt   uiPosX       = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+    UInt   uiCtxBase    = uiNum4x4Blk > 0 ? puiBaseCtx[ ( uiPosX >> 2 ) + ( uiPosY >> 2 ) * ( uiWidth >> 2 ) ] : 0;
+
+#if E243_CORE_TRANSFORMS
+    dTemp = dErrScale;
+#else
+    if      ( uiWidth == 4 ) dTemp = estErr4x4[ iQpRem ][ uiPosX ][ uiPosY ] / dNormFactor;
+    else if ( uiWidth == 8 ) dTemp = estErr8x8[ iQpRem ][ uiPosX ][ uiPosY ] / dNormFactor;
+#endif
+
+    UShort  uiCtxSig       = getSigCtxInc( piDstCoeff, uiPosX, uiPosY, uiLog2BlkSize, uiWidth );
+    UInt    uiMaxAbsLevel  = abs( piCoeff[ uiBlkPos ] );
+#if E253
+    UInt    uiLevel        = xGetCodedLevel( d64UncodedCost, d64CodedCost, d64CostLast, uiBestNonZeroLevel, plLevelDouble[ uiBlkPos ], uiMaxAbsLevel, uiCtxSig, puiOneCtx[ uiBlkPos ], puiAbsCtx[ uiBlkPos ], puiAbsGoRice[ uiBlkPos ], iQBits, dTemp, uiCtxBase );
+#else
+    UInt    uiLevel        = xGetCodedLevel( d64UncodedCost, d64CodedCost, d64CostLast, uiBestNonZeroLevel, plLevelDouble[ uiBlkPos ], uiMaxAbsLevel, uiCtxSig, puiOneCtx[ uiBlkPos ], puiAbsCtx[ uiBlkPos ], iQBits, dTemp, uiCtxBase );
+#endif
+    piDstCoeff[ uiBlkPos ] = plSrcCoeff[ uiBlkPos ] < 0 ? -Int( uiLevel ) : uiLevel;
+    d64BaseCost           -= d64UncodedCost;
+
+    if( uiBestNonZeroLevel != 0 )
+    {
+      d64CostLast        += d64BaseCost;
+      d64CostLast        += uiScanIdx == SCAN_VER ? xGetRateLast( uiPosY, uiPosX ) : xGetRateLast( uiPosX, uiPosY );
+      if( d64CostLast < d64BestCost )
+      {
+        d64BestCost       = d64CostLast;
+        uiBestLastIdxP1   = uiScanPos + 1;
+        uiBestLastBlkPos  = uiBlkPos;
+        iLastCoeffLevel   = plSrcCoeff[ uiBlkPos ] < 0 ? -Int( uiBestNonZeroLevel ) : uiBestNonZeroLevel;
+      }
+    }
+    d64BaseCost           += d64CodedCost;
+  }
+  if( uiBestLastBlkPos > 0)
+  {
+    piDstCoeff[ uiBestLastBlkPos ] = iLastCoeffLevel;
+  }
+#else
+  for( UInt uiScanPos = 0; uiScanPos < uiMaxNumCoeff; uiScanPos++ )
+  {
+#if QC_MDCS
+    UInt uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanPos];  
+#else
+    UInt   uiBlkPos     = g_auiFrameScanXY[ uiLog2BlkSize-1 ][ uiScanPos ];
+#endif //QC_MDCS
+    UInt   uiPosY       = uiBlkPos >> uiLog2BlkSize;
+    UInt   uiPosX       = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+    UInt   uiCtxBase    = uiNum4x4Blk > 0 ? puiBaseCtx[ ( uiPosX >> 2 ) + ( uiPosY >> 2 ) * ( uiWidth >> 2 ) ] : 0;
+    
+#if QC_MDCS
+    UInt uiLineNum = getCurrLineNum(uiScanIdx, uiPosX, uiPosY);
+    if ( uiLineNum > uiMaxLineNum )
+    {
+      break;
+    }
+#else 
+    if( uiPosY + uiPosX > uiMaxLineNum )
+    {
+      break;
+    }
+#endif //QC_MDCS
+    
+    if      ( uiWidth == 4 ) dTemp = estErr4x4[ iQpRem ][ uiPosX ][ uiPosY ] / dNormFactor;
+    else if ( uiWidth == 8 ) dTemp = estErr8x8[ iQpRem ][ uiPosX ][ uiPosY ] / dNormFactor;
+    
+    UShort  uiCtxSig                = getSigCtxInc( piDstCoeff, uiPosX, uiPosY, uiLog2BlkSize, uiWidth );
+    Bool    bLastScanPos            = ( uiScanPos == uiMaxNumCoeff - 1 );
+#if E253
+    UInt    uiLevel                 = xGetCodedLevel( d64UncodedCost, d64CodedCost, plLevelDouble[ uiBlkPos ], abs( piCoeff[ uiBlkPos ] ), bLastScanPos, uiCtxSig, puiOneCtx[ uiBlkPos ], puiAbsCtx[ uiBlkPos ], puiAbsGoRice[ uiBlkPos ], iQBits, dTemp, uiCtxBase );
+#else
+    UInt    uiLevel                 = xGetCodedLevel( d64UncodedCost, d64CodedCost, plLevelDouble[ uiBlkPos ], abs( piCoeff[ uiBlkPos ] ), bLastScanPos, uiCtxSig, puiOneCtx[ uiBlkPos ], puiAbsCtx[ uiBlkPos ], iQBits, dTemp, uiCtxBase );
+#endif
+    piDstCoeff[ uiBlkPos ]          = plSrcCoeff[ uiBlkPos ] < 0 ? -Int( uiLevel ) : uiLevel;
+    d64BaseCost                    -= d64UncodedCost;
+    d64BaseCost                    += d64CodedCost;
+    
+    if( uiLevel )
+    {
+      //----- check for last flag -----
+      UShort  uiCtxLast             = getLastCtxInc( uiPosX, uiPosY, uiLog2BlkSize );
+      Double  d64CostLastZero       = xGetICost( m_pcEstBitsSbac->lastBits[ uiCtxLast ][ 0 ] );
+      Double  d64CostLastOne        = xGetICost( m_pcEstBitsSbac->lastBits[ uiCtxLast ][ 1 ] );
+      Double  d64CurrIsLastCost     = d64BaseCost + d64CostLastOne;
+      d64BaseCost                  += d64CostLastZero;
+      
+      if( d64CurrIsLastCost < d64BestCost )
+      {
+        d64BestCost       = d64CurrIsLastCost;
+        uiBestLastIdxP1   = uiScanPos + 1;
+      }
+    }
+  }
+#endif
+  
+  //===== clean uncoded coefficients =====
+  {
+    for( UInt uiScanPos = 0; uiScanPos < uiMaxNumCoeff; uiScanPos++ )
+    {
+#if QC_MDCS
+      UInt uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanPos];  
+#else
+      UInt uiBlkPos = g_auiFrameScanXY[ uiLog2BlkSize-1 ][ uiScanPos ];
+#endif //QC_MDCS
+      
+      if( uiScanPos < uiBestLastIdxP1 )
+      {
+        uiAbsSum += abs( piDstCoeff[ uiBlkPos ] );
+      }
+      else
+      {
+        piDstCoeff[ uiBlkPos ] = 0;
+      }      
+    }
+  }
+}
+
+#if !SONY_SIG_CTX
+/** Context derivation process of coeff_abs_significant_flag
+ * \param pcCoeff pointer to prior coded transform coefficients
+ * \param uiPosX column of current scan position
+ * \param uiPosY row of current scan position
+ * \param uiLog2BlkSize log2 value of block size
+ * \param uiStride stride of the block
+ * \returns ctxInc for current scan position
+ */
+UInt TComTrQuant::getSigCtxInc    ( TCoeff*                         pcCoeff,
+                                    const UInt                      uiPosX,
+                                    const UInt                      uiPosY,
+                                    const UInt                      uiLog2BlkSize,
+                                    const UInt                      uiStride )
+{
+  UInt  uiCtxInc  = 0;
+  UInt  uiSizeM1  = ( 1 << uiLog2BlkSize ) - 1;
+  if( uiLog2BlkSize <= 3 )
+  {
+    UInt  uiShift = uiLog2BlkSize > 2 ? uiLog2BlkSize - 2 : 0;
+    uiCtxInc      = ( ( uiPosY >> uiShift ) << 2 ) + ( uiPosX >> uiShift );
+  }
+  else if( uiPosX <= 1 && uiPosY <= 1 )
+  {
+    uiCtxInc            = ( uiPosY << 1 ) + uiPosX;
+  }
+  else if( uiPosY == 0 )
+  {
+    const int*  pData   = &pcCoeff[ uiPosX + uiPosY * uiStride ];
+    int         iStride =  uiStride;
+    UInt        uiCnt   = ( pData[         -1 ] ? 1 : 0 );
+    uiCnt              += ( pData[         -2 ] ? 1 : 0 );
+    uiCnt              += ( pData[ iStride -2 ] ? 1 : 0 );
+    if( ! (uiPosX & 1) )
+    {
+      uiCnt            += ( pData[ iStride -1 ] ? 1 : 0 );
+    }
+    uiCtxInc            = 4 + ( ( uiCnt + 1 ) >> 1 );
+  }
+  else if( uiPosX == 0 )
+  {
+    const int*  pData   = &pcCoeff[ uiPosX + uiPosY * uiStride ];
+    int         iStride =  uiStride;
+    int         iStride2=  iStride << 1;
+    UInt        uiCnt   = ( pData[  -iStride  ] ? 1 : 0 );
+    uiCnt              += ( pData[  -iStride2 ] ? 1 : 0 );
+    uiCnt              += ( pData[ 1-iStride2 ] ? 1 : 0 );
+    if( uiPosY & 1 )
+    {
+      uiCnt            += ( pData[ 1-iStride  ] ? 1 : 0 );
+    }
+    uiCtxInc            = 7 + ( ( uiCnt + 1 ) >> 1 );
+  }
+  else
+  {
+    const int*  pData   = &pcCoeff[ uiPosX + uiPosY * uiStride ];
+    int         iStride =  uiStride;
+    int         iStride2=  iStride << 1;
+    UInt        uiCnt   = ( pData[    -iStride  ] ? 1 : 0 );
+    uiCnt              += ( pData[ -1           ] ? 1 : 0 );
+    uiCnt              += ( pData[ -1 -iStride  ] ? 1 : 0 );
+    if( uiPosX > 1 )
+    {
+      uiCnt            += ( pData[ -2           ] ? 1 : 0 );
+      uiCnt            += ( pData[ -2 -iStride  ] ? 1 : 0 );
+      if( uiPosY < uiSizeM1 )
+      {
+        uiCnt          += ( pData[ -2 +iStride  ] ? 1 : 0 );
+      }
+    }
+    if( uiPosY > 1 )
+    {
+      uiCnt            += ( pData[    -iStride2 ] ? 1 : 0 );
+      uiCnt            += ( pData[ -1 -iStride2 ] ? 1 : 0 );
+      if( uiPosX < uiSizeM1 )
+      {
+        uiCnt          += ( pData[  1 -iStride2 ] ? 1 : 0 );
+      }
+    }
+    if( (uiPosX + uiPosY) & 1 )
+    {
+      if( uiPosX < uiSizeM1 )
+      {
+        uiCnt          += ( pData[  1 -iStride  ] ? 1 : 0 );
+      }
+    }
+    else
+    {
+      if( uiPosY < uiSizeM1 )
+      {
+        uiCnt          += ( pData[ -1 +iStride  ] ? 1 : 0 );
+      }
+    }
+    uiCtxInc      = 10 + min<UInt>( 4, ( uiCnt + 1 ) >> 1 );
+  }
+  return uiCtxInc;
+}
+#else
+/** Context derivation process of coeff_abs_significant_flag
+ * \param pcCoeff pointer to prior coded transform coefficients
+ * \param uiPosX column of current scan position
+ * \param uiPosY row of current scan position
+ * \param uiLog2BlkSize log2 value of block size
+ * \param uiStride stride of the block
+ * \returns ctxInc for current scan position
+ */
+UInt TComTrQuant::getSigCtxInc    ( TCoeff*                         pcCoeff,
+                                    const UInt                      uiPosX,
+                                    const UInt                      uiPosY,
+                                    const UInt                      uiLog2BlkSize,
+                                    const UInt                      uiStride )
+{
+  UInt  uiCtxInc  = 0;
+  
+  if( uiLog2BlkSize <= 3 )
+  {
+    UInt  uiShift = uiLog2BlkSize > 2 ? uiLog2BlkSize - 2 : 0;
+    uiCtxInc      = ( ( uiPosY >> uiShift ) << 2 ) + ( uiPosX >> uiShift );
+  }
+  else if( uiPosX <= 1 && uiPosY <= 1 )
+  {
+    uiCtxInc            = ( uiPosY << 1 ) + uiPosX;
+  }
+  else if( uiPosY == 0 )
+  {
+    const int*  pData   = &pcCoeff[ uiPosX + uiPosY * uiStride ];
+    UInt        uiCnt   = ( pData[         -1 ] ? 1 : 0 );
+    uiCnt              += ( pData[         -2 ] ? 1 : 0 );
+    uiCtxInc            = 4 + uiCnt;
+  }
+  else if( uiPosX == 0 )
+  {
+    const int*  pData   = &pcCoeff[ uiPosX + uiPosY * uiStride ];
+    int         iStride =  uiStride;
+    int         iStride2=  iStride << 1;
+    UInt        uiCnt   = ( pData[  -iStride  ] ? 1 : 0 );
+    uiCnt              += ( pData[  -iStride2 ] ? 1 : 0 );
+    uiCtxInc            = 7 + uiCnt;
+  }
+  else
+  {
+    const int*  pData   = &pcCoeff[ uiPosX + uiPosY * uiStride ];
+    int         iStride =  uiStride;
+    int         iStride2=  iStride << 1;
+    UInt        uiCnt   = ( pData[ -1 -iStride  ] ? 1 : 0 );
+    uiCnt              += ( pData[    -iStride  ] ? 1 : 0 );
+    uiCnt              += ( pData[ -1           ] ? 1 : 0 );
+    if( uiPosX > 1 )
+    {
+      uiCnt          += ( pData[ -2           ] ? 1 : 0 );
+    }
+    if ( uiPosY > 1 )
+    {
+      uiCnt          += ( pData[    -iStride2 ] ? 1 : 0 );
+    }
+    uiCtxInc            = 10 + min<UInt>( 4, uiCnt);
+  }
+  return uiCtxInc;
+}
+#endif
+
+#if !PCP_SIGMAP_SIMPLE_LAST
+/** Context derivation of coeff_abs_last_significant_flag
+ * \param uiPosX column of current scan position
+ * \param uiPosY row of current scan position
+ * \param uiLog2BlkSize log2 value of block size
+ * \returns ctxInc for current scan position
+ */
+UInt TComTrQuant::getLastCtxInc   ( const UInt                      uiPosX,
+                                    const UInt                      uiPosY,
+                                    const UInt                      uiLog2BlkSize )
+{
+  if( uiLog2BlkSize <= 2 )
+  {
+    return ( uiPosY << 2 ) + uiPosX;
+  }
+  else
+  {
+    return ( uiPosX + uiPosY ) >> ( uiLog2BlkSize - 3 );
+  }
+}
+#endif
+
+#if E253 && PCP_SIGMAP_SIMPLE_LAST // only valid if both tools are enabled
+/** Get the best level in RD sense
+ * \param rd64UncodedCost reference to uncoded cost
+ * \param rd64CodedCost reference to current coded cost
+ * \param rd64CodedLastCost reference to coded cost of coefficient without the significance cost
+ * \param uiBestNonZeroLevel !!! not available yet
+ * \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 ui16CtxBase current global offset for coeff_abs_level_greater1 and coeff_abs_level_greater2
+ * \returns best quantized transform level for given scan position
+ * This method calculates the best quantized transform level for a given scan position.
+ */
+#else
+/** Get the best level in RD sense
+ * \param rd64UncodedCost reference to uncoded cost
+ * \param rd64CodedCost reference to current coded cost
+ * \param lLevelDouble reference to unscaled quantized level
+ * \param uiMaxAbsLevel scaled quantized level
+ * \param bLastScanPos last scan position
+ * \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_minus2 (remaining bins of coeff_abs_level_minus1 in AVC)
+ * \param iQBits quantization step size
+ * \param dTemp correction factor
+ * \param ui16CtxBase current global offset for coeff_abs_level_greater1 and coeff_abs_level_minus2
+ * \returns best quantized transform level for given scan position
+ * This method calculates the best quantized transform level for a given scan position.
+ */
+#endif
+__inline UInt TComTrQuant::xGetCodedLevel  ( Double&                         rd64UncodedCost,
+                                             Double&                         rd64CodedCost,
+#if PCP_SIGMAP_SIMPLE_LAST
+                                             Double&                         rd64CodedLastCost,
+                                             UInt&                           ruiBestNonZeroLevel,
+                                             Long                            lLevelDouble,
+                                             UInt                            uiMaxAbsLevel,
+#else
+                                             Long                            lLevelDouble,
+                                             UInt                            uiMaxAbsLevel,
+                                             bool                            bLastScanPos,
+#endif
+                                             UShort                          ui16CtxNumSig,
+                                             UShort                          ui16CtxNumOne,
+                                             UShort                          ui16CtxNumAbs,
+#if E253
+                                             UShort                          ui16AbsGoRice,
+#endif
+                                             Int                             iQBits,
+                                             Double                          dTemp,
+                                             UShort                          ui16CtxBase   ) const
+{
+  UInt   uiBestAbsLevel = 0;
+  Double dErr1          = Double( lLevelDouble );
+  
+  rd64UncodedCost = dErr1 * dErr1 * dTemp;
+#if PCP_SIGMAP_SIMPLE_LAST
+  rd64CodedCost   = rd64UncodedCost + xGetRateSigCoef( 0, ui16CtxNumSig );
+
+  ruiBestNonZeroLevel   = 0;
+  if( uiMaxAbsLevel )
+  {
+    UInt uiAbsLevel     = uiMaxAbsLevel;
+    ruiBestNonZeroLevel = uiMaxAbsLevel;
+    Double dErr         = Double( lLevelDouble - Long( uiAbsLevel << iQBits ) );
+#if E253
+    rd64CodedLastCost   = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, ui16CtxBase );
+#else
+    rd64CodedLastCost   = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16CtxBase );
+#endif
+  }
+  else
+  {
+    return uiBestAbsLevel;
+  }
+
+  UInt uiAbsLevel = ( uiMaxAbsLevel > 1 ? uiMaxAbsLevel - 1 : 1 );
+  if( uiAbsLevel != uiMaxAbsLevel )
+  {
+    Double dErr        = Double( lLevelDouble - Long( uiAbsLevel << iQBits ) );
+#if E253
+    Double dCurrCost   = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, ui16CtxBase );
+#else
+    Double dCurrCost   = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16CtxBase );
+#endif
+    if( dCurrCost < rd64CodedLastCost )
+    {
+      ruiBestNonZeroLevel = uiAbsLevel;
+      rd64CodedLastCost   = dCurrCost;
+    }  
+  }
+
+  Double dCurrCost = rd64CodedLastCost + xGetRateSigCoef( 1, ui16CtxNumSig );
+
+  if( dCurrCost < rd64CodedCost )
+  {
+    uiBestAbsLevel  = ruiBestNonZeroLevel;
+    rd64CodedCost   = dCurrCost;
+  }
+#else
+#if E253
+  rd64CodedCost   = rd64UncodedCost + xGetICRateCost( 0, bLastScanPos, ui16CtxNumSig, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, ui16CtxBase );
+#else
+  rd64CodedCost   = rd64UncodedCost + xGetICRateCost( 0, bLastScanPos, ui16CtxNumSig, ui16CtxNumOne, ui16CtxNumAbs, ui16CtxBase );
+#endif
+
+  UInt uiMinAbsLevel = ( uiMaxAbsLevel > 1 ? uiMaxAbsLevel - 1 : 1 );
+  for( UInt uiAbsLevel = uiMaxAbsLevel; uiAbsLevel >= uiMinAbsLevel ; uiAbsLevel-- )
+  {
+    Double i64Delta  = Double( lLevelDouble  - Long( uiAbsLevel << iQBits ) );
+    Double dErr      = Double( i64Delta );
+#if E253
+    Double dCurrCost = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, bLastScanPos, ui16CtxNumSig, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, ui16CtxBase );
+#else
+    Double dCurrCost = dErr * dErr * dTemp + xGetICRateCost( uiAbsLevel, bLastScanPos, ui16CtxNumSig, ui16CtxNumOne, ui16CtxNumAbs, ui16CtxBase );
+#endif
+
+    if( dCurrCost < rd64CodedCost )
+    {
+      uiBestAbsLevel  = uiAbsLevel;
+      rd64CodedCost   = dCurrCost;
+    }
+  }
+#endif
+  return uiBestAbsLevel;
+}
+
+#if E253 && PCP_SIGMAP_SIMPLE_LAST // only valid if both tools are enabled
+/** Calculates the cost for specific absolute transform level
+ * \param uiAbsLevel scaled quantized level
+ * \param bLastScanPos last scan position
+ * \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 Rice parameter for coeff_abs_level_minus3
+ * \param ui16CtxBase current global offset for coeff_abs_level_greater1 and coeff_abs_level_greater2
+ * \returns cost of given absolute transform level
+ */
+#endif
+__inline Double TComTrQuant::xGetICRateCost  ( UInt                            uiAbsLevel,
+#if !PCP_SIGMAP_SIMPLE_LAST
+                                               Bool                            bLastScanPos,
+                                               UShort                          ui16CtxNumSig,
+#endif
+                                               UShort                          ui16CtxNumOne,
+                                               UShort                          ui16CtxNumAbs,
+#if E253
+                                               UShort                          ui16AbsGoRice,
+#endif
+                                               UShort                          ui16CtxBase   ) const
+{
+#if PCP_SIGMAP_SIMPLE_LAST
+  Double iRate = xGetIEPRate();
+#else
+  if( uiAbsLevel == 0 )
+  {
+    Double iRate = 0;
+    if( !bLastScanPos )
+    {
+      iRate += m_pcEstBitsSbac->significantBits[ ui16CtxNumSig ][ 0 ];
+    }
+    return xGetICost( iRate );
+  }
+  Double iRate = xGetIEPRate();
+  if( !bLastScanPos )
+  {
+    iRate += m_pcEstBitsSbac->significantBits[ ui16CtxNumSig ][ 1 ];
+  }
+#endif
+  if( uiAbsLevel == 1 )
+  {
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 0 ][ ui16CtxNumOne ][ 0 ];
+  }
+#if E253
+  else if( uiAbsLevel == 2 )
+  {
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 0 ][ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 1 ][ ui16CtxNumAbs ][ 0 ];
+  }
+  else
+  {
+    UInt uiSymbol     = uiAbsLevel - 3;
+    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;
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 0 ][ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 1 ][ ui16CtxNumAbs ][ 1 ];
+  }
+#else
+  else if( uiAbsLevel < 15 )
+  {
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 0 ][ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 1 ][ ui16CtxNumAbs ][ 0 ];
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 1 ][ ui16CtxNumAbs ][ 1 ] * (int)( uiAbsLevel - 2 );
+  }
+  else
+  {
+    uiAbsLevel -= 14;
+    int iEGS    = 1;  for( UInt uiMax = 2; uiAbsLevel >= uiMax; uiMax <<= 1, iEGS += 2 );
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 0 ][ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->greaterOneBits[ ui16CtxBase ][ 1 ][ ui16CtxNumAbs ][ 1 ] * 13;
+    iRate += xGetIEPRate() * iEGS;
+  }
+#endif
+  return xGetICost( iRate );
+}
+
+#if PCP_SIGMAP_SIMPLE_LAST
+/** 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
+ */
+__inline Double TComTrQuant::xGetRateLast   ( UInt                            uiPosX,
+                                              UInt                            uiPosY ) const
+{
+  return xGetICost( m_pcEstBitsSbac->lastXBits[ uiPosX ] + m_pcEstBitsSbac->lastYBits[ uiPosY ] );
+}
+
+ /** 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 ] );
+}
+#endif
+
+/** 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;
+}
Index: /tags/0.2r1/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComTrQuant.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComTrQuant.h	(revision 19)
@@ -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-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     TComTrQuant.h
+    \brief    transform and quantization class (header)
+*/
+
+#ifndef __TCOMTRQUANT__
+#define __TCOMTRQUANT__
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComDataCU.h"
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define QP_BITS                 15
+
+// AQO Parameter
+#define QOFFSET_BITS            15
+#define QOFFSET_BITS_LTR        9
+
+// LTR Butterfly Paramter
+#define ECore16Shift            10
+#define DCore16Shift            10
+#define ECore32Shift            10
+#define DCore32Shift            10
+
+#define DenShift16              6
+#define DenShift32              8
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+typedef struct
+{
+  Int significantBits[16][2];
+#if PCP_SIGMAP_SIMPLE_LAST
+  Int lastXBits[32];
+  Int lastYBits[32];
+#else  
+  Int lastBits[16][2];
+#endif
+  Int greaterOneBits[6][2][5][2];
+  Int blockCbpBits[45][2];
+  Int blockRootCbpBits[4][2];
+  Int scanZigzag[2];            ///< flag for zigzag scan
+  Int scanNonZigzag[2];         ///< flag for non zigzag scan
+} estBitsSbacStruct;
+
+#if QC_MOD_LCEC_RDOQ
+typedef struct
+{
+  Int level[4];
+  Int pre_level;
+  Int coeff_ctr;
+  Long levelDouble;
+  Double errLevel[4];
+  Int noLevels;
+  Long levelQ;
+  Bool lowerInt;
+  UInt quantInd;
+} levelDataStruct;
+
+typedef struct
+{
+  Int run;
+  Int maxrun;
+  Int nextLev;
+  Int nexLevelVal;
+} quantLevelStruct;
+#endif
+
+
+
+class TEncCavlc;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// QP class
+class QpParam
+{
+public:
+  QpParam();
+  
+  Int m_iQP;
+  Int m_iPer;
+  Int m_iRem;
+  
+  Int m_iAdd2x2;
+  Int m_iAdd4x4;
+  Int m_iAdd8x8;
+  Int m_iAdd16x16;
+  Int m_iAdd32x32;
+private:
+  Int m_aiAdd2x2[MAX_QP+1][3];
+  Int m_aiAdd4x4[MAX_QP+1][3];
+  Int m_aiAdd8x8[MAX_QP+1][3];
+  Int m_aiAdd16x16[MAX_QP+1][3];
+  Int m_aiAdd32x32[MAX_QP+1][3];
+public:
+  Int m_iBits;
+  
+  Void initOffsetParam(Int iStartQP = MIN_QP, Int iEndQP = MAX_QP );
+  Void setQOffset( Int iQP, SliceType eSliceType )
+  {
+    m_iAdd2x2 = m_aiAdd2x2[iQP][eSliceType];
+    m_iAdd4x4 = m_aiAdd4x4[iQP][eSliceType];
+    m_iAdd8x8 = m_aiAdd8x8[iQP][eSliceType];
+    m_iAdd16x16 = m_aiAdd16x16[iQP][eSliceType];
+    m_iAdd32x32 = m_aiAdd32x32[iQP][eSliceType];
+  }
+  
+  Void setQpParam( Int iQP, Bool bLowpass, SliceType eSliceType, Bool bEnc )
+  {
+    assert ( iQP >= MIN_QP && iQP <= MAX_QP );
+    m_iQP   = iQP;
+    
+    m_iPer  = (iQP + 6*g_uiBitIncrement)/6;
+#if FULL_NBIT
+    m_iPer += g_uiBitDepth - 8;
+#endif
+    m_iRem  = (iQP + 6*g_uiBitIncrement)%6;
+    
+    m_iBits = QP_BITS + m_iPer;
+    
+    if ( bEnc )
+    {
+      setQOffset(iQP, eSliceType);
+    }
+  }
+  
+  Void clear()
+  {
+    m_iQP   = 0;
+    m_iPer  = 0;
+    m_iRem  = 0;
+    m_iBits = 0;
+  }
+  
+  
+  const Int per()   const { return m_iPer; }
+  const Int rem()   const { return m_iRem; }
+  const 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
+#if QC_MOD_LCEC
+  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 );
+#else
+  Void init                 ( UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxTrSize, Int iSymbolMode = 0, UInt *aTable4 = NULL, UInt *aTable8 = NULL, Bool bUseRDOQ = false,  Bool bEnc = false );
+#endif
+  
+  // transform & inverse transform functions
+  Void transformNxN         ( TComDataCU* pcCU, Pel*   pcResidual, UInt uiStride, TCoeff*& rpcCoeff, UInt uiWidth, UInt uiHeight,
+                             UInt& uiAbsSum, TextType eTType, UInt uiAbsPartIdx );
+#if INTRA_DST_TYPE_7
+  Void invtransformNxN      (TextType eText, UInt uiMode,Pel*& rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight);
+#else
+  Void invtransformNxN      ( Pel*& rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight );
+#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 iQP, Bool bLowpass, SliceType eSliceType, TextType eTxtType);
+  Void setLambda(Double dLambda) { m_dLambda = dLambda;}
+#if QC_MOD_LCEC_RDOQ
+  Void    setRDOQOffset ( UInt uiRDOQOffset ) { m_uiRDOQOffset = uiRDOQOffset; }
+#endif
+  estBitsSbacStruct* m_pcEstBitsSbac;
+  
+  static UInt     getSigCtxInc     ( TCoeff*                         pcCoeff,
+                                     const UInt                      uiPosX,
+                                     const UInt                      uiPosY,
+                                     const UInt                      uiLog2BlkSize,
+                                     const UInt                      uiStride );
+#if !PCP_SIGMAP_SIMPLE_LAST
+  static UInt     getLastCtxInc    ( const UInt                      uiPosX,
+                                     const UInt                      uiPosY,
+                                     const UInt                      uiLog2BlkSize );
+#endif
+protected:
+  Long*    m_plTempCoeff;
+  UInt*    m_puiQuantMtx;
+  
+  QpParam  m_cQP;
+  Double   m_dLambda;
+#if QC_MOD_LCEC_RDOQ
+  UInt     m_uiRDOQOffset;
+#endif
+  UInt     m_uiMaxTrSize;
+  Bool     m_bEnc;
+  Bool     m_bUseRDOQ;
+  
+  UInt     *m_uiLPTableE8;
+  UInt     *m_uiLPTableE4;
+  Int      m_iSymbolMode;
+#if QC_MOD_LCEC
+  UInt     *m_uiLastPosVlcIndex;
+#endif
+  
+private:
+  // forward Transform
+#if INTRA_DST_TYPE_7
+  Void xT   ( UInt uiMode,Pel* pResidual, UInt uiStride, Long* plCoeff, Int iSize );
+#else
+  Void xT   ( Pel* pResidual, UInt uiStride, Long* plCoeff, Int iSize );
+#endif
+  Void xT2  ( Pel* pResidual, UInt uiStride, Long* plCoeff );
+  Void xT4  ( Pel* pResidual, UInt uiStride, Long* plCoeff );
+  Void xT8  ( Pel* pResidual, UInt uiStride, Long* plCoeff );
+  Void xT16 ( Pel* pResidual, UInt uiStride, Long* plCoeff );
+  Void xT32 ( Pel* pResidual, UInt uiStride, Long* plCoeff );
+  
+  // quantization
+  Void xQuant     ( TComDataCU* pcCU, Long* pSrc, TCoeff*& pDes, Int iWidth, Int iHeight, UInt& uiAcSum, TextType eTType, UInt uiAbsPartIdx );
+  Void xQuantLTR  ( TComDataCU* pcCU, Long* pSrc, TCoeff*& pDes, Int iWidth, Int iHeight, UInt& uiAcSum, TextType eTType, UInt uiAbsPartIdx );
+  Void xQuant2x2  ( Long* plSrcCoef, TCoeff*& pDstCoef, UInt& uiAbsSum );
+  Void xQuant4x4  ( TComDataCU* pcCU, Long* plSrcCoef, TCoeff*& pDstCoef, UInt& uiAbsSum, TextType eTType, UInt uiAbsPartIdx );
+  Void xQuant8x8  ( TComDataCU* pcCU, Long* plSrcCoef, TCoeff*& pDstCoef, UInt& uiAbsSum, TextType eTType, UInt uiAbsPartIdx );
+
+
+  // RDOQ functions
+
+#if QC_MOD_LCEC_RDOQ
+  Int            xCodeCoeffCountBitsLast(TCoeff* scoeff, levelDataStruct* levelData, Int nTab, UInt uiNoCoeff);
+  UInt           xCountVlcBits(UInt uiTableNumber, UInt uiCodeNumber);
+#if CAVLC_COEF_LRG_BLK
+  Int            bitCountRDOQ(Int coeff, Int pos, Int nTab, Int lastCoeffFlag,Int levelMode,Int run, Int maxrun, Int vlc_adaptive, Int N, 
+                              UInt uiTr1, Int iSum_big_coef, Int iBlockType, TComDataCU* pcCU, const UInt **pLumaRunTr1);
+#else
+  Int            bitCountRDOQ(Int coeff, Int pos, Int nTab, Int lastCoeffFlag,Int levelMode,Int run, Int maxrun, Int vlc_adaptive, Int N, 
+                              UInt uiTr1, Int iSum_big_coef, Int iBlockType, TComDataCU* pcCU);
+#endif
+#else
+#if QC_MOD_LCEC 
+  Int            bitCount_LCEC(Int k,Int pos,Int nTab, Int lpflag,Int levelMode,Int run, Int maxrun, Int vlc_adaptive, Int N, UInt uiTr1);
+#else
+  Int            bitCount_LCEC(Int k,Int pos,Int n,Int lpflag,Int levelMode,Int run,Int maxrun,Int vlc_adaptive,Int N);
+#endif
+#endif
+#if QC_MDCS
+UInt             getCurrLineNum(UInt uiScanIdx, UInt uiPosX, UInt uiPosY);
+#endif
+  Void           xRateDistOptQuant_LCEC ( TComDataCU*                     pcCU,
+                                          Long*                           plSrcCoeff,
+                                          TCoeff*&                        piDstCoeff,
+                                          UInt                            uiWidth,
+                                          UInt                            uiHeight,
+                                          UInt&                           uiAbsSum,
+                                          TextType                        eTType,
+                                          UInt                            uiAbsPartIdx );
+  
+  Void           xRateDistOptQuant ( TComDataCU*                     pcCU,
+                                     Long*                           plSrcCoeff,
+                                     TCoeff*&                        piDstCoeff,
+                                     UInt                            uiWidth,
+                                     UInt                            uiHeight,
+                                     UInt&                           uiAbsSum,
+                                     TextType                        eTType,
+                                     UInt                            uiAbsPartIdx );
+  __inline UInt  xGetCodedLevel    ( Double&                         rd64UncodedCost,
+                                     Double&                         rd64CodedCost,
+#if PCP_SIGMAP_SIMPLE_LAST
+                                     Double&                         rd64CodedLastCost,
+                                     UInt&                           ruiBestNonZeroLevel,
+                                     Long                            lLevelDouble,
+                                     UInt                            uiMaxAbsLevel,
+#else
+                                     Long                            lLevelDouble,
+                                     UInt                            uiMaxAbsLevel,
+                                     bool                            bLastScanPos,
+#endif
+                                     UShort                          ui16CtxNumSig,
+                                     UShort                          ui16CtxNumOne,
+                                     UShort                          ui16CtxNumAbs,
+#if E253
+                                     UShort                          ui16AbsGoRice,
+#endif
+                                     Int                             iQBits,
+                                     Double                          dTemp,
+                                     UShort                          ui16CtxBase   ) const;
+  __inline Double xGetICRateCost   ( UInt                            uiAbsLevel,
+#if !PCP_SIGMAP_SIMPLE_LAST
+                                     Bool                            bLastScanPos,
+                                     UShort                          ui16CtxNumSig,
+#endif
+                                     UShort                          ui16CtxNumOne,
+                                     UShort                          ui16CtxNumAbs,
+#if E253
+                                     UShort                          ui16AbsGoRice,
+#endif
+                                     UShort                          ui16CtxBase   ) const;
+#if PCP_SIGMAP_SIMPLE_LAST
+  __inline Double xGetRateLast     ( UInt                            uiPosX,
+                                     UInt                            uiPosY        ) const;
+  __inline Double xGetRateSigCoef (  UShort                          uiSignificance,
+                                     UShort                          ui16CtxNumSig ) const;
+#endif
+  __inline Double xGetICost        ( Double                          dRate         ) const; 
+  __inline Double xGetIEPRate      (                                               ) const;
+  
+  
+  __inline Int          xRound   ( Int i )   { return ((i)+(1<<5))>>6; }
+  __inline static Long  xTrRound ( Long i, UInt uiShift ) { return ((i)>>uiShift); }
+  
+  // dequantization
+  Void xDeQuant         ( TCoeff* pSrc,     Long*& pDes,       Int iWidth, Int iHeight );
+  Void xDeQuantLTR      ( TCoeff* pSrc,     Long*&  pDes,      Int iWidth, Int iHeight );
+  Void xDeQuant2x2      ( TCoeff* pSrcCoef, Long*& rplDstCoef );
+  Void xDeQuant4x4      ( TCoeff* pSrcCoef, Long*& rplDstCoef );
+  Void xDeQuant8x8      ( TCoeff* pSrcCoef, Long*& rplDstCoef );
+  
+  // inverse transform
+#if INTRA_DST_TYPE_7
+  Void xIT    ( UInt uiMode, Long* plCoef, Pel* pResidual, UInt uiStride, Int iSize );
+#else
+  Void xIT    ( Long* plCoef, Pel* pResidual, UInt uiStride, Int iSize );
+#endif
+  Void xIT2   ( Long* plCoef, Pel* pResidual, UInt uiStride );
+  Void xIT4   ( Long* plCoef, Pel* pResidual, UInt uiStride );
+  Void xIT8   ( Long* plCoef, Pel* pResidual, UInt uiStride );
+  Void xIT16  ( Long* plCoef, Pel* pResidual, UInt uiStride );
+  Void xIT32  ( Long* plCoef, Pel* pResidual, UInt uiStride );
+
+
+};// END CLASS DEFINITION TComTrQuant
+
+
+#endif // __TCOMTRQUANT__
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComWedgelet.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 19)
@@ -0,0 +1,755 @@
+/* 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>
+
+
+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 )
+{
+  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 ),
+                                                            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) );
+}
+
+Void TComWedgelet::setWedgelet( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UChar uhOri, WedgeResolution eWedgeRes )
+{
+  m_uhXs      = uhXs;
+  m_uhYs      = uhYs;
+  m_uhXe      = uhXe;
+  m_uhYe      = uhYe;
+  m_uhOri     = uhOri;
+  m_eWedgeRes = eWedgeRes;
+
+  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::checkNotIdentical( Bool* pbRefPattern )
+{
+  for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ )
+  {
+    if( m_pbPattern[k] != pbRefPattern[k] )
+    {
+      return true;
+    }
+  }
+  return false;
+}
+
+Bool TComWedgelet::checkNotInvIdentical( Bool* pbRefPattern )
+{
+  for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ )
+  {
+    if( m_pbPattern[k] == pbRefPattern[k] )
+    {
+      return true;
+    }
+  }
+  return false;
+}
+
+#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;
+  UInt uiContDOri;
+
+  // 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; }
+  }
+
+  // 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 )
+    {
+      uiContDOri = 0;
+      ruhXe = 0;
+      ruhYe = (UChar)Min( Max( ((uiContDStartEndMax-1) + iXe), 0 ), (uiContDStartEndMax-1) );
+
+      return;
+    }
+    else if( iXe > (uiContDStartEndMax-1) )
+    {
+      uiContDOri = 1;
+      ruhXe = (UChar)(uiContDStartEndMax-1);
+      ruhYe = (UChar)Min( Max( ((uiContDStartEndMax-1) - (iXe - (uiContDStartEndMax-1))), 0 ), (uiContDStartEndMax-1) );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      uiContDOri = 4;
+      ruhXe = (UChar)iXe;
+      ruhYe = (UChar)(uiContDStartEndMax-1);
+
+      return;
+    }
+  }
+
+  // special for straight horizontal short bottom line
+  if( iA_DeltaY == 0 )
+  {
+    switch( (UInt)getOri() )
+    {
+    case( 2 ):
+      {
+        uiContDOri = 0;
+        ruhXs = (UChar)(iAlignedRefEndX-1);
+        ruhYs = 0;
+        ruhXe = 0;
+        ruhYe = (UChar)Min( Max( iDeltaEnd, 0 ), (uiContDStartEndMax-1) );
+
+        return;
+      }
+    case( 3 ):
+      {
+        uiContDOri = 1;
+        ruhXs = (UChar)(iAlignedRefEndX+1);
+        ruhYs = 0;
+        ruhXe = (UChar)(uiContDStartEndMax-1);
+        ruhYe = (UChar)Min( Max( -iDeltaEnd, 0 ), (uiContDStartEndMax-1) );
+
+        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)(uiContDStartEndMax-1) * ((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 )
+    {
+      uiContDOri = 0;
+      ruhXe = 0;
+      ruhYe = (UChar)Max( iYe, 0 );
+
+      return;
+    }
+    else
+    {
+      uiContDOri = 4;
+      ruhXe = (UChar)Min( (iYe - (uiContDStartEndMax-1)), (uiContDStartEndMax-1) );
+      ruhYe = (UChar)(uiContDStartEndMax-1);
+
+      return;
+    }
+  }
+  else if( iVirtualEndX > (uiContDStartEndMax-1) )
+  {
+    Int iYe = roftoi( (Double)((Int)(uiContDStartEndMax-1) - (Int)ruhXs) * ((Double)iA_DeltaY / (Double)iA_DeltaX) ) - iDeltaEnd;
+    if( iYe < (Int)uiContDStartEndMax )
+    {
+      uiContDOri = 1;
+      ruhXe = (UChar)(uiContDStartEndMax-1);
+      ruhYe = (UChar)Max( iYe, 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      uiContDOri = 4;
+      ruhXe = (UChar)Max( ((uiContDStartEndMax-1) - (iYe - (uiContDStartEndMax-1))), 0 );
+      ruhYe = (UChar)(uiContDStartEndMax-1);
+
+      return;
+    }
+  }
+  else
+  {
+    Int iXe = iVirtualEndX + iDeltaEnd;
+    if( iXe < 0 )
+    {
+      uiContDOri = 0;
+      ruhXe = 0;
+      ruhYe = (UChar)Max( ((uiContDStartEndMax-1) + iXe), 0 );
+
+      return;
+    }
+    else if( iXe > (uiContDStartEndMax-1) )
+    {
+      uiContDOri = 1;
+      ruhXe = (UChar)(uiContDStartEndMax-1);
+      ruhYe = (UChar)Max( ((uiContDStartEndMax-1) - (iXe - (uiContDStartEndMax-1))), 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      uiContDOri = 4;
+      ruhXe = (UChar)iXe;
+      ruhYe = (UChar)(uiContDStartEndMax-1);
+
+      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;
+  UInt uiContDOri;
+
+  // 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; }
+  }
+
+  // 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 )
+    {
+      uiContDOri = 0;
+      ruhXe = (UChar)Min( Max( ((uiContDStartEndMax-1) + iYe), 0 ), (uiContDStartEndMax-1) );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else if( iYe > (uiContDStartEndMax-1) )
+    {
+      uiContDOri = 3;
+      ruhXe = (UChar)Min( Max( ((uiContDStartEndMax-1) - (iYe - (uiContDStartEndMax-1))), 0 ), (uiContDStartEndMax-1) );
+      ruhYe = (UChar)(uiContDStartEndMax-1);
+
+      return;
+    }
+    else
+    {
+      uiContDOri = 5;
+      ruhXe = (UChar)(uiContDStartEndMax-1);
+      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 ):
+      {
+        uiContDOri = 3;
+        ruhXs = 0;
+        ruhYs = (UChar)(iAlignedRefEndY+1);
+        ruhXe = (UChar)Min( Max( iDeltaEnd, 0 ), (uiContDStartEndMax-1) );
+        ruhYe = (UChar)(uiContDStartEndMax-1);
+
+        return;
+      }
+    case( 2 ):
+      {
+        uiContDOri = 0;
+        ruhXs = 0;
+        ruhYs = (UChar)(iAlignedRefEndY-1);
+        ruhXe = (UChar)Min( Max( -iDeltaEnd, 0 ), (uiContDStartEndMax-1) );
+        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)(uiContDStartEndMax-1) * ((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 )
+    {
+      uiContDOri = 0;
+      ruhXe = (UChar)Max( iXe, 0 );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      uiContDOri = 5;
+      ruhXe = (UChar)(uiContDStartEndMax-1);
+      ruhYe = (UChar)Min( (iXe - (uiContDStartEndMax-1)), (uiContDStartEndMax-1) );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+  else if( iVirtualEndY > (uiContDStartEndMax-1) )
+  {
+    Int iXe = roftoi( (Double)((Int)(uiContDStartEndMax-1) - (Int)ruhYs ) * ((Double)iL_DeltaX / (Double)iL_DeltaY) ) + iDeltaEnd;
+    if( iXe < (Int)uiContDStartEndMax )
+    {
+      uiContDOri = 3;
+      ruhXe = (UChar)Max( iXe, 0 );
+      ruhYe = (UChar)(uiContDStartEndMax-1);
+
+      return;
+    }
+    else
+    {
+      uiContDOri = 5;
+      ruhXe = (UChar)(uiContDStartEndMax-1);
+      ruhYe = (UChar)Max( ((uiContDStartEndMax-1) - (iXe - (uiContDStartEndMax-1))), 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+  else
+  {
+    Int iYe = iVirtualEndY - iDeltaEnd;
+    if( iYe < 0 )
+    {
+      uiContDOri = 0;
+      ruhXe = (UChar)Max( ((uiContDStartEndMax-1) + iYe), 0 );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else if( iYe > (uiContDStartEndMax-1) )
+    {
+      uiContDOri = 3;
+      ruhXe = (UChar)Max( ((uiContDStartEndMax-1) - (iYe - (uiContDStartEndMax-1))), 0 );
+      ruhYe = (UChar)(uiContDStartEndMax-1);
+
+      return;
+    }
+    else
+    {
+      uiContDOri = 5;
+      ruhXe = (UChar)(uiContDStartEndMax-1);
+      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;
+  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;
+  }
+
+  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;
+      case( 4 ): { uiOffX = 0; uiOffY = 0; } break;
+      case( 5 ): { uiOffX = 0; uiOffY = 0; } break;
+      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;
+    }
+  }
+}
Index: /tags/0.2r1/source/Lib/TLibCommon/TComWedgelet.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComWedgelet.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComWedgelet.h	(revision 19)
@@ -0,0 +1,152 @@
+/* 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
+};
+
+enum WedgeDist
+{
+  WedgeDist_SAD  = 0,
+  WedgeDist_SSE  = 4,
+};
+
+// ====================================================================================================================
+// 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
+
+  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; }
+
+  Void  setWedgelet( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UChar uhOri, WedgeResolution eWedgeRes );
+
+  Bool  checkNotPlain();
+  Bool  checkNotIdentical( Bool* pbRefPattern );
+  Bool  checkNotInvIdentical( Bool* pbRefPattern );
+
+  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 );
+};  // 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;
+
+// ====================================================================================================================
+// 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: /tags/0.2r1/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 19)
@@ -0,0 +1,396 @@
+/* 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     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+// Include files
+#include "TComSlice.h"
+#include "TComWeightPrediction.h"
+
+#ifdef WEIGHT_PRED
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+TComWeightPrediction::TComWeightPrediction()
+{
+}
+
+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 o0      = wp0[0].o;
+  Int offset  = wp0[0].offset;
+  Int shiftNum = 14 - (g_uiBitDepth + g_uiBitIncrement);
+  Int shift   = wp0[0].shift + shiftNum;
+  Int round   = (1<<(shift-1)) * bRound;
+  Int w1      = wp1[0].w;
+  Int o1      = wp1[0].o;
+
+  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;
+  o0      = wp0[1].o;
+  offset  = wp0[1].offset;
+  shift   = wp0[1].shift + shiftNum;
+  round   = (1<<(shift-1));
+  w1      = wp1[1].w;
+  o1      = wp1[1].o;
+
+  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;
+  o0      = wp0[2].o;
+  offset  = wp0[2].offset;
+  shift   = wp0[2].shift + shiftNum;
+  round   = (1<<(shift-1));
+  w1      = wp1[2].w;
+  o1      = wp1[2].o;
+
+  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;
+  }
+}
+
+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 shift   = wp0[0].shift;
+  Int round   = wp0[0].round;
+
+  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;
+  round   = wp0[1].round;
+
+  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;
+  round   = wp0[2].round;
+
+  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()
+//  When called before SAD computation, ibdi is (g_uiBitDepth+g_uiBitIncrement), 
+//  when called before motion compensation (weighted prediction computation), ibdi is 14 (#if HIGH_ACCURACY_BI in bi-dir only). 
+//=======================================================
+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 + 1 ) >> 1 );
+      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);
+      }
+    }
+  }
+}
+
+Void TComWeightPrediction::xWeightedPredictionUni( TComDataCU* pcCU, TComYuv* pcYuvSrc, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iPartIdx )
+{ 
+  wpScalingParam  *pwp, *pwpTmp;
+  Int             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 );
+}
+
+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();
+
+  if ( !pps->getUseWP() ) {
+    printf("TComWeightPrediction::xWeightedPredictionBi():\tassert failed: useWP is false.\n");
+    exit(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);
+
+}
+
+#endif  // WEIGHT_PRED
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 19)
@@ -0,0 +1,67 @@
+
+
+/** \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"
+
+#ifdef WEIGHT_PRED
+
+// ====================================================================================================================
+// 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 );
+  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 + w1*P1 + round) >> shift ) + offset );
+}
+inline  Pel TComWeightPrediction::weightUnidir( Int w0, Pel P0, Int round, Int shift, Int offset) 
+{
+  return xClip( ( (w0*P0 + round) >> shift ) + offset );
+}
+
+#endif  // WEIGHT_PRED
+
+#endif
+
+
Index: /tags/0.2r1/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComYuv.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComYuv.cpp	(revision 19)
@@ -0,0 +1,949 @@
+/* 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     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"
+
+TComYuv::TComYuv()
+{
+  m_apiBufY = NULL;
+  m_apiBufU = NULL;
+  m_apiBufV = NULL;
+}
+
+TComYuv::~TComYuv()
+{
+}
+
+Void TComYuv::printout()
+{
+  Int  x, y;
+  
+  Pel* pSrc = getLumaAddr(  );
+  Int  iStride = getStride();
+  
+  
+  printf("\nY ...");
+  for ( y = 0; y < iStride; y++ )
+  {
+    printf ("\n");
+    for ( x = 0; x < iStride; x++ )
+    {
+      printf ("%d ", pSrc[x]);
+    }
+    pSrc += iStride;
+  }
+}
+
+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;
+  }
+}
+
+Void TComYuv::copyPartToPartYuv   ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  copyPartToPartLuma   (pcYuvDst, uiPartIdx, iWidth, iHeight );
+  copyPartToPartChroma (pcYuvDst, uiPartIdx, iWidth>>1, iHeight>>1 );
+}
+
+Void TComYuv::copyPartToPartLuma  ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  Pel* pSrc =           getLumaAddr(uiPartIdx);
+  Pel* pDst = pcYuvDst->getLumaAddr(uiPartIdx);
+  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] = xClip( 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] = xClip( 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] = xClip( pSrcU0[x] + pSrcU1[x] );
+      pDstV[x] = xClip( 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;
+  }
+}
+
+#ifdef ROUNDING_CONTROL_BIPRED
+
+Void TComYuv::addAvg( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, 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   = getLumaAddr( iPartUnitIdx );
+  Pel* pDstU   = getCbAddr  ( iPartUnitIdx );
+  Pel* pDstV   = getCrAddr  ( iPartUnitIdx );
+  
+  UInt  iSrc0Stride = pcYuvSrc0->getStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getStride();
+  UInt  iDstStride  = getStride();
+
+#if HIGH_ACCURACY_BI
+  Int shiftNum = 15 - (g_uiBitDepth + g_uiBitIncrement);
+  Int offset = (1<<(shiftNum - 1));
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: luma min width is 4
+      pDstY[x] = Clip((pSrcY0[x] + pSrcY1[x] + offset) >> shiftNum ); x--;
+      pDstY[x] = Clip((pSrcY0[x] + pSrcY1[x] + offset) >> shiftNum); x--;
+      pDstY[x] = Clip((pSrcY0[x] + pSrcY1[x] + offset) >> shiftNum); x--;
+      pDstY[x] = Clip((pSrcY0[x] + pSrcY1[x] + offset) >> shiftNum); x--;
+    }
+    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;
+  }
+
+#else
+
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: luma min width is 4
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + bRound) >> 1; x--;
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + bRound) >> 1; x--;
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + bRound) >> 1; x--;
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + bRound) >> 1; x--;
+    }
+    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] = (pSrcU0[x] + pSrcU1[x] + bRound) >> 1;
+      pDstV[x] = (pSrcV0[x] + pSrcV1[x] + bRound) >> 1; x--;
+      pDstU[x] = (pSrcU0[x] + pSrcU1[x] + bRound) >> 1;
+      pDstV[x] = (pSrcV0[x] + pSrcV1[x] + bRound) >> 1; x--;
+    }
+    
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+#endif
+}
+
+#endif
+
+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();
+#if HIGH_ACCURACY_BI
+  Int shiftNum = 15 - (g_uiBitDepth + g_uiBitIncrement);
+  Int offset = (1<<(shiftNum - 1));
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: luma min width is 4
+      pDstY[x] = Clip((pSrcY0[x] + pSrcY1[x] + offset) >> shiftNum ); x--;
+      pDstY[x] = Clip((pSrcY0[x] + pSrcY1[x] + offset) >> shiftNum); x--;
+      pDstY[x] = Clip((pSrcY0[x] + pSrcY1[x] + offset) >> shiftNum); x--;
+      pDstY[x] = Clip((pSrcY0[x] + pSrcY1[x] + offset) >> shiftNum); x--;
+    }
+    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;
+  }
+
+#else  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: luma min width is 4
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + 1) >> 1; x--;
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + 1) >> 1; x--;
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + 1) >> 1; x--;
+      pDstY[x] = (pSrcY0[x] + pSrcY1[x] + 1) >> 1; x--;
+    }
+    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] = (pSrcU0[x] + pSrcU1[x] + 1) >> 1;
+      pDstV[x] = (pSrcV0[x] + pSrcV1[x] + 1) >> 1; x--;
+      pDstU[x] = (pSrcU0[x] + pSrcU1[x] + 1) >> 1;
+      pDstV[x] = (pSrcV0[x] + pSrcV1[x] + 1) >> 1; x--;
+    }
+    
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+#endif
+}
+
+Void TComYuv::removeHighFreq( TComYuv* pcYuvSrc, UInt uiWidht, UInt uiHeight )
+{
+  Int x, y;
+  
+  Pel* pSrc  = pcYuvSrc->getLumaAddr();
+  Pel* pSrcU = pcYuvSrc->getCbAddr();
+  Pel* pSrcV = pcYuvSrc->getCrAddr();
+  
+  Pel* pDst  = m_apiBufY;
+  Pel* pDstU = m_apiBufU;
+  Pel* pDstV = m_apiBufV;
+  
+  Int  iSrcStride = pcYuvSrc->getStride();
+  Int  iDstStride = getStride();
+  
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidht-1; x >= 0; x-- )
+    {
+      pDst[x ] = xClip( (pDst[x ]<<1) - pSrc[x ] );
+    }
+    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-- )
+    {
+      pDstU[x ] = xClip( (pDstU[x ]<<1) - pSrcU[x ] );
+      pDstV[x ] = xClip( (pDstV[x ]<<1) - pSrcV[x ] );
+    }
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::removeHighFreq( TComYuv* pcYuvSrc, UInt uiPartIdx, UInt uiWidht, UInt uiHeight )
+{
+  Int x, y;
+  
+  Pel* pSrc  = pcYuvSrc->getLumaAddr(uiPartIdx);
+  Pel* pSrcU = pcYuvSrc->getCbAddr(uiPartIdx);
+  Pel* pSrcV = pcYuvSrc->getCrAddr(uiPartIdx);
+  
+  Pel* pDst  = getLumaAddr(uiPartIdx);
+  Pel* pDstU = getCbAddr(uiPartIdx);
+  Pel* pDstV = getCrAddr(uiPartIdx);
+  
+  Int  iSrcStride = pcYuvSrc->getStride();
+  Int  iDstStride = getStride();
+  
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidht-1; x >= 0; x-- )
+    {
+      pDst[x ] = xClip( (pDst[x ]<<1) - pSrc[x ] );
+    }
+    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-- )
+    {
+      pDstU[x ] = xClip( (pDstU[x ]<<1) - pSrcU[x ] );
+      pDstV[x ] = xClip( (pDstV[x ]<<1) - pSrcV[x ] );
+    }
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+
+Pel* TComYuv::getLumaAddr( UInt uiPartUnitIdx )
+{
+  UInt iBlkX;
+  UInt iBlkY;
+  iBlkX = g_auiRasterToPelX[g_auiZscanToRaster[uiPartUnitIdx]];
+  iBlkY = g_auiRasterToPelY[g_auiZscanToRaster[uiPartUnitIdx]];
+  
+  return m_apiBufY + iBlkY*getStride() + iBlkX;
+}
+
+Pel* TComYuv::getCbAddr( UInt uiPartUnitIdx )
+{
+  UInt iBlkX;
+  UInt iBlkY;
+  iBlkX = g_auiRasterToPelX[g_auiZscanToRaster[uiPartUnitIdx]] >> 1;
+  iBlkY = g_auiRasterToPelY[g_auiZscanToRaster[uiPartUnitIdx]] >> 1;
+  
+  return m_apiBufU + iBlkY*getCStride() + iBlkX;
+}
+
+Pel* TComYuv::getCrAddr( UInt uiPartUnitIdx )
+{
+  UInt iBlkX;
+  UInt iBlkY;
+  iBlkX = g_auiRasterToPelX[g_auiZscanToRaster[uiPartUnitIdx]] >> 1;
+  iBlkY = g_auiRasterToPelY[g_auiZscanToRaster[uiPartUnitIdx]] >> 1;
+  
+  return m_apiBufV + iBlkY*getCStride() + iBlkX;
+}
+
+Pel* TComYuv::getLumaAddr( UInt iTransUnitIdx, UInt iBlkSize )
+{
+  UInt uiNumTrInWidth = m_iWidth / iBlkSize;
+  UInt   iBlkX   = iTransUnitIdx % uiNumTrInWidth;
+  UInt   iBlkY   = iTransUnitIdx / uiNumTrInWidth;
+  
+  return m_apiBufY + (iBlkX + iBlkY * getStride()) * iBlkSize;
+}
+
+Pel* TComYuv::getCbAddr( UInt iTransUnitIdx, UInt iBlkSize )
+{
+  UInt uiNumTrInWidth = m_iCWidth / iBlkSize;
+  UInt   iBlkX   = iTransUnitIdx % uiNumTrInWidth;
+  UInt   iBlkY   = iTransUnitIdx / uiNumTrInWidth;
+  
+  return m_apiBufU + (iBlkX + iBlkY * getCStride()) * iBlkSize;
+}
+
+Pel* TComYuv::getCrAddr( UInt iTransUnitIdx, UInt iBlkSize )
+{
+  UInt uiNumTrInWidth = m_iCWidth / iBlkSize;
+  UInt   iBlkX   = iTransUnitIdx % uiNumTrInWidth;
+  UInt   iBlkY   = iTransUnitIdx / uiNumTrInWidth;
+  
+  return m_apiBufV + (iBlkX + iBlkY * getCStride()) * iBlkSize;
+}
Index: /tags/0.2r1/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TComYuv.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TComYuv.h	(revision 19)
@@ -0,0 +1,189 @@
+/* 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     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"
+
+// ====================================================================================================================
+// 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;
+  
+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 );
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  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
+
+  
+  //  pcYuvSrc0 - pcYuvSrc1 -> m_apiBuf
+  Void    subtract          ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    subtractLuma      ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    subtractChroma    ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  
+  //  (pcYuvSrc0 + pcYuvSrc1)/2 for YUV partition
+#ifdef ROUNDING_CONTROL_BIPRED
+  Void    addAvg            ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, Bool bRound );
+#endif
+  Void    addAvg            ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight );
+
+  //   Remove High frequency
+  Void    removeHighFreq    ( TComYuv* pcYuvSrc, UInt uiWidht, UInt uiHeight );
+  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 );
+  Pel*    getCbAddr         ( UInt iPartUnitIdx );
+  Pel*    getCrAddr         ( UInt iPartUnitIdx );
+  
+  //  Access starting position of YUV transform unit buffer
+  Pel*    getLumaAddr       ( UInt iTransUnitIdx, UInt iBlkSize );
+  Pel*    getCbAddr         ( UInt iTransUnitIdx, UInt iBlkSize );
+  Pel*    getCrAddr         ( UInt iTransUnitIdx, UInt iBlkSize );
+  
+  //  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;  }
+  
+  Void    printout();
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  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: /tags/0.2r1/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibCommon/TypeDef.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibCommon/TypeDef.h	(revision 19)
@@ -0,0 +1,699 @@
+/* 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     TypeDef.h
+    \brief    Define basic types, new types and enumerations
+*/
+
+#ifndef _TYPEDEF__
+#define _TYPEDEF__
+
+
+//>>>>> HHI 3DV tools >>>>>
+#define HHI_INTER_VIEW_MOTION_PRED      1   // inter-view motion parameter prediction
+#define HHI_INTER_VIEW_RESIDUAL_PRED    1   // inter-view residual prediction
+#define HHI_FULL_PEL_DEPTH_MAP_MV_ACC   1   // full-pel mv accuracy for depth maps
+#define HHI_MPI                         1   // motion parameter inheritance from texture picture for depth map coding
+#define HHI_INTERVIEW_SKIP              1   // skipping of residual for renderable regions
+#define HHI_INTERVIEW_SKIP_LAMBDA_SCALE 1   // scaling of lambda in cost calculation in rederable regions
+#define HHI_VSO                         1   // view synthesis optimization
+#define HHI_VSO_COLOR_PLANES            1   // view synthesis optimization in color planes
+#define HHI_VSO_DIST_INT                1   // view synthesis optimization integer distorition in rdo process
+
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE && !HHI_INTERVIEW_SKIP
+  #error "HHI_INTERVIEW_SKIP_LAMBDA_SCALE cannot be enabled if HHI_INTERVIEW_SKIP is not"
+#endif
+
+#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 model dependent on texture (inter-component Wedgelet and Contour prediction )
+
+#define HHI_NO_LowDelayCoding           0   // old-fashioned encoder control, should be adapted to hm5.0
+//<<<<< HHI 3DV tools <<<<<
+
+
+////////////////////////////
+// AHG18 Weighted Prediction defines section start
+////////////////////////////
+#define WEIGHT_PRED           ///< enable AVC based weighted prediction
+
+//////////////////////////
+// AHG18 Weighted Prediction defines section end
+//////////////////////////
+
+////////////////////////////
+// JCT-VC E start
+////////////////////////////
+
+#define E253                              1
+
+////////////////////////////
+// JCT-VC E end
+////////////////////////////
+
+
+
+#define HHI_DISABLE_INTER_NxN_SPLIT       1           ///< TN: disable redundant use of pu-mode NxN for CTBs larger 8x8 (inter only)
+#define HHI_RMP_SWITCH                    0
+
+#define HHI_RQT_FORCE_SPLIT_NxN           0           ///< MSHK: force split flags of residual quadtree for NxN PUs such that transform blocks are guaranteed to not span NxN PUs
+#define HHI_RQT_FORCE_SPLIT_RECT          0           ///< MSHK: force split flags of residual quadtree for rectangular PUs such that transform blocks are guaranteed to not span rectangular PUs
+#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
+
+#define PART_MRG                          1            // If the number of partitions is two and size > 8, only merging mode is enabled for the first partition & do not code merge_flag for the first partition
+#define HHI_MRG_SKIP                      1            // (JCTVC-E481 - merge skip) replaces the AMVP based skip by merge based skip (E481 - MERGE skip)
+
+#if HHI_RQT_INTRA_SPEEDUP_MOD && !HHI_RQT_INTRA_SPEEDUP
+#error
+#endif
+
+#if ( HHI_RQT_FORCE_SPLIT_NxN || HHI_RQT_FORCE_SPLIT_RECT)
+#define HHI_RQT_FORCE_SPLIT_ACC2_PU       1
+#else
+#define HHI_RQT_FORCE_SPLIT_ACC2_PU       0
+#endif
+
+// COLOCATED PREDICTOR
+// FOR MERGE
+#define MRG_NEIGH_COL                     1           ///< use of colocated MB in MERGE
+#define FT_TCTR_MRG                       1           ///< central colocated in MERGE
+#if !FT_TCTR_MRG
+#define PANASONIC_MERGETEMPORALEXT        1           ///<
+#endif
+#define MTK_TMVP_H_MRG                    1           ///< (JCTVC-E481 - D125 2.1) right-bottom collocated for merge
+#define PANASONIC_MRG_TMVP_REFIDX         1           ///< (JCTVC-E481 - D274 (2) ) refidx derivation for merge TMVP
+// FOR AMVP
+#define AMVP_NEIGH_COL                    1           ///< use of colocated MB in AMVP
+#define FT_TCTR_AMVP                      1           ///< central colocated in AMVP
+#if !FT_TCTR_AMVP
+#define PANASONIC_AMVPTEMPORALEXT         1           ///<
+#endif
+#define MTK_TMVP_H_AMVP                   1           ///< (JCTVC-E481 - D125 2.1) right-bottom collocated for amvp
+// FOR BOTH
+#define PANASONIC_AMVPTEMPORALMOD         1           ///< (JCTVC-E481 - D125 2.4' / D274 3')
+#define AMVP_BUFFERCOMPRESS               1           ///< motion vector buffer compression
+#define AMVP_DECIMATION_FACTOR            4
+#define MV_COMPRESS_MODE_REFIDX           1           ///< (JCTVC-E147) compress all inter prediction parameters according to 1)
+
+#define HIGH_ACCURACY_BI                  1          // High precision bi-prediction JCTVC-D321
+#define REMOVE_INTERMEDIATE_CLIPPING      1          // No intermediate clipping in bi-prediction JCTVC-E242
+
+////////////////
+// E494 (E227/E338/E344/E489/E494): PCP SIGMAP + REDUCED CONTEXTS
+////////////////
+
+#define PCP_SIGMAP_SIMPLE_LAST            1
+#define SIMPLE_CONTEXT_SIG                1
+
+
+#define QC_MOD_LCEC                       1           // JCTVC-D374: modified LCEC coeff. coding
+#define LCEC_INTRA_MODE                   1           // JCTVC-D366: improved luma intra mode coding
+#define QC_MOD_LCEC_RDOQ                  1           // JCTVC-D374: improved RDOQ
+#define QC_LCEC_INTER_MODE                1
+#define QC_MDIS                           1           // JCTVC-D282: enable mode dependent intra smoothing
+#define QC_MDCS                           1           // JCTVC-D393: mode dependent coefficients coding
+#if QC_MOD_LCEC
+#define RUNLEVEL_TABLE_CUT                1           // JCTVC-E384: Run-Level table size reduction
+#if RUNLEVEL_TABLE_CUT
+#define CAVLC_COEF_LRG_BLK                1           // JCTVC-E383: enable large block coeff. coding
+#endif
+#endif
+
+
+#define ENABLE_FORCECOEFF0  0
+
+/* Rounding control */
+//#define ROUNDING_CONTROL_BIPRED ///< From JCTVC-B074 This part of the code is not needed anymore : KU
+#define TRANS_PRECISION_EXT     ///< From JCTVC-B074
+
+#define HHI_RQT_DISABLE_SUB                   0           ///< disabling subtree whose node size is smaller than partition size
+
+#define FAST_UDI_MAX_RDMODE_NUM               35          ///< maximum number of RD comparison in fast-UDI estimation loop
+
+#define SAMSUNG_FAST_UDI_MODESET              0           ///< 0: {9,9,4,4,5} (default) and 1: {9,9,9,9,5} for {4x4,8x8,16x16,32x32,64x64}
+
+#define ZERO_MVD_EST                          0           ///< Zero Mvd Estimation in normal mode
+
+#define LM_CHROMA                             1           // JCTVC-E266: Chroma intra prediction based on luma signal
+
+#define UNIFY_INTER_TABLE                     1           // JCTVC-E381 CAVLC: Inter pred coding
+
+#define DCM_RDCOST_TEMP_FIX //Enables temporary bug fixes to RD cost computation
+
+#define DCM_DECODING_REFRESH              1           ///< enable/disable decoding refresh (IDR and CDR)
+#if DCM_DECODING_REFRESH
+#define DCM_SKIP_DECODING_FRAMES          1           ///< enable/disable the random access by the decoder
+#endif
+
+#define DCM_SIMPLIFIED_MVP                1           ///< enable/disable the simplified motion vector prediction(D231)
+#if DCM_SIMPLIFIED_MVP
+#define MTK_AMVP_SMVP_DERIVATION          1              ///< (JCTVC-E481 - D125 2.1) amvp spatial candidate derivation
+#define TI_AMVP_SMVP_SIMPLIFIED           1              ///< (JCTVC-E481 - F)amvp spatial candidate simplified scanning
+#endif
+
+#define DCM_COMB_LIST                  1           ///< Use of combined list for uni-prediction in B-slices
+
+#define ADD_PLANAR_MODE                   1           ///< enable/disable Planar mode for intra prediction (JCTVC-E321)
+#if ADD_PLANAR_MODE
+#define NUM_INTRA_MODE                    35
+#define PLANAR_IDX                        (NUM_INTRA_MODE-1)
+#endif
+
+#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            
+
+#if ADD_PLANAR_MODE
+#define  MAX_MODE_ID_INTRA_DIR            34
+#else
+#define  MAX_MODE_ID_INTRA_DIR            33
+#endif
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+enum MODE_IDX
+{
+  DMM_WEDGE_FULL_IDX         = MAX_MODE_ID_INTRA_DIR+1,
+  DMM_WEDGE_FULL_D_IDX       = MAX_MODE_ID_INTRA_DIR+2,
+  DMM_WEDGE_PREDTEX_IDX      = MAX_MODE_ID_INTRA_DIR+3,
+  DMM_WEDGE_PREDTEX_D_IDX    = MAX_MODE_ID_INTRA_DIR+4,
+  DMM_CONTOUR_PREDTEX_IDX    = MAX_MODE_ID_INTRA_DIR+5,
+  DMM_CONTOUR_PREDTEX_D_IDX  = MAX_MODE_ID_INTRA_DIR+6,
+  DMM_WEDGE_PREDDIR_IDX      = MAX_MODE_ID_INTRA_DIR+7,
+  DMM_WEDGE_PREDDIR_D_IDX    = MAX_MODE_ID_INTRA_DIR+8
+};
+#elif HHI_DMM_WEDGE_INTRA && !HHI_DMM_PRED_TEX
+enum MODE_IDX
+{
+  DMM_WEDGE_FULL_IDX         = MAX_MODE_ID_INTRA_DIR+1,
+  DMM_WEDGE_FULL_D_IDX       = MAX_MODE_ID_INTRA_DIR+2,
+  DMM_WEDGE_PREDDIR_IDX      = MAX_MODE_ID_INTRA_DIR+3,
+  DMM_WEDGE_PREDDIR_D_IDX    = MAX_MODE_ID_INTRA_DIR+4
+};
+#elif !HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+enum MODE_IDX
+{
+  DMM_WEDGE_PREDTEX_IDX      = MAX_MODE_ID_INTRA_DIR+1,
+  DMM_WEDGE_PREDTEX_D_IDX    = MAX_MODE_ID_INTRA_DIR+2,
+  DMM_CONTOUR_PREDTEX_IDX    = MAX_MODE_ID_INTRA_DIR+3,
+  DMM_CONTOUR_PREDTEX_D_IDX  = MAX_MODE_ID_INTRA_DIR+4,
+};
+#endif
+#endif
+
+#define TSB_ALF_HEADER                 1           // Send ALF ON/OFF flag in slice header
+#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 MS_LCEC_ONE_FRAME               1           // change the initial table in LCEC when there is up to one reference frame in each list, JCTVC-D141
+#define MS_LCEC_LOOKUP_TABLE_MAX_VALUE  1           // use the information of the max position in the lookup table, JCTVC-D141
+#define MS_LCEC_LOOKUP_TABLE_EXCEPTION  1           // deal with the case when the number of reference frames is greater than 2, JCTVC-D141
+#define MS_LCEC_UNI_EXCEPTION_THRES     1           // for GPB case, uni-prediction, > MS_LCEC_UNI_EXCEPTION_THRES is exception
+#define CAVLC_COUNTER_ADAPT             1          // counter based CAVLC adaptation, JCTVC-E143
+#if CAVLC_COUNTER_ADAPT
+#define CAVLC_RQT_CBP                   1           //CAVLC coding of cbf and split flag, JCTVC-E404
+#endif
+
+
+#define AVOID_ZERO_MERGE_CANDIDATE      1           // (JCTVC-E146/E118) insert zero MV if no merge candidates are available
+#define CHANGE_MERGE_CONTEXT            1           // (JCTVC-E146/E118) change merge flag context derivation
+#define CHANGE_GET_MERGE_CANDIDATE      1           // (JCTVC-E146/E118) merge flag parsing independent of number of merge candidates
+#if CHANGE_GET_MERGE_CANDIDATE && !CHANGE_MERGE_CONTEXT
+#error CHANGE_GET_MERGE_CANDIDATE can only be defined with CHANGE_MERGE_CONTEXT
+#endif
+
+#define MTK_DISABLE_INTRA_NxN_SPLIT       1           ///< Disable use of PUs-mode NxN for CUs larger 8x8 (intra only)
+#define MTK_NONCROSS_INLOOP_FILTER        1           ///< Allow non-cross-slice-boundary in-loop filtering, including DB & ALF (JCTVC-D128)
+
+#define RVM_VCEGAM10 1 // RVM model proposed in VCEG-AM10
+#if RVM_VCEGAM10
+#define RVM_VCEGAM10_M 4
+#endif
+
+#define MTK_DCM_MPM 1 // MostProbableModeSignaling
+
+#define FAST_UDI_USE_MPM 1
+#define SONY_SIG_CTX 1
+#define SNY_DQP                          1           ///< syntax change of dQP (JCT-VC D258)
+
+#define TI_ALF_MAX_VSIZE_7 1
+
+#define CHROMA_CODEWORD 1                             ///< enable new intra chroma mode encoding by setting to 1. setting to 0 should yield same results as TMuC 0.9
+#define CHROMA_CODEWORD_SWITCH  1                     ///< Switch the places of the last two codewords
+
+#define FULL_NBIT 0 ///< When enabled, does not use g_uiBitIncrement anymore to support > 8 bit data
+
+/////////////////////////////////
+// AHG SLICES defines section start
+/////////////////////////////////
+#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
+
+// 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
+/////////////////////////////////
+// AHG SLICES defines section end
+/////////////////////////////////
+
+#define CONSTRAINED_INTRA_PRED            1           // JCTVC-D086: constrained intra prediction
+
+#define MTK_SAO                           1           // JCTVC-E049: Sample adaptive offset
+
+#define MQT_ALF_NPASS                       1
+
+#define MQT_BA_RA                        1  // JCTVC-E323+E046
+#if MQT_BA_RA
+#define VAR_SIZE_H           4
+#define VAR_SIZE_W           4
+#define NO_VAR_BIN          16
+#endif
+
+#if QC_MDIS
+#define MN_MDIS_SIMPLIFICATION       1       ///< JCTVC-E069: simplification of MDIS
+#endif
+#define MN_DC_PRED_FILTER            1       ///< JCTVC-E069: DC prediction samples filtering
+
+#define MVD_CTX            1           // JCTVC-E324: Modified context selection for MVD
+#define PARALLEL_DEBLK_DECISION      1 // JCTC-E224: Parallel decisions
+#define PARALLEL_MERGED_DEBLK        1 // JCTC-E224, JCTVC-E181: Parallel decisions + Parallel filtering
+#define REFERENCE_SAMPLE_PADDING                1   // JCTVC-E488 padding of unavailable reference samples for intra prediction
+
+#define E243_CORE_TRANSFORMS                    1
+#if E243_CORE_TRANSFORMS
+#define MATRIX_MULT                             0   // Brute force matrix multiplication instead of partial butterfly
+#endif
+
+// Discrete Sine Transform (DST) Type - 7
+// Currently DST operates with E-243 only
+#define INTRA_DST_TYPE_7                      1           // JCTVC-E125 4x4 DST
+#if INTRA_DST_TYPE_7
+#define REG_DCT 65535
+#if !E243_CORE_TRANSFORMS                   // E243_CORE_TRANSFORMS should be ON when DST is used
+#error "E243_CORE_TRANSFORMS should be ON"
+#endif
+#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       long                Long;
+typedef       unsigned long       ULong;
+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;
+
+#if MTK_SAO
+
+#define NUM_DOWN_PART 4
+
+enum QAOTypeLen
+{
+  SAO_EO_LEN    = 4,
+  SAO_EO_LEN_2D = 6,
+  SAO_BO_LEN    = 16
+};
+
+enum QAOType
+{
+  SAO_EO_0 = 0,
+  SAO_EO_1,
+  SAO_EO_2,
+  SAO_EO_3,
+  SAO_BO_0,
+  SAO_BO_1,
+  MAX_NUM_SAO_TYPE
+};
+
+typedef struct _SaoQTPart
+{
+  Bool        bEnableFlag;
+  Int         iBestType;
+  Int         iLength;
+  Int         iOffset[32];
+
+  Int         StartCUX;
+  Int         StartCUY;
+  Int         EndCUX;
+  Int         EndCUY;
+
+  Int         part_xs;
+  Int         part_xe;
+  Int         part_ys;
+  Int         part_ye;
+  Int         part_width;
+  Int         part_height;
+
+  Int         PartIdx;
+  Int         PartLevel;
+  Int         PartCol;
+  Int         PartRow;
+
+  Int         DownPartsIdx[NUM_DOWN_PART];
+  Int         UpPartIdx;
+
+  Int*        pSubPartList;
+  Int         iLengthSubPartList;
+
+  Bool        bBottomLevel;
+  Bool        bSplit;
+  //    Bool        bAvailable;
+
+  //---- encoder only start -----//
+  Int64***    pppiCorr; //[filt_type][corr_row][corr_col]
+  Int**       ppCoeff;  //[filt_type][coeff]
+  Bool        bProcessed;
+  Double      dMinCost;
+  Int64       iMinDist;
+  Int         iMinRate;
+  //---- encoder only end -----//
+} SAOQTPart;
+
+struct _SaoParam
+{
+  Bool       bSaoFlag;
+  SAOQTPart* psSaoPart;
+  Int        iMaxSplitLevel;
+  Int        iNumClass[MAX_NUM_SAO_TYPE];
+};
+
+#endif
+
+struct _AlfParam
+{
+  Int alf_flag;                           ///< indicates use of ALF
+  Int cu_control_flag;                    ///< coding unit based control flag
+  Int chroma_idc;                         ///< indicates use of ALF for chroma
+#if TI_ALF_MAX_VSIZE_7
+  Int tap;                                ///< number of filter taps - horizontal
+  Int tapV;                               ///< number of filter taps - vertical
+#else
+  Int tap;                                ///< number of filter taps
+#endif
+  Int num_coeff;                          ///< number of filter coefficients
+  Int *coeff;                             ///< filter coefficient array
+  Int tap_chroma;                         ///< number of filter taps (chroma)
+  Int num_coeff_chroma;                   ///< number of filter coefficients (chroma)
+  Int *coeff_chroma;                      ///< filter coefficient array (chroma)
+  //CodeAux related
+  Int realfiltNo;
+  Int filtNo;
+#if MQT_BA_RA
+  Int filterPattern[NO_VAR_BIN];
+#else
+  Int filterPattern[16];
+#endif
+  Int startSecondFilter;
+  Int noFilters;
+#if MQT_BA_RA
+  Int varIndTab[NO_VAR_BIN];
+#else
+  Int varIndTab[16];
+#endif
+
+  //Coeff send related
+  Int filters_per_group_diff; //this can be updated using codedVarBins
+  Int filters_per_group;
+#if MQT_BA_RA
+  Int codedVarBins[NO_VAR_BIN];
+#else
+  Int codedVarBins[16];
+#endif
+  Int forceCoeff0;
+  Int predMethod;
+  Int **coeffmulti;
+  Int minKStart;
+  Int maxScanVal;
+  Int kMinTab[42];
+#if TSB_ALF_HEADER
+  UInt num_alf_cu_flag;
+  UInt num_cus_in_frame;
+  UInt alf_max_depth;
+  UInt *alf_cu_flag;
+#endif
+
+#if MQT_BA_RA
+  Int alf_pcr_region_flag;
+#endif
+};
+
+/// parameters for deblocking filter
+typedef struct _LFCUParam
+{
+  Bool bInternalEdge;                     ///< indicates internal edge
+  Bool bLeftEdge;                         ///< indicates left edge
+  Bool bTopEdge;                          ///< indicates top edge
+} LFCUParam;
+
+/// parapeters for TENTM coefficient VLC
+typedef struct _LastCoeffStruct
+{
+  int level;
+  int last_pos;
+} LastCoeffStruct;
+
+// ====================================================================================================================
+// Enumeration
+// ====================================================================================================================
+
+/// supported slice type
+enum SliceType
+{
+  I_SLICE,
+  P_SLICE,
+  B_SLICE
+};
+
+/// 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_NONE = 15
+};
+
+//GT
+enum InterViewReference
+{
+  PREVVIEW = 0,
+  CURRVIEW = 1,
+  NEXTVIEW = 2
+};
+
+/// 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
+};
+
+enum
+{
+  VIEWPOS_INVALID = -1,
+  VIEWPOS_LEFT    = 0,
+  VIEWPOS_RIGHT   = 1,
+  VIEWPOS_MERGED  = 2
+};
+
+/// reference list index
+enum RefPicList
+{
+  REF_PIC_LIST_0 = 0,   ///< reference list 0
+  REF_PIC_LIST_1 = 1,   ///< reference list 1
+#if DCM_COMB_LIST
+  REF_PIC_LIST_C = 2,   ///< combined reference list for uni-prediction in B-Slices
+#endif
+  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
+
+  DF_SSE_FRAME = 33     ///< Frame-based SSE
+};
+
+
+/// 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
+};
+
+/// interpolation filter type
+enum InterpFilterType
+{
+  IPF_SAMSUNG_DIF_DEFAULT = 0,          ///< Samsung DCT-based filter
+  IPF_HHI_4TAP_MOMS,                    ///< HHI 4-tap MOMS filter
+  IPF_HHI_6TAP_MOMS,                    ///< HHI 6-tap MOMS filter
+  IPF_LAST
+};
+
+#if QC_MDCS
+/// 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
+};
+#endif //QC_MDCS
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/SEIread.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/SEIread.cpp	(revision 19)
@@ -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-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 "../TLibCommon/TComBitStream.h"
+#include "../TLibCommon/SEI.h"
+#include "SEIread.h"
+
+static void parseSEIuserDataUnregistered(TComBitstream& bs, SEIuserDataUnregistered &sei, unsigned payloadSize);
+static void parseSEIpictureDigest(TComBitstream& bs, SEIpictureDigest& sei, unsigned payloadSize);
+
+/**
+ * unmarshal a single SEI message from bitstream @bs
+ */
+void parseSEImessage(TComBitstream& 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(TComBitstream& 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(TComBitstream& 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: /tags/0.2r1/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/SEIread.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/SEIread.h	(revision 19)
@@ -0,0 +1,41 @@
+/* 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.
+ */
+
+
+
+#pragma once
+
+class TComBitstream;
+class SEImessages;
+
+void parseSEImessage(TComBitstream& bs, SEImessages& seis);
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 19)
@@ -0,0 +1,64 @@
+/* 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     TDecBinCoder.h
+    \brief    binary entropy decoder interface
+*/
+
+#ifndef __TDEC_BIN_CODER__
+#define __TDEC_BIN_CODER__
+
+#include "../TLibCommon/ContextModel.h"
+#include "../TLibCommon/TComBitStream.h"
+
+
+class TDecBinIf
+{
+public:
+  virtual Void  init              ( TComBitstream* pcTComBitstream )          = 0;
+  virtual Void  uninit            ()                                          = 0;
+
+  virtual Void  start             ()                                          = 0;
+  virtual Void  finish            ()                                          = 0;
+
+  virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel )  = 0;
+  virtual Void  decodeBinEP       ( UInt& ruiBin                           )  = 0;
+  virtual Void  decodeBinTrm      ( UInt& ruiBin                           )  = 0;
+  
+  virtual ~TDecBinIf() {}
+};
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 19)
@@ -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     TDecBinCoderCABAC.cpp
+    \brief    binary entropy decoder of CABAC
+*/
+
+#include "TDecBinCoderCABAC.h"
+
+
+TDecBinCABAC::TDecBinCABAC()
+: m_pcTComBitstream( 0 )
+{
+}
+
+TDecBinCABAC::~TDecBinCABAC()
+{
+}
+
+Void
+TDecBinCABAC::init( TComBitstream* pcTComBitstream )
+{
+  m_pcTComBitstream = pcTComBitstream;
+}
+
+Void
+TDecBinCABAC::uninit()
+{
+  m_pcTComBitstream = 0;
+}
+
+Void
+TDecBinCABAC::start()
+{
+  m_pcTComBitstream->setModeSbac();
+  
+  m_uiRange    = 510;
+  m_uiValue    = 0;
+  for( UInt ui = 0; ui < 9; ui++ )
+  {
+    xReadBit( m_uiValue );
+  }
+}
+
+Void
+TDecBinCABAC::finish()
+{
+}
+
+Void
+TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel )
+{
+  UInt  uiLPS   = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) & 3 ];
+  m_uiRange    -= uiLPS;
+  if( m_uiValue < m_uiRange )
+  {
+    ruiBin      = rcCtxModel.getMps();
+    rcCtxModel.updateMPS();
+  }
+  else
+  {
+    m_uiValue  -= m_uiRange;
+    m_uiRange   = uiLPS;
+    ruiBin      = 1 - rcCtxModel.getMps();
+    rcCtxModel.updateLPS();
+  }
+  while( m_uiRange < 256 )
+  {
+    m_uiRange  += m_uiRange;
+    xReadBit( m_uiValue );
+  }
+}
+
+Void
+TDecBinCABAC::decodeBinEP( UInt& ruiBin )
+{
+  xReadBit( m_uiValue );
+  if( m_uiValue >= m_uiRange )
+  {
+    ruiBin      = 1;
+    m_uiValue  -= m_uiRange;
+  }
+  else
+  {
+    ruiBin      = 0;
+  }
+}
+
+Void
+TDecBinCABAC::decodeBinTrm( UInt& ruiBin )
+{
+  m_uiRange -= 2;
+  if( m_uiValue >= m_uiRange )
+  {
+    ruiBin = 1;
+  }
+  else
+  {
+    ruiBin = 0;
+    while( m_uiRange < 256 )
+    {
+      m_uiRange += m_uiRange;
+      xReadBit( m_uiValue );
+    }
+  }
+}
+
+Void  
+TDecBinCABAC::xReadBit( UInt& ruiVal )
+{
+  UInt uiBit = 0;
+  m_pcTComBitstream->read( 1, uiBit );
+  ruiVal  = ( ruiVal << 1 ) | uiBit;
+}
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 19)
@@ -0,0 +1,74 @@
+/* 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     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"
+
+
+class TDecBinCABAC : public TDecBinIf
+{
+public:
+  TDecBinCABAC ();
+  virtual ~TDecBinCABAC();
+
+  Void  init              ( TComBitstream* pcTComBitstream );
+  Void  uninit            ();
+
+  Void  start             ();
+  Void  finish            ();
+
+  Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel );
+  Void  decodeBinEP       ( UInt& ruiBin                           );
+  Void  decodeBinTrm      ( UInt& ruiBin                           );
+
+private:
+  Void  xReadBit          ( UInt& ruiVal );
+
+private:
+  TComBitstream*      m_pcTComBitstream;
+  UInt                m_uiRange;
+  UInt                m_uiValue;
+};
+
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 19)
@@ -0,0 +1,3859 @@
+/* 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     TDecCAVLC.cpp
+    \brief    CAVLC decoder class
+*/
+
+#include "TDecCAVLC.h"
+#include "SEIread.h"
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCavlc::TDecCavlc()
+{
+  m_bAlfCtrl = false;
+  m_uiMaxAlfCtrlDepth = 0;
+
+  m_aaiTempScale            = new Int* [ MAX_NUMBER_VIEWS ];
+  m_aaiTempOffset           = new Int* [ MAX_NUMBER_VIEWS ];
+  m_aaiTempPdmScaleNomDelta = new Int* [ MAX_NUMBER_VIEWS ];
+  m_aaiTempPdmOffset        = new Int* [ MAX_NUMBER_VIEWS ];
+  for( UInt uiVId = 0; uiVId < MAX_NUMBER_VIEWS; uiVId++ )
+  {
+    m_aaiTempScale            [ uiVId ] = new Int [ MAX_NUMBER_VIEWS ];
+    m_aaiTempOffset           [ uiVId ] = new Int [ MAX_NUMBER_VIEWS ];
+    m_aaiTempPdmScaleNomDelta [ uiVId ] = new Int [ MAX_NUMBER_VIEWS ];
+    m_aaiTempPdmOffset        [ uiVId ] = new Int [ MAX_NUMBER_VIEWS ];
+  }
+}
+
+TDecCavlc::~TDecCavlc()
+{
+  for( UInt uiVId = 0; uiVId < MAX_NUMBER_VIEWS; 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
+// ====================================================================================================================
+
+Void  TDecCavlc::parseNalUnitHeader ( NalUnitType& eNalUnitType, UInt& TemporalId, Bool& bOutputFlag )
+{
+  UInt  uiCode;
+
+  xReadCode ( 1, uiCode ); assert( 0 == uiCode); // forbidden_zero_bit
+  xReadCode ( 2, uiCode );                       // nal_ref_idc
+  xReadCode ( 5, uiCode );                       // nal_unit_type
+  eNalUnitType = (NalUnitType) uiCode;
+
+  if ( (eNalUnitType == NAL_UNIT_CODED_SLICE) || (eNalUnitType == NAL_UNIT_CODED_SLICE_IDR) || (eNalUnitType == NAL_UNIT_CODED_SLICE_CDR) )
+  {
+    xReadCode(3, uiCode); // temporal_id
+    TemporalId = uiCode;
+    xReadFlag(uiCode);    // output_flag
+    bOutputFlag = (0!=uiCode);
+    xReadCode(4, uiCode); // reserved_one_4bits
+  }
+  else
+  {
+    TemporalId = 0;
+    bOutputFlag = true;
+  }
+}
+
+/**
+ * unmarshal a sequence of SEI messages from bitstream.
+ */
+void TDecCavlc::parseSEI(SEImessages& seis)
+{
+  assert(!m_pcBitstream->getBitsUntilByteAligned());
+  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->getBitsUntilByteAligned());
+  } while (0x80 != m_pcBitstream->peekBits(8));
+  assert(m_pcBitstream->getBitsLeft() == 8); /* rsbp_trailing_bits */
+}
+
+Void TDecCavlc::parsePPS(TComPPS* pcPPS)
+{
+  UInt  uiCode;
+
+  xReadUvlc( uiCode ); pcPPS->setPPSId( uiCode );
+  xReadUvlc( uiCode ); pcPPS->setSPSId( uiCode );
+#if CONSTRAINED_INTRA_PRED
+  xReadFlag ( uiCode ); pcPPS->setConstrainedIntraPred( uiCode ? true : false );
+#endif
+
+#ifdef WEIGHT_PRED
+  xReadCode( 1, uiCode );           // Use of Weighting Prediction (P_SLICE)
+  pcPPS->setUseWP( uiCode==1 );
+  xReadCode( 2, uiCode );           // 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());
+#endif
+  return;
+}
+
+Void TDecCavlc::parseSPS(TComSPS* pcSPS)
+{
+  UInt  uiCode;
+  Int   iCode;
+
+  // Structure
+  xReadUvlc ( uiCode ); pcSPS->setSPSId       ( uiCode    );
+  xReadUvlc ( uiCode ); pcSPS->setWidth       ( uiCode    );
+  xReadUvlc ( uiCode ); pcSPS->setHeight      ( uiCode    );
+  xReadUvlc ( uiCode ); pcSPS->setPadX        ( uiCode    );
+  xReadUvlc ( uiCode ); pcSPS->setPadY        ( uiCode    );
+
+  xReadUvlc ( uiCode );
+  pcSPS->setMaxCUWidth  ( uiCode    ); g_uiMaxCUWidth  = uiCode;
+  pcSPS->setMaxCUHeight ( uiCode    ); g_uiMaxCUHeight = uiCode;
+
+  xReadUvlc ( uiCode );
+  pcSPS->setMaxCUDepth  ( uiCode+1  ); g_uiMaxCUDepth  = uiCode + 1;
+  UInt uiMaxCUDepthCorrect = uiCode;
+
+  xReadUvlc( uiCode ); pcSPS->setQuadtreeTULog2MinSize( uiCode + 2 );
+  xReadUvlc( uiCode ); pcSPS->setQuadtreeTULog2MaxSize( uiCode + pcSPS->getQuadtreeTULog2MinSize() );
+  pcSPS->setMaxTrSize( 1<<(uiCode + pcSPS->getQuadtreeTULog2MinSize()) );
+  xReadUvlc ( uiCode ); pcSPS->setQuadtreeTUMaxDepthInter( uiCode+1 );
+  xReadUvlc ( uiCode ); 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 );
+
+  xReadUvlc( uiCode ); pcSPS->setCodedPictureBufferSize( uiCode );
+
+  // Tool on/off
+  xReadFlag( uiCode ); pcSPS->setUseALF ( uiCode ? true : false );
+  xReadFlag( uiCode ); pcSPS->setUseDQP ( uiCode ? true : false );
+#if !HHI_NO_LowDelayCoding
+  xReadFlag( uiCode ); pcSPS->setUseLDC ( uiCode ? true : false );
+#endif
+  xReadFlag( uiCode ); pcSPS->setUseMRG ( uiCode ? true : false ); // SOPH:
+
+#if LM_CHROMA
+  xReadFlag( uiCode ); pcSPS->setUseLMChroma ( uiCode ? true : false );
+#endif
+
+#if HHI_RMP_SWITCH
+  xReadFlag( uiCode ); pcSPS->setUseRMP( uiCode ? true : false );
+#endif
+
+  // 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 );
+  }
+
+  // Bit-depth information
+#if FULL_NBIT
+  xReadUvlc( uiCode );
+  g_uiBitDepth = 8 + uiCode;
+  g_uiBitIncrement = 0;
+  pcSPS->setBitDepth(g_uiBitDepth);
+  pcSPS->setBitIncrement(g_uiBitIncrement);
+#else
+#if ENABLE_IBDI
+  xReadUvlc( uiCode ); pcSPS->setBitDepth     ( uiCode+8 ); g_uiBitDepth     = uiCode + 8;
+  xReadUvlc( uiCode ); pcSPS->setBitIncrement ( uiCode   ); g_uiBitIncrement = uiCode;
+#else
+  xReadUvlc( uiCode );
+  g_uiBitDepth = 8;
+  g_uiBitIncrement = uiCode;
+  pcSPS->setBitDepth(g_uiBitDepth);
+  pcSPS->setBitIncrement(g_uiBitIncrement);
+#endif
+#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 HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  g_dDeltaDCsQuantOffset = Double(g_uiBitIncrement) -  2.0;
+#endif
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  xReadFlag( uiCode );
+  pcSPS->setLFCrossSliceBoundaryFlag( uiCode ? true : false);
+#endif
+#if MTK_SAO
+  xReadFlag( uiCode ); pcSPS->setUseSAO       ( uiCode ? true : false );
+#endif
+
+  xReadFlag( uiCode ); // SPS base view flag
+  if( uiCode )
+  { // baseview SPS -> set standard values
+    pcSPS->initMultiviewSPS         ( 0 );
+#if DEPTH_MAP_GENERATION
+    pcSPS->setPredDepthMapGeneration( 0, false );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    pcSPS->setMultiviewResPredMode  ( 0 );
+#endif
+  }
+  else
+  {
+    xReadFlag  ( uiCode ); // depth flag
+    if( uiCode )
+    {
+      xReadUvlc( uiCode ); // view id
+      xReadSvlc(  iCode ); // view order index
+      pcSPS->initMultiviewSPSDepth    ( uiCode, iCode );
+#if DEPTH_MAP_GENERATION
+      pcSPS->setPredDepthMapGeneration( uiCode, true );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      pcSPS->setMultiviewResPredMode  ( 0 );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      xReadFlag( uiCode );
+      pcSPS->setUseDMM( uiCode ? true : false );
+#endif
+#if HHI_MPI
+      xReadFlag( uiCode );
+      pcSPS->setUseMVI( uiCode ? true : false );
+#endif
+    }
+    else
+    {
+      UInt  uiViewId, uiCamParPrecision;
+      Int   iVOI;
+      Bool  bCamParSlice;
+      xReadUvlc( uiViewId );  uiViewId++;
+      xReadSvlc( iVOI );
+      xReadUvlc( uiCamParPrecision );
+      xReadFlag( uiCode );    bCamParSlice = ( uiCode == 1 );
+      if( !bCamParSlice )
+      {
+        for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+        {
+          xReadSvlc( iCode );   m_aaiTempScale [ uiBaseId ][ uiViewId ] = iCode;
+          xReadSvlc( iCode );   m_aaiTempOffset[ uiBaseId ][ uiViewId ] = iCode;
+          xReadSvlc( iCode );   m_aaiTempScale [ uiViewId ][ uiBaseId ] = iCode - m_aaiTempScale [ uiBaseId ][ uiViewId ];
+          xReadSvlc( iCode );   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 HHI_INTER_VIEW_MOTION_PRED
+      UInt uiMultiviewMvPredMode = 0;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      UInt uiMultiviewResPredMode = 0;
+#endif
+      xReadUvlc( uiPredDepthMapGeneration );
+      if( uiPredDepthMapGeneration )
+      {
+        xReadUvlc  ( uiPdmPrecision );
+        for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+        {
+          xReadSvlc( iCode );   m_aaiTempPdmScaleNomDelta[ uiViewId ][ uiBaseId ] = iCode;
+          xReadSvlc( iCode );   m_aaiTempPdmOffset       [ uiViewId ][ uiBaseId ] = iCode;
+        }
+#if HHI_INTER_VIEW_MOTION_PRED
+        xReadUvlc  ( uiMultiviewMvPredMode );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        xReadFlag  ( uiMultiviewResPredMode );
+#endif
+      }
+#if HHI_INTER_VIEW_MOTION_PRED
+      pcSPS->setPredDepthMapGeneration( uiViewId, false, uiPredDepthMapGeneration, uiMultiviewMvPredMode, uiPdmPrecision, m_aaiTempPdmScaleNomDelta, m_aaiTempPdmOffset );
+#else
+      pcSPS->setPredDepthMapGeneration( uiViewId, false, uiPredDepthMapGeneration, 0, uiPdmPrecision, m_aaiTempPdmScaleNomDelta, m_aaiTempPdmOffset );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      pcSPS->setMultiviewResPredMode  ( uiMultiviewResPredMode );
+#endif
+#endif
+#if HHI_MPI
+      pcSPS->setUseMVI( false );
+#endif
+    }
+  }
+
+  return;
+}
+
+Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice)
+{
+  UInt  uiCode;
+  Int   iCode;
+
+  xReadFlag ( uiCode );
+  Bool bEntropySlice = uiCode ? true : false;
+  if (!bEntropySlice)
+  {
+    xReadUvlc ( uiCode ); rpcSlice->setPPSId( uiCode );
+    xReadCode (10, uiCode);  rpcSlice->setPOC              (uiCode);             // 9 == SPS->Log2MaxFrameNum()
+    xReadUvlc (   uiCode);  rpcSlice->setSliceType        ((SliceType)uiCode);
+    xReadSvlc (    iCode);  rpcSlice->setSliceQp          (iCode);
+  }
+  if (bEntropySlice)
+  {
+    rpcSlice->setNextSlice        ( false );
+    rpcSlice->setNextEntropySlice ( true  );
+
+    xReadUvlc(uiCode);
+    rpcSlice->setEntropySliceCurStartCUAddr( uiCode ); // start CU addr for entropy slice
+  }
+  else
+  {
+    rpcSlice->setNextSlice        ( true  );
+    rpcSlice->setNextEntropySlice ( false );
+
+    xReadUvlc(uiCode);
+    rpcSlice->setSliceCurStartCUAddr( uiCode );        // start CU addr for slice
+    rpcSlice->setEntropySliceCurStartCUAddr( uiCode ); // start CU addr for entropy slice
+
+    xReadFlag ( uiCode );
+    rpcSlice->setSymbolMode( uiCode );
+
+    if (!rpcSlice->isIntra())
+      xReadFlag (   uiCode);
+    else
+      uiCode = 1;
+
+    rpcSlice->setReferenced       (uiCode ? true : false);
+
+#if !HIGH_ACCURACY_BI
+#ifdef ROUNDING_CONTROL_BIPRED
+    if(!rpcSlice->isIntra())
+    {
+      xReadFlag( uiCode );
+      Bool b = (uiCode != 0);
+      rpcSlice->setRounding(b);
+    }
+#endif
+#else
+#if !HIGH_ACCURACY_BI
+    if(!rpcSlice->isIntra())
+    {
+      rpcSlice->setRounding(false);
+    }
+#endif
+#endif
+
+    xReadFlag (   uiCode);  rpcSlice->setLoopFilterDisable(uiCode ? 1 : 0);
+
+    if (!rpcSlice->isIntra())
+    {
+      xReadCode (3, uiCode);  rpcSlice->setNumRefIdx      (REF_PIC_LIST_0, uiCode);
+    }
+    else
+    {
+      rpcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
+    }
+    if (rpcSlice->isInterB())
+    {
+      xReadCode (3, uiCode);  rpcSlice->setNumRefIdx      (REF_PIC_LIST_1, uiCode);
+    }
+    else
+    {
+      rpcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+    }
+
+    if (!rpcSlice->isIntra())
+    {
+      for(Int i = 0; i<rpcSlice->getNumRefIdx(REF_PIC_LIST_0);i++)
+      {
+        xReadFlag( uiCode ) ;
+        if( uiCode ) // interview
+        {
+          xReadUvlc( uiCode ) ;
+          rpcSlice->setRefViewIdx(uiCode, REF_PIC_LIST_0, i) ;
+          rpcSlice->setRefPOC(rpcSlice->getPOC(), REF_PIC_LIST_0, i) ;
+        }
+        else
+        {
+          xReadSvlc( iCode ) ;
+          rpcSlice->setRefPOC(rpcSlice->getPOC()-iCode, REF_PIC_LIST_0, i) ;
+          rpcSlice->setRefViewIdx(rpcSlice->getViewIdx(), REF_PIC_LIST_0, i) ;
+        }
+      }
+    }
+    else
+    {
+      rpcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
+    }
+    if( rpcSlice->isInterB())
+    {
+      for(Int i = 0; i<rpcSlice->getNumRefIdx(REF_PIC_LIST_1);i++)
+      {
+        xReadFlag( uiCode ) ;
+        if( uiCode ) // interview
+        {
+          xReadUvlc( uiCode ) ;
+          rpcSlice->setRefViewIdx(uiCode, REF_PIC_LIST_1, i) ;
+          rpcSlice->setRefPOC(rpcSlice->getPOC(), REF_PIC_LIST_1, i) ;
+        }
+        else
+        {
+          xReadSvlc( iCode ) ;
+          rpcSlice->setRefPOC(rpcSlice->getPOC()-iCode, REF_PIC_LIST_1, i) ;
+          rpcSlice->setRefViewIdx(rpcSlice->getViewIdx(), REF_PIC_LIST_1, i) ;
+        }
+      }
+    }
+    else
+    {
+      rpcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+    }
+
+#if DCM_COMB_LIST
+    if (rpcSlice->isInterB())
+    {
+      xReadFlag (uiCode);      rpcSlice->setRefPicListCombinationFlag(uiCode ? 1 : 0);
+      if(uiCode)
+      {
+        xReadUvlc(uiCode);      rpcSlice->setNumRefIdx      (REF_PIC_LIST_C, uiCode+1);
+
+        xReadFlag (uiCode);     rpcSlice->setRefPicListModificationFlagLC(uiCode ? 1 : 0);
+        if(uiCode)
+        {
+          for (UInt i=0;i<rpcSlice->getNumRefIdx(REF_PIC_LIST_C);i++)
+          {
+            xReadFlag(uiCode);
+            rpcSlice->setListIdFromIdxOfLC(i, uiCode);
+            xReadUvlc(uiCode);
+            rpcSlice->setRefIdxFromIdxOfLC(i, uiCode);
+            rpcSlice->setRefIdxOfLC((RefPicList)rpcSlice->getListIdFromIdxOfLC(i), rpcSlice->getRefIdxFromIdxOfLC(i), i);
+          }
+        }
+      }
+      else
+      {
+        rpcSlice->setRefPicListCombinationFlag(false);
+        rpcSlice->setRefPicListModificationFlagLC(false);
+        rpcSlice->setNumRefIdx(REF_PIC_LIST_C, -1);
+      }
+    }
+#endif
+
+#if AMVP_NEIGH_COL
+    if ( rpcSlice->getSliceType() == B_SLICE )
+    {
+      xReadFlag (uiCode);
+      rpcSlice->setColDir(uiCode);
+    }
+#endif
+
+#ifdef WEIGHT_PRED
+    if ( (rpcSlice->getPPS()->getUseWP() && rpcSlice->getSliceType()==P_SLICE) || (rpcSlice->getPPS()->getWPBiPredIdc() && rpcSlice->getSliceType()==B_SLICE) )
+    {
+      parseWeightPredTable(rpcSlice);
+      rpcSlice->initWpScaling();
+      rpcSlice->displayWpScaling();
+    }
+#endif
+    if( rpcSlice->getPPS()->getPPSId() != rpcSlice->getPPSId() )
+    {
+      return;
+    }
+
+
+    if( rpcSlice->getSPS()->hasCamParInSliceHeader() )
+    {
+      UInt uiViewId = rpcSlice->getSPS()->getViewId();
+      for( UInt uiBaseId = 0; uiBaseId < uiViewId; uiBaseId++ )
+      {
+        xReadSvlc( iCode );   m_aaiTempScale [ uiBaseId ][ uiViewId ] = iCode;
+        xReadSvlc( iCode );   m_aaiTempOffset[ uiBaseId ][ uiViewId ] = iCode;
+        xReadSvlc( iCode );   m_aaiTempScale [ uiViewId ][ uiBaseId ] = iCode - m_aaiTempScale [ uiBaseId ][ uiViewId ];
+        xReadSvlc( iCode );   m_aaiTempOffset[ uiViewId ][ uiBaseId ] = iCode - m_aaiTempOffset[ uiBaseId ][ uiViewId ];
+      }
+      rpcSlice->initMultiviewSlice( m_aaiTempScale, m_aaiTempOffset );
+    }
+  }
+  return;
+}
+
+Void TDecCavlc::resetEntropy          (TComSlice* pcSlice)
+{
+  m_bRunLengthCoding = ! pcSlice->isIntra();
+  m_uiRun = 0;
+
+#if !CAVLC_COEF_LRG_BLK
+  ::memcpy(m_uiLPTableD8,        g_auiLPTableD8,        10*128*sizeof(UInt));
+#endif
+  ::memcpy(m_uiLPTableD4,        g_auiLPTableD4,        3*32*sizeof(UInt));
+  ::memcpy(m_uiLastPosVlcIndex,  g_auiLastPosVlcIndex,  10*sizeof(UInt));
+
+#if CAVLC_RQT_CBP
+  ::memcpy(m_uiCBP_YUV_TableD, g_auiCBP_YUV_TableD, 4*8*sizeof(UInt));
+  ::memcpy(m_uiCBP_YS_TableD,  g_auiCBP_YS_TableD,  2*4*sizeof(UInt));
+  ::memcpy(m_uiCBP_YCS_TableD, g_auiCBP_YCS_TableD, 2*8*sizeof(UInt));
+  ::memcpy(m_uiCBP_4Y_TableD,  g_auiCBP_4Y_TableD,  2*15*sizeof(UInt));
+  m_uiCBP_4Y_VlcIdx = 0;
+#else
+  m_uiCbpVlcIdx[0] = 0;
+  m_uiCbpVlcIdx[1] = 0;
+  ::memcpy(m_uiCBPTableD,        g_auiCBPTableD,        2*8*sizeof(UInt));
+  ::memcpy(m_uiBlkCBPTableD,     g_auiBlkCBPTableD,     2*15*sizeof(UInt));
+  m_uiBlkCbpVlcIdx = 0;
+#endif
+
+#if UNIFY_INTER_TABLE
+  ::memcpy(m_uiMI1TableD, g_auiComMI1TableD, 9*sizeof(UInt));
+#else
+  ::memcpy(m_uiMI1TableD,        g_auiMI1TableD,        8*sizeof(UInt));
+  ::memcpy(m_uiMI2TableD,        g_auiMI2TableD,        15*sizeof(UInt));
+
+#if DCM_COMB_LIST
+  if ( pcSlice->getNoBackPredFlag() || pcSlice->getNumRefIdx(REF_PIC_LIST_C)>0)
+#else
+  if ( pcSlice->getNoBackPredFlag() )
+#endif
+  {
+    ::memcpy(m_uiMI1TableD,        g_auiMI1TableDNoL1,        8*sizeof(UInt));
+    ::memcpy(m_uiMI2TableD,        g_auiMI2TableDNoL1,        15*sizeof(UInt));
+  }
+
+#if MS_LCEC_ONE_FRAME
+  if ( pcSlice->getNumRefIdx(REF_PIC_LIST_0) <= 1 && pcSlice->getNumRefIdx(REF_PIC_LIST_1) <= 1 )
+  {
+    if ( pcSlice->getNoBackPredFlag() || ( pcSlice->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcSlice->getNumRefIdx(REF_PIC_LIST_C) <= 1 ) )
+    {
+      ::memcpy(m_uiMI1TableD,        g_auiMI1TableDOnly1RefNoL1,        8*sizeof(UInt));
+    }
+    else
+    {
+      ::memcpy(m_uiMI1TableD,        g_auiMI1TableDOnly1Ref,        8*sizeof(UInt));
+    }
+  }
+#endif
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  if (pcSlice->getNumRefIdx(REF_PIC_LIST_C)>0)
+  {
+    m_uiMI1TableD[8] = 8;
+  }
+  else  // GPB case
+  {
+    m_uiMI1TableD[8] = m_uiMI1TableD[6];
+    m_uiMI1TableD[6] = 8;
+  }
+#endif
+#endif
+
+#if LCEC_INTRA_MODE
+#if MTK_DCM_MPM
+  ::memcpy(m_uiIntraModeTableD17[0], g_auiIntraModeTableD17[0], 16*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableD34[0], g_auiIntraModeTableD34[0], 33*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableD17[1], g_auiIntraModeTableD17[1], 16*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableD34[1], g_auiIntraModeTableD34[1], 33*sizeof(UInt));
+#else
+  ::memcpy(m_uiIntraModeTableD17, g_auiIntraModeTableD17, 16*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableD34, g_auiIntraModeTableD34, 33*sizeof(UInt));
+#endif
+#endif
+#if QC_LCEC_INTER_MODE
+  ::memcpy(m_uiSplitTableD, g_auiInterModeTableD, 4*7*sizeof(UInt));
+#endif
+  m_uiMITableVlcIdx = 0;
+
+#if CAVLC_COUNTER_ADAPT
+#if CAVLC_RQT_CBP
+  ::memset(m_ucCBP_YUV_TableCounter, 0, 4*4*sizeof(UChar));
+  ::memset(m_ucCBP_4Y_TableCounter,  0, 2*2*sizeof(UChar));
+  ::memset(m_ucCBP_YCS_TableCounter, 0, 2*4*sizeof(UChar));
+  ::memset(m_ucCBP_YS_TableCounter,  0, 2*3*sizeof(UChar));
+#else
+  ::memset(m_ucCBFTableCounter,        0,        2*4*sizeof(UChar));
+  ::memset(m_ucBlkCBPTableCounter,     0,        2*2*sizeof(UChar));
+#endif
+
+  ::memset(m_ucMI1TableCounter,        0,          4*sizeof(UChar));
+  ::memset(m_ucSplitTableCounter,      0,        4*4*sizeof(UChar));
+
+#if CAVLC_RQT_CBP
+  m_ucCBP_YUV_TableCounterSum[0] = m_ucCBP_YUV_TableCounterSum[1] = m_ucCBP_YUV_TableCounterSum[2] = m_ucCBP_YUV_TableCounterSum[3] = 0;
+  m_ucCBP_4Y_TableCounterSum[0] = m_ucCBP_4Y_TableCounterSum[1] = 0;
+  m_ucCBP_YCS_TableCounterSum[0] = m_ucCBP_YCS_TableCounterSum[1] = 0;
+  m_ucCBP_YS_TableCounterSum[0] = m_ucCBP_YS_TableCounterSum[1] = 0;
+#else
+  m_ucCBFTableCounterSum[0] = m_ucCBFTableCounterSum[1] = 0;
+  m_ucBlkCBPTableCounterSum[0] = m_ucBlkCBPTableCounterSum[1] = 0;
+#endif
+
+  m_ucSplitTableCounterSum[0] = m_ucSplitTableCounterSum[1] = m_ucSplitTableCounterSum[2]= m_ucSplitTableCounterSum[3] = 0;
+  m_ucMI1TableCounterSum = 0;
+#endif
+}
+
+Void TDecCavlc::parseTerminatingBit( UInt& ruiBit )
+{
+  ruiBit = false;
+  Int iBitsLeft = m_pcBitstream->getBitsLeft();
+  if(iBitsLeft <= 8)
+  {
+    UInt uiPeekValue = m_pcBitstream->peekBits(iBitsLeft);
+    if (uiPeekValue == (1<<(iBitsLeft-1)))
+      ruiBit = true;
+  }
+}
+
+Void TDecCavlc::parseAlfCtrlDepth              ( UInt& ruiAlfCtrlDepth )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, g_uiMaxCUDepth-1);
+  ruiAlfCtrlDepth = uiSymbol;
+}
+
+Void TDecCavlc::parseAlfCtrlFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if (!m_bAlfCtrl)
+    return;
+
+  if( uiDepth > m_uiMaxAlfCtrlDepth && !pcCU->isFirstAbsZorderIdxInDepth(uiAbsPartIdx, m_uiMaxAlfCtrlDepth))
+  {
+    return;
+  }
+
+  UInt uiSymbol;
+  xReadFlag( uiSymbol );
+
+  if (uiDepth > m_uiMaxAlfCtrlDepth)
+  {
+    pcCU->setAlfCtrlFlagSubParts( uiSymbol, uiAbsPartIdx, m_uiMaxAlfCtrlDepth);
+  }
+  else
+  {
+    pcCU->setAlfCtrlFlagSubParts( uiSymbol, uiAbsPartIdx, uiDepth );
+  }
+}
+
+Void TDecCavlc::parseSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+#if QC_LCEC_INTER_MODE
+  return;
+#else
+
+  if( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+
+  UInt uiSymbol = 0;
+  xReadFlag( uiSymbol );
+
+  if( uiSymbol )
+  {
+    pcCU->setPredModeSubParts( MODE_SKIP,  uiAbsPartIdx, uiDepth );
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+#if HHI_MRG_SKIP
+    pcCU->setMergeFlagSubParts( true , uiAbsPartIdx, 0, uiDepth );
+#else
+    TComMv cZeroMv(0,0);
+    pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+    pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+
+    pcCU->setTrIdxSubParts( 0, uiAbsPartIdx, uiDepth );
+    pcCU->setCbfSubParts  ( 0, 0, 0, uiAbsPartIdx, uiDepth );
+
+    if ( pcCU->getSlice()->isInterP() )
+    {
+      pcCU->setInterDirSubParts( 1, uiAbsPartIdx, 0, uiDepth );
+
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllRefIdx(  0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( NOT_VALID, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+    }
+    else
+    {
+      pcCU->setInterDirSubParts( 3, uiAbsPartIdx, 0, uiDepth );
+
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllRefIdx(  0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( 0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+    }
+  }
+#endif // HHI_MRG_SKIP
+#endif // QC_LCEC_INTER_MODE
+}
+
+/** parse the motion vector predictor index
+ * \param pcCU
+ * \param riMVPIdx
+ * \param iMVPNum
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param eRefList
+ * \returns Void
+ */
+Void TDecCavlc::parseMVPIdx( TComDataCU* pcCU, Int& riMVPIdx, Int iMVPNum, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, iMVPNum-1);
+  riMVPIdx = uiSymbol;
+}
+
+Void TDecCavlc::parseViewIdx(Int& riViewIdx)
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, MAX_NUMBER_VIEWS);
+  riViewIdx = uiSymbol;
+}
+
+#if QC_LCEC_INTER_MODE
+/** parse the split flag
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecCavlc::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if (pcCU->getSlice()->isIntra())
+  {
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+      return ;
+    }
+
+    UInt uiSymbol;
+    xReadFlag( uiSymbol );
+    pcCU->setDepthSubParts( uiDepth + uiSymbol, uiAbsPartIdx );
+
+    return ;
+  }
+  UInt tmp=0;
+  UInt cx=0;
+  UInt uiMode ;
+  {
+    UInt iMaxLen= (uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth)?5:6;
+    while (tmp==0 && cx<iMaxLen)
+    {
+      xReadFlag( tmp );
+      cx++;
+    };
+    if(tmp!=0)
+      cx--;
+
+    UInt uiDepthRemember = uiDepth;
+    if ( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      uiDepth = 3;
+    }
+    UInt x = m_uiSplitTableD[uiDepth][cx];
+    /* Adapt table */
+    uiMode = x;
+#if CAVLC_COUNTER_ADAPT
+    adaptCodeword(cx, m_ucSplitTableCounter[uiDepth],  m_ucSplitTableCounterSum[uiDepth],   m_uiSplitTableD[uiDepth],  NULL, 4 );
+#else
+    if (cx>0)
+    {
+      UInt cy = Max(0,cx-1);
+      UInt y = m_uiSplitTableD[uiDepth][cy];
+      m_uiSplitTableD[uiDepth][cy] = x;
+      m_uiSplitTableD[uiDepth][cx] = y;
+    }
+#endif
+    uiDepth = uiDepthRemember;
+  }
+  if (uiMode==0)
+  {
+    pcCU->setDepthSubParts( uiDepth + 1, uiAbsPartIdx );
+  }
+  else
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setMergeFlagSubParts(false, uiAbsPartIdx,0, uiDepth );
+    pcCU->setDepthSubParts( uiDepth    , uiAbsPartIdx );
+    if (uiMode ==1)
+    {
+      TComMv cZeroMv(0,0);
+      pcCU->setPredModeSubParts( MODE_SKIP,  uiAbsPartIdx, uiDepth );
+      pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+      pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+      pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      pcCU->setTrIdxSubParts( 0, uiAbsPartIdx, uiDepth );
+      pcCU->setCbfSubParts  ( 0, 0, 0, uiAbsPartIdx, uiDepth );
+
+#if HHI_MRG_SKIP
+      pcCU->setMergeFlagSubParts( true, uiAbsPartIdx, 0, uiDepth );
+#else
+      if ( pcCU->getSlice()->isInterP() )
+      {
+        pcCU->setInterDirSubParts( 1, uiAbsPartIdx, 0, uiDepth );
+
+        if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllRefIdx(  0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+        if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( NOT_VALID, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      }
+      else
+      {
+        pcCU->setInterDirSubParts( 3, uiAbsPartIdx, 0, uiDepth );
+
+        if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllRefIdx(  0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+        if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( 0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      }
+#endif
+    }
+    else if (uiMode==2)
+    {
+      pcCU->setPredModeSubParts( MODE_INTER, uiAbsPartIdx, uiDepth );
+      pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+      pcCU->setMergeFlagSubParts(true, uiAbsPartIdx,0, uiDepth );
+      pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    }
+    else if (uiMode==6)
+    {
+#if MTK_DISABLE_INTRA_NxN_SPLIT && HHI_DISABLE_INTER_NxN_SPLIT
+      if (uiDepth != g_uiMaxCUDepth - g_uiAddCUDepth)
+      {
+        pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+        pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+        pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+        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;
+        pcCU->setTrIdxSubParts( uiTrLevel, uiAbsPartIdx, uiDepth );
+      }
+      else
+#endif
+      {
+        pcCU->setPredModeSubParts( MODE_INTER, uiAbsPartIdx, uiDepth );
+        pcCU->setPartSizeSubParts( SIZE_NxN, uiAbsPartIdx, uiDepth );
+      }
+    }
+    else
+    {
+      pcCU->setPredModeSubParts( MODE_INTER, uiAbsPartIdx, uiDepth );
+      pcCU->setPartSizeSubParts( PartSize(uiMode-3), uiAbsPartIdx, uiDepth );
+      pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    }
+  }
+}
+#else
+Void TDecCavlc::parseSplitFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+  {
+    pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+    return ;
+  }
+
+  UInt uiSymbol;
+  xReadFlag( uiSymbol );
+  pcCU->setDepthSubParts( uiDepth + uiSymbol, uiAbsPartIdx );
+
+  return ;
+}
+#endif
+
+#if QC_LCEC_INTER_MODE
+
+/** parse partition size
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecCavlc::parsePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiMode=0;
+  if ( pcCU->getSlice()->isIntra()&& pcCU->isIntra( uiAbsPartIdx ) )
+  {
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+    uiMode = 1;
+    if ( uiDepth == (g_uiMaxCUDepth - g_uiAddCUDepth ))
+#endif
+    {
+      UInt uiSymbol;
+      xReadFlag( uiSymbol );
+      uiMode = uiSymbol ? 1 : 2;
+    }
+  }
+#if MTK_DISABLE_INTRA_NxN_SPLIT && HHI_DISABLE_INTER_NxN_SPLIT
+  else if (uiDepth != (g_uiMaxCUDepth - g_uiAddCUDepth ) || pcCU->getPartitionSize(uiAbsPartIdx ) != SIZE_NxN)
+#else
+  else if (pcCU->getPartitionSize(uiAbsPartIdx ) != SIZE_NxN)
+#endif
+  {
+    return;
+  }
+  else
+  {
+    UInt uiSymbol;
+    xReadFlag( uiSymbol );
+    if(uiSymbol)
+    {
+      uiMode = 1;
+    }
+    else
+    {
+#if (MTK_DISABLE_INTRA_NxN_SPLIT && !HHI_DISABLE_INTER_NxN_SPLIT) || (!MTK_DISABLE_INTRA_NxN_SPLIT && HHI_DISABLE_INTER_NxN_SPLIT )
+      if ( uiDepth != (g_uiMaxCUDepth - g_uiAddCUDepth ))
+      {
+#if MTK_DISABLE_INTRA_NxN_SPLIT && !HHI_DISABLE_INTER_NxN_SPLIT
+        uiMode = 0;
+#elif !MTK_DISABLE_INTRA_NxN_SPLIT && HHI_DISABLE_INTER_NxN_SPLIT
+        uiMode = 2;
+#endif
+      }
+      else
+#endif
+      {
+        xReadFlag( uiSymbol );
+        uiMode = uiSymbol ? 2 : 0;
+      }
+    }
+  }
+  PartSize ePartSize;
+  PredMode eMode;
+  if (uiMode > 0)
+  {
+    eMode = MODE_INTRA;
+    ePartSize = (uiMode==1) ? SIZE_2Nx2N:SIZE_NxN;
+  }
+  else
+  {
+    eMode = MODE_INTER;
+    ePartSize = SIZE_NxN;
+  }
+  pcCU->setPredModeSubParts( eMode    , uiAbsPartIdx, uiDepth );
+  pcCU->setPartSizeSubParts( ePartSize, uiAbsPartIdx, uiDepth );
+  pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
+  {
+    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( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN )
+    {
+      pcCU->setTrIdxSubParts( 1 + uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setTrIdxSubParts( uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+  }
+}
+#else
+Void TDecCavlc::parsePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol, uiMode = 0;
+  PartSize eMode;
+
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+    eMode = SIZE_2Nx2N;
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+    {
+      xReadFlag( uiSymbol );
+      eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
+    }
+  }
+  else
+  {
+#if HHI_RMP_SWITCH
+    if ( !pcCU->getSlice()->getSPS()->getUseRMP())
+    {
+      xReadFlag( uiSymbol );
+      if( uiSymbol )
+        uiMode = 0;
+      else
+        uiMode = 3;
+    }
+    else
+#endif
+    {
+      UInt uiMaxNumBits = 3;
+      for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
+      {
+        xReadFlag( uiSymbol );
+        if ( uiSymbol )
+        {
+          break;
+        }
+        uiMode++;
+      }
+    }
+    eMode = (PartSize) uiMode;
+
+    if (pcCU->getSlice()->isInterB() && uiMode == 3)
+    {
+#if HHI_DISABLE_INTER_NxN_SPLIT
+      uiSymbol = 0;
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+      {
+        xReadFlag( uiSymbol );
+      }
+
+      if (uiSymbol == 0)
+      {
+        pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+        if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+        {
+          xReadFlag( uiSymbol );
+        }
+        if (uiSymbol == 0)
+          eMode = SIZE_2Nx2N;
+      }
+    }
+
+  }
+
+  pcCU->setPartSizeSubParts( eMode, uiAbsPartIdx, uiDepth );
+  pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+
+  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( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
+  {
+    if( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN )
+    {
+      pcCU->setTrIdxSubParts( 1+uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setTrIdxSubParts( uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+  }
+}
+#endif
+
+/** parse prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecCavlc::parsePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( pcCU->getSlice()->isIntra() )
+  {
+    pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+    return ;
+  }
+#if !QC_LCEC_INTER_MODE
+  UInt uiSymbol;
+  Int  iPredMode = MODE_INTER;
+
+  if ( pcCU->getSlice()->isInterB() )
+  {
+    pcCU->setPredModeSubParts( (PredMode)iPredMode, uiAbsPartIdx, uiDepth );
+    return;
+  }
+  xReadFlag( uiSymbol );
+  iPredMode += uiSymbol;
+
+  pcCU->setPredModeSubParts( (PredMode)iPredMode, uiAbsPartIdx, uiDepth );
+#endif
+}
+
+#if LCEC_INTRA_MODE
+#if MTK_DCM_MPM
+Void TDecCavlc::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int  uiIPredMode = 0;
+  Int  iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+
+  Int uiPreds[2] = {-1, -1};
+  Int uiPredNum = pcCU->getIntraDirLumaPredictor(uiAbsPartIdx, uiPreds);
+
+  if ( g_aucIntraModeBitsAng[iIntraIdx] < 5 )
+  {
+     UInt uiSymbol;
+     xReadFlag( uiSymbol );
+     if ( uiSymbol )
+     {
+       if(uiPredNum == 1)
+       {
+        uiIPredMode = uiPreds[0];
+       }
+       else
+       {
+        xReadFlag( uiSymbol );
+        uiIPredMode = uiPreds[uiSymbol];
+       }
+     }
+     else
+     {
+      xReadFlag( uiSymbol ); uiIPredMode  = uiSymbol;
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) { xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 1; }
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) { xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 2; }
+
+      for(UInt i = 0; i < uiPredNum; i++)
+      {
+        if(uiIPredMode >= uiPreds[i]) { uiIPredMode ++;}
+      }
+
+    }
+  }
+  else
+  {
+  Int  iDir, iDirLarger, iRankIntraMode, iRankIntraModeLarger;
+
+  const UInt *huff;
+  const UInt *lengthHuff;
+  UInt  totMode;
+  UInt  *m_uiIntraModeTableD;
+
+  if ( g_aucIntraModeBitsAng[iIntraIdx] == 5 )
+  {
+  totMode = (uiPredNum == 1)? 17: 16;
+  huff = huff17_2[uiPredNum - 1];
+  lengthHuff = lengthHuff17_2[uiPredNum - 1];
+  m_uiIntraModeTableD = m_uiIntraModeTableD17[uiPredNum - 1];
+  }
+  else
+  {
+  totMode = (uiPredNum == 1)? 34: 33;
+  huff = huff34_2[uiPredNum - 1];
+  lengthHuff = lengthHuff34_2[uiPredNum - 1];
+  m_uiIntraModeTableD = m_uiIntraModeTableD34[uiPredNum - 1];
+  }
+
+  UInt uiCode;
+  UInt uiLength = lengthHuff[totMode - 1];
+
+  m_pcBitstream->pseudoRead(uiLength,uiCode);
+  if ((uiCode>>(uiLength- lengthHuff[0])) == huff[0])
+  {
+      m_pcBitstream->read(lengthHuff[0],uiCode);
+
+     if(uiPredNum == 1)
+     {
+        uiIPredMode = uiPreds[0];
+     }
+     else if(uiPredNum == 2)
+     {
+        UInt uiPredIdx= 0;
+        xReadFlag( uiPredIdx );
+        uiIPredMode = uiPreds[uiPredIdx];
+     }
+
+  }
+  else
+  {
+      iRankIntraMode = 0;
+
+      for(Int i = 1; i < totMode; i++)
+     {
+        if( (uiCode>>(uiLength- lengthHuff[i])) == huff[i])
+        {
+          m_pcBitstream->read(lengthHuff[i], uiCode);
+          iRankIntraMode = i;
+          break;
+        }
+      }
+
+     iRankIntraMode --;
+     iDir = m_uiIntraModeTableD[iRankIntraMode];
+     iRankIntraModeLarger = Max(0,iRankIntraMode-1);
+     iDirLarger = m_uiIntraModeTableD[iRankIntraModeLarger];
+     m_uiIntraModeTableD[iRankIntraModeLarger] = iDir;
+     m_uiIntraModeTableD[iRankIntraMode] = iDirLarger;
+
+     for(UInt i = 0; i < uiPredNum; i++)
+     {
+       if(iDir >= uiPreds[i])
+       {
+         iDir ++;
+       }
+     }
+
+     uiIPredMode = iDir;
+
+
+    }
+  }
+#if ADD_PLANAR_MODE
+  if (uiIPredMode == 2)
+  {
+    UInt planarFlag;
+    xReadFlag( planarFlag );
+    if ( planarFlag )
+    {
+      uiIPredMode = PLANAR_IDX;
+    }
+  }
+#endif
+
+  pcCU->setLumaIntraDirSubParts( (UChar)uiIPredMode, uiAbsPartIdx, uiDepth );
+}
+#else
+Void TDecCavlc::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  Int  uiIPredMode;
+  Int  iMostProbable = pcCU->getMostProbableIntraDirLuma( uiAbsPartIdx );
+  Int  iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+  Int  iDir, iDirLarger, iRankIntraMode, iRankIntraModeLarger;
+
+  Int  iLeft          = pcCU->getLeftIntraDirLuma( uiAbsPartIdx );
+  Int  iAbove         = pcCU->getAboveIntraDirLuma( uiAbsPartIdx );
+  UInt ind=(iLeft==iAbove)? 0 : 1;
+
+  const UInt *huff17=huff17_2[ind];
+  const UInt *lengthHuff17=lengthHuff17_2[ind];
+  const UInt *huff34=huff34_2[ind];
+  const UInt *lengthHuff34=lengthHuff34_2[ind];
+
+  if ( g_aucIntraModeBitsAng[iIntraIdx] < 5 )
+  {
+    xReadFlag( uiSymbol );
+    if ( uiSymbol )
+      uiIPredMode = iMostProbable;
+    else
+    {
+      xReadFlag( uiSymbol ); uiIPredMode  = uiSymbol;
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) { xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 1; }
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) { xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 2; }
+      if(uiIPredMode >= iMostProbable)
+        uiIPredMode ++;
+    }
+  }
+  else if ( g_aucIntraModeBitsAng[iIntraIdx] == 5 )
+  {
+    UInt uiCode;
+    UInt uiLength = lengthHuff17[15];
+    m_pcBitstream->pseudoRead(uiLength,uiCode);
+    if ((uiCode>>(uiLength- lengthHuff17[0])) == huff17[0])
+    {
+      m_pcBitstream->read(lengthHuff17[0],uiCode);
+      uiIPredMode = iMostProbable;
+    }
+    else
+    {
+      iRankIntraMode = 0;
+      for (Int i=1;i<17;i++)
+      {
+        if( (uiCode>>(uiLength- lengthHuff17[i])) == huff17[i])
+        {
+          m_pcBitstream->read(lengthHuff17[i], uiCode);
+          iRankIntraMode = i;
+          break;
+        }
+      }
+
+      if ( iRankIntraMode > 0 )
+        iRankIntraMode --;
+      iDir = m_uiIntraModeTableD17[iRankIntraMode];
+
+      iRankIntraModeLarger = Max(0,iRankIntraMode-1);
+      iDirLarger = m_uiIntraModeTableD17[iRankIntraModeLarger];
+
+      m_uiIntraModeTableD17[iRankIntraModeLarger] = iDir;
+      m_uiIntraModeTableD17[iRankIntraMode] = iDirLarger;
+
+      uiIPredMode = (iDir>=iMostProbable? iDir+1: iDir);
+    }
+  }
+  else
+  {
+    UInt uiCode;
+    UInt uiLength = lengthHuff34[32];
+    m_pcBitstream->pseudoRead(uiLength,uiCode);
+    if ((uiCode>>(uiLength- lengthHuff34[0])) == huff34[0])
+    {
+      m_pcBitstream->read(lengthHuff34[0],uiCode);
+      uiIPredMode = iMostProbable;
+    }
+    else
+    {
+      iRankIntraMode = 0;
+      for (Int i=1;i<34;i++)
+      {
+        if( (uiCode>>(uiLength- lengthHuff34[i])) == huff34[i])
+        {
+          m_pcBitstream->read(lengthHuff34[i], uiCode);
+          iRankIntraMode = i;
+          break;
+        }
+      }
+
+      if ( iRankIntraMode > 0 )
+        iRankIntraMode --;
+      iDir = m_uiIntraModeTableD34[iRankIntraMode];
+
+      iRankIntraModeLarger = Max(0,iRankIntraMode-1);
+      iDirLarger = m_uiIntraModeTableD34[iRankIntraModeLarger];
+
+      m_uiIntraModeTableD34[iRankIntraModeLarger] = iDir;
+      m_uiIntraModeTableD34[iRankIntraMode] = iDirLarger;
+
+      uiIPredMode = (iDir>=iMostProbable? iDir+1: iDir);
+    }
+  }
+
+#if ADD_PLANAR_MODE
+  if (uiIPredMode == 2)
+  {
+    UInt planarFlag;
+    xReadFlag( planarFlag );
+    if ( planarFlag )
+    {
+      uiIPredMode = PLANAR_IDX;
+    }
+  }
+#endif
+  pcCU->setLumaIntraDirSubParts( (UChar)uiIPredMode, uiAbsPartIdx, uiDepth );
+}
+#endif
+#else
+Void TDecCavlc::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  Int  uiIPredMode;
+  Int  iMostProbable = pcCU->getMostProbableIntraDirLuma( uiAbsPartIdx );
+
+  xReadFlag( uiSymbol );
+
+  if ( uiSymbol )
+    uiIPredMode = iMostProbable;
+  else
+  {
+    Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+    if ( g_aucIntraModeBitsAng[iIntraIdx] < 6 )
+    {
+      xReadFlag( uiSymbol ); uiIPredMode  = uiSymbol;
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) { xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 1; }
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) { xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 2; }
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 4 ) { xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 3; }
+    }
+    else
+    {
+      xReadFlag( uiSymbol ); uiIPredMode  = uiSymbol;
+      xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 1;
+      xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 2;
+      xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 3;
+      xReadFlag( uiSymbol ); uiIPredMode |= uiSymbol << 4;
+
+      if (uiIPredMode == 31)
+      { // Escape coding for the last two modes
+        xReadFlag( uiSymbol );
+        uiIPredMode = uiSymbol ? 32 : 31;
+      }
+    }
+
+    if (uiIPredMode >= iMostProbable)
+      uiIPredMode++;
+  }
+
+#if ADD_PLANAR_MODE
+  if (uiIPredMode == 2)
+  {
+    UInt planarFlag;
+    xReadFlag( planarFlag );
+    if ( planarFlag )
+    {
+      uiIPredMode = PLANAR_IDX;
+    }
+  }
+#endif
+  pcCU->setLumaIntraDirSubParts( (UChar)uiIPredMode, uiAbsPartIdx, uiDepth );
+}
+#endif
+
+Void TDecCavlc::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+#if CHROMA_CODEWORD
+  UInt uiMode = pcCU->getLumaIntraDir(uiAbsPartIdx);
+#if ADD_PLANAR_MODE
+  if ( (uiMode == 2 ) || (uiMode == PLANAR_IDX) )
+  {
+    uiMode = 4;
+  }
+#endif
+#if LM_CHROMA
+  Int  iMaxMode = pcCU->getSlice()->getSPS()->getUseLMChroma() ? 3 : 4;
+
+  Int  iMax = uiMode < iMaxMode ? 3 : 4;
+
+  xReadUnaryMaxSymbol( uiSymbol, iMax );
+
+  //switch codeword
+  if (uiSymbol == 0)
+  {
+    uiSymbol = 4;
+  }
+  else if (uiSymbol == 1 && pcCU->getSlice()->getSPS()->getUseLMChroma())
+  {
+    uiSymbol = 3;
+  }
+  else
+  {
+#if CHROMA_CODEWORD_SWITCH
+    uiSymbol = ChromaMapping[iMax-3][uiSymbol];
+#endif
+
+    if (pcCU->getSlice()->getSPS()->getUseLMChroma())
+       uiSymbol --;
+
+    if (uiSymbol <= uiMode)
+       uiSymbol --;
+  }
+
+#else // -- LM_CHROMA
+
+  Int  iMax = uiMode < 4 ? 3 : 4;
+  xReadUnaryMaxSymbol( uiSymbol, iMax );
+
+  //switch codeword
+  if (uiSymbol == 0)
+  {
+    uiSymbol = 4;
+  }
+#if CHROMA_CODEWORD_SWITCH
+  else
+  {
+    uiSymbol = ChromaMapping[iMax-3][uiSymbol];
+    if (uiSymbol <= uiMode)
+    {
+      uiSymbol --;
+    }
+  }
+#else
+  else if (uiSymbol <= uiMode)
+  {
+    uiSymbol --;
+  }
+#endif
+#endif // --> LM_CHROMA
+
+  //printf("uiMode %d, chroma %d, codeword %d, imax %d\n", uiMode, uiSymbol, uiRead, iMax);
+#else
+  xReadFlag( uiSymbol );
+
+  if ( uiSymbol )
+  {
+    xReadUnaryMaxSymbol( uiSymbol, 3 );
+    uiSymbol++;
+  }
+#endif
+
+#if ADD_PLANAR_MODE
+  if (uiSymbol == 2)
+  {
+#if CHROMA_CODEWORD
+    uiMode = pcCU->getLumaIntraDir(uiAbsPartIdx);
+    if (uiMode == 2)
+    {
+      uiSymbol = PLANAR_IDX;
+    }
+    else if (uiMode != PLANAR_IDX)
+#endif
+    {
+      UInt planarFlag;
+      xReadFlag( planarFlag );
+      if ( planarFlag )
+      {
+        uiSymbol = PLANAR_IDX;
+      }
+    }
+  }
+#endif
+  pcCU->setChromIntraDirSubParts( uiSymbol, uiAbsPartIdx, uiDepth );
+
+  return ;
+}
+
+Void TDecCavlc::parseInterDir( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+
+#if UNIFY_INTER_TABLE
+#if DCM_COMB_LIST
+  UInt uiNumRefIdxOfLC = pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C);
+#endif
+  #define min(a, b) (((a) < (b)) ? (a) : (b))
+#if DCM_COMB_LIST
+  UInt uiValNumRefIdxOfLC = min(4,pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C));
+#endif
+  UInt uiValNumRefIdxOfL0 = min(2,pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0));
+  UInt uiValNumRefIdxOfL1 = min(2,pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1));
+
+  if ( pcCU->getSlice()->getRefIdxCombineCoding() )
+  {
+    UInt uiIndex,tmp;
+#if CAVLC_COUNTER_ADAPT
+    Int x,cx;
+#else
+    Int x,cx,y,cy;
+#endif
+
+    UInt *m_uiMITableD = m_uiMI1TableD;
+
+    UInt uiMaxVal;
+#if DCM_COMB_LIST
+    if (uiNumRefIdxOfLC > 0)
+    {
+      uiMaxVal = uiValNumRefIdxOfLC + uiValNumRefIdxOfL0*uiValNumRefIdxOfL1;
+    }
+    else
+#endif
+    if (pcCU->getSlice()->getNoBackPredFlag())
+    {
+      uiMaxVal = uiValNumRefIdxOfL0 + uiValNumRefIdxOfL0*uiValNumRefIdxOfL1;
+    }
+    else
+    {
+      uiMaxVal = uiValNumRefIdxOfL0 + uiValNumRefIdxOfL1 + uiValNumRefIdxOfL0*uiValNumRefIdxOfL1;
+    }
+
+    xReadUnaryMaxSymbol( tmp, uiMaxVal );
+
+    x = m_uiMITableD[tmp];
+    uiIndex = x;
+
+    /* Adapt table */
+
+    cx = tmp;
+#if CAVLC_COUNTER_ADAPT
+    adaptCodeword(cx, m_ucMI1TableCounter,  m_ucMI1TableCounterSum,  m_uiMITableD,  NULL, 4 );
+#else
+    cy = Max(0,cx-1);
+    y = m_uiMITableD[cy];
+    m_uiMITableD[cy] = x;
+    m_uiMITableD[cx] = y;
+    m_uiMITableVlcIdx += cx == m_uiMITableVlcIdx ? 0 : (cx < m_uiMITableVlcIdx ? -1 : 1);
+#endif
+
+    if (uiIndex < uiMaxVal)
+    {
+#if DCM_COMB_LIST
+      if (uiNumRefIdxOfLC > 0)
+      {
+        if (uiIndex < uiValNumRefIdxOfLC)
+        {
+          ruiInterDir = 1;
+          m_iRefFrame0[uiAbsPartIdx] = uiIndex;
+        }
+        else
+        {
+          UInt uiTmp = uiIndex-uiValNumRefIdxOfLC;
+          ruiInterDir = 3;
+
+          m_iRefFrame0[uiAbsPartIdx] = uiTmp/uiValNumRefIdxOfL1; //uiValNumRefIdxOfL1 == 1 or 2, so division can be converted to shift op
+          m_iRefFrame1[uiAbsPartIdx] = uiTmp%uiValNumRefIdxOfL1;
+        }
+      }
+      else
+#endif
+      if (pcCU->getSlice()->getNoBackPredFlag())
+      {
+        if (uiIndex < uiValNumRefIdxOfL0)
+        {
+          ruiInterDir = 1;
+          m_iRefFrame0[uiAbsPartIdx] = uiIndex;
+        }
+        else
+        {
+          UInt uiTmp = uiIndex-uiValNumRefIdxOfL0;
+          ruiInterDir = 3;
+
+          m_iRefFrame0[uiAbsPartIdx] = uiTmp/uiValNumRefIdxOfL1; //uiValNumRefIdxOfL1 == 1 or 2, so division can be converted to shift op
+          m_iRefFrame1[uiAbsPartIdx] = uiTmp%uiValNumRefIdxOfL1;
+        }
+      }
+      else
+      {
+        if (uiIndex < uiValNumRefIdxOfL0)
+        {
+          ruiInterDir = 1;
+          m_iRefFrame0[uiAbsPartIdx] = uiIndex;
+        }
+        else if (uiIndex < uiValNumRefIdxOfL1)
+        {
+          ruiInterDir = 2;
+          m_iRefFrame1[uiAbsPartIdx] = uiIndex-uiValNumRefIdxOfL0;
+        }
+        else
+        {
+          UInt uiTmp = uiIndex-uiValNumRefIdxOfL0-uiValNumRefIdxOfL1;
+          ruiInterDir = 3;
+
+          m_iRefFrame0[uiAbsPartIdx] = uiTmp/uiValNumRefIdxOfL1; //uiValNumRefIdxOfL1 == 1 or 2, so division can be converted to shift op
+          m_iRefFrame1[uiAbsPartIdx] = uiTmp%uiValNumRefIdxOfL1;
+        }
+      }
+
+      return;
+    }
+  }
+#else  //UNIFY_INTER_TABLE
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  if ( pcCU->getSlice()->getRefIdxCombineCoding() )
+#else
+  if(pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 2 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 2)
+#endif
+  {
+    UInt uiIndex,uiInterDir,tmp;
+
+#if CAVLC_COUNTER_ADAPT
+    Int x,cx;
+#else
+    Int x,cx,y,cy;
+#endif
+
+#if MS_LCEC_LOOKUP_TABLE_MAX_VALUE
+    UInt uiMaxVal = 7;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+    uiMaxVal = 8;
+#endif
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 1 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 1 )
+    {
+      if ( pcCU->getSlice()->getNoBackPredFlag() || ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 1 ) )
+      {
+        uiMaxVal = 1;
+      }
+      else
+      {
+        uiMaxVal = 2;
+      }
+    }
+    else if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 2 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 2 )
+    {
+      if ( pcCU->getSlice()->getNoBackPredFlag() || ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 2 ) )
+      {
+        uiMaxVal = 5;
+      }
+      else
+      {
+        uiMaxVal = 7;
+      }
+    }
+    else if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0 )
+    {
+      uiMaxVal = 4+1+MS_LCEC_UNI_EXCEPTION_THRES;
+    }
+
+    xReadUnaryMaxSymbol( tmp, uiMaxVal );
+#else
+    UInt vlcn = g_auiMITableVlcNum[m_uiMITableVlcIdx];
+    tmp = xReadVlc( vlcn );
+#endif
+
+    UInt *m_uiMITableD = m_uiMI1TableD;
+    x = m_uiMITableD[tmp];
+    uiIndex = x;
+
+    /* Adapt table */
+
+    cx = tmp;
+
+#if CAVLC_COUNTER_ADAPT
+    adaptCodeword(cx, m_ucMI1TableCounter,  m_ucMI1TableCounterSum,  m_uiMITableD,  NULL, 4 );
+#else
+    cy = Max(0,cx-1);
+    y = m_uiMITableD[cy];
+    m_uiMITableD[cy] = x;
+    m_uiMITableD[cx] = y;
+    m_uiMITableVlcIdx += cx == m_uiMITableVlcIdx ? 0 : (cx < m_uiMITableVlcIdx ? -1 : 1);
+#endif
+    {
+      uiInterDir = Min(2,uiIndex>>1);
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+      if ( uiIndex >=4 )
+      {
+        uiInterDir = 2;
+      }
+      else
+      {
+        uiInterDir = 0;
+      }
+#endif
+#if DCM_COMB_LIST
+      if(uiInterDir!=2 && pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C)>0)
+      {
+        uiInterDir = 0;
+        m_iRefFrame0[uiAbsPartIdx] = uiIndex;
+      }
+      else
+#endif
+      if (uiInterDir==0)
+      {
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+        m_iRefFrame0[uiAbsPartIdx] = uiIndex;
+#else
+        m_iRefFrame0[uiAbsPartIdx] = uiIndex&1;
+#endif
+      }
+      else if (uiInterDir==1)
+        m_iRefFrame1[uiAbsPartIdx] = uiIndex&1;
+      else
+      {
+        m_iRefFrame0[uiAbsPartIdx] = (uiIndex>>1)&1;
+        m_iRefFrame1[uiAbsPartIdx] = (uiIndex>>0)&1;
+      }
+    }
+    ruiInterDir = uiInterDir+1;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+    if ( x < 8 )
+#endif
+    {
+      return;
+    }
+  }
+#endif //UNIFY_INTER_TABLE
+
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  m_iRefFrame0[uiAbsPartIdx] = 1000;
+  m_iRefFrame1[uiAbsPartIdx] = 1000;
+#endif
+
+  xReadFlag( uiSymbol );
+
+  if ( uiSymbol )
+  {
+    uiSymbol = 2;
+  }
+#if DCM_COMB_LIST
+  else if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+  {
+    uiSymbol = 0;
+  }
+#endif
+  else if ( pcCU->getSlice()->getNoBackPredFlag() )
+  {
+    uiSymbol = 0;
+  }
+  else
+  {
+    xReadFlag( uiSymbol );
+  }
+  uiSymbol++;
+  ruiInterDir = uiSymbol;
+  return;
+}
+
+Void TDecCavlc::parseRefFrmIdx( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+
+  if (pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 2 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 2 && pcCU->getSlice()->isInterB())
+  {
+#if DCM_COMB_LIST
+    if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C ) > 0 && eRefList==REF_PIC_LIST_C)
+    {
+      riRefFrmIdx = m_iRefFrame0[uiAbsPartIdx];
+    }
+    else
+#endif
+    if (eRefList==REF_PIC_LIST_0)
+    {
+      riRefFrmIdx = m_iRefFrame0[uiAbsPartIdx];
+    }
+    if (eRefList==REF_PIC_LIST_1)
+    {
+      riRefFrmIdx = m_iRefFrame1[uiAbsPartIdx];
+    }
+    return;
+  }
+
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  if ( ( m_iRefFrame0[uiAbsPartIdx] != 1000 || m_iRefFrame1[uiAbsPartIdx] != 1000 ) &&
+      pcCU->getSlice()->getRefIdxCombineCoding() )
+  {
+    if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C ) > 0 && eRefList==REF_PIC_LIST_C )
+    {
+      riRefFrmIdx = m_iRefFrame0[uiAbsPartIdx];
+    }
+    else if (eRefList==REF_PIC_LIST_0)
+    {
+      riRefFrmIdx = m_iRefFrame0[uiAbsPartIdx];
+    }
+    else if (eRefList==REF_PIC_LIST_1)
+    {
+      riRefFrmIdx = m_iRefFrame1[uiAbsPartIdx];
+    }
+    return;
+  }
+
+  UInt uiRefFrmIdxMinus = 0;
+  if ( pcCU->getSlice()->getRefIdxCombineCoding() )
+  {
+    if ( pcCU->getInterDir( uiAbsPartIdx ) != 3 )
+    {
+      if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 )
+      {
+        uiRefFrmIdxMinus = 4;
+      }
+      else
+      {
+        uiRefFrmIdxMinus = MS_LCEC_UNI_EXCEPTION_THRES+1;
+      }
+    }
+    else if ( eRefList == REF_PIC_LIST_1 && pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx ) < 2 )
+    {
+      uiRefFrmIdxMinus = 2;
+    }
+  }
+  if ( pcCU->getSlice()->getNumRefIdx( eRefList ) - uiRefFrmIdxMinus <= 1 )
+  {
+    uiSymbol = 0;
+    riRefFrmIdx = uiSymbol;
+    riRefFrmIdx += uiRefFrmIdxMinus;
+    return;
+  }
+#endif
+
+  xReadFlag ( uiSymbol );
+  if ( uiSymbol )
+  {
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+    xReadUnaryMaxSymbol( uiSymbol, pcCU->getSlice()->getNumRefIdx( eRefList )-2 - uiRefFrmIdxMinus );
+#else
+    xReadUnaryMaxSymbol( uiSymbol, pcCU->getSlice()->getNumRefIdx( eRefList )-2 );
+#endif
+
+    uiSymbol++;
+  }
+  riRefFrmIdx = uiSymbol;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  riRefFrmIdx += uiRefFrmIdxMinus;
+#endif
+
+  return;
+}
+
+Void TDecCavlc::parseMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  Int iHor, iVer;
+  UInt uiAbsPartIdxL, uiAbsPartIdxA;
+  Int iHorPred, iVerPred;
+
+  TComDataCU* pcCUL   = pcCU->getPULeft ( uiAbsPartIdxL, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  TComDataCU* pcCUA   = pcCU->getPUAbove( uiAbsPartIdxA, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+
+  TComCUMvField* pcCUMvFieldL = ( pcCUL == NULL || pcCUL->isIntra( uiAbsPartIdxL ) ) ? NULL : pcCUL->getCUMvField( eRefList );
+  TComCUMvField* pcCUMvFieldA = ( pcCUA == NULL || pcCUA->isIntra( uiAbsPartIdxA ) ) ? NULL : pcCUA->getCUMvField( eRefList );
+
+  iHorPred = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsHor() ) +
+  ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsHor() );
+  iVerPred = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsVer() ) +
+  ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsVer() );
+
+  TComMv cTmpMv( 0, 0 );
+  pcCU->getCUMvField( eRefList )->setAllMv( cTmpMv, pcCU->getPartitionSize( uiAbsPartIdx ), uiAbsPartIdx, uiPartIdx, uiDepth );
+
+  xReadSvlc( iHor );
+  xReadSvlc( iVer );
+
+  // set mvd
+  TComMv cMv( iHor, iVer );
+  pcCU->getCUMvField( eRefList )->setAllMvd( cMv, pcCU->getPartitionSize( uiAbsPartIdx ), uiAbsPartIdx, uiPartIdx, uiDepth );
+
+  return;
+}
+
+Void TDecCavlc::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiDQp;
+  Int  iDQp;
+
+  xReadFlag( uiDQp );
+
+  if ( uiDQp == 0 )
+  {
+    uiDQp = pcCU->getSlice()->getSliceQp();
+  }
+  else
+  {
+    xReadSvlc( iDQp );
+    uiDQp = pcCU->getSlice()->getSliceQp() + iDQp;
+  }
+
+  pcCU->setQPSubParts( uiDQp, uiAbsPartIdx, uiDepth );
+}
+
+#if CAVLC_RQT_CBP
+/** Function for parsing cbf and split
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param uiTrDepth Transform depth
+ * \param uiDepth CU Depth
+ * \param uiSubdiv split flag
+ * \returns
+ * This function performs parsing for cbf and split flag
+ */
+Void TDecCavlc::parseCbfTrdiv( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiTrDepth, UInt uiDepth, UInt& uiSubdiv )
+{
+  UInt uiCbf,tmp;
+  UInt uiCBP,uiCbfY,uiCbfU,uiCbfV;
+  UInt n,cx;
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+  UInt uiQPartNumParent  = pcCU->getPic()->getNumPartInCU() >> ((uiDepth-1) << 1);
+  UInt uiQPartNumCurr    = pcCU->getPic()->getNumPartInCU() >> ((uiDepth) << 1);
+
+  UInt uiFlagPattern = xGetFlagPattern( pcCU, uiAbsPartIdx, uiDepth, uiSubdiv );
+
+  n = pcCU->isIntra( uiAbsPartIdx ) ? 0 : 1;
+  uiCbfY = uiCbfU = uiCbfV = 0;
+
+  if(uiFlagPattern < 8)
+  {
+    if( uiLog2TrSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      if(uiFlagPattern & 0x04)
+      {
+        xReadFlag(uiCbfU);
+      }
+      if(uiFlagPattern & 0x02)
+      {
+        xReadFlag(uiCbfV);
+      }
+    }
+    else
+    {
+      uiCbfU = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1)?1:0;
+      uiCbfV = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1)?1:0;
+    }
+    if(uiFlagPattern & 0x01)
+    {
+      parseTransformSubdivFlag( uiSubdiv, 0);
+    }
+  }
+  else
+  {
+    if(uiFlagPattern == 8)
+    {
+      if (uiAbsPartIdx % uiQPartNumParent ==0)
+      {
+        parseBlockCbf(pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrDepth,uiDepth, uiQPartNumCurr);
+      }
+      uiCbfY = ( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA ) >> uiTrDepth) & 0x1;
+      if( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        uiCbfU = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1)?1:0;
+        uiCbfV = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1)?1:0;
+      }
+    }
+    else if(uiFlagPattern == 9)
+    {
+      bool bNeedToDecode = true;
+      if ( n==1 && (uiAbsPartIdx%uiQPartNumParent) / uiQPartNumCurr == 3 )  // last one
+      {
+        UInt uiTempAbsPartIdx = uiAbsPartIdx/uiQPartNumParent*uiQPartNumParent;
+        if ( pcCU->getCbf( uiTempAbsPartIdx + uiQPartNumCurr*0, TEXT_LUMA, uiTrDepth ) ||
+          pcCU->getCbf( uiTempAbsPartIdx + uiQPartNumCurr*1, TEXT_LUMA, uiTrDepth ) ||
+          pcCU->getCbf( uiTempAbsPartIdx + uiQPartNumCurr*2, TEXT_LUMA, uiTrDepth ) )
+        {
+          bNeedToDecode = true;
+        }
+        else
+        {
+          bNeedToDecode = false;
+          xReadFlag( uiSubdiv );
+          uiCbfY = 1;
+        }
+      }
+      if ( bNeedToDecode )
+      {
+        UInt uiSymbol;
+        xReadUnaryMaxSymbol(cx, n?2:3);
+        uiSymbol = m_uiCBP_YS_TableD[n][cx];
+        uiCbfY = uiSymbol >> 1;
+        uiSubdiv = uiSymbol & 0x01;
+        adaptCodeword(cx, m_ucCBP_YS_TableCounter[n],  m_ucCBP_YS_TableCounterSum[n],  m_uiCBP_YS_TableD[n],  NULL, 3);
+      }
+    }
+    else if (uiFlagPattern == 14)
+    {
+      UInt  uiIdx = uiTrDepth? (2 + n) : n;
+      xReadUnaryMaxSymbol(cx, 7);
+      uiCBP = m_uiCBP_YUV_TableD[uiIdx][cx];
+      adaptCodeword(cx,  m_ucCBP_YUV_TableCounter[uiIdx],  m_ucCBP_YUV_TableCounterSum[uiIdx],  m_uiCBP_YUV_TableD[uiIdx],  NULL, 4);
+      uiCbfY = (uiCBP>>2)&1;
+      uiCbfU = (uiCBP>>1)&1;
+      uiCbfV = (uiCBP>>0)&1;
+    }
+    else if ( uiFlagPattern == 11 || uiFlagPattern == 13 || uiFlagPattern == 15)
+    {
+      UInt uiSymbol, i;
+      m_pcBitstream->pseudoRead(6, uiSymbol);
+      for (i=0;i<8;i++)
+      {
+        if( (uiSymbol>>(6 - g_auiCBP_YCS_TableLen[n][i])) == g_auiCBP_YCS_Table[n][i] && g_auiCBP_YCS_TableLen[n][i])
+        {
+          m_pcBitstream->read(g_auiCBP_YCS_TableLen[n][i],uiSymbol);
+          uiSymbol =i;
+          break;
+        }
+      }
+
+      uiCBP = m_uiCBP_YCS_TableD[n][uiSymbol];
+      adaptCodeword(uiSymbol, m_ucCBP_YCS_TableCounter[n], m_ucCBP_YCS_TableCounterSum[n],  m_uiCBP_YCS_TableD[n],  NULL, 4);
+      uiCbfY = uiCBP >> 2;
+      UInt uiCbfUV = (uiCBP >> 1)& 0x01;
+      uiSubdiv = uiCBP & 0x01;
+
+      uiCbfU = 0; uiCbfV = 0;
+      if (uiFlagPattern == 15)
+      {
+        if(uiCbfUV)
+        {
+          xReadUnaryMaxSymbol( uiSymbol , 2);
+          uiSymbol = n? (uiSymbol + 1): (3 - uiSymbol);
+          uiCbfU = uiSymbol >> 1;
+          uiCbfV = uiSymbol & 0x01;
+        }
+      }
+      else
+      {
+        uiCbfU = (uiFlagPattern & 0x04) ?  uiCbfUV: 0;
+        uiCbfV = (uiFlagPattern & 0x02) ?  uiCbfUV: 0;
+      }
+    }
+    else if (uiFlagPattern == 10 || uiFlagPattern == 12)
+    {
+      UInt uiSymbol;
+      xReadUnaryMaxSymbol(tmp, 3);
+      uiSymbol = g_auiCBP_YC_TableD[n][tmp];
+      uiCbfY = uiSymbol >> 1;
+
+      uiCbfU = uiCbfV = 0;
+      if(uiSymbol & 0x01)
+      {
+        uiCbfU = (uiFlagPattern & 0x04)? 1 : 0;
+        uiCbfV = (uiFlagPattern & 0x02)? 1 : 0;
+      }
+    }
+  }
+
+  uiCbf = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA );
+  pcCU->setCbfSubParts( uiCbf | ( uiCbfY << uiTrDepth ), TEXT_LUMA, uiAbsPartIdx, uiDepth );
+
+  uiCbf = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U );
+  pcCU->setCbfSubParts( uiCbf | ( uiCbfU << uiTrDepth ), TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
+
+  uiCbf = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V );
+  pcCU->setCbfSubParts( uiCbf | ( uiCbfV << uiTrDepth ), TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
+
+  if(!pcCU->isIntra(uiAbsPartIdx) && uiCbfY == 0 && uiCbfU == 0 && uiCbfV == 0)
+  {
+    uiSubdiv = 0;
+  }
+
+  return;
+}
+
+/** Function for parsing cbf and split
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU Depth
+ * \param uiSubdiv split flag
+ * \returns flag pattern
+ * This function gets flagpattern for cbf and split flag
+ */
+UInt TDecCavlc::xGetFlagPattern( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiSubdiv )
+{
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
+  UInt uiTrDepth =  uiDepth - pcCU->getDepth( uiAbsPartIdx );
+  UInt patternYUV, patternDiv;
+  UInt bY, bU, bV;
+
+
+  UInt uiFullDepth = pcCU->getDepth(uiAbsPartIdx) + uiTrDepth;
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  if(uiTrDepth == 0)
+  {
+    patternYUV = 7;
+  }
+  else if( uiLog2TrSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    bY = pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, uiTrDepth - 1)?1:0;
+    bU = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1)?1:0;
+    bV = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1)?1:0;
+    patternYUV = (bY<<2) + (bU<<1) + bV;
+  }
+  else
+  {
+    bY = pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, uiTrDepth - 1)?1:0;
+    patternYUV = bY<<2;
+  }
+
+
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    patternDiv = 0; uiSubdiv = 1;
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    patternDiv = 0; uiSubdiv = 1;
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    patternDiv = 0; uiSubdiv = 0;
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    patternDiv = 0; uiSubdiv = 0;
+  }
+  else
+  {
+    patternDiv = 1;
+  }
+
+  return ((patternYUV<<1)+patternDiv);
+}
+#endif
+Void TDecCavlc::parseCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth )
+{
+  if (eType == TEXT_ALL)
+  {
+    UInt uiCbf,tmp;
+    UInt uiCBP,uiCbfY,uiCbfU,uiCbfV;
+
+#if CAVLC_COUNTER_ADAPT
+    Int n, cx;
+#else
+    Int n,x,cx,y,cy;
+#endif
+
+    /* Start adaptation */
+    n = pcCU->isIntra( uiAbsPartIdx ) ? 0 : 1;
+#if CAVLC_RQT_CBP
+    UInt vlcn = 0;
+#else
+    UInt vlcn = g_auiCbpVlcNum[n][m_uiCbpVlcIdx[n]];
+#endif
+    tmp = xReadVlc( vlcn );
+#if CAVLC_RQT_CBP
+    uiCBP = m_uiCBP_YUV_TableD[n][tmp];
+#else
+    uiCBP = m_uiCBPTableD[n][tmp];
+#endif
+
+    /* Adapt LP table */
+    cx = tmp;
+
+#if CAVLC_COUNTER_ADAPT
+#if CAVLC_RQT_CBP
+    adaptCodeword(cx, m_ucCBP_YUV_TableCounter[n],  m_ucCBP_YUV_TableCounterSum[n],  m_uiCBP_YUV_TableD[n],  NULL, 4);
+#else
+    adaptCodeword(cx, m_ucCBFTableCounter[n],  m_ucCBFTableCounterSum[n],  m_uiCBPTableD[n],  NULL, 4);
+#endif
+#else
+    cy = Max(0,cx-1);
+    x = uiCBP;
+    y = m_uiCBPTableD[n][cy];
+    m_uiCBPTableD[n][cy] = x;
+    m_uiCBPTableD[n][cx] = y;
+    m_uiCbpVlcIdx[n] += cx == m_uiCbpVlcIdx[n] ? 0 : (cx < m_uiCbpVlcIdx[n] ? -1 : 1);
+#endif
+
+    uiCbfY = (uiCBP>>0)&1;
+    uiCbfU = (uiCBP>>1)&1;
+    uiCbfV = (uiCBP>>2)&1;
+
+    uiCbf = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA );
+    pcCU->setCbfSubParts( uiCbf | ( uiCbfY << uiTrDepth ), TEXT_LUMA, uiAbsPartIdx, uiDepth );
+
+    uiCbf = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U );
+    pcCU->setCbfSubParts( uiCbf | ( uiCbfU << uiTrDepth ), TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
+
+    uiCbf = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V );
+    pcCU->setCbfSubParts( uiCbf | ( uiCbfV << uiTrDepth ), TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
+  }
+}
+
+Void TDecCavlc::parseBlockCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth, UInt uiQPartNum )
+{
+  assert(uiTrDepth > 0);
+  UInt uiCbf4, uiCbf;
+
+#if CAVLC_COUNTER_ADAPT
+  Int cx;
+#else
+  Int x,cx,y,cy;
+#endif
+
+  UInt tmp;
+
+  UInt n = (pcCU->isIntra(uiAbsPartIdx) && eType == TEXT_LUMA)? 0:1;
+#if CAVLC_RQT_CBP
+  UInt vlcn = (n==0)?g_auiCBP_4Y_VlcNum[m_uiCBP_4Y_VlcIdx]:11;
+#else
+  UInt vlcn = (n==0)?g_auiBlkCbpVlcNum[m_uiBlkCbpVlcIdx]:11;
+#endif
+  tmp = xReadVlc( vlcn );
+#if CAVLC_RQT_CBP
+  uiCbf4 = m_uiCBP_4Y_TableD[n][tmp];
+#else
+  uiCbf4 = m_uiBlkCBPTableD[n][tmp];
+#endif
+
+  cx = tmp;
+
+#if CAVLC_COUNTER_ADAPT
+#if CAVLC_RQT_CBP
+  adaptCodeword(cx, m_ucCBP_4Y_TableCounter[n], m_ucCBP_4Y_TableCounterSum[n], m_uiCBP_4Y_TableD[n], NULL, 2);
+#else
+  adaptCodeword(cx, m_ucBlkCBPTableCounter[n],  m_ucBlkCBPTableCounterSum[n],  m_uiBlkCBPTableD[n],  NULL, 2);
+#endif
+#else
+  cy = Max(0,cx-1);
+  x = uiCbf4;
+  y = m_uiBlkCBPTableD[n][cy];
+  m_uiBlkCBPTableD[n][cy] = x;
+  m_uiBlkCBPTableD[n][cx] = y;
+#endif
+
+#if CAVLC_RQT_CBP
+  if(n==0)
+    m_uiCBP_4Y_VlcIdx += cx == m_uiCBP_4Y_VlcIdx ? 0 : (cx < m_uiCBP_4Y_VlcIdx ? -1 : 1);
+#else
+  if(n==0)
+    m_uiBlkCbpVlcIdx += cx == m_uiBlkCbpVlcIdx ? 0 : (cx < m_uiBlkCbpVlcIdx ? -1 : 1);
+#endif
+
+  uiCbf4++;
+  uiCbf = pcCU->getCbf( uiAbsPartIdx, eType );
+  pcCU->setCbfSubParts( uiCbf | ( ((uiCbf4>>3)&0x01) << uiTrDepth ), eType, uiAbsPartIdx, uiDepth ); uiAbsPartIdx += uiQPartNum;
+  uiCbf = pcCU->getCbf( uiAbsPartIdx, eType );
+  pcCU->setCbfSubParts( uiCbf | ( ((uiCbf4>>2)&0x01) << uiTrDepth ), eType, uiAbsPartIdx, uiDepth ); uiAbsPartIdx += uiQPartNum;
+  uiCbf = pcCU->getCbf( uiAbsPartIdx, eType );
+  pcCU->setCbfSubParts( uiCbf | ( ((uiCbf4>>1)&0x01) << uiTrDepth ), eType, uiAbsPartIdx, uiDepth ); uiAbsPartIdx += uiQPartNum;
+  uiCbf = pcCU->getCbf( uiAbsPartIdx, eType );
+  pcCU->setCbfSubParts( uiCbf | ( (uiCbf4&0x01) << uiTrDepth ), eType, uiAbsPartIdx, uiDepth );
+
+  return;
+}
+
+Void TDecCavlc::parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+
+  if ( uiWidth > pcCU->getSlice()->getSPS()->getMaxTrSize() )
+  {
+    uiWidth  = pcCU->getSlice()->getSPS()->getMaxTrSize();
+    uiHeight = pcCU->getSlice()->getSPS()->getMaxTrSize();
+  }
+  UInt uiSize   = uiWidth*uiHeight;
+
+  // point to coefficient
+  TCoeff* piCoeff = pcCoef;
+
+  // initialize scan
+  const UInt*  pucScan;
+
+#if CAVLC_COEF_LRG_BLK
+  UInt maxBlSize = (eTType==TEXT_LUMA)? 32:8;
+  UInt uiBlSize = Min(maxBlSize,uiWidth);
+  UInt uiConvBit = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : uiBlSize];
+  UInt uiNoCoeff = uiBlSize*uiBlSize;
+#else
+  //UInt uiConvBit = g_aucConvertToBit[ Min(8,uiWidth) ];
+  UInt uiConvBit = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : Min(8,uiWidth)    ];
+#endif
+  pucScan        = g_auiFrameScanXY  [ uiConvBit + 1 ];
+
+#if QC_MDCS
+  UInt uiBlkPos;
+#if CAVLC_COEF_LRG_BLK
+  UInt uiLog2BlkSize = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : uiBlSize] + 2;
+#else
+  UInt uiLog2BlkSize = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : Min(8,uiWidth)    ] + 2;
+#endif
+  const UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+#endif //QC_MDCS
+
+  UInt uiDecodeDCCoeff = 0;
+  Int dcCoeff = 0;
+  if (pcCU->isIntra(uiAbsPartIdx))
+  {
+    UInt uiAbsPartIdxL, uiAbsPartIdxA;
+    TComDataCU* pcCUL   = pcCU->getPULeft (uiAbsPartIdxL, pcCU->getZorderIdxInCU() + uiAbsPartIdx);
+    TComDataCU* pcCUA   = pcCU->getPUAbove(uiAbsPartIdxA, pcCU->getZorderIdxInCU() + uiAbsPartIdx);
+    if (pcCUL == NULL && pcCUA == NULL)
+    {
+      uiDecodeDCCoeff = 1;
+      dcCoeff = xReadVlc(eTType == TEXT_LUMA ? 3 : 1);
+      if (dcCoeff)
+      {
+        UInt sign;
+        xReadFlag(sign);
+        if (sign)
+        {
+          dcCoeff = -dcCoeff;
+        }
+      }
+    }
+  }
+
+  UInt uiScanning;
+
+#if CAVLC_COEF_LRG_BLK
+  static TCoeff scoeff[1024];
+#else
+  TCoeff scoeff[64];
+#endif
+  Int iBlockType;
+  if( uiSize == 2*2 )
+  {
+    // hack: re-use 4x4 coding
+#if QC_MOD_LCEC
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+#else
+    iBlockType = pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType();
+#endif
+
+#if CAVLC_COEF_LRG_BLK
+    xParseCoeff( scoeff, iBlockType, 4 );
+#else
+    xParseCoeff4x4( scoeff, iBlockType );
+#endif
+
+    for (uiScanning=0; uiScanning<4; uiScanning++)
+    {
+#if QC_MDCS
+      uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+      piCoeff[ uiBlkPos ] =  scoeff[15-uiScanning];
+#else
+      piCoeff[ pucScan[ uiScanning ] ] = scoeff[15-uiScanning];
+#endif //QC_MDCS
+    }
+  }
+  else if ( uiSize == 4*4 )
+  {
+#if QC_MOD_LCEC
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+#else
+    iBlockType = pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType();
+#endif
+#if CAVLC_COEF_LRG_BLK
+    xParseCoeff( scoeff, iBlockType, 4 );
+#else
+    xParseCoeff4x4( scoeff, iBlockType );
+#endif
+
+    for (uiScanning=0; uiScanning<16; uiScanning++)
+    {
+#if QC_MDCS
+      uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+      piCoeff[ uiBlkPos ] =  scoeff[15-uiScanning];
+#else
+      piCoeff[ pucScan[ uiScanning ] ] = scoeff[15-uiScanning];
+#endif //QC_MDCS
+    }
+  }
+  else if ( uiSize == 8*8 )
+  {
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V) //8x8 specific
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+#if CAVLC_COEF_LRG_BLK
+    xParseCoeff( scoeff, iBlockType, 8 );
+#else
+    xParseCoeff8x8( scoeff, iBlockType );
+#endif
+
+    for (uiScanning=0; uiScanning<64; uiScanning++)
+    {
+#if QC_MDCS
+      uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+      piCoeff[ uiBlkPos ] =  scoeff[63-uiScanning];
+#else
+      piCoeff[ pucScan[ uiScanning ] ] = scoeff[63-uiScanning];
+#endif //QC_MDCS
+    }
+
+  }
+  else
+  {
+    if (!pcCU->isIntra( uiAbsPartIdx ))
+    {
+      memset(piCoeff,0,sizeof(TCoeff)*uiSize);
+      if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+        iBlockType = eTType-2;
+      else
+        iBlockType = 5 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+#if CAVLC_COEF_LRG_BLK
+      xParseCoeff( scoeff, iBlockType, uiBlSize );
+#else
+      xParseCoeff8x8( scoeff, iBlockType );
+#endif
+
+#if CAVLC_COEF_LRG_BLK
+      for (uiScanning=0; uiScanning<uiNoCoeff; uiScanning++)
+      {
+#if QC_MDCS
+        uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+        uiBlkPos = (uiBlkPos/uiBlSize)* uiWidth + (uiBlkPos&(uiBlSize-1));
+        piCoeff[ uiBlkPos ] =  scoeff[uiNoCoeff-uiScanning-1];
+#else
+        piCoeff[(pucScan[uiScanning]/uiBlSize)*uiWidth + (pucScan[uiScanning]&(uiBlSize-1))]=scoeff[uiNoCoeff-uiScanning-1];
+#endif
+      }
+#else
+      for (uiScanning=0; uiScanning<64; uiScanning++)
+      {
+#if QC_MDCS
+        uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+        uiBlkPos = (uiBlkPos/8)* uiWidth + uiBlkPos%8;
+        piCoeff[ uiBlkPos ] =  scoeff[63-uiScanning];
+#else
+        piCoeff[(pucScan[uiScanning]/8)*uiWidth + (pucScan[uiScanning]%8)] = scoeff[63-uiScanning];
+#endif //QC_MDCS
+      }
+#endif
+      return;
+    }
+
+    if(pcCU->isIntra( uiAbsPartIdx ))
+    {
+      memset(piCoeff,0,sizeof(TCoeff)*uiSize);
+
+      if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+        iBlockType = eTType-2;
+      else
+        iBlockType = 5 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+
+#if CAVLC_COEF_LRG_BLK
+      xParseCoeff( scoeff, iBlockType, uiBlSize );
+      for (uiScanning=0; uiScanning<uiNoCoeff; uiScanning++)
+      {
+#if QC_MDCS
+        uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+        piCoeff[ uiBlkPos ] =  scoeff[uiNoCoeff - uiScanning - 1];
+#else
+        piCoeff[ pucScan[ uiScanning ] ] = scoeff[uiNoCoeff - uiScanning - 1];
+#endif //QC_MDCS
+      }
+#else
+      xParseCoeff8x8( scoeff, iBlockType );
+
+      for (uiScanning=0; uiScanning<64; uiScanning++)
+      {
+#if QC_MDCS
+        uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+        piCoeff[ uiBlkPos ] =  scoeff[63-uiScanning];
+#else
+        piCoeff[ pucScan[ uiScanning ] ] = scoeff[63-uiScanning];
+#endif //QC_MDCS
+      }
+#endif
+    }
+  }
+
+  if (uiDecodeDCCoeff == 1)
+  {
+    piCoeff[0] = dcCoeff;
+  }
+
+  return ;
+}
+
+Void TDecCavlc::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
+{
+  xReadFlag( ruiSubdivFlag );
+}
+
+Void TDecCavlc::parseQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth )
+{
+  UInt uiSymbol;
+  xReadFlag( uiSymbol );
+  pcCU->setCbfSubParts( uiSymbol << uiTrDepth, eType, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecCavlc::parseQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& uiQtRootCbf )
+{
+  UInt uiSymbol;
+  xReadFlag( uiSymbol );
+  uiQtRootCbf = uiSymbol;
+}
+
+Void TDecCavlc::parseAlfFlag (UInt& ruiVal)
+{
+  xReadFlag( ruiVal );
+}
+
+#if TSB_ALF_HEADER
+Void TDecCavlc::parseAlfFlagNum( UInt& ruiVal, UInt minValue, UInt depth )
+{
+  UInt uiLength = 0;
+  UInt maxValue = (minValue << (depth*2));
+  UInt temp = maxValue - minValue;
+  for(UInt i=0; i<32; i++)
+  {
+    if(temp&0x1)
+    {
+      uiLength = i+1;
+    }
+    temp = (temp >> 1);
+  }
+  if(uiLength)
+  {
+    xReadCode( uiLength, ruiVal );
+  }
+  else
+  {
+    ruiVal = 0;
+  }
+  ruiVal += minValue;
+}
+
+Void TDecCavlc::parseAlfCtrlFlag( UInt &ruiAlfCtrlFlag )
+{
+  UInt uiSymbol;
+  xReadFlag( uiSymbol );
+  ruiAlfCtrlFlag = uiSymbol;
+}
+#endif
+
+Void TDecCavlc::parseAlfUvlc (UInt& ruiVal)
+{
+  xReadUvlc( ruiVal );
+}
+
+Void TDecCavlc::parseAlfSvlc (Int&  riVal)
+{
+  xReadSvlc( riVal );
+}
+
+
+
+#if MTK_SAO
+Void TDecCavlc::parseAoFlag (UInt& ruiVal)
+{
+  xReadFlag( ruiVal );
+}
+Void TDecCavlc::parseAoUvlc (UInt& ruiVal)
+{
+  xReadUvlc( ruiVal );
+}
+
+Void TDecCavlc::parseAoSvlc (Int&  riVal)
+{
+  xReadSvlc( riVal );
+}
+#endif
+
+Void TDecCavlc::parseMergeFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
+{
+#if QC_LCEC_INTER_MODE
+  if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N )
+    return;
+#endif
+  UInt uiSymbol;
+  xReadFlag( uiSymbol );
+  pcCU->setMergeFlagSubParts( uiSymbol ? true : false, uiAbsPartIdx, uiPUIdx, uiDepth );
+}
+
+
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+Void 
+TDecCavlc::parseMergeIndexMV( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt  uiNumCand = 0;
+#if HHI_MPI
+  const Bool bMVIAvailable = pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE;
+  const UInt uiMviMergePos = bMVIAvailable ? HHI_MPI_MERGE_POS : MRG_MAX_NUM_CANDS;
+  if( bMVIAvailable )
+    uiNumCand++;
+#endif
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS; uiIdx++ )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIdx, uiAbsPartIdx ) == uiIdx + 1 )
+    {
+      uiNumCand++;
+    }
+  }
+  AOF( uiNumCand > 1 );
+  UInt uiUnaryIdx = 0;
+  for( ; uiUnaryIdx < uiNumCand - 1; uiUnaryIdx++ )
+  {
+    UInt uiSymbol = 0;
+    xReadFlag( uiSymbol );
+    if( uiSymbol == 0 )
+    {
+      break;
+    }
+  }
+  ruiMergeIndex = uiUnaryIdx;
+  for( UInt uiIdx = 0; uiIdx <= ruiMergeIndex; uiIdx++ )
+  {
+#if HHI_MPI
+    if( uiIdx > uiMviMergePos )
+    {
+      if( pcCU->getNeighbourCandIdx( uiIdx - 1, uiAbsPartIdx ) != uiIdx )
+      {
+        ruiMergeIndex++;
+      }
+    }
+    else if( uiIdx < uiMviMergePos )
+#endif
+    if( pcCU->getNeighbourCandIdx( uiIdx, uiAbsPartIdx ) != uiIdx + 1 )
+    {
+      ruiMergeIndex++;
+    }
+  }
+#if HHI_MPI
+  if( ruiMergeIndex > uiMviMergePos )
+  {
+    ruiMergeIndex--;
+  }
+  else if( ruiMergeIndex == uiMviMergePos )
+  {
+    pcCU->setTextureModeDepthSubParts( uiDepth, uiAbsPartIdx, uiDepth );
+  }
+#endif
+}
+#endif
+
+
+/** parse merge index
+ * \param pcCU
+ * \param ruiMergeIndex
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecCavlc::parseMergeIndex ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth )
+{
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+  if(
+#if HHI_INTER_VIEW_MOTION_PRED
+      ( pcCU->getSlice()->getSPS()->getViewId() > 0 && ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) == PDM_USE_FOR_MERGE ) ||
+#endif
+#if HHI_MPI
+      ( pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N ) ||
+#endif
+      0
+    )
+  {
+    parseMergeIndexMV( pcCU, ruiMergeIndex, uiAbsPartIdx, uiDepth );
+    return;
+  }
+#endif
+
+  Bool bLeftInvolved = false;
+  Bool bAboveInvolved = false;
+  Bool bCollocatedInvolved = false;
+  Bool bCornerInvolved = false;
+  UInt uiNumCand = 0;
+  for( UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; ++uiIter )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == uiIter + 1 )
+    {
+      uiNumCand++;
+      if( uiIter == 0 )
+      {
+        bLeftInvolved = true;
+      }
+      else if( uiIter == 1 )
+      {
+        bAboveInvolved = true;
+      }
+      else if( uiIter == 2 )
+      {
+        bCollocatedInvolved = true;
+      }
+      else if( uiIter == 3 )
+      {
+        bCornerInvolved = true;
+      }
+    }
+  }
+  assert( uiNumCand > 1 );
+  UInt uiUnaryIdx = 0;
+  for( ; uiUnaryIdx < uiNumCand - 1; ++uiUnaryIdx )
+  {
+    UInt uiSymbol = 0;
+    xReadFlag( uiSymbol );
+    if( uiSymbol == 0 )
+    {
+      break;
+    }
+  }
+  if( !bLeftInvolved )
+  {
+    ++uiUnaryIdx;
+  }
+  if( !bAboveInvolved && uiUnaryIdx >= 1 )
+  {
+    ++uiUnaryIdx;
+  }
+  if( !bCollocatedInvolved && uiUnaryIdx >= 2 )
+  {
+    ++uiUnaryIdx;
+  }
+  if( !bCornerInvolved && uiUnaryIdx >= 3 )
+  {
+    ++uiUnaryIdx;
+  }
+  ruiMergeIndex = uiUnaryIdx;
+}
+
+
+Void
+TDecCavlc::parseResPredFlag( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol = 0;
+  xReadFlag( uiSymbol );
+  rbResPredFlag = ( uiSymbol != 0 );
+}
+
+
+// ====================================================================================================================
+// 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 );
+}
+
+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;
+}
+
+Int TDecCavlc::xReadVlc( Int n )
+{
+#if CAVLC_COEF_LRG_BLK
+  assert( n>=0 && n<=13 );
+#else
+  assert( n>=0 && n<=11 );
+#endif
+
+  UInt zeroes=0, done=0, tmp;
+  UInt cw, bit;
+  UInt val = 0;
+  UInt first;
+  UInt lead = 0;
+
+  if (n < 5)
+  {
+    while (!done && zeroes < 6)
+    {
+      xReadFlag( bit );
+      if (bit)
+      {
+        if (n)
+        {
+          xReadCode( n, cw );
+        }
+        else
+        {
+          cw = 0;
+        }
+        done = 1;
+      }
+      else
+      {
+        zeroes++;
+      }
+    }
+    if ( done )
+    {
+      val = (zeroes<<n)+cw;
+    }
+    else
+    {
+      lead = n;
+      while (!done)
+      {
+        xReadFlag( first );
+        if ( !first )
+        {
+          lead++;
+        }
+        else
+        {
+          if ( lead )
+          {
+            xReadCode( lead, tmp );
+          }
+          else
+          {
+            tmp = 0;
+          }
+          val = 6 * (1 << n) + (1 << lead) + tmp - (1 << n);
+          done = 1;
+        }
+      }
+    }
+  }
+  else if (n < 8)
+  {
+    while (!done)
+    {
+      xReadFlag( bit );
+      if ( bit )
+      {
+        xReadCode( n-4, cw );
+        done = 1;
+      }
+      else
+      {
+        zeroes++;
+      }
+    }
+    val = (zeroes<<(n-4))+cw;
+  }
+  else if (n == 8)
+  {
+    if ( xGetBit() )
+    {
+      val = 0;
+    }
+    else if ( xGetBit() )
+    {
+      val = 1;
+    }
+    else
+    {
+      val = 2;
+    }
+  }
+  else if (n == 9)
+  {
+    if ( xGetBit() )
+    {
+      if ( xGetBit() )
+      {
+        xReadCode(3, val);
+        val += 3;
+      }
+      else if ( xGetBit() )
+      {
+        val = xGetBit() + 1;
+      }
+      else
+      {
+        val = 0;
+      }
+    }
+    else
+    {
+      while (!done)
+      {
+        xReadFlag( bit );
+        if ( bit )
+        {
+          xReadCode(4, cw);
+          done = 1;
+        }
+        else
+        {
+          zeroes++;
+        }
+      }
+      val = (zeroes<<4)+cw+11;
+    }
+  }
+  else if (n == 10)
+  {
+    while (!done)
+    {
+      xReadFlag( first );
+      if ( !first )
+      {
+        lead++;
+      }
+      else
+      {
+        if ( !lead )
+        {
+          val = 0;
+        }
+        else
+        {
+          xReadCode(lead, val);
+          val += (1<<lead);
+          val--;
+        }
+        done = 1;
+      }
+    }
+  }
+  else if (n == 11)
+  {
+    UInt code;
+    xReadCode(3, val);
+    if(val)
+    {
+      xReadCode(1, code);
+      val = (val<<1)|code;
+      val--;
+    }
+  }
+#if CAVLC_COEF_LRG_BLK
+  else if (n == 12)
+  {
+    while (!done)
+    {
+      m_pcBitstream->pseudoRead(32,val);
+      if (val)
+      {
+        tmp = 31;
+        while(!done)
+        {
+          if( val>>tmp )
+          {
+            xReadCode(32-tmp, val);
+            lead += 31-tmp;
+            xReadCode(6, val);
+            val += (lead<<6);
+            done = 1;
+          }
+          tmp--;
+        }
+      }
+      else
+      {
+        xReadCode(32, val);
+        lead += 32;
+      }
+    }
+  }
+  else if (n == 13)
+  {
+    while (!done)
+    {
+      m_pcBitstream->pseudoRead(32,val);
+      if (val)
+      {
+        tmp = 31;
+        while(!done)
+        {
+          if(val>>tmp)
+          {
+            xReadCode(32-tmp, cw);
+            zeroes += 31-tmp;
+            xReadCode(4, cw);
+            done = 1;
+          }
+          tmp--;
+        }
+      }
+      else
+      {
+        xReadCode(32, val);
+        zeroes += 32;
+      }
+    }
+    val = (zeroes<<4)+cw;
+  }
+#endif
+
+  return val;
+}
+
+#if !CAVLC_COEF_LRG_BLK
+Void TDecCavlc::xParseCoeff4x4( TCoeff* scoeff, Int n )
+{
+  Int i;
+  UInt sign;
+  Int tmp;
+  Int vlc,cn,this_pos;
+  Int maxrun;
+  Int last_position;
+  Int atable[5] = {4,6,14,28,0xfffffff};
+  Int vlc_adaptive=0;
+  Int done;
+  LastCoeffStruct combo;
+
+#if QC_MOD_LCEC
+  Int nTab;
+  Int tr1;
+  nTab=max(0,n-2);
+#endif
+
+  for (i = 0; i < 16; i++)
+  {
+    scoeff[i] = 0;
+  }
+
+  {
+    /* Get the last nonzero coeff */
+    Int x,y,cx,cy,vlcNum;
+    Int vlcTable[8] = {2,2,2};
+
+    /* Decode according to current LP table */
+#if QC_MOD_LCEC
+    vlcNum = vlcTable[nTab];
+    tmp = xReadVlc( vlcNum );
+    cn = m_uiLPTableD4[nTab][tmp];
+#else
+    vlcNum = vlcTable[n];
+
+    tmp = xReadVlc( vlcNum );
+    cn = m_uiLPTableD4[n][tmp];
+#endif
+    combo.level = (cn>15);
+    combo.last_pos = cn&0x0f;
+
+    /* Adapt LP table */
+    cx = tmp;
+    cy = Max( 0, cx-1 );
+    x = cn;
+#if QC_MOD_LCEC
+    y = m_uiLPTableD4[nTab][cy];
+    m_uiLPTableD4[nTab][cy] = x;
+    m_uiLPTableD4[nTab][cx] = y;
+#else
+    y = m_uiLPTableD4[n][cy];
+    m_uiLPTableD4[n][cy] = x;
+    m_uiLPTableD4[n][cx] = y;
+#endif
+  }
+
+  if ( combo.level == 1 )
+  {
+    tmp = xReadVlc( 0 );
+    sign = tmp&1;
+    tmp = (tmp>>1)+2;
+  }
+  else
+  {
+    tmp = 1;
+    xReadFlag( sign );
+  }
+
+#if QC_MOD_LCEC
+  if (tmp>1)
+  {
+    tr1=0;
+  }
+  else
+  {
+    tr1=1;
+  }
+#endif
+
+  if ( sign )
+  {
+    tmp = -tmp;
+  }
+
+  last_position = combo.last_pos;
+  this_pos = 15 - last_position;
+  scoeff[this_pos] = tmp;
+  i = this_pos;
+  i++;
+
+  done = 0;
+  {
+    while (!done && i < 16)
+    {
+      maxrun = 15-i;
+#if QC_MOD_LCEC
+      if(n==2)
+        vlc = g_auiVlcTable8x8Intra[maxrun];
+      else
+        vlc = g_auiVlcTable8x8Inter[maxrun];
+#else
+      if (maxrun > 27)
+      {
+        maxrun = 28;
+        vlc = 3;
+      }
+      else
+      {
+        vlc = g_auiVlcTable8x8[maxrun];
+      }
+#endif
+
+      /* Go into run mode */
+      cn = xReadVlc( vlc );
+#if QC_MOD_LCEC
+      if(n==2)
+      {
+        xRunLevelIndInv(&combo, maxrun, g_auiLumaRunTr14x4[tr1][maxrun], cn);
+      }
+      else
+#endif
+      {
+#if RUNLEVEL_TABLE_CUT
+        xRunLevelIndInterInv(&combo, maxrun, cn);
+#else
+        combo = g_acstructLumaRun8x8[maxrun][cn];
+#endif
+      }
+      i += combo.last_pos;
+      /* No sign for last zeroes */
+      if (i < 16)
+      {
+        if (combo.level == 1)
+        {
+          tmp = xReadVlc( 0 );
+          sign = tmp&1;
+          tmp = (tmp>>1)+2;
+          done = 1;
+        }
+        else
+        {
+          tmp = 1;
+          xReadFlag( sign );
+        }
+        if ( sign )
+        {
+          tmp = -tmp;
+        }
+        scoeff[i] = tmp;
+      }
+      i++;
+#if QC_MOD_LCEC
+      if (tr1>0 && tr1<MAX_TR1)
+      {
+        tr1++;
+      }
+#endif
+    }
+  }
+  if (i < 16)
+  {
+    /* Get the rest in level mode */
+    while ( i < 16 )
+    {
+      tmp = xReadVlc( vlc_adaptive );
+      if ( tmp > atable[vlc_adaptive] )
+      {
+        vlc_adaptive++;
+      }
+      if ( tmp )
+      {
+        xReadFlag( sign );
+        if ( sign )
+        {
+          tmp = -tmp;
+        }
+      }
+      scoeff[i] = tmp;
+      i++;
+    }
+  }
+
+  return;
+}
+#endif
+
+#if QC_MOD_LCEC
+
+Void TDecCavlc::xRunLevelIndInv(LastCoeffStruct *combo, Int maxrun, UInt lrg1Pos, UInt cn)
+{
+  int lev, run;
+  if (lrg1Pos>0)
+  {
+    if(cn < min(lrg1Pos, maxrun+2))
+    {
+      lev = 0;
+      run = cn;
+    }
+    else if(cn < (maxrun<<1) + 4 - (Int)lrg1Pos)
+    {
+      if((cn+lrg1Pos)&1)
+      {
+        lev = 0;
+        run = (cn + lrg1Pos - 1) >> 1;
+      }
+      else
+      {
+        lev = 1;
+        run = (cn - lrg1Pos)>>1;
+      }
+    }
+    else
+    {
+      lev = 1;
+      run = cn - maxrun - 2;
+    }
+  }
+  else
+  {
+    if( cn & 1 )
+    {
+      lev = 0; run = (cn-1)>>1;
+    }
+    else
+    {
+      run = cn >> 1;
+      lev = (run <= maxrun)?1:0;
+    }
+  }
+  combo->level = lev;
+  combo->last_pos = run;
+}
+
+#if RUNLEVEL_TABLE_CUT
+/** Function for deriving run and level value in CAVLC run-level coding
+ * \param combo pointer to a struct of run and level
+ * \param maxrun maximum length of run for a given coefficient location
+ * \param cn codeword index
+ * \returns
+ * This function derives run and level value in CAVLC run-level coding based on codeword index and maximum run value.
+ */
+Void TDecCavlc::xRunLevelIndInterInv(LastCoeffStruct *combo, Int maxrun, UInt cn)
+{
+  if (maxrun<28)
+  {
+    if(cn > maxrun+1)
+    {
+      combo->level = 1;
+      combo->last_pos = g_acstructLumaRun8x8[maxrun][cn-maxrun-1];
+    }
+    else
+    {
+      combo->level = 0;
+      combo->last_pos = g_acstructLumaRun8x8[maxrun][cn];
+    }
+  }
+  else
+  {
+    if(cn<maxrun+2)
+    {
+      combo->level = 0;
+      combo->last_pos = cn;
+    }
+    else
+    {
+      combo->level = 1;
+      combo->last_pos = cn-maxrun-2;
+    }
+  }
+}
+#endif
+#endif
+
+
+#if !CAVLC_COEF_LRG_BLK
+Void TDecCavlc::xParseCoeff8x8(TCoeff* scoeff, int n)
+{
+  Int i;
+  UInt sign;
+  Int tmp;
+  LastCoeffStruct combo;
+  Int vlc,cn,this_pos;
+  Int maxrun;
+  Int last_position;
+  Int atable[5] = {4,6,14,28,0xfffffff};
+  Int vlc_adaptive=0;
+  Int done;
+#if QC_MOD_LCEC
+  Int tr1;
+#endif
+
+  static const Int switch_thr[10] = {49,49,0,49,49,0,49,49,49,49};
+  Int sum_big_coef = 0;
+
+  for (i = 0; i < 64; i++)
+  {
+    scoeff[i] = 0;
+  }
+
+  /* Get the last nonzero coeff */
+  {
+    Int x,y,cx,cy,vlcNum;
+
+    /* Decode according to current LP table */
+    // ADAPT_VLC_NUM
+    vlcNum = g_auiLastPosVlcNum[n][Min(16,m_uiLastPosVlcIndex[n])];
+    tmp = xReadVlc( vlcNum );
+    cn = m_uiLPTableD8[n][tmp];
+    combo.level = (cn>63);
+    combo.last_pos = cn&0x3f;
+
+    /* Adapt LP table */
+    cx = tmp;
+    cy = Max(0,cx-1);
+    x = cn;
+    y = m_uiLPTableD8[n][cy];
+    m_uiLPTableD8[n][cy] = x;
+    m_uiLPTableD8[n][cx] = y;
+
+    // ADAPT_VLC_NUM
+    m_uiLastPosVlcIndex[n] += cx == m_uiLastPosVlcIndex[n] ? 0 : (cx < m_uiLastPosVlcIndex[n] ? -1 : 1);
+  }
+
+  if (combo.level == 1)
+  {
+    tmp = xReadVlc( 0 );
+    sign = tmp&1;
+    tmp = (tmp>>1)+2;
+  }
+  else
+  {
+    tmp = 1;
+    xReadFlag( sign );
+  }
+
+#if QC_MOD_LCEC
+  if (tmp>1)
+  {
+    tr1=0;
+  }
+  else
+  {
+    tr1=1;
+  }
+#endif
+
+  if ( sign )
+  {
+    tmp = -tmp;
+  }
+
+  last_position = combo.last_pos;
+  this_pos = 63 - last_position;
+  scoeff[this_pos] = tmp;
+  i = this_pos;
+  i++;
+
+  done = 0;
+  {
+    while (!done && i < 64)
+    {
+      maxrun = 63-i;
+#if QC_MOD_LCEC
+      if (n == 2 || n == 5)
+        vlc = g_auiVlcTable8x8Intra[Min(maxrun,28)];
+      else
+        vlc = g_auiVlcTable8x8Inter[Min(maxrun,28)];
+#else
+      if (maxrun > 27)
+      {
+        maxrun = 28;
+        vlc = 3;
+      }
+      else
+      {
+        vlc = g_auiVlcTable8x8[maxrun];
+      }
+#endif
+
+      /* Go into run mode */
+      cn = xReadVlc( vlc );
+#if QC_MOD_LCEC
+      if (n == 2 || n == 5)
+        xRunLevelIndInv(&combo, maxrun, g_auiLumaRunTr18x8[tr1][min(maxrun,28)], cn);
+      else
+#if RUNLEVEL_TABLE_CUT
+        xRunLevelIndInterInv(&combo, maxrun, cn);
+#else
+        combo = g_acstructLumaRun8x8[Min(maxrun,28)][cn];
+#endif
+#else
+      combo = g_acstructLumaRun8x8[maxrun][cn];
+#endif
+      i += combo.last_pos;
+      /* No sign for last zeroes */
+      if (i < 64)
+      {
+        if (combo.level == 1)
+        {
+          tmp = xReadVlc( 0 );
+          sign = tmp&1;
+          tmp = (tmp>>1)+2;
+
+          sum_big_coef += tmp;
+          if (i > switch_thr[n] || sum_big_coef > 2)
+          {
+            done = 1;
+          }
+        }
+        else
+        {
+          tmp = 1;
+          xReadFlag( sign );
+        }
+        if ( sign )
+        {
+          tmp = -tmp;
+        }
+        scoeff[i] = tmp;
+      }
+      i++;
+#if QC_MOD_LCEC
+      if (tr1==0 || combo.level != 0)
+      {
+        tr1=0;
+      }
+      else if( tr1 < MAX_TR1)
+      {
+        tr1++;
+      }
+#endif
+    }
+  }
+  if (i < 64)
+  {
+    /* Get the rest in level mode */
+    while (i<64)
+    {
+      tmp = xReadVlc( vlc_adaptive );
+
+      if (tmp>atable[vlc_adaptive])
+      {
+        vlc_adaptive++;
+      }
+      if (tmp)
+      {
+        xReadFlag( sign );
+        if ( sign )
+        {
+          tmp = -tmp;
+        }
+      }
+      scoeff[i] = tmp;
+      i++;
+    }
+  }
+  return;
+}
+#endif
+
+
+#if CAVLC_COEF_LRG_BLK
+/** Function for parsing a block of transform coeffcients in CAVLC.
+ * \param scoeff pointer to transform coefficient buffer
+ * \param n block type information, e.g. luma, chroma, intra, inter, etc.
+ * \param blSize block size
+ * \returns
+ * This function performs parsing for a block of transform coefficient in CAVLC.
+ */
+Void TDecCavlc::xParseCoeff(TCoeff* scoeff, int n, Int blSize)
+{
+  static const Int switch_thr[10] = {49,49,0,49,49,0,49,49,49,49};
+  Int i, noCoeff=blSize*blSize;;
+  UInt sign;
+  LastCoeffStruct combo;
+  Int cn, maxrun, tmprun;
+  Int atable[5] = {4,6,14,28,0xfffffff};
+  Int done, tr1, tmp;
+  Int sum_big_coef = 0;
+
+  memset(scoeff,0,sizeof(TCoeff)*noCoeff);
+
+  /* Get the last nonzero coeff */
+  if(blSize >=8 )
+  {
+    /* Decode according to current LP table */
+    // ADAPT_VLC_NUM
+    tmp = g_auiLastPosVlcNum[n][Min(16,m_uiLastPosVlcIndex[n])];
+    cn = xReadVlc( tmp );
+    xLastLevelIndInv(combo.level, combo.last_pos, blSize, cn);
+
+    /* Adapt LP table */
+    cn = (blSize==8)?cn:(cn>>2);
+    // ADAPT_VLC_NUM
+    m_uiLastPosVlcIndex[n] += cn == m_uiLastPosVlcIndex[n] ? 0 : (cn < m_uiLastPosVlcIndex[n] ? -1 : 1);
+  }
+  else
+  {
+    /* Get the last nonzero coeff */
+    Int y,cy;
+    Int nTab = max(0,n-2);
+
+    /* Decode according to current LP table */
+    tmp = xReadVlc( 2 );
+    cn = m_uiLPTableD4[nTab][tmp];
+    combo.level = (cn>15)?1:0;
+    combo.last_pos = cn&0x0f;
+
+    /* Adapt LP table */
+    cy = Max( 0, tmp-1 );
+    y = m_uiLPTableD4[nTab][cy];
+    m_uiLPTableD4[nTab][cy] = cn;
+    m_uiLPTableD4[nTab][tmp] = y;
+  }
+
+  if (combo.level == 1)
+  {
+    tmp = xReadVlc( 0 );
+    sign = tmp&1;
+    tmp = (tmp>>1)+2;
+    tr1=0;
+  }
+  else
+  {
+    tmp = 1;
+    xReadFlag( sign );
+    tr1=1;
+  }
+
+  i = noCoeff - 1 - combo.last_pos;
+  scoeff[i++] = sign? -tmp:tmp;
+
+  done = 0;
+  const UInt *vlcTable = (n == 2||n == 5)? ((blSize<=8)? g_auiVlcTable8x8Intra:g_auiVlcTable16x16Intra):
+    ((blSize<=8)? g_auiVlcTable8x8Inter:g_auiVlcTable16x16Inter);
+  const UInt **pLumaRunTr1 = (blSize==4)? g_pLumaRunTr14x4:g_pLumaRunTr18x8;
+  while (!done && i < noCoeff)
+  {
+    maxrun = noCoeff - 1 -i;
+    tmprun = min(maxrun,28);
+    tmp = vlcTable[tmprun];
+
+    /* Go into run mode */
+    cn = xReadVlc( tmp );
+    if (n == 2 || n == 5)
+    {
+      xRunLevelIndInv(&combo, maxrun, pLumaRunTr1[tr1][tmprun], cn);
+    }
+    else
+    {
+      xRunLevelIndInterInv(&combo, maxrun, cn);
+    }
+
+    i += combo.last_pos;
+    if (i < noCoeff)
+    {
+      if (combo.level == 1)
+      {
+        tmp = xReadVlc( 0 );
+        sign = tmp&1;
+        tmp = (tmp>>1)+2;
+
+        sum_big_coef += tmp;
+        if (blSize==4 ||i > switch_thr[n] || sum_big_coef > 2)
+        {
+          done = 1;
+        }
+      }
+      else
+      {
+        tmp = 1;
+        xReadFlag( sign );
+      }
+      scoeff[i++] = sign? -tmp:tmp;
+    }
+
+    if (tr1==0 || combo.level != 0)
+    {
+      tr1=0;
+    }
+    else if( tr1 < MAX_TR1)
+    {
+      tr1++;
+    }
+  }
+
+  if (i < noCoeff)
+  {
+    /* Get the rest in level mode */
+    Int vlc_adaptive = 0;
+    while (i < noCoeff)
+    {
+      tmp = xReadVlc( vlc_adaptive );
+
+      if (tmp)
+      {
+        xReadFlag( sign );
+        scoeff[i] = sign?-tmp:tmp;
+        if (tmp > atable[vlc_adaptive])
+        {
+          vlc_adaptive++;
+        }
+      }
+      i++;
+    }
+  }
+
+  return;
+}
+
+#endif
+
+#ifdef WEIGHT_PRED
+Void TDecCavlc::parseWeightPredTable( TComSlice* pcSlice )
+{
+  wpScalingParam  *wp;
+  Bool            bChroma     = true; // color always present in HEVC ?
+  TComPPS*        pps         = pcSlice->getPPS();
+  SliceType       eSliceType  = pcSlice->getSliceType();
+  Int             nbRef       = (eSliceType == B_SLICE ) ? (2) : (1);
+  UInt            uiLog2WeightDenomLuma, uiLog2WeightDenomChroma;
+  UInt            uiMode      = 0;
+
+  if ( (eSliceType==P_SLICE && pps->getUseWP()) || (eSliceType==B_SLICE && pps->getWPBiPredIdc()==1) )
+    uiMode = 1;
+  else if ( eSliceType==B_SLICE && pps->getWPBiPredIdc()==2 )
+    uiMode = 2;
+
+  if ( uiMode == 1 )  // explicit
+  {
+    printf("\nTDecCavlc::parseWeightPredTable(poc=%d) explicit...\n", pcSlice->getPOC());
+
+    // decode luma_log2_weight_denom :
+    xReadUvlc( uiLog2WeightDenomLuma );     // ue(v): luma_log2_weight_denom
+    if( bChroma ) {                         // color always present in HEVC ?
+      xReadUvlc( uiLog2WeightDenomChroma ); // ue(v): chroma_log2_weight_denom
+    }
+
+    for ( Int numRef=0 ; numRef<nbRef ; numRef++ ) {
+      RefPicList  eRefPicList = ( numRef ? 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;
+        xReadFlag( uiCode );           // u(1): luma_weight_l0_flag
+        wp[0].bPresentFlag = ( uiCode == 1 );
+        if ( wp[0].bPresentFlag ) {
+          xReadSvlc( wp[0].iWeight ); // se(v): luma_weight_l0[i]
+          xReadSvlc( wp[0].iOffset ); // se(v): luma_offset_l0[i]
+        }
+        else {
+          wp[0].iWeight = (1 << wp[0].uiLog2WeightDenom);
+          wp[0].iOffset = 0;
+        }
+        if ( bChroma ) {
+          xReadFlag( uiCode );           // 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++ ) {
+              xReadSvlc( wp[j].iWeight ); // se(v): chroma_weight_l0[i][j]
+              xReadSvlc( wp[j].iOffset ); // se(v): chroma_offset_l0[i][j]
+            }
+          }
+          else {
+            for ( Int j=1 ; j<3 ; j++ ) {
+              wp[j].iWeight = (1 << wp[j].uiLog2WeightDenom);
+              wp[j].iOffset = 0;
+            }
+          }
+        }
+      }
+
+      // Just for displayWpScaling():
+      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::parseWeightPredTable(poc=%d) implicit...\n", pcSlice->getPOC());
+  }
+  else
+    assert(0);
+}
+#endif
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 19)
@@ -0,0 +1,236 @@
+/* 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     TDecCAVLC.h
+    \brief    CAVLC decoder class (header)
+*/
+
+#ifndef __TDECCAVLC__
+#define __TDECCAVLC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TDecEntropy.h"
+
+// ====================================================================================================================
+// 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 );
+  
+  UInt  xGetBit             ();
+  Int   xReadVlc            ( Int n );
+#if CAVLC_COEF_LRG_BLK
+  Void  xParseCoeff         ( TCoeff* scoeff, Int iTableNumber, Int blSize);
+#else
+  Void  xParseCoeff4x4      ( TCoeff* scoeff, Int iTableNumber );
+  Void  xParseCoeff8x8      ( TCoeff* scoeff, Int iTableNumber );
+#endif
+#if QC_MOD_LCEC
+  Void  xRunLevelIndInv     (LastCoeffStruct *combo, Int maxrun, UInt lrg1Pos, UInt cn);
+#if RUNLEVEL_TABLE_CUT
+  Void  xRunLevelIndInterInv(LastCoeffStruct *combo, Int maxrun, UInt cn);
+#endif
+#endif
+  
+private:
+  TComBitstream*        m_pcBitstream;
+  UInt                  m_uiCoeffCost;
+  Bool                  m_bRunLengthCoding;
+  UInt                  m_uiRun;
+  Bool m_bAlfCtrl;
+  UInt m_uiMaxAlfCtrlDepth;
+  UInt                      m_uiLPTableD4[3][32];
+#if !CAVLC_COEF_LRG_BLK
+  UInt                      m_uiLPTableD8[10][128];
+#endif
+  UInt                      m_uiLastPosVlcIndex[10];
+  
+#if LCEC_INTRA_MODE
+#if MTK_DCM_MPM
+  UInt                      m_uiIntraModeTableD17[2][16];
+  UInt                      m_uiIntraModeTableD34[2][33];
+#else
+  UInt                      m_uiIntraModeTableD17[16];
+  UInt                      m_uiIntraModeTableD34[33];
+#endif
+#endif
+#if QC_LCEC_INTER_MODE
+  UInt                      m_uiSplitTableD[4][7];
+#endif
+#if CAVLC_RQT_CBP
+  UInt                      m_uiCBP_YUV_TableD[4][8];
+  UInt                      m_uiCBP_YS_TableD[2][4];
+  UInt                      m_uiCBP_YCS_TableD[2][8];
+  UInt                      m_uiCBP_4Y_TableD[2][15];
+  UInt                      m_uiCBP_4Y_VlcIdx;
+#else
+  UInt                      m_uiBlkCBPTableD[2][15];
+  UInt                      m_uiCBPTableD[2][8];
+  UInt                      m_uiCbpVlcIdx[2];
+  UInt                      m_uiBlkCbpVlcIdx;
+#endif
+
+
+  
+  Int                   m_iRefFrame0[1000];
+  Int                   m_iRefFrame1[1000];
+  Bool                  m_bMVres0[1000];
+  Bool                  m_bMVres1[1000];
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  UInt                  m_uiMI1TableD[9];
+#else
+  UInt                  m_uiMI1TableD[8];
+#endif
+  UInt                  m_uiMI2TableD[15]; 
+  UInt                  m_uiMITableVlcIdx;
+
+#if CAVLC_COUNTER_ADAPT
+#if CAVLC_RQT_CBP
+  UChar         m_ucCBP_YUV_TableCounter[4][4];
+  UChar         m_ucCBP_4Y_TableCounter[2][2];
+  UChar         m_ucCBP_YS_TableCounter[2][3];
+  UChar         m_ucCBP_YCS_TableCounter[2][4];
+  UChar         m_ucCBP_YUV_TableCounterSum[4];
+  UChar         m_ucCBP_4Y_TableCounterSum[2];
+  UChar         m_ucCBP_YS_TableCounterSum[2];
+  UChar         m_ucCBP_YCS_TableCounterSum[2];
+#else
+  UChar         m_ucCBFTableCounter    [2][4];
+  UChar         m_ucBlkCBPTableCounter [2][2];
+  UChar         m_ucCBFTableCounterSum[2];
+  UChar         m_ucBlkCBPTableCounterSum[2];
+#endif
+
+  UChar         m_ucMI1TableCounter[4];
+  UChar         m_ucSplitTableCounter[4][4];
+  UChar         m_ucSplitTableCounterSum[4];
+  UChar         m_ucMI1TableCounterSum;
+#endif
+
+  Int**    m_aaiTempScale;
+  Int**    m_aaiTempOffset;
+  Int**    m_aaiTempPdmScaleNomDelta;
+  Int**    m_aaiTempPdmOffset;
+  
+public:
+  Void  resetEntropy        ( TComSlice* pcSlice  );
+  Void  setBitstream        ( TComBitstream* p    )      { m_pcBitstream = p; }
+  Void  setAlfCtrl          ( Bool bAlfCtrl )            { m_bAlfCtrl = bAlfCtrl; }
+  Void  setMaxAlfCtrlDepth  ( UInt uiMaxAlfCtrlDepth )  { m_uiMaxAlfCtrlDepth = uiMaxAlfCtrlDepth; }
+  
+  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  parseAlfFlag        ( UInt& ruiVal );
+  Void  parseAlfUvlc        ( UInt& ruiVal );
+  Void  parseAlfSvlc        ( Int&  riVal  );
+#if MTK_SAO
+  Void  parseAoFlag        ( UInt& ruiVal );
+  Void  parseAoUvlc        ( UInt& ruiVal );
+  Void  parseAoSvlc        ( Int&  riVal  );
+#endif
+  
+  Void  parseNalUnitHeader  ( NalUnitType& eNalUnitType, UInt& TemporalId, Bool& bOutputFlag );
+  
+  Void  parseSPS            ( TComSPS* pcSPS );
+  Void  parsePPS            ( TComPPS* pcPPS);
+  void parseSEI(SEImessages&);
+  Void  parseSliceHeader    ( TComSlice*& rpcSlice );
+  Void  parseTerminatingBit ( UInt& ruiBit );
+  
+  Void  parseMVPIdx         ( TComDataCU* pcCU, Int& riMVPIdx, Int iMVPNum, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  
+  Void  parseSkipFlag       ( 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 HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+  Void parseMergeIndexMV    ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void parseResPredFlag     ( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth );
+  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 );
+#if CAVLC_RQT_CBP
+  Void parseCbfTrdiv        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiTrDepth, UInt uiDepth, UInt& uiSubdiv );
+  UInt xGetFlagPattern      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth,  UInt& uiSubdiv );
+#endif
+  Void parseCbf             ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void parseBlockCbf        ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth, UInt uiQPartNum );
+  Void parseCoeffNxN        ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  
+  Void parseAlfCtrlDepth    ( UInt& ruiAlfCtrlDepth );
+  Void parseAlfCtrlFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if TSB_ALF_HEADER
+  Void parseAlfFlagNum      ( UInt& ruiVal, UInt minValue, UInt depth );
+  Void parseAlfCtrlFlag     ( UInt &ruiAlfCtrlFlag );
+#endif
+
+#ifdef WEIGHT_PRED
+  Void parseWeightPredTable ( TComSlice* pcSlice );
+#endif
+
+  Void parseViewIdx         (Int& riViewIdx) ;
+};
+#endif // !defined(AFX_TDECCAVLC_H__9732DD64_59B0_4A41_B29E_1A5B18821EAD__INCLUDED_)
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecCu.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecCu.cpp	(revision 19)
@@ -0,0 +1,980 @@
+/* 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     TDecCu.cpp
+    \brief    CU decoder class
+*/
+
+#include "TDecCu.h"
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCu::TDecCu()
+{
+  m_ppcYuvResi    = NULL;
+  m_ppcYuvReco    = NULL;
+  m_ppcYuvResPred = NULL;
+  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];
+  m_ppcYuvResPred = new TComYuv*    [m_uiMaxDepth-1];
+  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 );
+    m_ppcYuvResPred[ui] = new TComYuv;    m_ppcYuvResPred[ui]->create( uiWidth, uiHeight );
+    m_ppcCU        [ui] = new TComDataCU; m_ppcCU        [ui]->create( uiNumPartitions, uiWidth, uiHeight, true );
+  }
+  
+  // 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 );
+}
+
+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;
+    m_ppcYuvResPred[ui]->destroy(); delete m_ppcYuvResPred[ui]; m_ppcYuvResPred[ui] = NULL;
+    m_ppcCU        [ui]->destroy(); delete m_ppcCU        [ui]; m_ppcCU        [ui] = NULL;
+  }
+  
+  delete [] m_ppcYuvResi;    m_ppcYuvResi    = NULL;
+  delete [] m_ppcYuvReco;    m_ppcYuvReco    = NULL;
+  delete [] m_ppcYuvResPred; m_ppcYuvResPred = NULL;
+  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 SNY_DQP   
+  if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+  {
+    pcCU->setdQPFlag(true); 
+  }
+#endif//SNY_DQP
+  // start from the top level CU
+  xDecodeCU( pcCU, 0, 0 );
+  
+#if SNY_DQP 
+  // dQP: only for LCU
+  if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+  {
+    if ( pcCU->isSkipped( 0 ) && pcCU->getDepth( 0 ) == 0 )
+    {
+    }
+    else if ( pcCU->getdQPFlag())// non-skip
+    {
+      m_pcEntropyDecoder->decodeQP( pcCU, 0, 0 );
+      pcCU->setdQPFlag(false);
+    }
+  }
+#else
+  // dQP: only for LCU
+  if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+  {
+    if ( pcCU->isSkipped( 0 ) && pcCU->getDepth( 0 ) == 0 )
+    {
+    }
+    else
+    {
+      m_pcEntropyDecoder->decodeQP( pcCU, 0, 0 );
+    }
+  }
+#endif//SNY_DQP
+  
+  //--- Read terminating bit ---
+  m_pcEntropyDecoder->decodeTerminatingBit( ruiIsLast );
+}
+
+/** \param    pcCU        pointer of CU data
+ */
+Void TDecCu::decompressCU( TComDataCU* pcCU )
+{
+  xDecompressCU( pcCU, pcCU, 0,  0 );
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/** decode CU block recursively
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth 
+ * \returns Void
+ */
+Void TDecCu::xDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  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()->getWidth() ) && ( uiBPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+  {
+#if HHI_MPI
+    if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 || uiDepth < pcCU->getTextureModeDepth( uiAbsPartIdx ) )
+#endif
+      m_pcEntropyDecoder->decodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+        xDecodeCU( pcCU, uiIdx, uiDepth+1 );
+      
+      uiIdx += uiQNumParts;
+    }
+    
+    return;
+  }
+  
+#if TSB_ALF_HEADER
+#else
+  m_pcEntropyDecoder->decodeAlfCtrlFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+  
+  // decode CU mode and the partition size
+#if HHI_MPI
+  if( !pcCU->getSlice()->isIntra() && pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 )
+#else
+  if( !pcCU->getSlice()->isIntra() )
+#endif
+  {
+    m_pcEntropyDecoder->decodeSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  
+
+  if( pcCU->isSkipped(uiAbsPartIdx) )
+  {
+#if HHI_MRG_SKIP
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+    UInt uiNeighbourCandIdx[MRG_MAX_NUM_CANDS]; //MVs with same idx => same cand
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+    {
+      uhInterDirNeighbours[ui] = 0;
+      uiNeighbourCandIdx[ui] = 0;
+    }
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, uiNeighbourCandIdx );
+    for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+  {
+      pcCU->setNeighbourCandIdxSubParts( uiIter, uiNeighbourCandIdx[uiIter], uiAbsPartIdx, 0, uiDepth );
+    }
+    m_pcEntropyDecoder->decodeMergeIndex( pcCU, 0, uiAbsPartIdx, SIZE_2Nx2N, uhInterDirNeighbours, cMvFieldNeighbours, uiDepth );
+#else
+    pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_0, uiAbsPartIdx, 0, uiDepth);
+    pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_0, uiAbsPartIdx, 0, uiDepth);
+    
+    pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_1, uiAbsPartIdx, 0, uiDepth);
+    pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_1, uiAbsPartIdx, 0, uiDepth);
+    
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 ) //if ( ref. frame list0 has at least 1 entry )
+    {
+      m_pcEntropyDecoder->decodeMVPIdx( pcCU, uiAbsPartIdx, uiDepth, REF_PIC_LIST_0, m_ppcCU[uiDepth]);
+    }
+    
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 ) //if ( ref. frame list1 has at least 1 entry )
+    {
+      m_pcEntropyDecoder->decodeMVPIdx( pcCU, uiAbsPartIdx, uiDepth, REF_PIC_LIST_1, m_ppcCU[uiDepth]);
+    }
+#endif
+#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( uiDepth, pcTextureCU->getDepth( uiAbsPartIdx + ui ) );
+        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 );
+      }
+    }
+#endif
+ 
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    m_pcEntropyDecoder->decodeResPredFlag( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth], 0 );
+#endif
+    return;
+  }
+
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 )
+  {
+#endif
+    m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );
+
+    m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+
+    // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
+    m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
+
+#if HHI_MPI
+    if( !pcCU->isIntra( uiAbsPartIdx ) )
+    {
+      m_ppcCU[uiDepth]  ->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+      m_ppcCU[uiDepth]  ->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      m_pcEntropyDecoder->decodeResPredFlag    ( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth], 0 );
+#endif
+    }
+
+    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( uiDepth, pcTextureCU->getDepth( uiAbsPartIdx + ui ) );
+        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( ( ( 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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+            xDecodeCU( pcCU, uiIdx, uiDepth+1 );
+
+          uiIdx += uiQNumParts;
+        }
+        return;
+      }
+    }
+  }
+#endif
+
+  UInt uiCurrWidth      = pcCU->getWidth ( uiAbsPartIdx );
+  UInt uiCurrHeight     = pcCU->getHeight( uiAbsPartIdx );
+  
+  // Coefficient decoding
+  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, uiCurrWidth, uiCurrHeight );
+  
+}
+
+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;
+  
+  if( ( uiRPelX >= pcCU->getSlice()->getSPS()->getWidth() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() ) )
+  {
+    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] ];
+      
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+        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:
+      xReconIntraQT( m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth );
+      break;
+    default:
+      assert(0);
+      break;
+  }
+  
+  xCopyToPic( m_ppcCU[uiDepth], pcPic, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecCu::xReconInter( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( 0 ) != -1 )
+    pcCU->setPartSizeSubParts( SIZE_NxN, 0, uiDepth );
+#endif
+  
+  // inter prediction
+  m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth] );
+  
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( 0 ) != -1 )
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+#endif
+  
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  if( pcCU->getResPredFlag( 0 ) )
+  {
+    AOF( pcCU->getResPredAvail( 0 ) );
+    Bool bOK = pcCU->getResidualSamples( 0, m_ppcYuvResPred[uiDepth] );
+    AOF( bOK );
+    m_ppcYuvReco[uiDepth]->add( m_ppcYuvResPred[uiDepth], pcCU->getWidth( 0 ), pcCU->getHeight( 0 ) );
+  }
+#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 HHI_INTER_VIEW_RESIDUAL_PRED
+    if( pcCU->getResPredFlag( 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::xDecodeIntraTexture( TComDataCU* pcCU, UInt uiPartIdx, Pel* piReco, Pel* piPred, Pel* piResi, UInt uiStride, TCoeff* pCoeff, UInt uiWidth, UInt uiHeight, UInt uiCurrDepth )
+{
+  if( pcCU->getTransformIdx(0) == uiCurrDepth )
+  {
+    UInt uiX, uiY;
+    TComPattern* pcPattern = pcCU->getPattern();
+    UInt uiZorder          = pcCU->getZorderIdxInCU()+uiPartIdx;
+    Pel* pPred             = piPred;
+    Pel* pResi             = piResi;
+    Pel* piPicReco         = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), uiZorder);
+    UInt uiPicStride       = pcCU->getPic()->getPicYuvRec()->getStride();
+    
+    pcPattern->initPattern( pcCU, uiCurrDepth, uiPartIdx );
+    
+    Bool bAboveAvail = false;
+    Bool bLeftAvail  = false;
+    
+    pcPattern->initAdiPattern(pcCU, uiPartIdx, uiCurrDepth, m_pcPrediction->getPredicBuf(), m_pcPrediction->getPredicBufWidth(), m_pcPrediction->getPredicBufHeight(), bAboveAvail, bLeftAvail);
+    
+    m_pcPrediction->predIntraLumaAng( pcPattern, pcCU->getLumaIntraDir(uiPartIdx), pPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+    
+    m_pcTrQuant->setQPforQuant( pcCU->getQP(uiPartIdx), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_LUMA );
+#if INTRA_DST_TYPE_7
+  m_pcTrQuant->invtransformNxN(TEXT_LUMA, pcCU->getLumaIntraDir(uiPartIdx), pResi, uiStride, pCoeff, uiWidth, uiHeight );
+#else
+  m_pcTrQuant->invtransformNxN( pResi, uiStride, pCoeff, uiWidth, uiHeight );
+#endif
+    // Reconstruction
+    {
+      pResi = piResi;
+      pPred = piPred;
+      for( uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          piReco   [uiX] = Clip(pPred[uiX] + pResi[uiX]);
+          piPicReco[uiX] = piReco[uiX];
+        }
+        piReco    += uiStride;
+        pPred     += uiStride;
+        pResi     += uiStride;
+        piPicReco += uiPicStride;
+      }
+    }
+  }
+  else
+  {
+    uiCurrDepth++;
+    uiWidth  >>= 1;
+    uiHeight >>= 1;
+    UInt uiPartOffset  = pcCU->getTotalNumPart()>>(uiCurrDepth<<1);
+    UInt uiCoeffOffset = uiWidth  * uiHeight;
+    UInt uiPelOffset   = uiHeight * uiStride;
+    Pel* pResi = piResi;
+    Pel* pReco = piReco;
+    Pel* pPred = piPred;
+    xDecodeIntraTexture( pcCU, uiPartIdx, pReco, pPred, pResi, uiStride, pCoeff, uiWidth, uiHeight, uiCurrDepth );
+    uiPartIdx += uiPartOffset;
+    pCoeff    += uiCoeffOffset;
+    pResi      = piResi + uiWidth;
+    pReco      = piReco + uiWidth;
+    pPred      = piPred + uiWidth;
+    xDecodeIntraTexture( pcCU, uiPartIdx, pReco, pPred, pResi, uiStride, pCoeff, uiWidth, uiHeight, uiCurrDepth );
+    uiPartIdx += uiPartOffset;
+    pCoeff    += uiCoeffOffset;
+    pResi      = piResi + uiPelOffset;
+    pReco      = piReco + uiPelOffset;
+    pPred      = piPred + uiPelOffset;
+    xDecodeIntraTexture( pcCU, uiPartIdx, pReco, pPred, pResi, uiStride, pCoeff, uiWidth, uiHeight, uiCurrDepth );
+    uiPartIdx += uiPartOffset;
+    pCoeff    += uiCoeffOffset;
+    pResi      = piResi + uiPelOffset + uiWidth;
+    pReco      = piReco + uiPelOffset + uiWidth;
+    pPred      = piPred + uiPelOffset + uiWidth;
+    xDecodeIntraTexture( pcCU, uiPartIdx, pReco, pPred, pResi, uiStride, pCoeff, uiWidth, uiHeight, uiCurrDepth );
+  }
+}
+
+// ADI chroma
+Void TDecCu::xRecurIntraInvTransChroma(TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piResi, Pel* piPred, Pel* piReco, UInt uiStride, TCoeff* piCoeff, UInt uiWidth, UInt uiHeight, UInt uiTrMode, UInt uiCurrTrMode, TextType eText )
+{
+  if( uiTrMode == uiCurrTrMode )
+  {
+    UInt uiX, uiY;
+    UInt uiZorder    = pcCU->getZorderIdxInCU()+uiAbsPartIdx;
+    Pel* pResi       = piResi;
+    Pel* pPred       = piPred;
+    Pel* piPicReco;
+    if( eText == TEXT_CHROMA_U )
+      piPicReco= pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), uiZorder);
+    else
+      piPicReco= pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), uiZorder);
+    
+    UInt uiPicStride = pcCU->getPic()->getPicYuvRec()->getCStride();
+    
+    pcCU->getPattern()->initPattern( pcCU, uiCurrTrMode, uiAbsPartIdx );
+    
+    Bool bAboveAvail = false;
+    Bool bLeftAvail  = false;
+    
+    pcCU->getPattern()->initAdiPatternChroma(pcCU,uiAbsPartIdx, uiCurrTrMode, m_pcPrediction->getPredicBuf(),m_pcPrediction->getPredicBufWidth(),m_pcPrediction->getPredicBufHeight(),bAboveAvail,bLeftAvail);
+    
+    UInt uiModeL        = pcCU->getLumaIntraDir(0);
+    UInt uiMode         = pcCU->getChromaIntraDir(0);
+    
+    if (uiMode==4) uiMode = uiModeL;
+    
+    Int*   pPatChr;
+    
+    if (eText==TEXT_CHROMA_U)
+    {
+      pPatChr=  pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_pcPrediction->getPredicBuf() );
+    }
+    else // (eText==TEXT_CHROMA_V)
+    {
+      pPatChr=  pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_pcPrediction->getPredicBuf() );
+    }
+    
+    m_pcPrediction-> predIntraChromaAng( pcCU->getPattern(), pPatChr, uiMode, pPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+    
+    // Inverse Transform
+    if( pcCU->getCbf(0, eText, uiCurrTrMode) )
+    {
+#if INTRA_DST_TYPE_7
+    m_pcTrQuant->invtransformNxN( eText, REG_DCT, pResi, uiStride, piCoeff, uiWidth, uiHeight);
+#else
+    m_pcTrQuant->invtransformNxN( pResi, uiStride, piCoeff, uiWidth, uiHeight );
+#endif
+    }
+    pResi = piResi;
+    
+    for( uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        piReco   [uiX] = Clip( pPred[uiX] + pResi[uiX] );
+        piPicReco[uiX] = piReco[uiX];
+      }
+      
+      pPred     += uiStride;
+      pResi     += uiStride;
+      piReco    += uiStride;
+      piPicReco += uiPicStride;
+    }
+  }
+  else
+  {
+    uiCurrTrMode++;
+    uiWidth  >>= 1;
+    uiHeight >>= 1;
+    UInt uiCoeffOffset = uiWidth*uiHeight;
+    UInt uiPelOffset   = uiHeight*uiStride;
+    UInt uiPartOffst   = pcCU->getTotalNumPart()>>(uiCurrTrMode<<1);
+    Pel* pResi = piResi;
+    Pel* pPred = piPred;
+    Pel* pReco = piReco;
+    xRecurIntraInvTransChroma( pcCU, uiAbsPartIdx, pResi, pPred, pReco, uiStride, piCoeff, uiWidth, uiHeight, uiTrMode, uiCurrTrMode, eText );
+    uiAbsPartIdx += uiPartOffst;
+    piCoeff      += uiCoeffOffset;
+    pResi         = piResi + uiWidth; pPred = piPred + uiWidth; pReco = piReco + uiWidth;
+    xRecurIntraInvTransChroma( pcCU, uiAbsPartIdx, pResi, pPred, pReco, uiStride, piCoeff, uiWidth, uiHeight, uiTrMode, uiCurrTrMode, eText );
+    uiAbsPartIdx += uiPartOffst;
+    piCoeff      += uiCoeffOffset;
+    pResi         = piResi + uiPelOffset; pPred = piPred + uiPelOffset; pReco = piReco + uiPelOffset;
+    xRecurIntraInvTransChroma( pcCU, uiAbsPartIdx, pResi, pPred, pReco, uiStride, piCoeff, uiWidth, uiHeight, uiTrMode, uiCurrTrMode, eText );
+    uiAbsPartIdx += uiPartOffst;
+    piCoeff      += uiCoeffOffset;
+    pResi         = piResi + uiPelOffset + uiWidth; pPred = piPred + uiPelOffset + uiWidth; pReco = piReco + uiPelOffset + uiWidth;
+    xRecurIntraInvTransChroma( pcCU, uiAbsPartIdx, pResi, pPred, pReco, uiStride, piCoeff, uiWidth, uiHeight, uiTrMode, uiCurrTrMode, eText );
+  }
+}
+
+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 HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( uiLumaPredMode > MAX_MODE_ID_INTRA_DIR )
+  {
+    m_pcPrediction->predIntraLumaDMM( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail, false );
+  } 
+  else
+#endif
+  {    
+  //===== get prediction signal =====
+  m_pcPrediction->predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+  }
+  //===== inverse transform =====
+  m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_LUMA );
+#if INTRA_DST_TYPE_7
+  m_pcTrQuant->invtransformNxN( TEXT_LUMA, pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight );
+#else
+  m_pcTrQuant->invtransformNxN( piResi, uiStride, pcCoeff, uiWidth, uiHeight );
+#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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    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 );
+  
+#if !LM_CHROMA
+  if( uiChromaPredMode == 4 )
+  {
+    uiChromaPredMode          = pcCU->getLumaIntraDir( 0 );
+  }
+#endif
+  
+  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 );
+  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 LM_CHROMA
+  if(pcCU->getSlice()->getSPS()->getUseLMChroma() && uiChromaPredMode == 3)
+  {
+      m_pcPrediction->predLMIntraChroma( pcCU->getPattern(), pPatChroma, piPred, uiStride, uiWidth, uiHeight, uiChromaId );
+  }
+  else
+  {
+    if( uiChromaPredMode == 4 )
+    {
+    uiChromaPredMode          = pcCU->getLumaIntraDir( 0 );
+    }
+  m_pcPrediction->predIntraChromaAng( pcCU->getPattern(), pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );  
+  }
+#else // LM_CHROMA
+  m_pcPrediction->predIntraChromaAng( pcCU->getPattern(), pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+#endif
+
+  //===== inverse transform =====
+  m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), eText );
+#if INTRA_DST_TYPE_7 
+  m_pcTrQuant->invtransformNxN( eText, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight );
+#else
+  m_pcTrQuant->invtransformNxN( piResi, uiStride, pcCoeff, uiWidth, uiHeight );
+#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 LM_CHROMA
+  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] );
+  }
+#else
+
+  for( UInt uiPU = 0; uiPU < uiNumPart; uiPU++ )
+  {
+    xIntraRecQT( pcCU, uiInitTrDepth, uiPU * uiNumQParts, m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth] );
+  }
+#endif
+
+}
+
+#if LM_CHROMA
+
+/** Funtion 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 );
+    }
+  }
+}
+
+/** Funtion 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 );
+    }
+  }
+}
+#endif
+
+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 );
+  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 );
+  
+  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 );
+  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 );
+}
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecCu.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecCu.h	(revision 19)
@@ -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-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     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"
+
+// ====================================================================================================================
+// 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
+  TComYuv**           m_ppcYuvResPred;    ///< residual prediction buffer
+  TComDataCU**        m_ppcCU;            ///< CU data array
+  
+  // access channel
+  TComTrQuant*        m_pcTrQuant;
+  TComPrediction*     m_pcPrediction;
+  TDecEntropy*        m_pcEntropyDecoder;
+  
+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 );
+  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 xDecodeInterTexture      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void xDecodeIntraTexture      ( TComDataCU* pcCU, UInt uiPartIdx, Pel* piReco, Pel* pPred, Pel* piResi, UInt uiStride, TCoeff* pCoeff, UInt uiWidth, UInt uiHeight, UInt uiCurrDepth );
+  Void xRecurIntraInvTransChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piResi, Pel* piPred, Pel* piReco, UInt uiStride, TCoeff* piCoeff, UInt uiWidth, UInt uiHeight, UInt uiTrMode, UInt uiCurrTrMode, TextType eText );
+  
+  Void xCopyToPic               ( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth );
+
+#if LM_CHROMA
+  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 );
+#endif
+};
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 19)
@@ -0,0 +1,1980 @@
+/* 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     TDecEntropy.cpp
+    \brief    entropy decoder class
+*/
+
+#include "TDecEntropy.h"
+
+Void TDecEntropy::setEntropyDecoder         ( TDecEntropyIf* p )
+{
+  m_pcEntropyDecoderIf = p;
+}
+
+#include "../TLibCommon/TComAdaptiveLoopFilter.h"
+
+Void TDecEntropy::decodeAux(ALFParam* pAlfParam)
+{
+  UInt uiSymbol;
+  Int sqrFiltLengthTab[3] = {SQR_FILT_LENGTH_9SYM, SQR_FILT_LENGTH_7SYM, SQR_FILT_LENGTH_5SYM};
+  Int FiltTab[3] = {9, 7, 5};
+  
+  pAlfParam->filters_per_group = 0;
+  
+  memset (pAlfParam->filterPattern, 0 , sizeof(Int)*NO_VAR_BINS);
+#if ENABLE_FORCECOEFF0
+  m_pcEntropyDecoderIf->parseAlfFlag(uiSymbol);
+  if (!uiSymbol) pAlfParam->filtNo = -1;
+  else pAlfParam->filtNo = uiSymbol; //nonZeroCoeffs
+#else
+  pAlfParam->filtNo = 1; //nonZeroCoeffs
+#endif
+
+#if MQT_BA_RA
+  m_pcEntropyDecoderIf->parseAlfFlag (uiSymbol);
+  pAlfParam->alf_pcr_region_flag = uiSymbol;  
+#endif
+
+  m_pcEntropyDecoderIf->parseAlfUvlc(uiSymbol);
+  Int TabIdx = uiSymbol;
+  pAlfParam->realfiltNo = 2-TabIdx;
+  pAlfParam->tap = FiltTab[pAlfParam->realfiltNo];
+#if TI_ALF_MAX_VSIZE_7
+  pAlfParam->tapV = TComAdaptiveLoopFilter::ALFTapHToTapV(pAlfParam->tap);
+#endif
+  pAlfParam->num_coeff = sqrFiltLengthTab[pAlfParam->realfiltNo];
+  
+  if (pAlfParam->filtNo>=0)
+  {
+    if(pAlfParam->realfiltNo >= 0)
+    {
+      // filters_per_fr
+      m_pcEntropyDecoderIf->parseAlfUvlc(uiSymbol);
+      pAlfParam->noFilters = uiSymbol + 1;
+      pAlfParam->filters_per_group = pAlfParam->noFilters; 
+
+      if(pAlfParam->noFilters == 2)
+      {
+        m_pcEntropyDecoderIf->parseAlfUvlc(uiSymbol);
+        pAlfParam->startSecondFilter = uiSymbol;
+        pAlfParam->filterPattern [uiSymbol] = 1;
+      }
+      else if (pAlfParam->noFilters > 2)
+      {
+        pAlfParam->filters_per_group = 1;
+        for (int i=1; i<NO_VAR_BINS; i++) 
+        {
+          m_pcEntropyDecoderIf->parseAlfFlag (uiSymbol);
+          pAlfParam->filterPattern[i] = uiSymbol;
+          pAlfParam->filters_per_group += uiSymbol;
+        }
+      }
+    }
+  }
+  else
+  {
+    memset (pAlfParam->filterPattern, 0, NO_VAR_BINS*sizeof(Int));
+  }
+  // Reconstruct varIndTab[]
+  memset(pAlfParam->varIndTab, 0, NO_VAR_BINS * sizeof(int));
+  if(pAlfParam->filtNo>=0)
+  {
+    for(Int i = 1; i < NO_VAR_BINS; ++i)
+    {
+      if(pAlfParam->filterPattern[i])
+        pAlfParam->varIndTab[i] = pAlfParam->varIndTab[i-1] + 1;
+      else
+        pAlfParam->varIndTab[i] = pAlfParam->varIndTab[i-1];
+    }
+  }
+}
+
+Void TDecEntropy::readFilterCodingParams(ALFParam* pAlfParam)
+{
+  UInt uiSymbol;
+  int ind, scanPos;
+  int golombIndexBit;
+  int kMin;
+  int maxScanVal;
+  int *pDepthInt;
+  int fl;
+  
+  // Determine fl
+  if(pAlfParam->num_coeff == SQR_FILT_LENGTH_9SYM)
+    fl = 4;
+  else if(pAlfParam->num_coeff == SQR_FILT_LENGTH_7SYM)
+    fl = 3;
+  else
+    fl = 2;
+  
+  // Determine maxScanVal
+  maxScanVal = 0;
+  pDepthInt = pDepthIntTab[fl - 2];
+  for(ind = 0; ind < pAlfParam->num_coeff; ind++)
+    maxScanVal = max(maxScanVal, pDepthInt[ind]);
+  
+  // Golomb parameters
+  m_pcEntropyDecoderIf->parseAlfUvlc(uiSymbol);
+  pAlfParam->minKStart = 1 + uiSymbol;
+  
+  kMin = pAlfParam->minKStart;
+  for(scanPos = 0; scanPos < maxScanVal; scanPos++)
+  {
+    m_pcEntropyDecoderIf->parseAlfFlag(uiSymbol);
+    golombIndexBit = uiSymbol;
+    if(golombIndexBit)
+      pAlfParam->kMinTab[scanPos] = kMin + 1;
+    else
+      pAlfParam->kMinTab[scanPos] = kMin;
+    kMin = pAlfParam->kMinTab[scanPos];
+  }
+}
+
+Int TDecEntropy::golombDecode(Int k)
+{
+  UInt uiSymbol;
+  Int q = -1;
+  Int nr = 0;
+  Int m = (Int)pow(2.0, k);
+  Int a;
+  
+  uiSymbol = 1;
+  while (uiSymbol)
+  {
+    m_pcEntropyDecoderIf->parseAlfFlag(uiSymbol);
+    q++;
+  }
+  for(a = 0; a < k; ++a)          // read out the sequential log2(M) bits
+  {
+    m_pcEntropyDecoderIf->parseAlfFlag(uiSymbol);
+    if(uiSymbol)
+      nr += 1 << a;
+  }
+  nr += q * m;                    // add the bits and the multiple of M
+  if(nr != 0)
+  {
+    m_pcEntropyDecoderIf->parseAlfFlag(uiSymbol);
+    nr = (uiSymbol)? nr: -nr;
+  }
+  return nr;
+}
+
+
+
+Void TDecEntropy::readFilterCoeffs(ALFParam* pAlfParam)
+{
+  int ind, scanPos, i;
+  int *pDepthInt;
+  int fl;
+  
+  if(pAlfParam->num_coeff == SQR_FILT_LENGTH_9SYM)
+    fl = 4;
+  else if(pAlfParam->num_coeff == SQR_FILT_LENGTH_7SYM)
+    fl = 3;
+  else
+    fl = 2;
+  
+  pDepthInt = pDepthIntTab[fl - 2];
+  
+  for(ind = 0; ind < pAlfParam->filters_per_group_diff; ++ind)
+  {
+    for(i = 0; i < pAlfParam->num_coeff; i++)
+    {
+      scanPos = pDepthInt[i] - 1;
+      pAlfParam->coeffmulti[ind][i] = golombDecode(pAlfParam->kMinTab[scanPos]);
+    }
+  }
+  
+}
+Void TDecEntropy::decodeFilterCoeff (ALFParam* pAlfParam)
+{
+  readFilterCodingParams (pAlfParam);
+  readFilterCoeffs (pAlfParam);
+}
+
+
+
+Void TDecEntropy::decodeFilt(ALFParam* pAlfParam)
+{
+  UInt uiSymbol;
+  
+  if (pAlfParam->filtNo >= 0)
+  {
+    pAlfParam->filters_per_group_diff = pAlfParam->filters_per_group;
+    if (pAlfParam->filters_per_group > 1)
+    {
+#if ENABLE_FORCECOEFF0
+      m_pcEntropyDecoderIf->parseAlfFlag (uiSymbol);
+      pAlfParam->forceCoeff0 = uiSymbol;
+
+      if (pAlfParam->forceCoeff0)
+      {
+        pAlfParam->filters_per_group_diff = 0;
+        for (int i=0; i<pAlfParam->filters_per_group; i++)
+        {
+          m_pcEntropyDecoderIf->parseAlfFlag (uiSymbol);
+          pAlfParam->codedVarBins[i] = uiSymbol;
+          pAlfParam->filters_per_group_diff += uiSymbol;
+        }
+      }
+      else
+#else
+      pAlfParam->forceCoeff0 = 0;
+#endif
+      {
+        for (int i=0; i<NO_VAR_BINS; i++)
+          pAlfParam->codedVarBins[i] = 1;
+
+      }
+      m_pcEntropyDecoderIf->parseAlfFlag (uiSymbol);
+      pAlfParam->predMethod = uiSymbol;
+    }
+    else
+    {
+      pAlfParam->forceCoeff0 = 0;
+      pAlfParam->predMethod = 0;
+    }
+
+    decodeFilterCoeff (pAlfParam);
+  }
+}
+
+Void TDecEntropy::decodeAlfParam(ALFParam* pAlfParam)
+{
+  UInt uiSymbol;
+  Int iSymbol;
+  m_pcEntropyDecoderIf->parseAlfFlag(uiSymbol);
+  pAlfParam->alf_flag = uiSymbol;
+  
+  if (!pAlfParam->alf_flag)
+  {
+    m_pcEntropyDecoderIf->setAlfCtrl(false);
+    m_pcEntropyDecoderIf->setMaxAlfCtrlDepth(0); //unncessary
+    return;
+  }
+  
+  Int pos;
+  decodeAux(pAlfParam);
+  decodeFilt(pAlfParam);
+  // filter parameters for chroma
+  m_pcEntropyDecoderIf->parseAlfUvlc(uiSymbol);
+  pAlfParam->chroma_idc = uiSymbol;
+  
+  if(pAlfParam->chroma_idc)
+  {
+    m_pcEntropyDecoderIf->parseAlfUvlc(uiSymbol);
+    pAlfParam->tap_chroma = (uiSymbol<<1) + 5;
+    pAlfParam->num_coeff_chroma = ((pAlfParam->tap_chroma*pAlfParam->tap_chroma+1)>>1) + 1;
+    
+    // filter coefficients for chroma
+    for(pos=0; pos<pAlfParam->num_coeff_chroma; pos++)
+    {
+      m_pcEntropyDecoderIf->parseAlfSvlc(iSymbol);
+      pAlfParam->coeff_chroma[pos] = iSymbol;
+    }
+  }
+  
+  // region control parameters for luma
+  m_pcEntropyDecoderIf->parseAlfFlag(uiSymbol);
+  pAlfParam->cu_control_flag = uiSymbol;
+  if (pAlfParam->cu_control_flag)
+  {
+    m_pcEntropyDecoderIf->setAlfCtrl(true);
+    m_pcEntropyDecoderIf->parseAlfCtrlDepth(uiSymbol);
+    m_pcEntropyDecoderIf->setMaxAlfCtrlDepth(uiSymbol);
+#if TSB_ALF_HEADER
+    pAlfParam->alf_max_depth = uiSymbol;
+    decodeAlfCtrlParam(pAlfParam);
+#endif
+  }
+  else
+  {
+    m_pcEntropyDecoderIf->setAlfCtrl(false);
+    m_pcEntropyDecoderIf->setMaxAlfCtrlDepth(0); //unncessary
+  }
+}
+
+#if TSB_ALF_HEADER
+Void TDecEntropy::decodeAlfCtrlParam( ALFParam* pAlfParam )
+{
+  UInt uiSymbol;
+  m_pcEntropyDecoderIf->parseAlfFlagNum( uiSymbol, pAlfParam->num_cus_in_frame, pAlfParam->alf_max_depth );
+  pAlfParam->num_alf_cu_flag = uiSymbol;
+  
+  for(UInt i=0; i<pAlfParam->num_alf_cu_flag; i++)
+  {
+    m_pcEntropyDecoderIf->parseAlfCtrlFlag( pAlfParam->alf_cu_flag[i] );
+  }
+}
+#endif
+
+Void TDecEntropy::decodeAlfCtrlFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseAlfCtrlFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+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 )
+{ 
+#if !CHANGE_GET_MERGE_CANDIDATE
+  UInt uiNumCand = 0;
+  for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+  {
+    if( pcSubCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == ( uiIter + 1 ) )
+    {
+      uiNumCand++;
+      break;
+    }
+  }
+  if( uiNumCand )
+  {
+#endif
+    // at least one merge candidate exists
+    m_pcEntropyDecoderIf->parseMergeFlag( pcSubCU, uiAbsPartIdx, uiDepth, uiPUIdx );
+#if !CHANGE_GET_MERGE_CANDIDATE
+  }
+  else
+  {
+    assert( !pcSubCU->getMergeFlag( uiAbsPartIdx ) );
+  }
+#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 uiNumCand = 0;
+  for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == ( uiIter + 1 ) )
+    {
+      uiNumCand++;
+    }
+  }
+#if HHI_MPI
+  if( pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+    uiNumCand++;
+#endif
+  // Merge to left or above depending on uiMergeIndex
+  UInt uiMergeIndex = 0;
+  if ( uiNumCand > 1 )
+  {
+    // two different motion parameter sets exist
+    // parse merge index.
+    m_pcEntropyDecoderIf->parseMergeIndex( pcCU, uiMergeIndex, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    for( UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+    {
+      if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == ( uiIter + 1 ) )
+      {
+        uiMergeIndex = uiIter;
+        break;
+      }
+    }
+  }
+  pcCU->setMergeIndexSubParts( uiMergeIndex, uiAbsPartIdx, uiPartIdx, uiDepth );
+  pcCU->setInterDirSubParts( puhInterDirNeighbours[uiMergeIndex], uiAbsPartIdx, uiPartIdx, uiDepth );
+
+  TComMv cTmpMv( 0, 0 );
+  if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0  ) //if ( ref. frame list0 has at least 1 entry )
+  {
+    pcCU->setMVPIdxSubParts( 0, REF_PIC_LIST_0, uiAbsPartIdx, uiPartIdx, uiDepth);
+    pcCU->setMVPNumSubParts( 0, REF_PIC_LIST_0, uiAbsPartIdx, uiPartIdx, uiDepth);
+    pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvd( cTmpMv, eCUMode, uiAbsPartIdx, uiPartIdx, uiDepth );
+    pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( pcMvFieldNeighbours[ 2*uiMergeIndex ].getMv(), pcMvFieldNeighbours[ 2*uiMergeIndex ].getRefIdx(), eCUMode, uiAbsPartIdx, uiPartIdx, uiDepth );
+
+  }
+  if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 ) //if ( ref. frame list1 has at least 1 entry )
+  {
+    pcCU->setMVPIdxSubParts( 0, REF_PIC_LIST_1, uiAbsPartIdx, uiPartIdx, uiDepth);
+    pcCU->setMVPNumSubParts( 0, REF_PIC_LIST_1, uiAbsPartIdx, uiPartIdx, uiDepth);
+    pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvd( cTmpMv, eCUMode, uiAbsPartIdx, uiPartIdx, uiDepth );
+    pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( pcMvFieldNeighbours[ 2*uiMergeIndex + 1 ].getMv(), pcMvFieldNeighbours[ 2*uiMergeIndex + 1 ].getRefIdx(), eCUMode, uiAbsPartIdx, uiPartIdx, uiDepth );
+  }
+}
+
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+Void
+TDecEntropy::decodeResPredFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU, UInt uiPUIdx )
+{
+  Bool  bResPredAvailable   = false;
+  Bool  bResPredFlag        = false;
+
+  Bool  bResPredAllowed     =                    (!pcCU->getSlice()->getSPS()->isDepth                () );
+  bResPredAllowed           = bResPredAllowed && ( pcCU->getSlice()->getSPS()->getViewId              () );
+  bResPredAllowed           = bResPredAllowed && ( pcCU->getSlice()->getSPS()->getMultiviewResPredMode() );
+  bResPredAllowed           = bResPredAllowed && (!pcCU->isIntra           ( uiAbsPartIdx )              );
+
+  // check if supported
+  if( bResPredAllowed )
+  {
+    bResPredAvailable       = pcSubCU->getResidualSamples( uiPUIdx );
+  }
+
+  // read from bitstream
+  if( bResPredAvailable )
+  {
+    m_pcEntropyDecoderIf->parseResPredFlag( pcCU, bResPredFlag, uiAbsPartIdx, uiDepth );
+  }
+
+  // set data
+  pcCU->setResPredAvailSubParts ( bResPredAvailable, uiAbsPartIdx, uiPUIdx, uiDepth );
+  pcCU->setResPredFlagSubParts  ( bResPredFlag,      uiAbsPartIdx, uiPUIdx, uiDepth );
+}
+#endif
+
+
+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 );
+}
+
+Void TDecEntropy::decodePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parsePartSize( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodePredInfo    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU )
+{
+  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
+  {
+    if ( pcCU->getSlice()->getSPS()->getUseMRG() )
+    {
+      decodePUWise( pcCU, uiAbsPartIdx, uiDepth, pcSubCU );
+    }
+    else
+    {
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+      if ( pcCU->getSlice()->getSymbolMode() == 0 )
+      {
+        if ( pcCU->isSuroundingRefIdxException( uiAbsPartIdx ) )
+        {
+          pcCU->getSlice()->setRefIdxCombineCoding( false );
+        }
+        else
+        {
+          pcCU->getSlice()->setRefIdxCombineCoding( true );
+        }
+      }
+#endif
+      decodeInterDir( pcCU, uiAbsPartIdx, uiDepth );
+
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 ) //if ( ref. frame list0 has at least 1 entry )
+      {
+        decodeRefFrmIdx ( pcCU, uiAbsPartIdx, uiDepth, REF_PIC_LIST_0 );
+        decodeMvd       ( pcCU, uiAbsPartIdx, uiDepth, REF_PIC_LIST_0 );
+        decodeMVPIdx( pcCU, uiAbsPartIdx, uiDepth, REF_PIC_LIST_0, pcSubCU);
+      }
+
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 ) //if ( ref. frame list1 has at least 1 entry )
+      {
+        decodeRefFrmIdx ( pcCU, uiAbsPartIdx, uiDepth, REF_PIC_LIST_1 );
+        decodeMvd       ( pcCU, uiAbsPartIdx, uiDepth, REF_PIC_LIST_1 );
+        decodeMVPIdx( pcCU, uiAbsPartIdx, uiDepth, REF_PIC_LIST_1, pcSubCU);
+      }
+    }
+  }
+}
+
+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 );
+}
+
+Void TDecEntropy::decodeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if ( pcCU->getSlice()->isInterP() )
+  {
+    memset( pcCU->getInterDir() + uiAbsPartIdx, 1, sizeof(UChar)*( pcCU->getTotalNumPart() >> (uiDepth << 1) ) );
+    return;
+  }
+  
+  UInt uiInterDir;
+  
+  UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 ) ) >> 2;
+  
+  switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+  {
+      
+    case SIZE_2Nx2N:
+    {
+      m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx, uiDepth );
+      pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+      break;
+    }
+      
+    case SIZE_2NxN:
+    {
+      m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx, uiDepth );
+      pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+      
+      uiAbsPartIdx += uiPartOffset << 1;
+      m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx, uiDepth );
+      pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx, uiDepth );
+      pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+      
+      uiAbsPartIdx += uiPartOffset;
+      m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx, uiDepth );
+      pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+      break;
+    }
+    case SIZE_NxN:
+    {
+      for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+      {
+        m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx, uiDepth );
+        pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+        uiAbsPartIdx += uiPartOffset;
+      }
+      break;
+    }
+    default:
+      break;
+  }
+  
+  return;
+}
+
+/** decode motion information for every PU block
+ * \param pcCU
+ * \param uiPartIdx 
+ * \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;
+
+  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 )
+  {
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+    UInt uiNeighbourCandIdx[MRG_MAX_NUM_CANDS]; //MVs with same idx => same cand
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+    {
+      uhInterDirNeighbours[ui] = 0;
+      uiNeighbourCandIdx[ui] = 0;
+    }
+#if !CHANGE_GET_MERGE_CANDIDATE
+    pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, uiNeighbourCandIdx );
+    for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+    {
+      pcCU->setNeighbourCandIdxSubParts( uiIter, uiNeighbourCandIdx[uiIter], uiSubPartIdx, uiPartIdx, uiDepth );
+    }
+#endif
+#if PART_MRG
+    if (pcCU->getWidth( uiAbsPartIdx ) > 8 && uiNumPU == 2 && uiPartIdx == 0)
+    {
+      pcCU->setMergeFlagSubParts( true, uiSubPartIdx, uiPartIdx, uiDepth );
+    }
+    else
+#endif
+    decodeMergeFlag( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+#if CHANGE_GET_MERGE_CANDIDATE
+      pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, uiDepth, cMvFieldNeighbours, uhInterDirNeighbours, uiNeighbourCandIdx );
+      for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+      {
+        pcCU->setNeighbourCandIdxSubParts( uiIter, uiNeighbourCandIdx[uiIter], uiSubPartIdx, uiPartIdx, uiDepth );
+      }
+#endif
+      decodeMergeIndex( pcCU, uiPartIdx, uiSubPartIdx, ePartSize, uhInterDirNeighbours, cMvFieldNeighbours, uiDepth );
+    }
+    else
+    {
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+      if ( pcCU->getSlice()->getSymbolMode() == 0 )
+      {
+        if ( pcCU->isSuroundingRefIdxException( uiAbsPartIdx ) )
+        {
+          pcCU->getSlice()->setRefIdxCombineCoding( false );
+        }
+        else
+        {
+          pcCU->getSlice()->setRefIdxCombineCoding( true );
+        }
+      }
+#endif
+      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 DCM_COMB_LIST 
+  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, uiPartIdx, uiDepth );
+
+    pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, uiPartIdx, uiDepth );
+  }
+  else
+  {
+#endif
+
+  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, uiPartIdx, uiDepth );
+
+#if DCM_COMB_LIST
+  }
+#endif  
+}
+
+/** 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;
+
+  TComMv cZeroMv( 0, 0 );
+  TComMv cMv     = cZeroMv;
+  Int    iRefIdx = -1;
+
+  TComCUMvField* pcSubCUMvField = pcSubCU->getCUMvField( eRefList );
+  AMVPInfo* pAMVPInfo = pcSubCUMvField->getAMVPInfo();
+
+  iRefIdx = pcSubCUMvField->getRefIdx(uiPartAddr);
+  iMVPIdx = -1;
+  cMv = cZeroMv;
+  pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo);
+#if DCM_SIMPLIFIED_MVP==0
+  pcSubCU->clearMVPCand(pcSubCUMvField->getMvd(uiPartAddr), pAMVPInfo);
+#endif
+  pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, uiPartAddr, uiPartIdx, uiDepth);
+  if ( (pcSubCU->getInterDir(uiPartAddr) & ( 1 << eRefList )) && (pAMVPInfo->iN > 1) && (pcSubCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+  {
+    m_pcEntropyDecoderIf->parseMVPIdx( pcSubCU, iMVPIdx, pAMVPInfo->iN, uiPartAddr, uiDepth, eRefList );
+  }
+  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, uiPartIdx, 0);
+}
+
+Void TDecEntropy::decodeMVPIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList, TComDataCU* pcSubCU )
+{
+  Int iMVPIdx;
+  
+  TComMv cZeroMv( 0, 0 );
+  TComMv cMv     = cZeroMv;
+  Int    iRefIdx = -1;
+  
+  UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 ) ) >> 2;
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  
+  pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, eRefList );
+  
+  TComCUMvField* pcSubCUMvField = pcSubCU->getCUMvField( eRefList );
+  AMVPInfo* pAMVPInfo = pcSubCUMvField->getAMVPInfo();
+  
+  switch ( ePartSize )
+  {
+    case SIZE_2Nx2N:
+    {
+      iRefIdx = pcSubCUMvField->getRefIdx(0);
+      iMVPIdx =-1;
+      cMv = cZeroMv;
+      pcSubCU->fillMvpCand(0, 0, eRefList, iRefIdx, pAMVPInfo);
+#if DCM_SIMPLIFIED_MVP==0
+      pcSubCU->clearMVPCand(pcSubCUMvField->getMvd(0), pAMVPInfo);
+#endif
+      pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, 0, 0, uiDepth);
+      if ( (pcSubCU->getInterDir(0) & ( 1 << eRefList )) && (pAMVPInfo->iN > 1) && (pcSubCU->getAMVPMode(0) == AM_EXPL) )
+      {
+        m_pcEntropyDecoderIf->parseMVPIdx( pcSubCU, iMVPIdx, pAMVPInfo->iN, uiAbsPartIdx, uiDepth, eRefList );
+      }
+      pcSubCU->setMVPIdxSubParts( iMVPIdx, eRefList, 0, 0, uiDepth );
+      
+      if ( iRefIdx >= 0 )
+      {
+        m_pcPrediction->getMvPredAMVP( pcSubCU, 0, 0, eRefList, iRefIdx, cMv);
+        cMv += pcSubCUMvField->getMvd( 0 );
+      }
+      
+      pcSubCU->getCUMvField( eRefList )->setAllMv(cMv, ePartSize, 0, 0, 0);
+      break;
+    }
+    case SIZE_2NxN:
+    {
+      for ( UInt uiPartIdx = 0, uiPartAddr = 0; uiPartIdx < 2; uiPartIdx++, uiPartAddr+=(uiPartOffset << 1))
+      {
+        iRefIdx = pcSubCUMvField->getRefIdx(uiPartAddr);
+        iMVPIdx =-1;
+        cMv = cZeroMv;
+        pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo);
+#if DCM_SIMPLIFIED_MVP==0
+        pcSubCU->clearMVPCand(pcSubCUMvField->getMvd(uiPartAddr), pAMVPInfo);
+#endif
+        pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, uiPartAddr, uiPartIdx, uiDepth);
+        if ( (pcSubCU->getInterDir(uiPartAddr) & ( 1 << eRefList )) && (pAMVPInfo->iN > 1) && (pcSubCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+        {
+          m_pcEntropyDecoderIf->parseMVPIdx( pcSubCU, iMVPIdx, pAMVPInfo->iN, uiPartAddr, uiDepth, eRefList );
+        }
+        pcSubCU->setMVPIdxSubParts( iMVPIdx, eRefList, uiPartAddr, uiPartIdx, uiDepth );
+        if ( iRefIdx >= 0 )
+        {
+          m_pcPrediction->getMvPredAMVP( pcSubCU, uiPartIdx, uiPartAddr, eRefList, iRefIdx, cMv);
+          cMv += pcSubCUMvField->getMvd( uiPartAddr );
+        }
+        
+        pcSubCU->getCUMvField( eRefList )->setAllMv(cMv, ePartSize, uiPartAddr, uiPartIdx, 0);
+        
+      }
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      for ( UInt uiPartIdx = 0, uiPartAddr = 0; uiPartIdx < 2; uiPartIdx++, uiPartAddr+=uiPartOffset)
+      {
+        iRefIdx = pcSubCUMvField->getRefIdx(uiPartAddr);
+        iMVPIdx =-1;
+        cMv = cZeroMv;
+        pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo);
+#if DCM_SIMPLIFIED_MVP==0
+        pcSubCU->clearMVPCand(pcSubCUMvField->getMvd(uiPartAddr), pAMVPInfo);
+#endif
+        pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, uiPartAddr, uiPartIdx, uiDepth);
+        if ( (pcSubCU->getInterDir(uiPartAddr) & ( 1 << eRefList )) && (pAMVPInfo->iN > 1) && (pcSubCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+        {
+          m_pcEntropyDecoderIf->parseMVPIdx( pcSubCU, iMVPIdx, pAMVPInfo->iN, uiPartAddr, uiDepth, eRefList );
+        }
+        pcSubCU->setMVPIdxSubParts( iMVPIdx, eRefList, uiPartAddr, uiPartIdx, uiDepth );
+        
+        if ( iRefIdx >= 0 )
+        {
+          m_pcPrediction->getMvPredAMVP( pcSubCU, uiPartIdx, uiPartAddr, eRefList, iRefIdx, cMv);
+          cMv += pcSubCUMvField->getMvd( uiPartAddr );
+        }
+        
+        pcSubCU->getCUMvField( eRefList )->setAllMv(cMv, ePartSize, uiPartAddr, uiPartIdx, 0);
+        
+      }
+      break;
+    }
+    case SIZE_NxN:
+    {
+      for ( UInt uiPartIdx = 0, uiPartAddr = 0; uiPartIdx < 4; uiPartIdx++, uiPartAddr+=uiPartOffset)
+      {
+        iRefIdx = pcSubCUMvField->getRefIdx(uiPartAddr);
+        iMVPIdx =-1;
+        cMv = cZeroMv;
+        pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo);
+#if DCM_SIMPLIFIED_MVP==0
+        pcSubCU->clearMVPCand(pcSubCUMvField->getMvd(uiPartAddr), pAMVPInfo);
+#endif
+        pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, uiPartAddr, uiPartIdx, uiDepth);
+        if ( (pcSubCU->getInterDir(uiPartAddr) & ( 1 << eRefList )) && (pAMVPInfo->iN > 1) && (pcSubCU->getAMVPMode(uiPartAddr) == AM_EXPL) )
+        {
+          m_pcEntropyDecoderIf->parseMVPIdx( pcSubCU, iMVPIdx, pAMVPInfo->iN, uiPartAddr, uiDepth, eRefList );
+        }
+        pcSubCU->setMVPIdxSubParts( iMVPIdx, eRefList, uiPartAddr, uiPartIdx, uiDepth );
+        if ( iRefIdx >= 0 )
+        {
+          m_pcPrediction->getMvPredAMVP( pcSubCU, uiPartIdx, uiPartAddr, eRefList, iRefIdx, cMv);
+          cMv += pcSubCUMvField->getMvd( uiPartAddr );
+        }
+        
+        pcSubCU->getCUMvField( eRefList )->setAllMv(cMv, ePartSize, uiPartAddr, uiPartIdx, 0);
+      }
+      break;
+    }
+    default:
+      break;
+  }
+  
+  return;
+}
+
+/** decode reference frame index
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param eRefList 
+ * \returns Void
+ */
+Void TDecEntropy::decodeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+#if DCM_COMB_LIST
+  if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+  {
+    Int iRefFrmIdx = 0;
+
+    Int iRefFrmIdxTemp;
+    UInt uiInterDir;
+    RefPicList eRefListTemp;
+
+    UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 ) ) >> 2;
+
+    switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+    {
+      case SIZE_2Nx2N:
+      {
+        if( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList == REF_PIC_LIST_0)
+        {
+          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, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+          pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+        }
+        else if(pcCU->getInterDir( uiAbsPartIdx ) == 3)
+        {
+          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;
+          }
+      
+          pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+        }
+        break;
+      }
+      case SIZE_2NxN:
+      {
+        if( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList == REF_PIC_LIST_0)
+        {
+          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, SIZE_2NxN, uiAbsPartIdx, 0, uiDepth );
+          pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+        }
+        else if(pcCU->getInterDir( uiAbsPartIdx ) == 3)
+        {
+          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;
+          }
+      
+          pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_2NxN, uiAbsPartIdx, 0, uiDepth );
+        }
+
+        uiAbsPartIdx += uiPartOffset << 1;
+
+        if( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList == REF_PIC_LIST_0)
+        {
+          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, SIZE_2NxN, uiAbsPartIdx, 1, uiDepth );
+          pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+        }
+        else if(pcCU->getInterDir( uiAbsPartIdx ) == 3)
+        {
+          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;
+          }
+          pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_2NxN, uiAbsPartIdx, 1, uiDepth );
+        }
+        break;
+      }
+      case SIZE_Nx2N:
+      {
+        if( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList == REF_PIC_LIST_0)
+        {
+          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, SIZE_Nx2N, uiAbsPartIdx, 0, uiDepth );
+          pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+        }
+        else if(pcCU->getInterDir( uiAbsPartIdx ) == 3)
+        {
+          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;
+          }
+          pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_Nx2N, uiAbsPartIdx, 0, uiDepth );
+        }
+
+        uiAbsPartIdx += uiPartOffset;
+        
+        if( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList == REF_PIC_LIST_0)
+        {
+          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, SIZE_Nx2N, uiAbsPartIdx, 1, uiDepth );
+          pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+        }
+        else if(pcCU->getInterDir( uiAbsPartIdx ) == 3)
+        {
+          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;
+          }
+          pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_Nx2N, uiAbsPartIdx, 1, uiDepth );
+        }
+        break;
+      }
+      case SIZE_NxN:
+      {
+        for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+        {
+          if( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList == REF_PIC_LIST_0)
+          {
+            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, SIZE_NxN, uiAbsPartIdx, iPartIdx, uiDepth );
+            pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, 0, uiDepth );
+          }
+          else if(pcCU->getInterDir( uiAbsPartIdx ) == 3)
+          {
+            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;
+            }
+            pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_NxN, uiAbsPartIdx, iPartIdx, uiDepth );
+          }
+          uiAbsPartIdx += uiPartOffset;
+        }
+        break;
+      }
+      default:
+        break;
+    }
+  }
+  else
+  {
+#endif
+
+  Int iRefFrmIdx = 0;
+  Int iParseRefFrmIdx = pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList );
+  UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+  
+  switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+  {
+    case SIZE_2Nx2N:
+    {
+      if ( pcCU->getSlice()->getNumRefIdx( eRefList ) > 1 && iParseRefFrmIdx)
+      {
+        m_pcEntropyDecoderIf->parseRefFrmIdx( pcCU, iRefFrmIdx, uiAbsPartIdx, uiDepth, eRefList );
+      }
+      else if ( !iParseRefFrmIdx )
+      {
+        iRefFrmIdx = NOT_VALID;
+      }
+      else
+      {
+        iRefFrmIdx = 0;
+      }
+      
+      pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      break;
+    }
+    case SIZE_2NxN:
+    {
+      if ( pcCU->getSlice()->getNumRefIdx( eRefList ) > 1 && iParseRefFrmIdx)
+      {
+        m_pcEntropyDecoderIf->parseRefFrmIdx( pcCU, iRefFrmIdx, uiAbsPartIdx, uiDepth, eRefList );
+      }
+      else if ( !iParseRefFrmIdx )
+      {
+        iRefFrmIdx = NOT_VALID;
+      }
+      else
+      {
+        iRefFrmIdx = 0;
+      }
+      
+      pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_2NxN, uiAbsPartIdx, 0, uiDepth );
+      uiAbsPartIdx += (uiPartOffset << 1);
+      
+      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;
+      }
+      pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_2NxN, uiAbsPartIdx, 1, uiDepth );
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      if ( pcCU->getSlice()->getNumRefIdx( eRefList ) > 1 && iParseRefFrmIdx)
+      {
+        m_pcEntropyDecoderIf->parseRefFrmIdx( pcCU, iRefFrmIdx, uiAbsPartIdx, uiDepth, eRefList );
+      }
+      else if ( !iParseRefFrmIdx )
+      {
+        iRefFrmIdx = NOT_VALID;
+      }
+      else
+      {
+        iRefFrmIdx = 0;
+      }
+      pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_Nx2N, uiAbsPartIdx, 0, uiDepth );
+      uiAbsPartIdx += uiPartOffset;
+      
+      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;
+      }
+      pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_Nx2N, uiAbsPartIdx, 1, uiDepth );
+      break;
+    }
+    case SIZE_NxN:
+    {
+      for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+      {
+        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;
+        }
+        pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, SIZE_NxN, uiAbsPartIdx, iPartIdx, uiDepth );
+        uiAbsPartIdx += uiPartOffset;
+      }
+      break;
+    }
+    default:
+      break;
+  }
+#if DCM_COMB_LIST
+  }
+#endif
+
+  return;
+}
+
+Void TDecEntropy::decodeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 ) ) >> 2;
+  
+  switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+  {
+    case SIZE_2Nx2N:
+    {
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, 0, uiDepth, eRefList );
+      }
+      break;
+    }
+    case SIZE_2NxN:
+    {
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, 0, uiDepth, eRefList );
+      }
+      
+      uiAbsPartIdx += (uiPartOffset << 1);
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, 0, uiDepth, eRefList );
+      }
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, 0, uiDepth, eRefList );
+      }
+      
+      uiAbsPartIdx += uiPartOffset;
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, 0, uiDepth, eRefList );
+      }
+      break;
+    }
+    case SIZE_NxN:
+    {
+      for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+      {
+        if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+        {
+          m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, 0, uiDepth, eRefList );
+        }
+        uiAbsPartIdx += uiPartOffset;
+      }
+      break;
+    }
+    default:
+      break;
+  }
+  return;
+}
+
+Void TDecEntropy::xDecodeTransformSubdiv( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiInnerQuadIdx, UInt& uiYCbfFront3, UInt& uiUCbfFront3, UInt& uiVCbfFront3 )
+{
+  UInt uiSubdiv;
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
+  
+#if CAVLC_RQT_CBP
+  if(pcCU->getSlice()->getSymbolMode()==0)
+  {
+    // code CBP and transform split flag jointly
+    UInt uiTrDepth =  uiDepth - pcCU->getDepth( uiAbsPartIdx );
+    m_pcEntropyDecoderIf->parseCbfTrdiv( pcCU, uiAbsPartIdx, uiTrDepth, uiDepth, uiSubdiv );
+  }
+  else
+  {//CABAC
+#endif
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    uiSubdiv = 1;
+  }
+  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) );
+#if HHI_RQT_FORCE_SPLIT_ACC2_PU
+    const UInt uiTrMode = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+    UInt uiCtx = uiDepth;
+#if HHI_RQT_FORCE_SPLIT_NxN
+    const Bool bNxNOK = pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN && uiTrMode > 0;
+#else
+    const Bool bNxNOK = pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN;
+#endif
+#if HHI_RQT_FORCE_SPLIT_RECT
+    const Bool bSymmetricOK  = pcCU->getPartitionSize( uiAbsPartIdx ) >= SIZE_2NxN  && pcCU->getPartitionSize( uiAbsPartIdx ) < SIZE_NxN   && uiTrMode > 0;
+#else
+    const Bool bSymmetricOK  = pcCU->getPartitionSize( uiAbsPartIdx ) >= SIZE_2NxN  && pcCU->getPartitionSize( uiAbsPartIdx ) < SIZE_NxN;
+#endif
+    const Bool bNeedSubdivFlag = pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N || pcCU->getPredictionMode( uiAbsPartIdx ) == MODE_INTRA ||
+    bNxNOK || bSymmetricOK;
+    
+    if( ! bNeedSubdivFlag )
+    {
+      uiSubdiv = 1;
+    }
+    else
+      m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, uiCtx );
+#else
+    m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, uiDepth );
+#endif
+  }
+#if CAVLC_RQT_CBP
+  }
+#endif
+  
+  const UInt uiTrDepth = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+  
+  if(pcCU->getSlice()->getSymbolMode()==0)
+  {
+    if( uiSubdiv )
+    {
+      ++uiDepth;
+      const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+      
+      for( Int i = 0; i < 4; i++ )
+      {
+        UInt uiDummyCbfY = 0;
+        UInt uiDummyCbfU = 0;
+        UInt uiDummyCbfV = 0;
+        xDecodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, i, uiDummyCbfY, uiDummyCbfU, uiDummyCbfV );
+        uiAbsPartIdx += uiQPartNum;
+      }
+    }
+    else
+    {
+      assert( uiDepth >= pcCU->getDepth( uiAbsPartIdx ) );
+      pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiDepth );
+    }
+  }
+  else
+  {
+    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && 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 > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+        {
+          uiUCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+          uiVCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+        }
+      }
+    }
+    
+    if( uiSubdiv )
+    {
+      ++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++ )
+      {
+        xDecodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, i, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV );
+        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;
+      }
+      
+      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_V( 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 );
+      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
+      {
+        if ( pcCU->getPredictionMode( uiAbsPartIdx ) != MODE_INTRA && uiInnerQuadIdx == 3 && uiYCbfFront3 == 0 && uiUCbfFront3 == 0 && uiVCbfFront3 == 0 && 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 );
+        }
+      }
+      
+      if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
+      {
+        Bool bCodeChroma   = true;
+        UInt uiDepthChroma = uiDepth;
+        if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+        {
+          UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+          bCodeChroma  = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+          uiDepthChroma--;
+        }
+        if( bCodeChroma )
+        {
+          pcCU->setCbfSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiDepthChroma );
+          pcCU->setCbfSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiDepthChroma );
+          m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiChromaTrMode, uiDepthChroma );
+          m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiChromaTrMode, uiDepthChroma );
+        }
+      }
+    }
+  }
+}
+
+Void TDecEntropy::decodeTransformIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  DTRACE_CABAC_V( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
+  DTRACE_CABAC_V( uiDepth )
+  DTRACE_CABAC_T( "\n" )
+  UInt temp = 0;
+  UInt temp1 = 0;
+  UInt temp2 = 0;
+  xDecodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 0, temp, temp1, temp2 );
+}
+
+Void TDecEntropy::decodeQP          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+  {
+    m_pcEntropyDecoderIf->parseDeltaQP( pcCU, uiAbsPartIdx, uiDepth );
+  }
+}
+
+Void TDecEntropy::decodeViewidx(Int & riViewIdx)
+{
+  m_pcEntropyDecoderIf->parseViewIdx( riViewIdx );
+}
+
+Void TDecEntropy::xDecodeCoeff( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, UInt uiTrIdx, UInt uiCurrTrIdx, TextType eType )
+{
+  if ( pcCU->getCbf( uiAbsPartIdx, eType, uiTrIdx ) )
+  {
+#if SNY_DQP   
+    // dQP: only for LCU
+    if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+    {
+      if ( pcCU->getdQPFlag())// non-skip
+      {
+        decodeQP( pcCU, 0, 0 );
+        pcCU->setdQPFlag(false);
+      }
+    }   
+#endif//SNY_DQP
+    UInt uiLumaTrMode, uiChromaTrMode;
+    pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx( uiAbsPartIdx ), uiLumaTrMode, uiChromaTrMode );
+    const UInt uiStopTrMode = eType == TEXT_LUMA ? uiLumaTrMode : uiChromaTrMode;
+    
+    if( uiTrIdx == uiStopTrMode )
+    {
+      UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+      if( eType != TEXT_LUMA && uiLog2TrSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+        if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+        {
+          return;
+        }
+        uiWidth  <<= 1;
+        uiHeight <<= 1;
+      }
+      m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, pcCoeff, uiAbsPartIdx, uiWidth, uiHeight, uiDepth, eType );
+    }
+    else
+    {
+      {
+        DTRACE_CABAC_V( g_nSymbolCounter++ );
+        DTRACE_CABAC_T( "\tgoing down\tdepth=" );
+        DTRACE_CABAC_V( uiDepth );
+        DTRACE_CABAC_T( "\ttridx=" );
+        DTRACE_CABAC_V( uiTrIdx );
+        DTRACE_CABAC_T( "\n" );
+      }
+      if( uiCurrTrIdx <= uiTrIdx )
+        assert(1);
+      UInt uiSize;
+      uiWidth  >>= 1;
+      uiHeight >>= 1;
+      uiSize = uiWidth*uiHeight;
+      uiDepth++;
+      uiTrIdx++;
+      
+      UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+      UInt uiIdx      = uiAbsPartIdx;
+      
+#if !CAVLC_RQT_CBP
+      if(pcCU->getSlice()->getSymbolMode() == 0)
+      {
+        UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+        if( eType == TEXT_LUMA || uiLog2TrSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+          m_pcEntropyDecoderIf->parseBlockCbf(pcCU, uiIdx, eType, uiTrIdx, uiDepth, uiQPartNum);
+        else
+        {
+          UInt uiCbf = pcCU->getCbf( uiIdx, eType );
+          pcCU->setCbfSubParts( uiCbf | ( 0x01 << uiTrIdx ), eType, uiIdx, uiDepth ); 
+          uiCbf = pcCU->getCbf( uiIdx + uiQPartNum, eType );
+          pcCU->setCbfSubParts( uiCbf | ( 0x01 << uiTrIdx ), eType, uiIdx + uiQPartNum, uiDepth ); 
+          uiCbf = pcCU->getCbf( uiIdx + 2*uiQPartNum, eType );
+          pcCU->setCbfSubParts( uiCbf | ( 0x01 << uiTrIdx ), eType, uiIdx + 2*uiQPartNum, uiDepth ); 
+          uiCbf = pcCU->getCbf( uiIdx + 3*uiQPartNum, eType );
+          pcCU->setCbfSubParts( uiCbf | ( 0x01 << uiTrIdx ), eType, uiIdx + 3*uiQPartNum, uiDepth ); 
+        }
+        xDecodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xDecodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xDecodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xDecodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType );
+      }
+      else
+      {
+#endif
+        xDecodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xDecodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xDecodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xDecodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType );
+#if !CAVLC_RQT_CBP
+      }
+#endif
+      {
+        DTRACE_CABAC_V( g_nSymbolCounter++ );
+        DTRACE_CABAC_T( "\tgoing up\n" );
+      }
+    }
+  }
+}
+
+/** 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 )
+{
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+  UInt uiLumaTrMode, uiChromaTrMode;
+  
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+    decodeTransformIdx( pcCU, uiAbsPartIdx, pcCU->getDepth(uiAbsPartIdx) );
+    
+    pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx(uiAbsPartIdx), uiLumaTrMode, uiChromaTrMode );
+    
+    if (pcCU->getSlice()->getSymbolMode() == 0)
+    {
+#if !CAVLC_RQT_CBP
+      m_pcEntropyDecoderIf->parseCbf( pcCU, uiAbsPartIdx, TEXT_ALL, 0, uiDepth );
+#endif
+      if(pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, 0)==0 && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, 0)==0
+         && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, 0)==0)
+        return;
+    }
+  }
+  else
+  {
+    if (pcCU->getSlice()->getSymbolMode()==0)
+    {
+#if !CAVLC_RQT_CBP
+      m_pcEntropyDecoderIf->parseCbf( pcCU, uiAbsPartIdx, TEXT_ALL, 0, uiDepth );
+      if(pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, 0)==0 && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, 0)==0
+         && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, 0)==0)
+        return;
+#endif
+    }
+    else
+    {
+#if HHI_MRG_SKIP
+      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 );
+      }
+#else
+      UInt uiQtRootCbf;
+      m_pcEntropyDecoderIf->parseQtRootCbf( pcCU, uiAbsPartIdx, uiDepth, uiQtRootCbf );
+#endif
+      if ( !uiQtRootCbf )
+      {
+        pcCU->setCbfSubParts( 0, 0, 0, uiAbsPartIdx, uiDepth );
+        pcCU->setTrIdxSubParts( 0 , uiAbsPartIdx, uiDepth );
+        return;
+      }
+    }
+    
+    decodeTransformIdx( pcCU, uiAbsPartIdx, pcCU->getDepth(uiAbsPartIdx) );
+    
+#if CAVLC_RQT_CBP
+    if (pcCU->getSlice()->getSymbolMode() == 0)
+    {
+      if(pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, 0)==0 && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, 0)==0
+         && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, 0)==0)
+         return;
+    }
+#endif
+    pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx(uiAbsPartIdx), uiLumaTrMode, uiChromaTrMode );
+  }
+  
+  xDecodeCoeff( pcCU, pcCU->getCoeffY()  + uiLumaOffset,   uiAbsPartIdx, uiDepth, uiWidth,    uiHeight,    0, uiLumaTrMode,   TEXT_LUMA     );
+  xDecodeCoeff( pcCU, pcCU->getCoeffCb() + uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth>>1, uiHeight>>1, 0, uiChromaTrMode, TEXT_CHROMA_U );
+  xDecodeCoeff( pcCU, pcCU->getCoeffCr() + uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth>>1, uiHeight>>1, 0, uiChromaTrMode, TEXT_CHROMA_V );
+}
+
+#if MTK_SAO
+/** decodeQAO One Part
+ * \param  pQaoParam, iPartIdx
+ */
+Void TDecEntropy::decodeQAOOnePart(SAOParam* pQaoParam, Int iPartIdx)
+{
+  UInt uiSymbol;
+  Int iSymbol;  
+
+  SAOQTPart*  pAlfPart = &(pQaoParam->psSaoPart[iPartIdx]);
+  static Int iTypeLength[MAX_NUM_SAO_TYPE] = {
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_BO_LEN,
+    SAO_BO_LEN
+  };  
+  if(!pAlfPart->bSplit)
+  {
+
+    m_pcEntropyDecoderIf->parseAoUvlc(uiSymbol);
+
+    if (uiSymbol)
+    {
+      pAlfPart->iBestType = uiSymbol-1;
+      pAlfPart->bEnableFlag = true;
+    }
+    else
+    {
+      pAlfPart->iBestType = -1;
+      pAlfPart->bEnableFlag = false;
+    }
+
+    if (pAlfPart->bEnableFlag)
+    {
+
+      pAlfPart->iLength = iTypeLength[pAlfPart->iBestType];
+
+      for(Int i=0; i< pAlfPart->iLength; i++)
+      {
+        m_pcEntropyDecoderIf->parseAoSvlc(iSymbol);
+        pAlfPart->iOffset[i] = iSymbol;
+      }
+
+    }
+    return;
+  }
+
+  //split
+  if (pAlfPart->PartLevel < pQaoParam->iMaxSplitLevel)
+  {
+    for(Int i=0;i<NUM_DOWN_PART;i++)
+    {
+      decodeQAOOnePart(pQaoParam, pAlfPart->DownPartsIdx[i]);
+    }
+  }
+}
+/** decode QuadTree Split Flag
+ * \param  pQaoParam, iPartIdx
+ */
+Void TDecEntropy::decodeQuadTreeSplitFlag(SAOParam* pQaoParam, Int iPartIdx)
+{
+  UInt uiSymbol;
+  SAOQTPart*  pAlfPart = &(pQaoParam->psSaoPart[iPartIdx]);
+
+  if(pAlfPart->PartLevel < pQaoParam->iMaxSplitLevel)
+  {
+
+    //send one flag
+    m_pcEntropyDecoderIf->parseAoFlag(uiSymbol); 
+    pAlfPart->bSplit = uiSymbol? true:false; 
+    if(pAlfPart->bSplit)
+    {
+      for (Int i=0;i<NUM_DOWN_PART;i++)
+      {
+        decodeQuadTreeSplitFlag(pQaoParam, pAlfPart->DownPartsIdx[i]);
+      }
+    }
+  }
+
+}
+/** decode Sao Param
+ * \param  pQaoParam
+ */
+Void TDecEntropy::decodeSaoParam(SAOParam* pQaoParam)
+{
+  UInt uiSymbol;
+
+  m_pcEntropyDecoderIf->parseAoFlag(uiSymbol);
+  if (uiSymbol)
+  {
+    pQaoParam->bSaoFlag = true;
+  }
+  else
+  {
+    pQaoParam->bSaoFlag = false;
+  }
+  if (pQaoParam->bSaoFlag)
+  {
+    decodeQuadTreeSplitFlag(pQaoParam, 0);
+    decodeQAOOnePart(pQaoParam, 0);
+  }
+
+}
+
+#endif
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecEntropy.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecEntropy.h	(revision 19)
@@ -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-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     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"
+
+class TDecSbac;
+class TDecCavlc;
+class SEImessages;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// entropy decoder pure class
+class TDecEntropyIf
+{
+public:
+  //  Virtual list for SBAC/CAVLC
+  virtual Void setAlfCtrl(Bool bAlfCtrl)  = 0;
+  virtual Void setMaxAlfCtrlDepth(UInt uiMaxAlfCtrlDepth)  = 0;
+
+  virtual Void  resetEntropy          (TComSlice* pcSlice)                = 0;
+  virtual Void  setBitstream          ( TComBitstream* p )  = 0;
+
+  virtual Void  parseNalUnitHeader    ( NalUnitType& eNalUnitType, UInt& TemporalId, Bool& bOutputFlag )  = 0;
+
+  virtual Void  parseSPS                  ( TComSPS* pcSPS )                                      = 0;
+  virtual Void  parsePPS                  ( TComPPS* pcPPS )                                      = 0;
+  virtual void parseSEI(SEImessages&) = 0;
+  virtual Void  parseSliceHeader          ( TComSlice*& rpcSlice )                                = 0;
+  virtual Void  parseTerminatingBit       ( UInt& ruilsLast )                                     = 0;
+
+  virtual Void parseMVPIdx      ( TComDataCU* pcCU, Int& riMVPIdx, Int iMVPNum, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList ) = 0;
+
+public:
+  virtual Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  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;
+  virtual Void parseResPredFlag   ( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  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 parseCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth ) = 0;
+  virtual Void parseBlockCbf      ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth, UInt uiQPartNum ) = 0;
+#if CAVLC_RQT_CBP
+  virtual Void parseCbfTrdiv      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiTrDepth, UInt uiDepth, UInt& uiSubdiv ) = 0;
+#endif
+
+  virtual Void parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
+
+  virtual Void parseAlfFlag       ( UInt& ruiVal           ) = 0;
+  virtual Void parseAlfUvlc       ( UInt& ruiVal           ) = 0;
+  virtual Void parseAlfSvlc       ( Int&  riVal            ) = 0;
+  virtual Void parseAlfCtrlDepth  ( UInt& ruiAlfCtrlDepth  ) = 0;
+  virtual Void parseAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#if TSB_ALF_HEADER
+  virtual Void parseAlfFlagNum    ( UInt& ruiVal, UInt minValue, UInt depth ) = 0;
+  virtual Void parseAlfCtrlFlag   ( UInt &ruiAlfCtrlFlag ) = 0;
+#endif
+
+#if MTK_SAO
+  virtual Void parseAoFlag       ( UInt& ruiVal           ) = 0;
+  virtual Void parseAoUvlc       ( UInt& ruiVal           ) = 0;
+  virtual Void parseAoSvlc       ( Int&  riVal            ) = 0;
+#endif
+  virtual Void parseViewIdx       ( Int& riViewIdx ) = 0;
+  virtual ~TDecEntropyIf() {}
+};
+
+/// entropy decoder class
+class TDecEntropy
+{
+private:
+  TDecEntropyIf*  m_pcEntropyDecoderIf;
+  TComPrediction* m_pcPrediction;
+
+public:
+  Void init (TComPrediction* p) {m_pcPrediction = p;}
+  Void decodeMVPIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList, TComDataCU* pcSubCU );
+  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                ( TComBitstream* p )      { m_pcEntropyDecoderIf->setBitstream(p);                    }
+  Void    resetEntropy                ( TComSlice* p)           { m_pcEntropyDecoderIf->resetEntropy(p);                    }
+
+  Void    decodeNalUnitHeader         ( NalUnitType& eNalUnitType, UInt& TemporalId, Bool& bOutputFlag )
+                                                                { m_pcEntropyDecoderIf->parseNalUnitHeader(eNalUnitType, TemporalId, bOutputFlag ); }
+
+
+  Void    decodeSPS                   ( TComSPS* pcSPS     )    { m_pcEntropyDecoderIf->parseSPS(pcSPS);                    }
+  Void    decodePPS                   ( TComPPS* pcPPS     )    { m_pcEntropyDecoderIf->parsePPS(pcPPS);                    }
+  void decodeSEI(SEImessages& seis) { m_pcEntropyDecoderIf->parseSEI(seis); }
+  Void    decodeSliceHeader           ( TComSlice*& rpcSlice )  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice);         }
+  Void    decodeTerminatingBit        ( UInt& ruiIsLast )       { m_pcEntropyDecoderIf->parseTerminatingBit(ruiIsLast);     }
+
+  // Adaptive Loop filter
+  Void decodeAlfParam(ALFParam* pAlfParam);
+  //--Adaptive Loop filter
+
+  TDecEntropyIf* getEntropyDecoder() { return m_pcEntropyDecoderIf; }
+
+public:
+  Void decodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  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 );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Void decodeResPredFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU, UInt uiPUIdx );
+#endif
+  Void decodeAlfCtrlFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if TSB_ALF_HEADER
+  Void decodeAlfCtrlParam      ( ALFParam *pAlfParam );
+#endif
+
+  Void decodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodePartSize          ( 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 decodeInterDir          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeRefFrmIdx         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  Void decodeMvd               ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  Void decodeRefViewIdx        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  //
+  Void decodeTransformIdx      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeQP                ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void decodeViewidx           ( Int& riViewIdx );
+
+
+private:
+  Void xDecodeTransformSubdiv  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiInnerQuadIdx, UInt& uiYCbfFront3, UInt& uiUCbfFront3, UInt& uiVCbfFront3 );
+
+  Void xDecodeCoeff            ( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, UInt uiTrIdx, UInt uiCurrTrIdx, TextType eType );
+public:
+  Void decodeCoeff             ( TComDataCU* pcCU                 , UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight );
+
+  // ALF-related
+  Void decodeAux(ALFParam* pAlfParam);
+  Void decodeFilt(ALFParam* pAlfParam);
+  Void readFilterCodingParams(ALFParam* pAlfParam);
+  Void readFilterCoeffs(ALFParam* pAlfParam);
+  Void decodeFilterCoeff (ALFParam* pAlfParam);
+  Int golombDecode(Int k);
+
+#if MTK_SAO
+  Void decodeQAOOnePart(SAOParam* pQaoParam, Int part_idx);
+  Void decodeQuadTreeSplitFlag(SAOParam* pQaoParam, Int part_idx);
+  Void decodeSaoParam(SAOParam* pQaoParam) ;
+#endif
+
+};// END CLASS DEFINITION TDecEntropy
+
+
+#endif // __TDECENTROPY__
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecGop.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecGop.cpp	(revision 19)
@@ -0,0 +1,386 @@
+/* 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     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>
+
+static void calcAndPrintMD5Status(TComPicYuv& pic, const SEImessages* seis);
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TDecGop::TDecGop()
+{
+  m_iGopSize = 0;
+  m_dDecTime = 0;
+}
+
+TDecGop::~TDecGop()
+{
+  
+}
+
+Void TDecGop::create()
+{
+  
+}
+
+
+Void TDecGop::destroy()
+{
+
+}
+
+Void TDecGop::init( TDecEntropy*            pcEntropyDecoder, 
+                   TDecSbac*               pcSbacDecoder, 
+                   TDecBinCABAC*           pcBinCABAC,
+                   TDecCavlc*              pcCavlcDecoder, 
+                   TDecSlice*              pcSliceDecoder, 
+                   TComLoopFilter*         pcLoopFilter, 
+                   TComAdaptiveLoopFilter* pcAdaptiveLoopFilter, 
+#if MTK_SAO
+                   TComSampleAdaptiveOffset* pcSAO
+#endif              
+#if DEPTH_MAP_GENERATION
+                  ,TComDepthMapGenerator*  pcDepthMapGenerator
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+                  ,TComResidualGenerator*  pcResidualGenerator 
+#endif
+                  )
+{
+  m_pcEntropyDecoder      = pcEntropyDecoder;
+  m_pcSbacDecoder         = pcSbacDecoder;
+  m_pcBinCABAC            = pcBinCABAC;
+  m_pcCavlcDecoder        = pcCavlcDecoder;
+  m_pcSliceDecoder        = pcSliceDecoder;
+  m_pcLoopFilter          = pcLoopFilter;
+  m_pcAdaptiveLoopFilter  = pcAdaptiveLoopFilter;
+#if MTK_SAO
+  m_pcSAO  = pcSAO;
+#endif
+#if DEPTH_MAP_GENERATION
+  m_pcDepthMapGenerator   = pcDepthMapGenerator;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_pcResidualGenerator   = pcResidualGenerator;
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecGop::decompressGop (Bool bEos, TComBitstream* pcBitstream, TComPic*& rpcPic, Bool bExecuteDeblockAndAlf)
+{
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+
+  //-- For time output for each slice
+  long iBeforeTime = clock();
+  
+  UInt uiStartCUAddr   = pcSlice->getEntropySliceCurStartCUAddr();
+#if MTK_NONCROSS_INLOOP_FILTER
+  static Bool  bFirst = true;
+  static UInt  uiILSliceCount;
+  static UInt* puiILSliceStartLCU;
+  if (!bExecuteDeblockAndAlf)
+  {
+    if(bFirst)
+    {
+      uiILSliceCount = 0;
+      if(!pcSlice->getSPS()->getLFCrossSliceBoundaryFlag())
+      {
+        puiILSliceStartLCU = new UInt[rpcPic->getNumCUsInFrame() +1];
+      }
+      bFirst = false;
+    }
+    
+    if(!pcSlice->getSPS()->getLFCrossSliceBoundaryFlag())
+    {
+      UInt uiSliceStartCuAddr = pcSlice->getSliceCurStartCUAddr();
+      if(uiSliceStartCuAddr == uiStartCUAddr)
+      {
+        puiILSliceStartLCU[uiILSliceCount] = uiSliceStartCuAddr;
+        uiILSliceCount++;
+      }
+    }
+#endif //MTK_NONCROSS_INLOOP_FILTER
+
+    UInt iSymbolMode = pcSlice->getSymbolMode();
+    if (iSymbolMode)
+    {
+      m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
+      m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
+    }
+    else
+    {
+      m_pcEntropyDecoder->setEntropyDecoder (m_pcCavlcDecoder);
+    }
+    
+    m_pcEntropyDecoder->setBitstream      (pcBitstream);
+    m_pcEntropyDecoder->resetEntropy      (pcSlice);
+    
+    if (uiStartCUAddr==0)  // decode ALF params only from first slice header
+    {
+#if MTK_SAO
+      if( rpcPic->getSlice(0)->getSPS()->getUseSAO() )
+      {  
+        m_pcSAO->InitSao(&m_cSaoParam);
+        m_pcEntropyDecoder->decodeSaoParam(&m_cSaoParam);
+      }
+#endif
+
+      if ( rpcPic->getSlice(0)->getSPS()->getUseALF() )
+      {
+#if TSB_ALF_HEADER
+        m_pcAdaptiveLoopFilter->setNumCUsInFrame(rpcPic);
+#endif
+        m_pcAdaptiveLoopFilter->allocALFParam(&m_cAlfParam);
+        m_pcEntropyDecoder->decodeAlfParam( &m_cAlfParam );
+      }
+    }
+    
+#if DEPTH_MAP_GENERATION
+    // init view component and predict virtual depth map
+    if( uiStartCUAddr == 0 )
+    {
+      m_pcDepthMapGenerator->initViewComponent( rpcPic );
+      m_pcDepthMapGenerator->predictDepthMap  ( rpcPic );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      m_pcResidualGenerator->initViewComponent( rpcPic );
+#endif
+    }
+#endif
+
+    // decode slice
+    m_pcSliceDecoder->decompressSlice(pcBitstream, rpcPic);
+    
+    m_dDecTime += (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+  }
+  else
+  {
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    // set residual picture
+    m_pcResidualGenerator->setRecResidualPic( rpcPic );
+#endif
+#if DEPTH_MAP_GENERATION
+    // update virtual depth map
+    m_pcDepthMapGenerator->updateDepthMap( rpcPic );
+#endif
+
+    // deblocking filter
+    m_pcLoopFilter->setCfg(pcSlice->getLoopFilterDisable(), 0, 0);
+    m_pcLoopFilter->loopFilterPic( rpcPic );
+#if MTK_SAO
+    {
+      if( rpcPic->getSlice(0)->getSPS()->getUseSAO())
+      {
+        m_pcSAO->SAOProcess(rpcPic, &m_cSaoParam);
+      }
+    }
+#endif
+    // adaptive loop filter
+    if( pcSlice->getSPS()->getUseALF() )
+    {
+#if MTK_NONCROSS_INLOOP_FILTER  
+      if(pcSlice->getSPS()->getLFCrossSliceBoundaryFlag())
+      {
+        m_pcAdaptiveLoopFilter->setUseNonCrossAlf(false);
+      }
+      else
+      {
+        puiILSliceStartLCU[uiILSliceCount] = rpcPic->getNumCUsInFrame();
+        m_pcAdaptiveLoopFilter->setUseNonCrossAlf( (uiILSliceCount > 1) );
+        if(m_pcAdaptiveLoopFilter->getUseNonCrossAlf())
+        {
+          m_pcAdaptiveLoopFilter->setNumSlicesInPic( uiILSliceCount );
+          m_pcAdaptiveLoopFilter->createSlice();
+          for(UInt i=0; i< uiILSliceCount ; i++)
+          {
+            (*m_pcAdaptiveLoopFilter)[i].create(rpcPic, i, puiILSliceStartLCU[i], puiILSliceStartLCU[i+1]-1);
+          }
+        }
+      }
+#endif
+      m_pcAdaptiveLoopFilter->ALFProcess(rpcPic, &m_cAlfParam);
+#if MTK_NONCROSS_INLOOP_FILTER
+      if(m_pcAdaptiveLoopFilter->getUseNonCrossAlf())
+      {
+        m_pcAdaptiveLoopFilter->destroySlice();
+      }
+#endif
+      m_pcAdaptiveLoopFilter->freeALFParam(&m_cAlfParam);
+    }
+    
+/*#if AMVP_BUFFERCOMPRESS
+    rpcPic->compressMotion(); // move to end of access unit
+#endif */
+    
+    //-- For time output for each slice
+    if(rpcPic->getViewIdx()!=-1)
+    {
+      if( !pcSlice->getSPS()->isDepth())
+      {
+        printf("\nView \t\t%4d\t POC %4d ( %c-SLICE, QP%3d ) ",
+                        rpcPic->getViewIdx(),
+                        pcSlice->getPOC(),
+                        pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B',
+                        pcSlice->getSliceQp() );
+      }
+      else
+      {
+        printf("\nDepth View \t%4d\t POC %4d ( %c-SLICE, QP%3d ) ",
+                              rpcPic->getViewIdx(),
+                              pcSlice->getPOC(),
+                              pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B',
+                              pcSlice->getSliceQp() );
+      }
+    }
+    else
+      printf("\nPOC %4d ( %c-SLICE, QP%3d ) ",
+             pcSlice->getPOC(),
+             pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B',
+             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->getViewIdx() != pcSlice->getRefViewIdx( RefPicList(iRefList), iRefIndex ) )
+        {
+          printf( "V%d", pcSlice->getRefViewIdx( RefPicList(iRefList), iRefIndex ) );
+          if( pcSlice->getPOC() != pcSlice->getRefPOC( RefPicList(iRefList), iRefIndex ) )
+            printf( "(%d)", pcSlice->getRefPOC( RefPicList(iRefList), iRefIndex ) );
+          printf( " " );
+        }
+        else
+          printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
+      }
+      printf ("] ");
+    }
+#if DCM_COMB_LIST
+    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->getViewIdx() != pcSlice->getRefViewIdx( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) )
+        {
+          printf( "V%d", pcSlice->getRefViewIdx( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) );
+          if( pcSlice->getPOC() != pcSlice->getRefPOC( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) )
+            printf( "(%d)", pcSlice->getRefPOC( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) );
+          printf( " " );
+        }
+        else
+          printf ("%d ", pcSlice->getRefPOC((RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex)));
+      }
+      printf ("] ");
+    }
+#endif
+#if FIXED_ROUNDING_FRAME_MEMORY
+    rpcPic->getPicYuvRec()->xFixedRoundingPic();
+#endif 
+
+    if (m_pictureDigestEnabled) {
+      calcAndPrintMD5Status(*rpcPic->getPicYuvRec(), rpcPic->getSEIs());
+    }
+
+    rpcPic->setReconMark(true);
+#if MTK_NONCROSS_INLOOP_FILTER
+    uiILSliceCount = 0;
+#endif
+  }
+}
+
+/**
+ * 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: /tags/0.2r1/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecGop.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecGop.h	(revision 19)
@@ -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-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     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/TComDepthMapGenerator.h"
+#include "../TLibCommon/TComResidualGenerator.h"
+
+#include "TDecEntropy.h"
+#include "TDecSlice.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP decoder class
+class TDecGop
+{
+private:
+  Int                   m_iGopSize;
+  TComList<TComPic*>    m_cListPic;         //  Dynamic buffer
+  
+  //  Access channel
+  TDecEntropy*          m_pcEntropyDecoder;
+  TDecSbac*             m_pcSbacDecoder;
+  TDecBinCABAC*         m_pcBinCABAC;
+  TDecCavlc*            m_pcCavlcDecoder;
+  TDecSlice*            m_pcSliceDecoder;
+  TComLoopFilter*       m_pcLoopFilter;
+
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator*  m_pcDepthMapGenerator;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  TComResidualGenerator*  m_pcResidualGenerator;
+#endif
+  
+  // Adaptive Loop filter
+  TComAdaptiveLoopFilter*       m_pcAdaptiveLoopFilter;
+#if MTK_SAO
+  TComSampleAdaptiveOffset*              m_pcSAO;
+  SAOParam              m_cSaoParam;
+#endif
+  ALFParam              m_cAlfParam;
+  Double                m_dDecTime;
+
+  bool m_pictureDigestEnabled; ///< if true, handle picture_digest SEI messages
+
+public:
+  TDecGop();
+  virtual ~TDecGop();
+  
+  Void  init    ( TDecEntropy*            pcEntropyDecoder, 
+                 TDecSbac*               pcSbacDecoder, 
+                 TDecBinCABAC*           pcBinCABAC,
+                 TDecCavlc*              pcCavlcDecoder, 
+                 TDecSlice*              pcSliceDecoder, 
+                 TComLoopFilter*         pcLoopFilter, 
+                 TComAdaptiveLoopFilter* pcAdaptiveLoopFilter,
+#if MTK_SAO
+                 TComSampleAdaptiveOffset*                pcSAO
+#endif
+#if DEPTH_MAP_GENERATION
+                ,TComDepthMapGenerator*  pcDepthMapGenerator
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+                ,TComResidualGenerator*  pcResidualGenerator 
+#endif
+                 );
+  Void  create  ();
+  Void  destroy ();
+  Void  decompressGop ( Bool bEos, TComBitstream* pcBitstream, TComPic*& rpcPic, Bool bExecuteDeblockAndAlf );
+  Void  setGopSize( Int i) { m_iGopSize = i; }
+
+  void setPictureDigestEnabled(bool enabled) { m_pictureDigestEnabled = enabled; }
+};
+
+#endif // !defined(AFX_TDECGOP_H__29440B7A_7CC0_48C7_8DD5_1A531D3CED45__INCLUDED_)
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 19)
@@ -0,0 +1,2324 @@
+/* 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     TDecSbac.cpp
+    \brief    Context-adaptive entropy decoder class
+*/
+
+#include "TDecSbac.h"
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+TDecSbac::TDecSbac() 
+// new structure here
+: m_pcBitstream               ( 0 )
+, m_pcTDecBinIf               ( NULL )
+, m_bAlfCtrl                  ( false )
+, m_uiMaxAlfCtrlDepth         ( 0 )
+, m_cCUSkipFlagSCModel        ( 1,             1,               NUM_SKIP_FLAG_CTX             )
+, m_cCUSplitFlagSCModel       ( 1,             1,               NUM_SPLIT_FLAG_CTX            )
+, m_cCUMergeFlagExtSCModel    ( 1,             1,               NUM_MERGE_FLAG_EXT_CTX        )
+, m_cCUMergeIdxExtSCModel     ( 1,             1,               NUM_MERGE_IDX_EXT_CTX         )
+, m_cCUMVMergeIdxExtSCModel   ( 1,             1,               NUM_MV_MERGE_IDX_EXT_CTX      )
+, m_cResPredFlagSCModel       ( 1,             1,               NUM_RES_PRED_FLAG_CTX         )
+, m_cCUAlfCtrlFlagSCModel     ( 1,             1,               NUM_ALF_CTRL_FLAG_CTX         )
+, m_cCUPartSizeSCModel        ( 1,             1,               NUM_PART_SIZE_CTX             )
+, m_cCUPredModeSCModel        ( 1,             1,               NUM_PRED_MODE_CTX             )
+, m_cCUIntraPredSCModel       ( 1,             1,               NUM_ADI_CTX                   )
+#if ADD_PLANAR_MODE
+, m_cPlanarFlagSCModel        ( 1,             1,               NUM_PLANARFLAG_CTX            )
+#endif
+, m_cCUChromaPredSCModel      ( 1,             1,               NUM_CHROMA_PRED_CTX           )
+, m_cCUInterDirSCModel        ( 1,             1,               NUM_INTER_DIR_CTX             )
+, m_cCURefPicSCModel          ( 1,             1,               NUM_REF_NO_CTX                )
+, m_cCUMvdSCModel             ( 1,             2,               NUM_MV_RES_CTX                )
+, m_cCUTransSubdivFlagSCModel ( 1,             1,               NUM_TRANS_SUBDIV_FLAG_CTX     )
+, m_cCUQtRootCbfSCModel       ( 1,             1,               NUM_QT_ROOT_CBF_CTX           )
+, m_cCUDeltaQpSCModel         ( 1,             1,               NUM_DELTA_QP_CTX              )
+, m_cCUQtCbfSCModel           ( 1,             3,               NUM_QT_CBF_CTX                )
+#if SIMPLE_CONTEXT_SIG
+, m_cCUSigSCModel             ( 4,             2,               NUM_SIG_FLAG_CTX              ) 
+#else
+, m_cCUSigSCModel             ( MAX_CU_DEPTH,  2,               NUM_SIG_FLAG_CTX              )
+#endif
+#if PCP_SIGMAP_SIMPLE_LAST
+, m_cCuCtxLastX               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          )
+, m_cCuCtxLastY               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          )
+#else
+, m_cCULastSCModel            ( MAX_CU_DEPTH,  2,               NUM_LAST_FLAG_CTX             )
+#endif
+, m_cCUOneSCModel             ( 1,             2,               NUM_ONE_FLAG_CTX              )
+, m_cCUAbsSCModel             ( 1,             2,               NUM_ABS_FLAG_CTX              )
+, m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               )
+, m_cALFFlagSCModel           ( 1,             1,               NUM_ALF_FLAG_CTX              )
+, m_cALFUvlcSCModel           ( 1,             1,               NUM_ALF_UVLC_CTX              )
+, m_cALFSvlcSCModel           ( 1,             1,               NUM_ALF_SVLC_CTX              )
+#if MTK_SAO
+, m_cAOFlagSCModel            ( 1,             1,               NUM_AO_FLAG_CTX              )
+, m_cAOUvlcSCModel            ( 1,             1,               NUM_AO_UVLC_CTX              )
+, m_cAOSvlcSCModel            ( 1,             1,               NUM_AO_SVLC_CTX              )
+#endif
+, m_cViewIdxSCModel           ( 1,             1,               NUM_VIEW_IDX_CTX              )
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+, m_cIntraDMMSCModel          ( 1,             1,               NUM_DMM_CTX                   )
+, m_cIntraWedgeSCModel        ( 1,             1,               NUM_WEDGE_CTX                 )
+#endif
+{
+}
+
+TDecSbac::~TDecSbac()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecSbac::resetEntropy          (TComSlice* pcSlice)
+{
+  Int  iQp              = pcSlice->getSliceQp();
+  SliceType eSliceType  = pcSlice->getSliceType();
+  
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (Short*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_SKIP_FLAG );
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (Short*)INIT_MERGE_FLAG_EXT );
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (Short*)INIT_MERGE_IDX_EXT );
+  m_cCUMVMergeIdxExtSCModel.initBuffer   ( eSliceType, iQp, (Short*)INIT_MV_MERGE_IDX_EXT );
+  m_cResPredFlagSCModel.initBuffer       ( eSliceType, iQp, (Short*)INIT_RES_PRED_FLAG );
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( eSliceType, iQp, (Short*)INIT_ALF_CTRL_FLAG );
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (Short*)INIT_INTRA_PRED_MODE );
+#if ADD_PLANAR_MODE
+  m_cPlanarFlagSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_PLANARFLAG );
+#endif
+  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (Short*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (Short*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (Short*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (Short*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (Short*)INIT_QT_ROOT_CBF );
+  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (Short*)INIT_SIG_FLAG );
+#if PCP_SIGMAP_SIMPLE_LAST
+  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (Short*)INIT_LAST_X );
+  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (Short*)INIT_LAST_Y );
+#else
+  m_cCULastSCModel.initBuffer            ( eSliceType, iQp, (Short*)INIT_LAST_FLAG );
+#endif
+  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (Short*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (Short*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (Short*)INIT_MVP_IDX );
+  m_cALFFlagSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_ALF_SVLC );
+#if MTK_SAO
+  m_cAOFlagSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_AO_FLAG );
+  m_cAOUvlcSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_AO_UVLC );
+  m_cAOSvlcSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_AO_SVLC );
+#endif
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (Short*)INIT_TRANS_SUBDIV_FLAG );
+  m_cViewIdxSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_VIEW_IDX );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  m_cIntraDMMSCModel.initBuffer          ( eSliceType, iQp, (Short*)INIT_INTRA_DMM );
+  m_cIntraWedgeSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_INTRA_WEDGELET );
+#endif
+  
+  m_uiLastDQpNonZero  = 0;
+  
+  // new structure
+  m_uiLastQp          = iQp;
+  
+  m_pcTDecBinIf->start();
+}
+
+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;
+}
+
+#if MVD_CTX
+/** Decode a motion vector difference
+ * \param riMvdComp motion vector difference
+ * \param uiAbsSumL motion vector difference of left PU
+ * \param uiAbsSumA motion vector difference of above PU
+ * \param uiCtx index for context set based on vertical or horizontal component
+ */
+Void TDecSbac::xReadMvd( Int& riMvdComp, UInt uiAbsSumL, UInt uiAbsSumA, UInt uiCtx )
+#else
+Void TDecSbac::xReadMvd( Int& riMvdComp, UInt uiAbsSum, UInt uiCtx )
+#endif
+{
+  UInt uiLocalCtx = 0;
+
+#if MVD_CTX
+  uiLocalCtx += (uiAbsSumA>16) ? 1 : 0;
+  uiLocalCtx += (uiAbsSumL>16) ? 1 : 0;
+#else
+  if( uiAbsSum >= 3 )
+  {
+    uiLocalCtx += ( uiAbsSum > 32) ? 2 : 1;
+  }
+#endif
+
+  riMvdComp = 0;
+  
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMvdSCModel.get( 0, uiCtx, uiLocalCtx ) );
+  
+  if (!uiSymbol)
+  {
+    return;
+  }
+  
+  xReadExGolombMvd( uiSymbol, &m_cCUMvdSCModel.get( 0, uiCtx, 3 ), 3 );
+  uiSymbol++;
+  
+  UInt uiSign;
+  m_pcTDecBinIf->decodeBinEP( uiSign );
+  
+  riMvdComp = ( 0 != uiSign ) ? -(Int)uiSymbol : (Int)uiSymbol;
+  
+  return;
+}
+
+Void TDecSbac::xReadExGolombMvd( UInt& ruiSymbol, ContextModel* pcSCModel, UInt uiMaxBin )
+{
+  UInt uiSymbol;
+  
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
+  
+  if( !ruiSymbol )
+  {
+    return;
+  }
+  
+  m_pcTDecBinIf->decodeBin( uiSymbol, pcSCModel[1] );
+  
+  ruiSymbol = 1;
+  
+  if( !uiSymbol )
+  {
+    return;
+  }
+  
+  pcSCModel += 2;
+  UInt uiCount = 2;
+  
+  do
+  {
+    if( uiMaxBin == uiCount )
+    {
+      pcSCModel++;
+    }
+    m_pcTDecBinIf->decodeBin( uiSymbol, *pcSCModel );
+    uiCount++;
+  }
+  while( uiSymbol && ( uiCount != 8 ) );
+  
+  ruiSymbol = uiCount - 1;
+  
+  if( uiSymbol )
+  {
+    xReadEpExGolomb( uiSymbol, 3 );
+    ruiSymbol += uiSymbol + 1;
+  }
+  
+  return;
+}
+
+Void TDecSbac::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
+{
+  UInt uiSymbol = 0;
+  UInt uiBit = 1;
+  
+  while( uiBit )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiBit );
+    uiSymbol += uiBit << uiCount++;
+  }
+  
+  uiCount--;
+  while( uiCount-- )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiBit );
+    uiSymbol += uiBit << uiCount;
+  }
+  
+  ruiSymbol = uiSymbol;
+  
+  return;
+}
+
+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;
+}
+
+#if E253
+/** 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;
+
+  for( UInt ui = 0; ui < ruiGoRiceParam; ui++ )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiCodeWord );
+    if( uiCodeWord )
+    {
+      uiRemainder += 1 << ui;
+    }
+  }
+
+  ruiSymbol      = uiRemainder + ( uiQuotient << ruiGoRiceParam );
+  bExGolomb      = ruiSymbol == ( uiMaxVlc + 1 );
+
+  if( bExGolomb )
+  {
+    xReadEpExGolomb( uiCodeWord, 0 );
+    ruiSymbol += uiCodeWord;
+  }
+
+  ruiGoRiceParam = g_aauiGoRiceUpdate[ ruiGoRiceParam ][ min<UInt>( ruiSymbol, 15 ) ];
+
+  return;
+}
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+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
+#else
+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
+
+Void TDecSbac::parseAlfCtrlDepth( UInt& ruiAlfCtrlDepth )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol( uiSymbol, m_cALFUvlcSCModel.get( 0 ), 1, g_uiMaxCUDepth - 1 );
+  ruiAlfCtrlDepth = uiSymbol;
+}
+
+Void TDecSbac::parseAlfCtrlFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( !m_bAlfCtrl )
+  {
+    return;
+  }
+  
+  if( uiDepth > m_uiMaxAlfCtrlDepth && !pcCU->isFirstAbsZorderIdxInDepth( uiAbsPartIdx, m_uiMaxAlfCtrlDepth ) )
+  {
+    return;
+  }
+  
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUAlfCtrlFlagSCModel.get( 0, 0, pcCU->getCtxAlfCtrlFlag( uiAbsPartIdx ) ) );
+  
+  if( uiDepth > m_uiMaxAlfCtrlDepth )
+  {
+    pcCU->setAlfCtrlFlagSubParts( uiSymbol, uiAbsPartIdx, m_uiMaxAlfCtrlDepth );
+  }
+  else
+  {
+    pcCU->setAlfCtrlFlagSubParts( uiSymbol, uiAbsPartIdx, uiDepth );
+  }
+}
+
+/** 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_V( 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 );
+    
+#if HHI_MRG_SKIP
+    pcCU->setMergeFlagSubParts( true , uiAbsPartIdx, 0, uiDepth );
+#else
+    TComMv cZeroMv(0,0);
+    pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+    pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+    
+    pcCU->setTrIdxSubParts( 0, uiAbsPartIdx, uiDepth );
+    pcCU->setCbfSubParts  ( 0, 0, 0, uiAbsPartIdx, uiDepth );
+    
+    if ( pcCU->getSlice()->isInterP() )
+    {
+      pcCU->setInterDirSubParts( 1, uiAbsPartIdx, 0, uiDepth );
+      
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllRefIdx(  0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( NOT_VALID, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+    }
+    else
+    {
+      pcCU->setInterDirSubParts( 3, uiAbsPartIdx, 0, uiDepth );
+      
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllRefIdx(  0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( 0, SIZE_2Nx2N, uiAbsPartIdx, 0, uiDepth );
+    }
+#endif // HHI_MRG_SKIP
+  }
+}
+
+/** 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;
+  UInt uiCtx = 0;
+#if CHANGE_MERGE_CONTEXT
+  uiCtx = pcCU->getCtxMergeFlag( uiAbsPartIdx );
+#else
+  for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == uiIter + 1 )
+    {
+      if( uiIter == 0 )
+      {
+        uiCtx++;
+      }
+      else if( uiIter == 1 )
+      {
+        uiCtx++;
+      }
+    }
+  }
+#endif
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMergeFlagExtSCModel.get( 0, 0, uiCtx ) );
+  pcCU->setMergeFlagSubParts( uiSymbol ? true : false, uiAbsPartIdx, uiPUIdx, uiDepth );
+
+  DTRACE_CABAC_V( 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 );
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    DTRACE_CABAC_T( "\tNumMrgCand: " );
+    DTRACE_CABAC_V( ui );
+    DTRACE_CABAC_T( "\t==\t" );
+    DTRACE_CABAC_V( UInt( pcCU->getNeighbourCandIdx( ui, uiAbsPartIdx ) ) );
+  }
+  DTRACE_CABAC_T( "\n" );
+}
+
+
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+Void TDecSbac::parseMergeIndexMV( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth )
+{
+#if HHI_MPI
+  const Bool bMVIAvailable = pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE;
+  const UInt uiMviMergePos = bMVIAvailable ? HHI_MPI_MERGE_POS : MRG_MAX_NUM_CANDS;
+#endif
+  //--- set number of candidates and availability ---
+  Bool  abAvailable[ MRG_MAX_NUM_CANDS ];
+  UInt  uiNumCand = 0;
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS; uiIdx++ )
+  {
+#if HHI_MPI
+    if( uiIdx == uiMviMergePos )
+    {
+      abAvailable[ uiIdx ] = true;
+      uiNumCand++;
+    }
+    else if( uiIdx > uiMviMergePos )
+    {
+      if( ( abAvailable[ uiIdx ] = ( pcCU->getNeighbourCandIdx( uiIdx - 1, uiAbsPartIdx ) == uiIdx ) ) )
+      {
+        uiNumCand++;
+      }
+    }
+    else
+#endif
+    if( ( abAvailable[ uiIdx ] = ( pcCU->getNeighbourCandIdx( uiIdx, uiAbsPartIdx ) == uiIdx + 1 ) ) )
+    {
+      uiNumCand++;
+    }
+  }
+  AOF( uiNumCand > 1 );
+
+  //--- determine contexts ---
+  AOF( NUM_MV_MERGE_IDX_EXT_CTX >= MRG_MAX_NUM_CANDS - 1 );
+  UInt  auiCtx[ MRG_MAX_NUM_CANDS - 1 ];
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS - 1; uiIdx++ )
+  {
+    auiCtx[ uiIdx ] = MRG_MAX_NUM_CANDS;
+    if( uiNumCand > uiIdx + 1 )
+    {
+      Bool bAvComb    = false;
+      for( UInt uiCId = uiIdx; uiCId < MRG_MAX_NUM_CANDS - 1; uiCId++ )
+      {
+        bAvComb = ( bAvComb || abAvailable[ uiCId ] );
+        if( abAvailable[ uiCId + 1 ] && bAvComb )
+        {
+          auiCtx[ uiIdx ] = uiCId;
+          break;
+        }
+      }
+      AOT( auiCtx[ uiIdx ] == MRG_MAX_NUM_CANDS );
+    }
+  }
+
+  //--- parse unary index ---
+  UInt uiUnaryIdx = 0;
+  for( ; uiUnaryIdx < uiNumCand - 1; uiUnaryIdx++ )
+  {
+    UInt uiSymbol = 0;
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMVMergeIdxExtSCModel.get( 0, 0, auiCtx[uiUnaryIdx] ) );
+    if( uiSymbol == 0 )
+    {
+      break;
+    }
+  }
+
+  //--- determine merge index ---
+  ruiMergeIndex = uiUnaryIdx;
+  for( UInt uiIdx = 0; uiIdx <= ruiMergeIndex; uiIdx++ )
+  {
+    if( ! abAvailable[ uiIdx ] )
+    {
+      ruiMergeIndex++;
+    }
+  }
+
+#if HHI_MPI
+  if( ruiMergeIndex > uiMviMergePos )
+  {
+    ruiMergeIndex--;
+  }
+  else if( ruiMergeIndex == uiMviMergePos )
+  {
+    pcCU->setTextureModeDepthSubParts( uiDepth, uiAbsPartIdx, uiDepth );
+  }
+#endif
+
+  //--- trace ---
+  DTRACE_CABAC_V( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tparseMergeIndex():" );
+  DTRACE_CABAC_T( "   MRGIdx = " );
+  DTRACE_CABAC_V( ruiMergeIndex );
+  DTRACE_CABAC_T( "   UnaryIdx = " );
+  DTRACE_CABAC_V( uiUnaryIdx );
+  DTRACE_CABAC_T( "   NumCand = " );
+  DTRACE_CABAC_V( uiNumCand );
+  DTRACE_CABAC_T( "   Availibility = " );
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS; uiIdx++ )
+  {
+    DTRACE_CABAC_V( abAvailable[ uiIdx ] ? 1 : 0 );
+  }
+  DTRACE_CABAC_T( "   Contexts = " );
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS - 1; uiIdx++ )
+  {
+    DTRACE_CABAC_V( auiCtx[ uiIdx ] );
+  }
+  DTRACE_CABAC_T( "\n" );
+}
+#endif
+
+
+Void TDecSbac::parseMergeIndex ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth )
+{
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+  if(
+#if HHI_INTER_VIEW_MOTION_PRED
+      ( pcCU->getSlice()->getSPS()->getViewId() > 0 && ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) == PDM_USE_FOR_MERGE ) ||
+#endif
+#if HHI_MPI
+      ( pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N ) ||
+#endif
+      0
+    )
+  {
+    parseMergeIndexMV( pcCU, ruiMergeIndex, uiAbsPartIdx, uiDepth );
+    return;
+  }
+#endif
+
+  Bool bLeftInvolved = false;
+  Bool bAboveInvolved = false;
+  Bool bCollocatedInvolved = false;
+  Bool bCornerInvolved = false;
+  Bool bCornerBLInvolved = false;
+  UInt uiNumCand = 0;
+  for( UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; ++uiIter )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == uiIter + 1 )
+    {
+      uiNumCand++;
+      if( uiIter == 0 )
+      {
+        bLeftInvolved = true;
+      }
+      else if( uiIter == 1 )
+      {
+        bAboveInvolved = true;
+      }
+      else if( uiIter == 2 )
+      {
+        bCollocatedInvolved = true;
+      }
+      else if( uiIter == 3 )
+      {
+        bCornerInvolved = true;
+      }
+      else if( uiIter == 4 )
+      {
+        bCornerBLInvolved = true;
+      }
+    }
+  }
+  assert( uiNumCand > 1 );
+
+  UInt auiCtx[4] = { 0, 0, 0, 3 };
+  if( bLeftInvolved && bAboveInvolved )
+  {
+    auiCtx[0] = 0;
+  }
+  else if( bLeftInvolved || bAboveInvolved )
+  {
+    auiCtx[0] = bCollocatedInvolved ? 1 : 2;
+  }
+  else
+  {
+    auiCtx[0] = bCollocatedInvolved ? 2 : 3;
+  }
+
+  if( uiNumCand >= 3 )
+  {
+    if( bAboveInvolved )
+    {
+      auiCtx[1] = bCollocatedInvolved ? 1 : 2;
+    }
+    else
+    {
+      auiCtx[1] = bCollocatedInvolved ? 2 : 3;
+    }
+  }
+
+  if( uiNumCand >= 4 )
+  {
+    auiCtx[2] =  bCollocatedInvolved ? 2 : 3;
+  }
+
+  UInt uiUnaryIdx = 0;
+  for( ; uiUnaryIdx < uiNumCand - 1; ++uiUnaryIdx )
+  {
+    UInt uiSymbol = 0;
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, auiCtx[uiUnaryIdx] ) );
+    if( uiSymbol == 0 )
+    {
+      break;
+    }
+  }
+
+  if( !bLeftInvolved )
+  {
+    ++uiUnaryIdx;
+  }
+  if( !bAboveInvolved && uiUnaryIdx >= 1 )
+  {
+    ++uiUnaryIdx;
+  }
+  if( !bCollocatedInvolved && uiUnaryIdx >= 2 )
+  {
+    ++uiUnaryIdx;
+  }
+  if( !bCornerInvolved && uiUnaryIdx >= 3 )
+  {
+    ++uiUnaryIdx;
+  }
+
+  ruiMergeIndex = uiUnaryIdx;
+
+  DTRACE_CABAC_V( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseMergeIndex()" )
+  DTRACE_CABAC_T( "\tuiMRGIdx= " )
+  DTRACE_CABAC_V( ruiMergeIndex )
+  DTRACE_CABAC_T( "\tuiNumCand= " )
+  DTRACE_CABAC_V( uiNumCand )
+  DTRACE_CABAC_T( "\tbLeftInvolved= " )
+  DTRACE_CABAC_V( bLeftInvolved )
+  DTRACE_CABAC_T( "\tbAboveInvolved= " )
+  DTRACE_CABAC_V( bAboveInvolved )
+  DTRACE_CABAC_T( "\tbCollocatedInvolved= " )
+  DTRACE_CABAC_V( bCollocatedInvolved )
+  DTRACE_CABAC_T( "\tbCornerRTInvolved= " )
+  DTRACE_CABAC_V( bCornerInvolved )
+  DTRACE_CABAC_T( "\tbCornerBLInvolved= " )
+  DTRACE_CABAC_V( bCornerBLInvolved )
+  DTRACE_CABAC_T( "\n" )
+}
+
+
+Void 
+TDecSbac::parseResPredFlag( TComDataCU* pcCU, Bool& rbResPredFlag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCtx    = 0;
+  UInt uiSymbol = 0;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cResPredFlagSCModel.get( 0, 0, uiCtx ) );
+  rbResPredFlag = ( uiSymbol != 0 );
+}
+
+
+Void TDecSbac::parseMVPIdx      ( TComDataCU* pcCU, Int& riMVPIdx, Int iMVPNum, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, m_cMVPIdxSCModel.get(0), 1, iMVPNum-1);
+
+  riMVPIdx = uiSymbol;
+}
+
+Void TDecSbac::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+  {
+    pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+    return;
+  }
+  
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSplitFlagSCModel.get( 0, 0, pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ) ) );
+  DTRACE_CABAC_V( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tSplitFlag\n" )
+  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 ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+    uiSymbol = 1;
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+    }
+    eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
+  }
+  else
+  {
+#if HHI_RMP_SWITCH
+    if ( !pcCU->getSlice()->getSPS()->getUseRMP())
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      if( uiSymbol )
+        uiMode = 0;
+      else
+        uiMode = 3;
+    }
+    else
+#endif
+    {
+      UInt uiMaxNumBits = 3;
+      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()->isInterB() && uiMode == 3)
+    {
+#if HHI_DISABLE_INTER_NxN_SPLIT
+      uiSymbol = 0;
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3) );
+      }
+      
+      if (uiSymbol == 0)
+      {
+        pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+        if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+        {
+          m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 4) );
+        }
+        if (uiSymbol == 0)
+          eMode = SIZE_2Nx2N;
+      }
+    }
+  }
+  
+  pcCU->setPartSizeSubParts( eMode, uiAbsPartIdx, uiDepth );
+  pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+  
+  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( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
+  {
+    if( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN )
+    {
+      pcCU->setTrIdxSubParts( 1+uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setTrIdxSubParts( uiTrLevel, 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;
+  if ( pcCU->getSlice()->isInterB() )
+  {
+    pcCU->setPredModeSubParts( (PredMode)iPredMode, uiAbsPartIdx, uiDepth );
+    return;
+  }
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPredModeSCModel.get( 0, 0, 1 ) );
+  iPredMode += uiSymbol;
+  pcCU->setPredModeSubParts( (PredMode)iPredMode, uiAbsPartIdx, uiDepth );
+}
+
+#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_cIntraWedgeSCModel.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_cIntraWedgeSCModel.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_cIntraWedgeSCModel.get(0, 0, 1) );
+  Int iDC1 = uiDC1;
+  if ( uiDC1 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC1 = -iDC1;
+    }
+  }
+  xReadExGolombLevel( uiDC2, m_cIntraWedgeSCModel.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_cIntraWedgeSCModel.get(0, 0, 3) );
+
+    Int iDeltaEnd;
+    if( uiDeltaEnd != 0 )
+    {
+      UInt uiAbsValMinus1;
+      UInt uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraWedgeSCModel.get(0, 0, 3) ); uiAbsValMinus1  = uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraWedgeSCModel.get(0, 0, 3) ); 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_cIntraWedgeSCModel.get(0, 0, 3) );
+
+    Int iDeltaEnd;
+    if( uiDeltaEnd != 0 )
+    {
+      UInt uiAbsValMinus1;
+      UInt uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraWedgeSCModel.get(0, 0, 3) ); uiAbsValMinus1  = uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraWedgeSCModel.get(0, 0, 3) ); 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_cIntraWedgeSCModel.get(0, 0, 1) );
+  Int iDC1 = uiDC1;
+  if ( uiDC1 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC1 = -iDC1;
+    }
+  }
+  xReadExGolombLevel( uiDC2, m_cIntraWedgeSCModel.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
+Void TDecSbac::xParseWedgePredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiDC1, uiDC2;
+  xReadExGolombLevel( uiDC1, m_cIntraWedgeSCModel.get(0, 0, 1) );
+  Int iDC1 = uiDC1;
+  if ( uiDC1 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC1 = -iDC1;
+    }
+  }
+  xReadExGolombLevel( uiDC2, m_cIntraWedgeSCModel.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_cIntraWedgeSCModel.get(0, 0, 1) );
+  Int iDC1 = uiDC1;
+  if ( uiDC1 )
+{
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      iDC1 = -iDC1;
+    }
+  }
+  xReadExGolombLevel( uiDC2, m_cIntraWedgeSCModel.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 MTK_DCM_MPM
+Void TDecSbac::parseIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int  uiIPredMode;
+  UInt uiSymbol;
+  
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  UInt uiFlag = 0;
+  if ( pcCU->getSlice()->getSPS()->isDepth() && pcCU->getSlice()->getSPS()->getUseDMM() && g_uiMaxCUWidth>>uiDepth < 64 )
+  {
+    m_pcTDecBinIf->decodeBin( uiFlag, m_cIntraDMMSCModel.get(0, 0, 0) );
+  }
+  if ( uiFlag )
+  {
+    UInt uiDMMode;
+
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode  = uiSymbol;
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode |= uiSymbol << 1;
+    if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && g_uiMaxCUWidth>>uiDepth > 4 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode |= uiSymbol << 2;
+    }
+#else
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode  = uiSymbol;
+      if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && g_uiMaxCUWidth>>uiDepth > 4 )
+      {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode |= uiSymbol << 1;
+    }
+#endif
+    uiIPredMode = uiDMMode + MAX_MODE_ID_INTRA_DIR + 1;
+
+#if HHI_DMM_WEDGE_INTRA
+    if( uiIPredMode == DMM_WEDGE_FULL_IDX )          { xParseWedgeFullInfo          ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( uiIPredMode == DMM_WEDGE_FULL_D_IDX )        { xParseWedgeFullDeltaInfo     ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( uiIPredMode == DMM_WEDGE_PREDDIR_IDX )       { xParseWedgePredDirInfo       ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( uiIPredMode == DMM_WEDGE_PREDDIR_D_IDX )     { xParseWedgePredDirDeltaInfo  ( pcCU, uiAbsPartIdx, uiDepth ); }
+#endif
+#if HHI_DMM_PRED_TEX
+    if( uiIPredMode == DMM_WEDGE_PREDTEX_D_IDX )     { xParseWedgePredTexDeltaInfo  ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( uiIPredMode == DMM_CONTOUR_PREDTEX_D_IDX )   { xParseContourPredTexDeltaInfo( pcCU, uiAbsPartIdx, uiDepth ); }
+#endif
+  }
+  else
+#endif
+  {
+    Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+   
+    Int uiPreds[2] = {-1, -1};
+    Int uiPredNum = pcCU->getIntraDirLumaPredictor(uiAbsPartIdx, uiPreds);  
+
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 0) );
+   
+    if ( uiSymbol )
+    {
+      if(uiPredNum == 1)   
+      {
+        uiIPredMode = uiPreds[0];
+      }
+      else 
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 2) );
+        uiIPredMode = uiPreds[uiSymbol];
+      }
+    }
+    else
+    {
+      if ( g_aucIntraModeBitsAng[iIntraIdx] < 6 )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode  = uiSymbol;
+        if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) { m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 1; }
+        if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) { m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 2; }
+        if ( g_aucIntraModeBitsAng[iIntraIdx] > 4 ) { m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 3; }
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode  = uiSymbol;
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 1;
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 2;
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 3;
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 4;
+
+        if (uiIPredMode == 31)
+        { // Escape coding for the last two modes
+          m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) );
+          uiIPredMode = uiSymbol ? 32 : 31;
+        }
+      }
+
+      for(UInt i = 0; i < uiPredNum; i++)
+      {
+        if(uiIPredMode >= uiPreds[i]) {  uiIPredMode ++; }
+      }
+    }
+#if ADD_PLANAR_MODE
+    if (uiIPredMode == 2)
+    {
+      UInt planarFlag;
+      m_pcTDecBinIf->decodeBin( planarFlag, m_cPlanarFlagSCModel.get(0,0,0) );
+      if ( planarFlag )
+      {
+        uiIPredMode = PLANAR_IDX;
+      }
+    }
+#endif
+  }
+
+  pcCU->setLumaIntraDirSubParts( (UChar)uiIPredMode, uiAbsPartIdx, uiDepth );
+}
+#else
+Void TDecSbac::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int  uiIPredMode;
+  UInt uiSymbol;
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  UInt uiFlag = 0;
+  if ( pcCU->getSlice()->getSPS()->isDepth() && pcCU->getSlice()->getSPS()->getUseDMM() && g_uiMaxCUWidth>>uiDepth < 64 )
+  {
+    m_pcTDecBinIf->decodeBin( uiFlag, m_cIntraDMMSCModel.get(0, 0, 0) );
+  }
+  if ( uiFlag )
+  {
+    UInt uiDMMode;
+
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode  = uiSymbol;
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode |= uiSymbol << 1;
+      if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && g_uiMaxCUWidth>>uiDepth > 4 )
+      {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode |= uiSymbol << 2;
+        }
+#else
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode  = uiSymbol;
+      if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && g_uiMaxCUWidth>>uiDepth > 4 )
+      {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cIntraDMMSCModel.get(0, 0, 1) ); uiDMMode |= uiSymbol << 1;
+    }
+#endif
+    uiIPredMode = g_aucAdditionalIntraModeList[uiDMMode];
+
+#if HHI_DMM_WEDGE_INTRA
+    if( uiIPredMode == DMM_WEDGE_FULL_IDX )          { xParseWedgeFullInfo          ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( uiIPredMode == DMM_WEDGE_FULL_D_IDX )        { xParseWedgeFullDeltaInfo     ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( uiIPredMode == DMM_WEDGE_PREDDIR_IDX )       { xParseWedgePredDirInfo       ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( uiIPredMode == DMM_WEDGE_PREDDIR_D_IDX )     { xParseWedgePredDirDeltaInfo  ( pcCU, uiAbsPartIdx, uiDepth ); }
+#endif
+#if HHI_DMM_PRED_TEX
+    if( uiIPredMode == DMM_WEDGE_PREDTEX_D_IDX )     { xParseWedgePredTexDeltaInfo  ( pcCU, uiAbsPartIdx, uiDepth ); }
+    if( uiIPredMode == DMM_CONTOUR_PREDTEX_D_IDX )   { xParseContourPredTexDeltaInfo( pcCU, uiAbsPartIdx, uiDepth ); }
+#endif
+  }
+  else
+#endif
+  {
+  Int  iMostProbable = pcCU->getMostProbableIntraDirLuma( uiAbsPartIdx );
+  
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 0) );
+  
+  if ( uiSymbol )
+    uiIPredMode = iMostProbable;
+  else
+  {
+    Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+    if ( g_aucIntraModeBitsAng[iIntraIdx] < 6 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode  = uiSymbol;
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) { m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 1; }
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) { m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 2; }
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 4 ) { m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 3; }
+    }
+    else
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode  = uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 1;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 2;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 3;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) ); uiIPredMode |= uiSymbol << 4;
+      
+      if (uiIPredMode == 31)
+      { // Escape coding for the last two modes
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUIntraPredSCModel.get( 0, 0, 1 ) );
+        uiIPredMode = uiSymbol ? 32 : 31;
+      }
+    }
+    
+    if (uiIPredMode >= iMostProbable)
+      uiIPredMode++;
+  }
+  
+#if ADD_PLANAR_MODE
+  if (uiIPredMode == 2)
+  {
+    UInt planarFlag;
+    m_pcTDecBinIf->decodeBin( planarFlag, m_cPlanarFlagSCModel.get(0,0,0) );
+    if ( planarFlag )
+    {
+      uiIPredMode = PLANAR_IDX;
+    }
+  }
+#endif
+  }
+
+  pcCU->setLumaIntraDirSubParts( (UChar)uiIPredMode, uiAbsPartIdx, uiDepth );
+}
+#endif
+Void TDecSbac::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  
+#if CHROMA_CODEWORD
+  UInt uiMode = pcCU->getLumaIntraDir(uiAbsPartIdx);
+#if ADD_PLANAR_MODE
+  if ( (uiMode == 2 ) || (uiMode == PLANAR_IDX) )
+  {
+    uiMode = 4;
+  }
+#endif
+
+#if LM_CHROMA
+  Int  iMaxMode = pcCU->getSlice()->getSPS()->getUseLMChroma() ? 3 : 4;
+  Int  iMax = uiMode < iMaxMode ? 2 : 3; 
+  
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, pcCU->getCtxIntraDirChroma( uiAbsPartIdx ) ) );
+  
+  if ( uiSymbol )
+  {
+    xReadUnaryMaxSymbol( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0 ) + 3, 0, iMax );
+    uiSymbol++;
+  }
+  
+  //switch codeword
+  if (uiSymbol == 0)
+  {
+    uiSymbol = 4;
+  } 
+  else if (uiSymbol == 1 && pcCU->getSlice()->getSPS()->getUseLMChroma())
+  {
+    uiSymbol = 3;
+  }
+  else 
+  {
+#if CHROMA_CODEWORD_SWITCH 
+    uiSymbol = ChromaMapping[iMax-2][uiSymbol];
+#endif
+
+    if (pcCU->getSlice()->getSPS()->getUseLMChroma())
+       uiSymbol --;
+
+    if (uiSymbol <= uiMode)
+       uiSymbol --;
+  }
+#else // <-- LM_CHROMA
+  Int  iMax = uiMode < 4 ? 2 : 3;
+  
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, pcCU->getCtxIntraDirChroma( uiAbsPartIdx ) ) );
+  
+  if ( uiSymbol )
+  {
+    xReadUnaryMaxSymbol( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0 ) + 3, 0, iMax );
+    uiSymbol++;
+  }
+  
+  //switch codeword
+  if (uiSymbol == 0)
+  {
+    uiSymbol = 4;
+  } 
+#if CHROMA_CODEWORD_SWITCH 
+  else
+  {
+    uiSymbol = ChromaMapping[iMax-2][uiSymbol];
+    if (uiSymbol <= uiMode)
+    {
+      uiSymbol --;
+    }
+  }
+#else
+  else if (uiSymbol <= uiMode)
+  {
+    uiSymbol --;
+  }
+#endif
+#endif // <-- LM_CHROMA
+
+#else // CHROMA_CODEWORD
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, pcCU->getCtxIntraDirChroma( uiAbsPartIdx ) ) );
+  
+  if ( uiSymbol )
+  {
+    xReadUnaryMaxSymbol( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0 ) + 3, 0, 3 );
+    uiSymbol++;
+  }
+#endif
+  
+#if ADD_PLANAR_MODE
+  if (uiSymbol == 2)
+  {
+#if CHROMA_CODEWORD
+    uiMode = pcCU->getLumaIntraDir(uiAbsPartIdx);
+    if (uiMode == 2)
+    {
+      uiSymbol = PLANAR_IDX;
+    }
+    else if (uiMode != PLANAR_IDX)
+#endif
+    {
+      UInt planarFlag;
+      m_pcTDecBinIf->decodeBin( planarFlag, m_cPlanarFlagSCModel.get(0,0,1) );
+      if ( planarFlag )
+      {
+        uiSymbol = PLANAR_IDX;
+      }
+    }
+  }
+#endif
+  pcCU->setChromIntraDirSubParts( uiSymbol, uiAbsPartIdx, uiDepth );
+  
+  return;
+}
+
+Void TDecSbac::parseInterDir( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  UInt uiCtx = pcCU->getCtxInterDir( uiAbsPartIdx );
+  
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUInterDirSCModel.get( 0, 0, uiCtx ) );
+  
+  if ( uiSymbol )
+  {
+    uiSymbol = 2;
+  }
+#if DCM_COMB_LIST
+  else if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+  {
+    uiSymbol = 0;
+  }
+#endif
+  else if ( pcCU->getSlice()->getNoBackPredFlag() )
+  {
+    uiSymbol = 0;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUInterDirSCModel.get( 0, 0, 3 ) );
+  }
+  uiSymbol++;
+  ruiInterDir = uiSymbol;
+  return;
+}
+
+Void TDecSbac::parseRefFrmIdx( TComDataCU* pcCU, Int& riRefFrmIdx, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+
+#if DCM_COMB_LIST
+  if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C ) > 0 && eRefList==REF_PIC_LIST_C)
+  {
+    UInt uiCtx;
+
+    uiCtx = pcCU->getCtxRefIdx( uiAbsPartIdx, RefPicList(pcCU->getSlice()->getListIdFromIdxOfLC(0)) );
+
+    m_pcTDecBinIf->decodeBin ( uiSymbol, m_cCURefPicSCModel.get( 0, 0, uiCtx ) );
+
+    if ( uiSymbol )
+    {
+      xReadUnaryMaxSymbol( uiSymbol, &m_cCURefPicSCModel.get( 0, 0, 4 ), 1, pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C )-2 );
+
+      uiSymbol++;
+    }
+
+    riRefFrmIdx = uiSymbol;
+  }
+  else
+  {
+#endif
+
+  UInt uiCtx = pcCU->getCtxRefIdx( uiAbsPartIdx, eRefList );
+  
+  m_pcTDecBinIf->decodeBin ( uiSymbol, m_cCURefPicSCModel.get( 0, 0, uiCtx ) );
+  if ( uiSymbol )
+  {
+    xReadUnaryMaxSymbol( uiSymbol, &m_cCURefPicSCModel.get( 0, 0, 4 ), 1, pcCU->getSlice()->getNumRefIdx( eRefList )-2 );
+    
+    uiSymbol++;
+  }
+  riRefFrmIdx = uiSymbol;
+
+#if DCM_COMB_LIST
+  }
+#endif
+
+  return;
+}
+
+Void TDecSbac::parseViewIdx(Int &riViewIdx)
+{
+  assert(0) ; // not implemented yet
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, &m_cViewIdxSCModel.get(0,0,4), 1, MAX_NUMBER_VIEWS);
+  riViewIdx = uiSymbol;
+}
+
+Void TDecSbac::parseMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  Int iHor, iVer;
+  UInt uiAbsPartIdxL, uiAbsPartIdxA;
+#if MVD_CTX
+  Int iHorPredL, iVerPredL;
+  Int iHorPredA, iVerPredA;
+#else
+  Int iHorPred, iVerPred;
+#endif
+
+  TComDataCU* pcCUL   = pcCU->getPULeft ( uiAbsPartIdxL, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  TComDataCU* pcCUA   = pcCU->getPUAbove( uiAbsPartIdxA, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  
+  TComCUMvField* pcCUMvFieldL = ( pcCUL == NULL || pcCUL->isIntra( uiAbsPartIdxL ) ) ? NULL : pcCUL->getCUMvField( eRefList );
+  TComCUMvField* pcCUMvFieldA = ( pcCUA == NULL || pcCUA->isIntra( uiAbsPartIdxA ) ) ? NULL : pcCUA->getCUMvField( eRefList );
+
+#if MVD_CTX
+  iHorPredL = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsHor() );
+  iVerPredL = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsVer() );
+  iHorPredA = ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsHor() );
+  iVerPredA = ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsVer() );
+#else
+  iHorPred = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsHor() ) +
+  ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsHor() );
+  iVerPred = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsVer() ) +
+  ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsVer() );
+#endif
+
+  TComMv cTmpMv( 0, 0 );
+  pcCU->getCUMvField( eRefList )->setAllMv( cTmpMv, pcCU->getPartitionSize( uiAbsPartIdx ), uiAbsPartIdx, uiPartIdx, uiDepth );
+  
+#if MVD_CTX
+  xReadMvd( iHor, iHorPredL, iHorPredA, 0 );
+  xReadMvd( iVer, iVerPredL, iVerPredA, 1 );
+#else
+  xReadMvd( iHor, iHorPred, 0 );
+  xReadMvd( iVer, iVerPred, 1 );
+#endif  
+
+  // set mvd
+  TComMv cMv( iHor, iVer );
+  pcCU->getCUMvField( eRefList )->setAllMvd( cMv, pcCU->getPartitionSize( uiAbsPartIdx ), uiAbsPartIdx, uiPartIdx, uiDepth );
+  
+  return;
+}
+
+
+Void TDecSbac::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
+{
+  m_pcTDecBinIf->decodeBin( ruiSubdivFlag, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiLog2TransformBlockSize ) );
+  DTRACE_CABAC_V( 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 = pcCU->getCtxQtRootCbf( uiAbsPartIdx );
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_V( 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 )
+{
+  UInt uiDQp;
+  Int  iDQp;
+  
+  m_pcTDecBinIf->decodeBin( uiDQp, m_cCUDeltaQpSCModel.get( 0, 0, 0 ) );
+  
+  if ( uiDQp == 0 )
+  {
+    uiDQp = pcCU->getSlice()->getSliceQp();
+  }
+  else
+  {
+    xReadUnarySymbol( uiDQp, &m_cCUDeltaQpSCModel.get( 0, 0, 2 ), 1 );
+    iDQp = ( uiDQp + 2 ) / 2;
+    
+    if ( uiDQp & 1 )
+    {
+      iDQp = -iDQp;
+    }
+    uiDQp = pcCU->getSlice()->getSliceQp() + iDQp;
+  }
+  
+  pcCU->setQPSubParts( uiDQp, uiAbsPartIdx, uiDepth );
+}
+
+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 ? eType - 1: eType, uiCtx ) );
+  
+  DTRACE_CABAC_V( 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 );
+}
+
+
+#if PCP_SIGMAP_SIMPLE_LAST
+/** 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 uiWidth block width
+ * \param eTType plane type / luminance or chrominance
+ * \param uiCTXIdx block size context
+ * \param uiScanIdx scan type (zig-zag, hor, ver)
+ * \returns Void
+ * This method decodes the X and Y component within a block of the last significant coefficient.
+ */
+__inline Void TDecSbac::parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, const UInt uiWidth, const TextType eTType, const UInt uiCTXIdx, const UInt uiScanIdx )
+{
+  UInt uiLast;
+  const UInt uiCtxOffset = g_uiCtxXYOffset[uiCTXIdx];
+
+  for(uiPosLastX=0; uiPosLastX<uiWidth-1; uiPosLastX++)
+  {
+    m_pcTDecBinIf->decodeBin( uiLast, m_cCuCtxLastX.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiPosLastX] ) );
+    if(uiLast)
+    {
+      break;
+    }
+  }
+
+  for(uiPosLastY=0; uiPosLastY<uiWidth-1; uiPosLastY++)
+  {
+    m_pcTDecBinIf->decodeBin( uiLast, m_cCuCtxLastY.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiPosLastY] ) );
+    if(uiLast)
+    {
+      break;
+    }
+  }
+
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosLastX, uiPosLastY );
+  }
+}
+#endif
+
+Void TDecSbac::parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+  DTRACE_CABAC_V( 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();
+  }
+  
+  UInt uiCTXIdx;
+  
+  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;
+  }
+  
+  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     = 1 << ( uiLog2BlockSize << 1 );
+  const UInt  uiMaxNumCoeffM1   = uiMaxNumCoeff - 1;
+  const UInt  uiNum4x4Blk       = max<UInt>( 1, uiMaxNumCoeff >> 4 );
+#if !PCP_SIGMAP_SIMPLE_LAST
+  bool        bLastReceived     = false;
+#endif
+#if QC_MDCS
+  const UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+#endif //QC_MDCS
+  
+#if PCP_SIGMAP_SIMPLE_LAST
+    //===== decode last significant =====
+    UInt uiPosLastX, uiPosLastY;
+    parseLastSignificantXY( uiPosLastX, uiPosLastY, uiWidth, eTType, uiCTXIdx, uiScanIdx );
+    UInt uiBlkPosLast      = uiPosLastX + (uiPosLastY<<uiLog2BlockSize);
+    pcCoef[ uiBlkPosLast ] = 1;
+
+    //===== decode significance flags =====
+    for( UInt uiScanPos = 0; uiScanPos < uiMaxNumCoeffM1; uiScanPos++ )
+    {
+#if QC_MDCS
+      UInt uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlockSize-1][uiScanPos]; 
+#else
+      UInt  uiBlkPos  = g_auiFrameScanXY[ uiLog2BlockSize-1 ][ uiScanPos ];
+#endif //QC_MDCS
+      if( uiBlkPosLast == uiBlkPos )
+      {
+        break;
+      }
+      UInt  uiPosY    = uiBlkPos >> uiLog2BlockSize;
+      UInt  uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+      UInt  uiSig     = 0;
+      UInt  uiCtxSig  = TComTrQuant::getSigCtxInc( pcCoef, uiPosX, uiPosY, uiLog2BlockSize, uiWidth );
+#if SIMPLE_CONTEXT_SIG
+      if( uiCtxSig < 4 || eTType )
+      {
+        m_pcTDecBinIf->decodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx-2, eTType, uiCtxSig ) );
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx-2 ? uiCTXIdx-2 : 1 , eTType, uiCtxSig ) );
+      }
+#else
+      m_pcTDecBinIf->decodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx, eTType, uiCtxSig ) );
+#endif
+      pcCoef[ uiBlkPos ] = uiSig;
+    }
+
+#else
+  for( UInt uiScanPos = 0; uiScanPos < uiMaxNumCoeffM1; uiScanPos++ )
+  {
+#if QC_MDCS
+    UInt uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlockSize-1][uiScanPos]; 
+#else
+    UInt  uiBlkPos  = g_auiFrameScanXY[ uiLog2BlockSize-1 ][ uiScanPos ];
+#endif //QC_MDCS
+    UInt  uiPosY    = uiBlkPos >> uiLog2BlockSize;
+    UInt  uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+    
+    //===== code significance flag =====
+    UInt  uiSig     = 0;
+    UInt  uiCtxSig  = TComTrQuant::getSigCtxInc( pcCoef, uiPosX, uiPosY, uiLog2BlockSize, uiWidth );
+#if SIMPLE_CONTEXT_SIG
+      if( uiCtxSig < 4 || eTType )
+      {
+        m_pcTDecBinIf->decodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx-2, eTType, uiCtxSig ) );
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx-2 ? uiCTXIdx-2 : 1 , eTType, uiCtxSig ) );
+      }
+#else
+    m_pcTDecBinIf->decodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx, eTType, uiCtxSig ) );
+#endif
+    if( uiSig )
+    {
+      pcCoef[ uiBlkPos ] = 1;
+      
+      //===== code last flag =====
+      UInt  uiLast     = 0;
+      UInt  uiCtxLast  = TComTrQuant::getLastCtxInc( uiPosX, uiPosY, uiLog2BlockSize );
+      m_pcTDecBinIf->decodeBin( uiLast, m_cCULastSCModel.get( uiCTXIdx, eTType, uiCtxLast ) );
+      
+      if( uiLast )
+      {
+        bLastReceived = true;
+        break;
+      }
+    }
+  }
+  if( !bLastReceived )
+  {
+    pcCoef[ uiMaxNumCoeffM1 ] = 1;
+  }
+#endif
+  
+  /*
+   * Sign and bin0 PCP (Section 3.2 and 3.3 of JCTVC-B088)
+   */
+  Int  c1, c2;
+  UInt uiSign;
+  UInt uiLevel;
+#if E253
+  UInt uiGoRiceParam = 0;
+#endif
+
+  if( uiNum4x4Blk > 1 )
+  {
+    Bool b1stBlk  = true;
+    UInt uiNumOne = 0;
+    
+    for( UInt uiSubBlk = 0; uiSubBlk < uiNum4x4Blk; uiSubBlk++ )
+    {
+      UInt uiCtxSet    = 0;
+      UInt uiSubNumSig = 0;
+      UInt uiSubPosX   = 0;
+      UInt uiSubPosY   = 0;
+#if E253
+      uiGoRiceParam    = 0;
+#endif
+
+      uiSubPosX = g_auiFrameScanX[ g_aucConvertToBit[ uiWidth ] - 1 ][ uiSubBlk ] << 2;
+      uiSubPosY = g_auiFrameScanY[ g_aucConvertToBit[ uiWidth ] - 1 ][ uiSubBlk ] << 2;
+      
+      TCoeff* piCurr = &pcCoef[ uiSubPosX + uiSubPosY * uiWidth ];
+      
+      for( UInt uiY = 0; uiY < 4; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < 4; uiX++ )
+        {
+          if( piCurr[ uiX ] )
+          {
+            uiSubNumSig++;
+          }
+        }
+        piCurr += uiWidth;
+      }
+      
+      if( uiSubNumSig > 0 )
+      {
+        c1 = 1;
+        c2 = 0;
+        
+        if( b1stBlk )
+        {
+          b1stBlk  = false;
+          uiCtxSet = 5;
+        }
+        else
+        {
+          uiCtxSet = ( uiNumOne >> 2 ) + 1;
+          uiNumOne = 0;
+        }
+        
+        for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+        {
+          UInt  uiBlkPos  = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+          UInt  uiPosY    = uiBlkPos >> 2;
+          UInt  uiPosX    = uiBlkPos - ( uiPosY << 2 );
+          UInt  uiIndex   = ( ( uiSubPosY + uiPosY ) << uiLog2BlockSize ) + uiSubPosX + uiPosX;
+          
+          uiLevel = pcCoef[ uiIndex ];
+          
+          if( uiLevel )
+          {
+            UInt uiCtx = min<UInt>(c1, 4);
+            m_pcTDecBinIf->decodeBin( uiLevel, m_cCUOneSCModel.get( 0, eTType, ( uiCtxSet << 2 ) + uiCtxSet + uiCtx ) );
+            if( uiLevel == 1 )
+            {
+              c1      = 0;
+              uiLevel = 2;
+            }
+            else if( c1 )
+            {
+              c1++;
+              uiLevel++;
+            }
+            else
+            {
+              uiLevel++;
+            }
+            pcCoef[ uiIndex ] = uiLevel;
+          }
+        }
+        
+        for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+        {
+          UInt  uiBlkPos  = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+          UInt  uiPosY    = uiBlkPos >> 2;
+          UInt  uiPosX    = uiBlkPos - ( uiPosY << 2 );
+          UInt  uiIndex   = ( ( uiSubPosY + uiPosY ) << uiLog2BlockSize ) + uiSubPosX + uiPosX;
+          
+          uiLevel = pcCoef[ uiIndex ];
+          
+          if( uiLevel )
+          {
+            if( uiLevel == 2 )
+            {
+              UInt uiCtx = min<UInt>(c2, 4);
+              c2++;
+              uiNumOne++;
+#if E253
+              m_pcTDecBinIf->decodeBin( uiLevel, m_cCUAbsSCModel.get( 0, eTType, ( uiCtxSet << 2 ) + uiCtxSet + uiCtx ) );
+
+              if( uiLevel )
+              {
+                xReadGoRiceExGolomb( uiLevel, uiGoRiceParam );
+                uiLevel += 3;
+              }
+              else
+              {
+                uiLevel = 2;
+              }
+#else
+              xReadExGolombLevel( uiLevel, m_cCUAbsSCModel.get( 0, eTType, ( uiCtxSet << 2 ) + uiCtxSet + uiCtx ) );
+              uiLevel += 2;
+#endif
+            }
+            pcCoef[ uiIndex ] = uiLevel;
+          }
+        }
+        
+        for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+        {
+          UInt  uiBlkPos  = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+          UInt  uiPosY    = uiBlkPos >> 2;
+          UInt  uiPosX    = uiBlkPos - ( uiPosY << 2 );
+          UInt  uiIndex   = (uiSubPosY + uiPosY) * uiWidth + uiSubPosX + uiPosX;
+          
+          uiLevel = pcCoef[ uiIndex ];
+          
+          if( uiLevel )
+          {
+            m_pcTDecBinIf->decodeBinEP( uiSign );
+            pcCoef[ uiIndex ] = ( uiSign ? -(Int)uiLevel : (Int)uiLevel );
+          }
+        }
+      }
+    }
+  }
+  else
+  {
+    c1 = 1;
+    c2 = 0;
+    
+    for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+    {
+      UInt uiIndex = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+      uiLevel = pcCoef[ uiIndex ];
+      
+      if( uiLevel )
+      {
+        UInt uiCtx = min<UInt>(c1, 4);
+        m_pcTDecBinIf->decodeBin( uiLevel, m_cCUOneSCModel.get( 0, eTType, uiCtx ) );
+        if( uiLevel == 1 )
+        {
+          c1      = 0;
+          uiLevel = 2;
+        }
+        else if( c1 )
+        {
+          c1++;
+          uiLevel++;
+        }
+        else
+        {
+          uiLevel++;
+        }
+        pcCoef[ uiIndex ] = uiLevel;
+      }
+    }
+    
+    for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+    {
+      UInt uiIndex = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+      uiLevel = pcCoef[ uiIndex ];
+      
+      if( uiLevel )
+      {
+        if( uiLevel == 2 )
+        {
+          UInt uiCtx = min<UInt>(c2, 4);
+          c2++;
+#if E253
+          m_pcTDecBinIf->decodeBin( uiLevel, m_cCUAbsSCModel.get( 0, eTType, uiCtx ) );
+
+          if( uiLevel )
+          {
+            xReadGoRiceExGolomb( uiLevel, uiGoRiceParam );
+            uiLevel += 3;
+          }
+          else
+          {
+            uiLevel = 2;
+          }
+#else
+          xReadExGolombLevel( uiLevel, m_cCUAbsSCModel.get( 0, eTType, uiCtx ) );
+          uiLevel += 2;
+#endif
+        }
+        pcCoef[ uiIndex ] = uiLevel;
+      }
+    }
+    
+    for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+    {
+      UInt uiIndex = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+      uiLevel = pcCoef[ uiIndex ];
+      
+      if( uiLevel )
+      {
+        m_pcTDecBinIf->decodeBinEP( uiSign );
+        pcCoef[ uiIndex ] = ( uiSign ? -(Int)uiLevel : (Int)uiLevel );
+      }
+    }
+  }
+  
+  return;
+}
+
+Void TDecSbac::parseAlfFlag (UInt& ruiVal)
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cALFFlagSCModel.get( 0, 0, 0 ) );
+  
+  ruiVal = uiSymbol;
+}
+
+#if TSB_ALF_HEADER
+Void TDecSbac::parseAlfFlagNum( UInt& ruiVal, UInt minValue, UInt depth )
+{
+  UInt uiLength = 0;
+  UInt maxValue = (minValue << (depth*2));
+  UInt temp = maxValue - minValue;
+  for(UInt i=0; i<32; i++)
+  {
+    if(temp&0x1)
+    {
+      uiLength = i+1;
+    }
+    temp = (temp >> 1);
+  }
+  ruiVal = 0;
+  UInt uiBit;
+  if(uiLength)
+  {
+    while( uiLength-- )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiBit );
+      ruiVal += uiBit << uiLength;
+    }
+  }
+  else
+  {
+    ruiVal = 0;
+  }
+  ruiVal += minValue;
+}
+
+Void TDecSbac::parseAlfCtrlFlag( UInt &ruiAlfCtrlFlag )
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUAlfCtrlFlagSCModel.get( 0, 0, 0 ) );
+  ruiAlfCtrlFlag = uiSymbol;
+}
+#endif
+
+Void TDecSbac::parseAlfUvlc (UInt& ruiVal)
+{
+  UInt uiCode;
+  Int  i;
+  
+  m_pcTDecBinIf->decodeBin( uiCode, m_cALFUvlcSCModel.get( 0, 0, 0 ) );
+  if ( uiCode == 0 )
+  {
+    ruiVal = 0;
+    return;
+  }
+  
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBin( uiCode, m_cALFUvlcSCModel.get( 0, 0, 1 ) );
+    if ( uiCode == 0 ) break;
+    i++;
+  }
+  
+  ruiVal = i;
+}
+
+Void TDecSbac::parseAlfSvlc (Int&  riVal)
+{
+  UInt uiCode;
+  Int  iSign;
+  Int  i;
+  
+  m_pcTDecBinIf->decodeBin( uiCode, m_cALFSvlcSCModel.get( 0, 0, 0 ) );
+  
+  if ( uiCode == 0 )
+  {
+    riVal = 0;
+    return;
+  }
+  
+  // read sign
+  m_pcTDecBinIf->decodeBin( uiCode, m_cALFSvlcSCModel.get( 0, 0, 1 ) );
+  
+  if ( uiCode == 0 ) iSign =  1;
+  else               iSign = -1;
+  
+  // read magnitude
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBin( uiCode, m_cALFSvlcSCModel.get( 0, 0, 2 ) );
+    if ( uiCode == 0 ) break;
+    i++;
+  }
+  
+  riVal = i*iSign;
+}
+
+#if MTK_SAO
+Void TDecSbac::parseAoFlag (UInt& ruiVal)
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cAOFlagSCModel.get( 0, 0, 0 ) );
+
+  ruiVal = uiSymbol;
+}
+
+Void TDecSbac::parseAoUvlc (UInt& ruiVal)
+{
+  UInt uiCode;
+  Int  i;
+
+  m_pcTDecBinIf->decodeBin( uiCode, m_cAOUvlcSCModel.get( 0, 0, 0 ) );
+  if ( uiCode == 0 )
+  {
+    ruiVal = 0;
+    return;
+  }
+
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBin( uiCode, m_cAOUvlcSCModel.get( 0, 0, 1 ) );
+    if ( uiCode == 0 ) break;
+    i++;
+  }
+
+  ruiVal = i;
+}
+
+Void TDecSbac::parseAoSvlc (Int&  riVal)
+{
+  UInt uiCode;
+  Int  iSign;
+  Int  i;
+
+  m_pcTDecBinIf->decodeBin( uiCode, m_cAOSvlcSCModel.get( 0, 0, 0 ) );
+
+  if ( uiCode == 0 )
+  {
+    riVal = 0;
+    return;
+  }
+
+  // read sign
+  m_pcTDecBinIf->decodeBin( uiCode, m_cAOSvlcSCModel.get( 0, 0, 1 ) );
+
+  if ( uiCode == 0 ) iSign =  1;
+  else               iSign = -1;
+
+  // read magnitude
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBin( uiCode, m_cAOSvlcSCModel.get( 0, 0, 2 ) );
+    if ( uiCode == 0 ) break;
+    i++;
+  }
+
+  riVal = i*iSign;
+}
+#endif
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecSbac.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecSbac.h	(revision 19)
@@ -0,0 +1,236 @@
+/* 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     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"
+
+// ====================================================================================================================
+// 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  resetEntropy              ( TComSlice* pcSlice     );
+  Void  setBitstream              ( TComBitstream* p       ) { m_pcBitstream = p; m_pcTDecBinIf->init( p ); }
+  
+  Void  setAlfCtrl                ( Bool bAlfCtrl          ) { m_bAlfCtrl = bAlfCtrl;                   }
+  Void  setMaxAlfCtrlDepth        ( UInt uiMaxAlfCtrlDepth ) { m_uiMaxAlfCtrlDepth = uiMaxAlfCtrlDepth; }
+  
+  Void  parseNalUnitHeader    ( NalUnitType& eNalUnitType, UInt& TemporalId, Bool& bOutputFlag ) {}
+  
+  Void  parseSPS                  ( TComSPS* pcSPS         ) {}
+  Void  parsePPS                  ( TComPPS* pcPPS         ) {}
+  void parseSEI(SEImessages&) {}
+  Void  parseSliceHeader          ( TComSlice*& rpcSlice   ) {}
+  Void  parseTerminatingBit       ( UInt& ruiBit );
+  Void  parseMVPIdx               ( TComDataCU* pcCU, Int& riMVPIdx, Int iMVPNum, UInt uiAbsPartIdx, UInt uiDepth, RefPicList eRefList );
+  
+  Void  parseAlfFlag              ( UInt& ruiVal           );
+  Void  parseAlfUvlc              ( UInt& ruiVal           );
+  Void  parseAlfSvlc              ( Int&  riVal            );
+  Void  parseAlfCtrlDepth         ( UInt& ruiAlfCtrlDepth  );
+#if MTK_SAO
+  Void  parseAoFlag              ( UInt& ruiVal           );
+  Void  parseAoUvlc              ( UInt& ruiVal           );
+  Void  parseAoSvlc              ( Int&  riVal            );
+#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 );
+#if E253
+  Void  xReadGoRiceExGolomb ( UInt &ruiSymbol, UInt &ruiGoRiceParam );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void  xReadExGolombLevel  ( UInt& ruiSymbol, ContextModel& rcSCModel  );
+#endif
+#else
+  Void  xReadExGolombLevel  ( UInt& ruiSymbol, ContextModel& rcSCModel  );
+#endif
+  
+#if MVD_CTX
+  Void  xReadMvd            ( Int& riMvdComp, UInt uiAbsSumL, UInt uiAbsSumA, UInt uiCtx );
+#else
+  Void  xReadMvd            ( Int& riMvdComp, UInt uiAbsSum, UInt uiCtx );
+#endif
+
+  Void  xReadExGolombMvd    ( UInt& ruiSymbol, ContextModel* pcSCModel, UInt uiMaxBin );
+  
+#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
+  Void xParseWedgePredTexDeltaInfo  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void xParseContourPredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  
+private:
+  TComBitstream*    m_pcBitstream;
+  TDecBinIf*        m_pcTDecBinIf;
+  
+  Bool m_bAlfCtrl;
+  UInt m_uiMaxAlfCtrlDepth;
+  
+public:
+  Void parseAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if TSB_ALF_HEADER
+  Void parseAlfFlagNum    ( UInt& ruiVal, UInt minValue, UInt depth );
+  Void parseAlfCtrlFlag   ( UInt &ruiAlfCtrlFlag );
+#endif
+  
+  Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  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 HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+  Void parseMergeIndexMV  ( TComDataCU* pcCU, UInt& ruiMergeIndex, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void parseResPredFlag   ( TComDataCU* pcCU, Bool& rbResPredFlag, 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 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 parseCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth ) {}
+  Void parseBlockCbf      ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth, UInt uiQPartNum ) {}
+  
+#if CAVLC_RQT_CBP
+  Void parseCbfTrdiv      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiTrDepth, UInt uiDepth, UInt& uiSubdiv ) {}
+#endif
+
+#if PCP_SIGMAP_SIMPLE_LAST
+  __inline Void parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, const UInt uiWidth, const TextType eTType, const UInt uiCTXIdx, const UInt uiScanIdx );
+#endif
+  Void parseCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  Void parseViewIdx       (Int &riViewIdx );
+  
+private:
+  UInt m_uiLastDQpNonZero;
+  UInt m_uiLastQp;
+  
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+  ContextModel3DBuffer m_cCUMVMergeIdxExtSCModel;
+  ContextModel3DBuffer m_cResPredFlagSCModel;
+  ContextModel3DBuffer m_cCUAlfCtrlFlagSCModel;
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+#if ADD_PLANAR_MODE
+  ContextModel3DBuffer m_cPlanarFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  
+  ContextModel3DBuffer m_cCUSigSCModel;
+#if PCP_SIGMAP_SIMPLE_LAST
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+#else  
+  ContextModel3DBuffer m_cCULastSCModel;
+#endif
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+  
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+  
+  ContextModel3DBuffer m_cALFFlagSCModel;
+  ContextModel3DBuffer m_cALFUvlcSCModel;
+  ContextModel3DBuffer m_cALFSvlcSCModel;
+#if MTK_SAO
+  ContextModel3DBuffer m_cAOFlagSCModel;
+  ContextModel3DBuffer m_cAOUvlcSCModel;
+  ContextModel3DBuffer m_cAOSvlcSCModel;
+#endif
+  ContextModel3DBuffer m_cViewIdxSCModel;
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  ContextModel3DBuffer m_cIntraDMMSCModel;
+  ContextModel3DBuffer m_cIntraWedgeSCModel;
+#endif
+};
+
+#endif // !defined(AFX_TDECSBAC_H__CFCAAA19_8110_47F4_9A16_810C4B5499D5__INCLUDED_)
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 19)
@@ -0,0 +1,109 @@
+/* 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     TDecSlice.cpp
+    \brief    slice decoder class
+*/
+
+#include "TDecSlice.h"
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+TDecSlice::TDecSlice()
+{
+}
+
+TDecSlice::~TDecSlice()
+{
+}
+
+Void TDecSlice::create( TComSlice* pcSlice, Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth )
+{
+}
+
+Void TDecSlice::destroy()
+{
+}
+
+Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcCuDecoder       = pcCuDecoder;
+}
+
+Void TDecSlice::decompressSlice(TComBitstream* pcBitstream, TComPic*& rpcPic)
+{
+  TComDataCU* pcCU;
+  UInt        uiIsLast = 0;
+  Int   iStartCUAddr = max(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr(), rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getEntropySliceCurStartCUAddr());
+
+  // 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_V( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( rpcPic->getPOC() );
+  DTRACE_CABAC_T( "\n" );
+
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+  // for all CUs in slice
+  UInt  uiLastCUAddr = iStartCUAddr;
+  for( Int iCUAddr = iStartCUAddr; !uiIsLast && iCUAddr < rpcPic->getNumCUsInFrame(); iCUAddr++, uiLastCUAddr++ )
+  {
+    pcCU = rpcPic->getCU( iCUAddr );
+    pcCU->initCU( rpcPic, iCUAddr );
+    
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+    m_pcCuDecoder->decodeCU     ( pcCU, uiIsLast );
+    m_pcCuDecoder->decompressCU ( pcCU );
+    
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+  }
+
+
+}
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecSlice.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecSlice.h	(revision 19)
@@ -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     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"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice decoder class
+class TDecSlice
+{
+private:
+  // access channel
+  TDecEntropy*    m_pcEntropyDecoder;
+  TDecCu*         m_pcCuDecoder;
+  UInt            m_uiCurrSliceIdx;
+
+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   ( TComBitstream* pcBitstream, TComPic*& rpcPic );
+
+};
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecTop.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecTop.cpp	(revision 19)
@@ -0,0 +1,792 @@
+/* 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.cpp
+    \brief    decoder class
+*/
+
+#include "../../App/TAppDecoder/TAppDecTop.h"
+#include "TDecTop.h"
+
+
+
+CamParsCollector::CamParsCollector()
+: m_bInitialized( false )
+{
+  m_aaiCodedOffset         = new Int* [ MAX_NUMBER_VIEWS ];
+  m_aaiCodedScale          = new Int* [ MAX_NUMBER_VIEWS ];
+  m_aiViewOrderIndex       = new Int  [ MAX_NUMBER_VIEWS ];
+  m_aiViewReceived         = new Int  [ MAX_NUMBER_VIEWS ];
+  for( UInt uiId = 0; uiId < MAX_NUMBER_VIEWS; uiId++ )
+  {
+    m_aaiCodedOffset      [ uiId ] = new Int [ MAX_NUMBER_VIEWS ];
+    m_aaiCodedScale       [ uiId ] = new Int [ MAX_NUMBER_VIEWS ];
+  }
+}
+
+CamParsCollector::~CamParsCollector()
+{
+  for( UInt uiId = 0; uiId < MAX_NUMBER_VIEWS; uiId++ )
+  {
+    delete [] m_aaiCodedOffset      [ uiId ];
+    delete [] m_aaiCodedScale       [ uiId ];
+  }
+  delete [] m_aaiCodedOffset;
+  delete [] m_aaiCodedScale;
+  delete [] m_aiViewOrderIndex;
+  delete [] m_aiViewReceived;
+}
+
+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;
+}
+
+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_NUMBER_VIEWS );
+  if ( pcSlice->getSPS()->isDepth  () )
+  {
+    return;
+  }
+  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 );
+  AOT( !bFirstSliceInAU  &&   pcSlice->getSPS()->getViewId()   < UInt( m_iLastViewId ) );
+  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_NUMBER_VIEWS * 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 ];
+      }
+      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 ];
+      }
+    }
+  }
+  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 ];
+      }
+    }
+  }
+  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_iGopSize      = 0;
+  m_bGopSizeSet   = false;
+  m_iMaxRefPicNum = 0;
+  m_uiValidPS = 0;
+  m_bIsDepth = false ;
+  m_iViewIdx = 0 ;
+#if ENC_DEC_TRACE
+  g_hTrace = fopen( "TraceDec.txt", "wb" );
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#endif
+#if DCM_DECODING_REFRESH
+  m_bRefreshPending = 0;
+  m_uiPOCCDR = 0;
+#if DCM_SKIP_DECODING_FRAMES
+  m_uiPOCRA = MAX_UINT;
+#endif
+#endif
+  m_uiPrevPOC               = UInt(-1);
+  m_bFirstSliceInPicture    = true;
+  m_bFirstSliceInSequence   = true;
+  m_pcCamParsCollector = 0;
+}
+
+TDecTop::~TDecTop()
+{
+#if ENC_DEC_TRACE
+  fclose( g_hTrace );
+#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();
+
+#if DEPTH_MAP_GENERATION
+  m_cDepthMapGenerator.destroy();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_cResidualGenerator.destroy();
+#endif
+}
+
+Void TDecTop::init( TAppDecTop* pcTAppDecTop, Bool bFirstInstance )
+{
+  // initialize ROM
+  if( bFirstInstance )
+    initROM();
+#if MTK_SAO
+  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 HHI_INTER_VIEW_RESIDUAL_PRED
+                      , &m_cResidualGenerator 
+#endif
+                      );
+#else
+  m_cGopDecoder.  init( &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cAdaptiveLoopFilter
+#if DEPTH_MAP_GENERATION
+                      , &m_cDepthMapGenerator
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+                      , &m_cResidualGenerator 
+#endif
+                      );
+#endif
+  m_cSliceDecoder.init( &m_cEntropyDecoder, &m_cCuDecoder );
+  m_cEntropyDecoder.init(&m_cPrediction);
+
+  m_pcTAppDecTop = pcTAppDecTop;
+#if DEPTH_MAP_GENERATION
+  m_cDepthMapGenerator.init( &m_cPrediction, m_pcTAppDecTop->getSPSAccess(), m_pcTAppDecTop->getAUPicAccess() );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_cResidualGenerator.init( &m_cTrQuant, &m_cDepthMapGenerator );
+#endif
+}
+
+Void TDecTop::setSPS(TComSPS cSPS)
+{
+  m_cSPS = cSPS ;
+      if ( !m_cAdaptiveLoopFilter.isCreated())
+      {
+  m_cAdaptiveLoopFilter.create( m_cSPS.getWidth(), m_cSPS.getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#if MTK_SAO
+  m_cSAO.create( m_cSPS.getWidth(), m_cSPS.getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif
+  m_cLoopFilter.        create( g_uiMaxCUDepth );
+      }
+  m_uiValidPS |= 1;
+}
+
+Void TDecTop::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;
+  }
+
+  // destroy ALF temporary buffers
+  m_cAdaptiveLoopFilter.destroy();
+
+#if MTK_SAO
+  m_cSAO.destroy();
+#endif
+
+  m_cLoopFilter.        destroy();
+
+  // destroy ROM
+  if( m_iViewIdx <= 0 && !m_bIsDepth)
+    destroyROM();
+}
+
+Void TDecTop::xGetNewPicBuffer ( TComSlice* pcSlice, TComPic*& rpcPic )
+{
+  m_iMaxRefPicNum = getCodedPictureBufferSize( );
+
+#if DEPTH_MAP_GENERATION
+  Bool bNeedPrdDepthMapBuffer = ( !pcSlice->getSPS()->isDepth() && ( pcSlice->getSPS()->getViewId() == 0 || pcSlice->getSPS()->getPredDepthMapGeneration() > 0 ) );
+#endif
+
+  if (m_cListPic.size() < (UInt)m_iMaxRefPicNum)
+  {
+    rpcPic = new TComPic;
+    rpcPic->create ( pcSlice->getSPS()->getWidth(), pcSlice->getSPS()->getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#if DEPTH_MAP_GENERATION
+    if( bNeedPrdDepthMapBuffer )
+    {
+      rpcPic->addPrdDepthMapBuffer();
+    }
+#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 )
+    {
+      bBufferIsAvailable = true;
+      break;
+    }
+  }
+
+  if ( !bBufferIsAvailable )
+  {
+    pcSlice->sortPicList(m_cListPic);
+    iterPic = m_cListPic.begin();
+    rpcPic = *(iterPic);
+    rpcPic->setReconMark(false);
+
+    // mark it should be extended
+  }
+  rpcPic->getPicYuvRec()->setBorderExtension(false);
+
+#if DEPTH_MAP_GENERATION
+  if( bNeedPrdDepthMapBuffer && !rpcPic->getPredDepthMap() )
+  {
+    rpcPic->addPrdDepthMapBuffer();
+  }
+#endif
+}
+
+
+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->removeOriginalBuffer   ();
+#if HHI_INTER_VIEW_MOTION_PRED
+    pcPic->removeOrgDepthMapBuffer();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    pcPic->removeResidualBuffer   ();
+#endif
+#if HHI_INTERVIEW_SKIP
+    pcPic->removeUsedPelsMapBuffer();
+#endif
+  }
+}
+
+#if AMVP_BUFFERCOMPRESS
+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();
+  }
+}
+#endif
+
+
+Void TDecTop::executeDeblockAndAlf(Bool bEos, TComBitstream* pcBitstream, UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, Int& iSkipFrame,  Int& iPOCLastDisplay)
+{
+  TComPic*&   pcPic         = m_pcPic;
+
+  // Execute Deblock and ALF only + Cleanup
+  TComSlice* pcSlice  = pcPic->getPicSym()->getSlice( m_uiSliceIdx                  );
+  m_cGopDecoder.decompressGop ( bEos, pcBitstream, pcPic, true);
+
+  if( m_pcCamParsCollector && bEos )
+  {
+    m_pcCamParsCollector->setSlice( 0 );
+  }
+
+  pcSlice->sortPicList        ( m_cListPic );       //  sorting for application output
+  ruiPOC              = pcPic->getSlice(m_uiSliceIdx-1)->getPOC();
+  rpcListPic          = &m_cListPic;
+  m_cCuDecoder.destroy();
+  m_bFirstSliceInPicture  = true;
+
+  return;
+}
+
+#if DCM_SKIP_DECODING_FRAMES
+Bool TDecTop::decode (Bool bEos, TComBitstream* pcBitstream, UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, NalUnitType& reNalUnitType, TComSPS& cComSPS, Int& iSkipFrame,  Int& iPOCLastDisplay)
+#else
+Void TDecTop::decode (Bool bEos, TComBitstream* pcBitstream, UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, NalUnitType& reNalUnitType, TComSPS& cComSPS )
+#endif
+{
+  if (m_bFirstSliceInPicture)
+  {
+    rpcListPic = NULL;
+  }
+  TComPic*&   pcPic         = m_pcPic;
+
+  // Initialize entropy decoder
+  m_cEntropyDecoder.setEntropyDecoder (&m_cCavlcDecoder);
+  m_cEntropyDecoder.setBitstream      (pcBitstream);
+
+  NalUnitType eNalUnitType;
+  UInt        TemporalId;
+  Bool        OutputFlag;
+
+  m_cEntropyDecoder.decodeNalUnitHeader(eNalUnitType, TemporalId, OutputFlag);
+  reNalUnitType = eNalUnitType;
+
+  switch (eNalUnitType)
+  {
+    case NAL_UNIT_SPS:
+    {
+      TComSPS cTempSPS;
+      m_cEntropyDecoder.decodeSPS( &cTempSPS );
+
+      if( (m_iViewIdx == cTempSPS.getViewId()) && ( m_bIsDepth == cTempSPS.isDepth() ) )
+      {
+        m_cSPS = cTempSPS;
+        cComSPS = m_cSPS;
+      }
+      else
+      {
+        cComSPS = cTempSPS;
+        return false;
+      }
+
+      // create ALF temporary buffer
+      if ( !m_cAdaptiveLoopFilter.isCreated())
+      {
+      m_cAdaptiveLoopFilter.create( m_cSPS.getWidth(), m_cSPS.getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#if MTK_SAO
+      m_cSAO.create( m_cSPS.getWidth(), m_cSPS.getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif
+      m_cLoopFilter.        create( g_uiMaxCUDepth );
+      }
+      m_uiValidPS |= 1;
+
+      return false;
+    }
+
+    case NAL_UNIT_PPS:
+      m_cEntropyDecoder.decodePPS( &m_cPPS );
+      assert( m_cPPS.getSPSId() == m_cSPS.getSPSId() );
+      m_uiValidPS |= 2;
+      return false;
+
+    case NAL_UNIT_SEI:
+      m_SEIs = new SEImessages;
+      m_cEntropyDecoder.decodeSEI(*m_SEIs);
+      return false;
+
+    case NAL_UNIT_CODED_SLICE:
+    case NAL_UNIT_CODED_SLICE_IDR:
+    case NAL_UNIT_CODED_SLICE_CDR:
+    {
+      // make sure we already received both parameter sets
+      assert( 3 == m_uiValidPS );
+      if (m_bFirstSliceInPicture)
+      {
+        m_apcSlicePilot->initSlice();
+        m_uiSliceIdx     = 0;
+        m_uiLastSliceIdx = 0;
+      }
+      m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
+
+      //  Read slice header
+      m_apcSlicePilot->setSPS( &m_cSPS );
+      m_apcSlicePilot->setPPS( &m_cPPS );
+      m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
+      m_apcSlicePilot->setViewIdx( m_cSPS.getViewId() );
+      if (!m_bFirstSliceInPicture)
+      {
+        memcpy(m_apcSlicePilot, pcPic->getPicSym()->getSlice(m_uiSliceIdx-1), sizeof(TComSlice));
+      }
+
+#if DCM_DECODING_REFRESH
+      m_apcSlicePilot->setNalUnitType        (eNalUnitType);
+#endif
+      m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot);
+
+//      if (m_apcSlicePilot->isNextSlice() && m_apcSlicePilot->getPOC()!=m_uiPrevPOC && !m_bFirstSliceInSequence)
+//      if (m_apcSlicePilot->isNextSlice() && ( m_apcSlicePilot->getPOC()!=m_uiPrevPOC || m_apcSlicePilot->getPPSId() != m_cPPS.getPPSId() ) && !m_bFirstSliceInSequence)
+      if (m_apcSlicePilot->isNextSlice() && ( m_apcSlicePilot->getPOC()!=m_uiPrevPOC || m_apcSlicePilot->getPPSId() != m_cPPS.getPPSId() ) && !m_bFirstSliceInPicture)
+      {
+        m_uiPrevPOC = m_apcSlicePilot->getPOC();
+        return true;
+      }
+      if (m_apcSlicePilot->isNextSlice())
+        m_uiPrevPOC = m_apcSlicePilot->getPOC();
+      m_bFirstSliceInSequence = false;
+      if (m_apcSlicePilot->isNextSlice())
+      {
+#if DCM_SKIP_DECODING_FRAMES
+        // Skip pictures due to random access
+        if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
+        {
+          return false;
+        }
+#endif
+      }
+
+      if (m_bFirstSliceInPicture)
+      {
+        // Buffer initialize for prediction.
+        m_cPrediction.initTempBuff();
+        //  Get a new picture buffer
+        xGetNewPicBuffer (m_apcSlicePilot, pcPic);
+
+        pcPic->setViewIdx( m_cSPS.getViewId() );
+
+        /* 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()->getWidth(), m_apcSlicePilot->getSPS()->getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+
+#if DEPTH_MAP_GENERATION
+        m_cDepthMapGenerator.create( true, m_apcSlicePilot->getSPS()->getWidth(), m_apcSlicePilot->getSPS()->getHeight(), g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiBitDepth + g_uiBitIncrement );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        m_cResidualGenerator.create( true, m_apcSlicePilot->getSPS()->getWidth(), m_apcSlicePilot->getSPS()->getHeight(), g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiBitDepth + g_uiBitIncrement );
+#endif
+      }
+
+      //  Set picture slice pointer
+      TComSlice*  pcSlice = m_apcSlicePilot;
+      Bool bNextSlice     = pcSlice->isNextSlice();
+      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);
+
+      if (bNextSlice)
+      {
+#if DCM_DECODING_REFRESH
+        // Do decoding refresh marking if any
+        pcSlice->decodingRefreshMarking(m_uiPOCCDR, m_bRefreshPending, m_cListPic);
+#endif
+
+        // Set reference list
+        std::vector<TComPic*> apcSpatRefPics = getDecTop()->getSpatialRefPics( pcPic->getViewIdx(), pcSlice->getPOC(), m_cSPS.isDepth() );
+        TComPic * const pcTexturePic = m_cSPS.isDepth() ? getDecTop()->getPicFromView( pcPic->getViewIdx(), pcSlice->getPOC(), false ) : NULL;
+        assert( ! m_cSPS.isDepth() || pcTexturePic != NULL );
+        pcSlice->setTexturePic( pcTexturePic );
+        pcSlice->setViewIdx( pcPic->getViewIdx() );
+        pcSlice->setRefPicListExplicitlyDecoderSided(m_cListPic, apcSpatRefPics) ;// temporary solution
+
+#if DCM_COMB_LIST
+        if(!pcSlice->getRefPicListModificationFlagLC())
+        {
+          pcSlice->generateCombinedList();
+        }
+#endif
+
+        pcSlice->setNoBackPredFlag( false );
+#if DCM_COMB_LIST
+        if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
+#else
+          if ( pcSlice->getSliceType() == B_SLICE )
+#endif
+          {
+            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;
+                }
+              }
+            }
+          }
+      }
+
+      pcPic->setCurrSliceIdx(m_uiSliceIdx);
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    if ( m_cSPS.getUseDMM() && g_aacWedgeLists.empty() && m_bIsDepth )
+      {
+        initWedgeLists();
+      }
+#endif
+
+      //  Decode a picture
+      m_cGopDecoder.decompressGop ( bEos, pcBitstream, pcPic, false );
+
+      if( m_pcCamParsCollector )
+      {
+        m_pcCamParsCollector->setSlice( pcSlice );
+      }
+
+      m_bFirstSliceInPicture = false;
+      m_uiSliceIdx++;
+    }
+      break;
+    default:
+      assert (1);
+  }
+
+  return false;
+}
+
+#if DCM_SKIP_DECODING_FRAMES
+/** 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 CDR, pictures with POC equal to or greater than the CDR 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 CDR, 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/CDR 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_uiPOCRA == MAX_UINT) // start of random access point, m_uiPOCRA has not been set yet.
+  {
+    if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CDR)
+    {
+      m_uiPOCRA = m_apcSlicePilot->getPOC(); // set the POC random access since we need to skip the reordered pictures in CDR.
+    }
+    else if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR)
+    {
+      m_uiPOCRA = 0; // no need to skip the reordered pictures in IDR, they are decodable.
+    }
+    else
+    {
+      printf("\nUnsafe random access point. Decoder may crash.");
+      m_uiPOCRA = m_apcSlicePilot->getPOC(); // set the POC random access skip the reordered pictures and try to decode if possible.  This increases the chances of avoiding a decoder crash.
+      //m_uiPOCRA = 0;
+    }
+  }
+  else if (m_apcSlicePilot->getPOC() < m_uiPOCRA)  // skip the reordered pictures if necessary
+  {
+    iPOCLastDisplay++;
+    return true;
+  }
+  // if we reach here, then the picture is not skipped.
+  return false;
+}
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibDecoder/TDecTop.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibDecoder/TDecTop.h	(revision 19)
@@ -0,0 +1,204 @@
+/* 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 __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/TComResidualGenerator.h"
+#include "../TLibCommon/SEI.h"
+
+#include "TDecGop.h"
+#include "TDecEntropy.h"
+#include "TDecSbac.h"
+#include "TDecCAVLC.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TAppDecTop ;
+
+
+class CamParsCollector
+{
+public:
+  CamParsCollector  ();
+  ~CamParsCollector ();
+
+  Void  init        ( FILE* pCodedScaleOffsetFile );
+  Void  uninit      ();
+  Void  setSlice    ( TComSlice* pcSlice );
+
+private:
+  Bool  xIsComplete ();
+  Void  xOutput     ( Int iPOC );
+
+private:
+  Bool    m_bInitialized;
+  FILE*   m_pCodedScaleOffsetFile;
+
+  Int**   m_aaiCodedOffset;
+  Int**   m_aaiCodedScale;
+  Int*    m_aiViewOrderIndex;
+  Int*    m_aiViewReceived;
+  UInt    m_uiCamParsCodedPrecision;
+  Bool    m_bCamParsVaryOverTime;
+  Int     m_iLastViewId;
+  Int     m_iLastPOC;
+  UInt    m_uiMaxViewId;
+};
+
+
+/// decoder class
+class TDecTop
+{
+private:
+  Int                     m_iGopSize;
+  Bool                    m_bGopSizeSet;
+  int                     m_iMaxRefPicNum;
+
+#if DCM_DECODING_REFRESH
+  Bool                    m_bRefreshPending;    ///< refresh pending flag
+  UInt                    m_uiPOCCDR;           ///< temporal reference of the CDR picture
+#if DCM_SKIP_DECODING_FRAMES
+  UInt                    m_uiPOCRA;            ///< temporal reference of the random access point
+#endif
+#endif
+
+  UInt                    m_uiValidPS;
+  TComList<TComPic*>      m_cListPic;         //  Dynamic buffer
+  TComSPS                 m_cSPS;
+  TComPPS                 m_cPPS;
+  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;
+#if MTK_SAO
+  TComSampleAdaptiveOffset m_cSAO;
+#endif
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator   m_cDepthMapGenerator;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  TComResidualGenerator   m_cResidualGenerator;
+#endif
+
+  Bool                    m_bIsDepth;
+  Int                     m_iViewIdx;
+  TAppDecTop*             m_pcTAppDecTop;
+  CamParsCollector*       m_pcCamParsCollector;
+
+#if DCM_SKIP_DECODING_FRAMES
+  Bool isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay);
+#endif
+  TComPic*                m_pcPic;
+  UInt                    m_uiSliceIdx;
+  UInt                    m_uiLastSliceIdx;
+  UInt                    m_uiPrevPOC;
+  Bool                    m_bFirstSliceInPicture;
+  Bool                    m_bFirstSliceInSequence;
+
+public:
+  TDecTop();
+  virtual ~TDecTop();
+
+  Void  create  ();
+  Void  destroy ();
+
+  void setPictureDigestEnabled(bool enabled) { m_cGopDecoder.setPictureDigestEnabled(enabled); }
+
+  Void  init( TAppDecTop* pcTAppDecTop, Bool bFirstInstance = true );
+#if DCM_SKIP_DECODING_FRAMES
+  Bool  decode (Bool bEos, TComBitstream* pcBitstream, UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, NalUnitType& reNalUnitType, TComSPS& cComSPS, Int& iSkipFrame, Int& iPOCLastDisplay);
+#else
+  Void  decode ( Bool bEos, TComBitstream* pcBitstream, UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, NalUnitType& reNalUnitType, TComSPS& cComSPS );
+#endif
+
+  TComSPS *getSPS() { return (m_uiValidPS & 1) ? &m_cSPS : NULL; }
+
+  Void  deletePicBuffer();
+
+  Void  deleteExtraPicBuffers( Int iPoc );
+#if AMVP_BUFFERCOMPRESS
+  Void  compressMotion       ( Int iPoc );
+#endif
+
+  Void setViewIdx(Int i)					{ m_iViewIdx = i ;}
+  Int  getViewIdx()								{ return m_iViewIdx ; }
+
+  Void setToDepth(Bool b)         { m_bIsDepth = b ;}
+  Bool getIsDepth()               { return m_bIsDepth ;}
+
+  Void setCamParsCollector( CamParsCollector* pcCamParsCollector ) { m_pcCamParsCollector = pcCamParsCollector; }
+
+  TComList<TComPic*>*     getListPic            () { return  &m_cListPic;             }
+  TAppDecTop*             getDecTop           ( ){ return  m_pcTAppDecTop ;};
+
+  Void                    setSPS                (TComSPS cSPS );
+
+  UInt                    getCodedPictureBufferSize() { return m_cSPS.getCodedPictureBufferSize() ; }
+
+  Void executeDeblockAndAlf(Bool bEos, TComBitstream* pcBitstream, UInt& ruiPOC, TComList<TComPic*>*& rpcListPic, Int& iSkipFrame,  Int& iPOCLastDisplay);
+
+protected:
+  Void  xGetNewPicBuffer  (TComSlice* pcSlice, TComPic*& rpcPic);
+
+};// END CLASS DEFINITION TDecTop
+
+
+#endif // __TDECTOP__
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 19)
@@ -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-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 "../TLibCommon/TComBitCounter.h"
+#include "../TLibCommon/TComBitStream.h"
+#include "../TLibCommon/SEI.h"
+#include "SEIwrite.h"
+
+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: /tags/0.2r1/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/SEIwrite.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/SEIwrite.h	(revision 19)
@@ -0,0 +1,41 @@
+/* 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.
+ */
+
+
+
+#pragma once
+
+class TComBitIf;
+class SEI;
+
+void writeSEImessage(TComBitIf& bs, const SEI& sei);
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.cpp	(revision 19)
@@ -0,0 +1,5037 @@
+/* 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     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>
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define ALF_NUM_OF_REDESIGN 3
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const Int TEncAdaptiveLoopFilter::m_aiSymmetricArray9x9[81] =
+{
+   0,  1,  2,  3,  4,  5,  6,  7,  8,
+   9, 10, 11, 12, 13, 14, 15, 16, 17,
+  18, 19, 20, 21, 22, 23, 24, 25, 26,
+  27, 28, 29, 30, 31, 32, 33, 34, 35,
+  36, 37, 38, 39, 40, 39, 38, 37, 36,
+  35, 34, 33, 32, 31, 30, 29, 28, 27,
+  26, 25, 24, 23, 22, 21, 20, 19, 18,
+  17, 16, 15, 14, 13, 12, 11, 10,  9,
+   8,  7,  6,  5,  4,  3,  2,  1,  0
+};
+
+const Int TEncAdaptiveLoopFilter::m_aiSymmetricArray7x7[49] =
+{
+  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, 23, 22, 21,
+  20, 19, 18, 17, 16, 15, 14,
+  13, 12, 11, 10,  9,  8,  7,
+  6,  5,  4,  3,  2,  1,  0,
+};
+
+const Int TEncAdaptiveLoopFilter::m_aiSymmetricArray5x5[25] =
+{
+  0,  1,  2,  3,  4,
+  5,  6,  7,  8,  9,
+  10, 11, 12, 11, 10,
+  9,  8,  7,  6,  5,
+  4,  3,  2,  1,  0,
+};
+
+#if TI_ALF_MAX_VSIZE_7
+const Int TEncAdaptiveLoopFilter::m_aiSymmetricArray9x7[63] =
+{
+   0,  1,  2,  3,  4,  5,  6,  7,  8,
+   9, 10, 11, 12, 13, 14, 15, 16, 17,
+  18, 19, 20, 21, 22, 23, 24, 25, 26,
+  27, 28, 29, 30, 31, 30, 29, 28, 27,
+  26, 25, 24, 23, 22, 21, 20, 19, 18,
+  17, 16, 15, 14, 13, 12, 11, 10,  9,
+   8,  7,  6,  5,  4,  3,  2,  1,  0
+};
+#endif
+
+#if MQT_ALF_NPASS
+#if TI_ALF_MAX_VSIZE_7
+Int TEncAdaptiveLoopFilter::m_aiTapPos9x9_In9x9Sym[21] =
+#else
+Int TEncAdaptiveLoopFilter::m_aiTapPos9x9_In9x9Sym[22] =
+#endif
+{
+#if TI_ALF_MAX_VSIZE_7
+                  0,  1,  2,
+              3,  4,  5,  6,  7,
+          8,  9, 10, 11, 12, 13, 14,
+     15, 16, 17, 18, 19, 20
+#else
+                   0,
+               1,  2,  3,
+           4,  5,  6,  7,  8,
+       9, 10, 11, 12, 13, 14, 15,
+  16, 17, 18, 19, 20, 21
+#endif
+};
+
+Int TEncAdaptiveLoopFilter::m_aiTapPos7x7_In9x9Sym[14] =
+{                 
+#if TI_ALF_MAX_VSIZE_7
+                  1,    
+              4,  5,  6,    
+          9, 10, 11, 12, 13,    
+     16, 17, 18, 19, 20
+
+#else
+
+               2,
+           5,  6,  7,
+      10, 11, 12, 13, 14,
+  17, 18, 19, 20, 21
+#endif
+};
+
+Int TEncAdaptiveLoopFilter::m_aiTapPos5x5_In9x9Sym[8]  =
+{
+
+#if TI_ALF_MAX_VSIZE_7
+            5,
+       10, 11, 12, 
+   17, 18, 19, 20
+#else
+           6,
+      11, 12, 13,
+  18, 19, 20, 21
+
+#endif
+
+};
+
+Int* TEncAdaptiveLoopFilter::m_iTapPosTabIn9x9Sym[NO_TEST_FILT] =
+{
+  m_aiTapPos9x9_In9x9Sym, m_aiTapPos7x7_In9x9Sym, m_aiTapPos5x5_In9x9Sym
+};
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor
+// ====================================================================================================================
+
+TEncAdaptiveLoopFilter::TEncAdaptiveLoopFilter()
+{
+  m_ppdAlfCorr = NULL;
+  m_pdDoubleAlfCoeff = NULL;
+  m_pcPic = NULL;
+  m_pcEntropyCoder = NULL;
+  m_pcBestAlfParam = NULL;
+  m_pcTempAlfParam = NULL;
+  m_pcPicYuvBest = NULL;
+  m_pcPicYuvTmp = NULL;
+#if MTK_NONCROSS_INLOOP_FILTER
+  m_pcSliceYuvTmp = NULL;
+#endif
+#if MQT_BA_RA && MQT_ALF_NPASS
+  m_aiFilterCoeffSaved = NULL;
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+#if MQT_BA_RA && MQT_ALF_NPASS
+Void TEncAdaptiveLoopFilter::createAlfGlobalBuffers(Int iALFEncodePassReduction)
+{
+  if(iALFEncodePassReduction)
+  {
+    for(Int i=0; i< NUM_ALF_CLASS_METHOD; i++)
+    {
+      m_aiFilterCoeffSavedMethods[i] = new Int**[9];
+      for(Int j=0; j< 9; j++)
+      {
+        m_aiFilterCoeffSavedMethods[i][j] = new Int*[NO_VAR_BINS];
+        for(Int k=0; k< NO_VAR_BINS; k++)
+        {
+          m_aiFilterCoeffSavedMethods[i][j][k] = new Int[MAX_SQR_FILT_LENGTH];
+        }
+      }
+    }
+
+  }
+}
+
+Void TEncAdaptiveLoopFilter::destroyAlfGlobalBuffers()
+{
+  if(m_iALFEncodePassReduction)
+  {
+    for(Int i=0; i< NUM_ALF_CLASS_METHOD; i++)
+    {
+      for(Int j=0; j< 9; j++)
+      {
+        for(Int k=0; k< NO_VAR_BINS; k++)
+        {
+          delete[] m_aiFilterCoeffSavedMethods[i][j][k];
+        }
+        delete[] m_aiFilterCoeffSavedMethods[i][j];
+      }
+      delete[] m_aiFilterCoeffSavedMethods[i];
+    }
+
+  }
+
+}
+#endif
+
+/**
+ \param pcPic           picture (TComPic) pointer
+ \param pcEntropyCoder  entropy coder class
+ */
+Void TEncAdaptiveLoopFilter::startALFEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder )
+{
+  m_pcPic = pcPic;
+  m_pcEntropyCoder = pcEntropyCoder;
+  
+  m_eSliceType = pcPic->getSlice(0)->getSliceType();
+  m_iPicNalReferenceIdc = (pcPic->getSlice(0)->isReferenced() ? 1 :0);
+  
+  m_uiNumSCUInCU = m_pcPic->getNumPartInCU();
+  
+  xInitParam();
+  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();
+  
+  m_pcBestAlfParam = new ALFParam;
+  m_pcTempAlfParam = new ALFParam;
+  allocALFParam(m_pcBestAlfParam);
+  allocALFParam(m_pcTempAlfParam);
+  m_im_width = iWidth;
+  m_im_height = iHeight;
+  
+  // init qc_filter
+  initMatrix4D_double(&m_EGlobalSym, NO_TEST_FILT,  NO_VAR_BINS, MAX_SQR_FILT_LENGTH, MAX_SQR_FILT_LENGTH);
+  initMatrix3D_double(&m_yGlobalSym, NO_TEST_FILT, NO_VAR_BINS, MAX_SQR_FILT_LENGTH); 
+  initMatrix_int(&m_filterCoeffSymQuant, NO_VAR_BINS, MAX_SQR_FILT_LENGTH); 
+  
+  m_pixAcc = (double *) calloc(NO_VAR_BINS, sizeof(double));
+#if !MQT_BA_RA
+  get_mem2Dpel(&m_varImg, m_im_height, m_im_width);
+#endif
+  get_mem2Dpel(&m_maskImg, m_im_height, m_im_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(MAX_SQR_FILT_LENGTH, sizeof(int));//
+  m_filterCoeff = (double *) calloc(MAX_SQR_FILT_LENGTH, sizeof(double));//
+  m_filterCoeffQuant = (int *) calloc(MAX_SQR_FILT_LENGTH, sizeof(int));//
+  initMatrix_int(&m_diffFilterCoeffQuant, NO_VAR_BINS, MAX_SQR_FILT_LENGTH);//
+  initMatrix_int(&m_FilterCoeffQuantTemp, NO_VAR_BINS, MAX_SQR_FILT_LENGTH);//
+  
+  m_tempALFp = new ALFParam;
+  allocALFParam(m_tempALFp);
+  m_pcDummyEntropyCoder = m_pcEntropyCoder;
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  if( m_bUseNonCrossALF )
+  {
+    m_pcSliceYuvTmp = new TComPicYuv();
+    m_pcSliceYuvTmp->create(iWidth, iHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+  }
+#endif
+
+
+}
+
+Void TEncAdaptiveLoopFilter::endALFEnc()
+{
+  xUninitParam();
+  xDestroyTmpAlfCtrlFlags();
+  
+  m_pcPicYuvTmp->destroyLuma();
+  delete m_pcPicYuvTmp;
+  m_pcPicYuvTmp = NULL;
+  m_pcPic = NULL;
+  m_pcEntropyCoder = NULL;
+  
+  freeALFParam(m_pcBestAlfParam);
+  freeALFParam(m_pcTempAlfParam);
+  delete m_pcBestAlfParam;
+  delete m_pcTempAlfParam;
+  // delete qc filters
+  destroyMatrix4D_double(m_EGlobalSym, NO_TEST_FILT,  NO_VAR_BINS);
+  destroyMatrix3D_double(m_yGlobalSym, NO_TEST_FILT);
+  destroyMatrix_int(m_filterCoeffSymQuant);
+  
+  free(m_pixAcc);
+#if !MQT_BA_RA
+  free_mem2Dpel(m_varImg);
+#endif
+  free_mem2Dpel(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);
+  
+  freeALFParam(m_tempALFp);
+  delete m_tempALFp;
+
+#if MTK_NONCROSS_INLOOP_FILTER
+
+  if(m_bUseNonCrossALF)
+  {
+    m_pcSliceYuvTmp->destroy();
+    delete m_pcSliceYuvTmp;
+    m_pcSliceYuvTmp = NULL;
+  }
+#endif
+
+}
+
+/**
+ \param pcAlfParam           ALF parameter
+ \param dLambda              lambda value for RD cost computation
+ \retval ruiDist             distortion
+ \retval ruiBits             required bits
+ \retval ruiMaxAlfCtrlDepth  optimal partition depth
+ */
+Void TEncAdaptiveLoopFilter::ALFProcess( ALFParam* pcAlfParam, Double dLambda, UInt64& ruiDist, UInt64& ruiBits, UInt& ruiMaxAlfCtrlDepth )
+{
+  Int tap, num_coef;
+  
+  // set global variables
+  tap         = ALF_MAX_NUM_TAP;
+#if TI_ALF_MAX_VSIZE_7
+  Int tapV = TComAdaptiveLoopFilter::ALFTapHToTapV(tap);
+  num_coef = (tap * tapV + 1) >> 1;
+#else
+  num_coef    = (tap*tap+1)>>1;
+#endif
+  num_coef    = num_coef + 1; // DC offset
+  
+  // set lambda
+  m_dLambdaLuma   = dLambda;
+  m_dLambdaChroma = dLambda;
+  
+  TComPicYuv* pcPicOrg = m_pcPic->getPicYuvOrg();
+  
+  // extend image for filtering
+  TComPicYuv* pcPicYuvRec    = m_pcPic->getPicYuvRec();
+  TComPicYuv* pcPicYuvExtRec = m_pcTempPicYuv;
+  
+  pcPicYuvRec->copyToPic(pcPicYuvExtRec);
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(!m_bUseNonCrossALF)
+  {
+#endif  
+  pcPicYuvExtRec->setBorderExtension( false );
+  pcPicYuvExtRec->extendPicBorder   ();
+#if MTK_NONCROSS_INLOOP_FILTER
+  }
+#endif  
+ 
+  // set min cost
+  UInt64 uiMinRate = MAX_INT;
+  UInt64 uiMinDist = MAX_INT;
+  Double dMinCost  = MAX_DOUBLE;
+  
+  UInt64  uiOrigRate;
+  UInt64  uiOrigDist;
+  Double  dOrigCost;
+  
+  // calc original cost
+  xCalcRDCost( pcPicOrg, pcPicYuvRec, NULL, uiOrigRate, uiOrigDist, dOrigCost );
+  m_pcBestAlfParam->alf_flag = 0;
+  m_pcBestAlfParam->cu_control_flag = 0;
+  
+  // initialize temp_alfps
+  m_pcTempAlfParam->alf_flag        = 1;
+  m_pcTempAlfParam->tap             = tap;
+#if TI_ALF_MAX_VSIZE_7
+  m_pcTempAlfParam->tapV            = tapV;
+#endif
+  m_pcTempAlfParam->num_coeff       = num_coef;
+  m_pcTempAlfParam->chroma_idc      = 0;
+  m_pcTempAlfParam->cu_control_flag = 0;
+  
+#if MQT_ALF_NPASS
+  setALFEncodingParam(m_pcPic);
+#endif
+
+  // adaptive in-loop wiener filtering
+  xEncALFLuma_qc( pcPicOrg, pcPicYuvExtRec, pcPicYuvRec, uiMinRate, uiMinDist, dMinCost );
+  
+  // cu-based filter on/off control
+  xCUAdaptiveControl_qc( pcPicOrg, pcPicYuvExtRec, pcPicYuvRec, uiMinRate, uiMinDist, dMinCost );
+  
+  // adaptive tap-length
+  xFilterTapDecision_qc( pcPicOrg, pcPicYuvExtRec, pcPicYuvRec, uiMinRate, uiMinDist, dMinCost );
+  
+  // compute RD cost
+  xCalcRDCost( pcPicOrg, pcPicYuvRec, m_pcBestAlfParam, uiMinRate, uiMinDist, dMinCost );
+  
+  // compare RD cost to non-ALF case
+  if( dMinCost < dOrigCost )
+  {
+    m_pcBestAlfParam->alf_flag = 1;
+    
+    ruiBits = uiMinRate;
+    ruiDist = uiMinDist;
+  }
+  else
+  {
+    m_pcBestAlfParam->alf_flag        = 0;
+    m_pcBestAlfParam->cu_control_flag = 0;
+    
+    uiMinRate = uiOrigRate;
+    uiMinDist = uiOrigDist;
+    dMinCost = dMinCost;
+    
+    m_pcEntropyCoder->setAlfCtrl(false);
+    pcPicYuvExtRec->copyToPicLuma(pcPicYuvRec);
+    
+    ruiBits = uiOrigRate;
+    ruiDist = uiOrigDist;
+  }
+  
+  // if ALF works
+  if( m_pcBestAlfParam->alf_flag )
+  {
+    // predict ALF coefficients
+    predictALFCoeff( m_pcBestAlfParam );
+    
+    // do additional ALF process for chroma
+    xEncALFChroma( uiMinRate, pcPicOrg, pcPicYuvExtRec, pcPicYuvRec, ruiDist, ruiBits );
+  }
+  
+  // copy to best storage
+  copyALFParam(pcAlfParam, m_pcBestAlfParam);
+  
+  // store best depth
+  ruiMaxAlfCtrlDepth = m_pcEntropyCoder->getMaxAlfCtrlDepth();
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TEncAdaptiveLoopFilter::xEncALFChroma( UInt64 uiLumaRate, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiDist, UInt64& ruiBits )
+{
+  // restriction for non-referenced B-slice
+  if (m_eSliceType == B_SLICE && m_iPicNalReferenceIdc == 0)
+  {
+    return;
+  }
+  
+  Int tap, num_coef;
+  
+  // set global variables
+  tap         = ALF_MAX_NUM_TAP_C;
+  num_coef    = (tap*tap+1)>>1;
+  num_coef    = num_coef + 1; // DC offset
+  
+  // set min cost
+  UInt64 uiMinRate = uiLumaRate;
+  UInt64 uiMinDist = MAX_INT;
+  Double dMinCost  = MAX_DOUBLE;
+  
+  // calc original cost
+  copyALFParam(m_pcTempAlfParam, m_pcBestAlfParam);
+  xCalcRDCostChroma(pcPicOrg, pcPicRest, m_pcTempAlfParam, uiMinRate, uiMinDist, dMinCost);
+  
+  // initialize temp_alfps
+  m_pcTempAlfParam->chroma_idc = 3;
+  m_pcTempAlfParam->tap_chroma       = tap;
+  m_pcTempAlfParam->num_coeff_chroma = num_coef;
+  
+  // Adaptive in-loop wiener filtering for chroma
+  xFilteringFrameChroma(pcPicOrg, pcPicDec, pcPicRest);
+  
+  // filter on/off decision for chroma
+  Int iCWidth = (pcPicOrg->getWidth()>>1);
+  Int iCHeight = (pcPicOrg->getHeight()>>1);
+  Int iCStride = pcPicOrg->getCStride();
+  UInt64 uiFiltDistCb = xCalcSSD(pcPicOrg->getCbAddr(), pcPicRest->getCbAddr(), iCWidth, iCHeight, iCStride);
+  UInt64 uiFiltDistCr = xCalcSSD(pcPicOrg->getCrAddr(), pcPicRest->getCrAddr(), iCWidth, iCHeight, iCStride);
+  UInt64 uiOrgDistCb = xCalcSSD(pcPicOrg->getCbAddr(), pcPicDec->getCbAddr(), iCWidth, iCHeight, iCStride);
+  UInt64 uiOrgDistCr = xCalcSSD(pcPicOrg->getCrAddr(), pcPicDec->getCrAddr(), iCWidth, iCHeight, iCStride);
+  
+  m_pcTempAlfParam->chroma_idc = 0;
+  if(uiOrgDistCb > uiFiltDistCb)
+    m_pcTempAlfParam->chroma_idc += 2;
+  if(uiOrgDistCr  > uiFiltDistCr )
+    m_pcTempAlfParam->chroma_idc += 1;
+  
+  if(m_pcTempAlfParam->chroma_idc)
+  {
+    if(m_pcTempAlfParam->chroma_idc!=3)
+    {
+      // chroma filter re-design
+      xFilteringFrameChroma(pcPicOrg, pcPicDec, pcPicRest);
+    }
+    
+    UInt64 uiRate, uiDist;
+    Double dCost;
+    xCalcRDCostChroma(pcPicOrg, pcPicRest, m_pcTempAlfParam, uiRate, uiDist, dCost);
+    
+    if( dCost < dMinCost )
+    {
+      copyALFParam(m_pcBestAlfParam, m_pcTempAlfParam);
+      predictALFCoeffChroma(m_pcBestAlfParam);
+      
+      ruiBits += uiRate;
+      ruiDist += uiDist;
+    }
+    else
+    {
+      m_pcBestAlfParam->chroma_idc = 0;
+      
+      if((m_pcTempAlfParam->chroma_idc>>1)&0x01)
+        pcPicDec->copyToPicCb(pcPicRest);
+      if(m_pcTempAlfParam->chroma_idc&0x01)
+        pcPicDec->copyToPicCr(pcPicRest);
+      
+      ruiBits += uiMinRate;
+      ruiDist += uiMinDist;
+    }
+  }
+  else
+  {
+    m_pcBestAlfParam->chroma_idc = 0;
+    
+    ruiBits += uiMinRate;
+    ruiDist += uiMinDist;
+    
+    pcPicDec->copyToPicCb(pcPicRest);
+    pcPicDec->copyToPicCr(pcPicRest);
+  }
+}
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+Void TEncAdaptiveLoopFilter::xInitParam()
+{
+  Int i, j;
+  
+  if (m_ppdAlfCorr != NULL)
+  {
+    for (i = 0; i < ALF_MAX_NUM_COEF; i++)
+    {
+      for (j = 0; j < ALF_MAX_NUM_COEF+1; j++)
+      {
+        m_ppdAlfCorr[i][j] = 0;
+      }
+    }
+  }
+  else
+  {
+    m_ppdAlfCorr = new Double*[ALF_MAX_NUM_COEF];
+    for (i = 0; i < ALF_MAX_NUM_COEF; i++)
+    {
+      m_ppdAlfCorr[i] = new Double[ALF_MAX_NUM_COEF+1];
+      for (j = 0; j < ALF_MAX_NUM_COEF+1; j++)
+      {
+        m_ppdAlfCorr[i][j] = 0;
+      }
+    }
+  }
+  
+  if (m_pdDoubleAlfCoeff != NULL)
+  {
+    for (i = 0; i < ALF_MAX_NUM_COEF; i++)
+    {
+      m_pdDoubleAlfCoeff[i] = 0;
+    }
+  }
+  else
+  {
+    m_pdDoubleAlfCoeff = new Double[ALF_MAX_NUM_COEF];
+    for (i = 0; i < ALF_MAX_NUM_COEF; i++)
+    {
+      m_pdDoubleAlfCoeff[i] = 0;
+    }
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xUninitParam()
+{
+  Int i;
+  
+  if (m_ppdAlfCorr != NULL)
+  {
+    for (i = 0; i < ALF_MAX_NUM_COEF; i++)
+    {
+      delete[] m_ppdAlfCorr[i];
+      m_ppdAlfCorr[i] = NULL;
+    }
+    delete[] m_ppdAlfCorr;
+    m_ppdAlfCorr = NULL;
+  }
+  
+  if (m_pdDoubleAlfCoeff != NULL)
+  {
+    delete[] m_pdDoubleAlfCoeff;
+    m_pdDoubleAlfCoeff = NULL;
+  }
+}
+
+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();
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xEncodeCUAlfCtrlFlags()
+{
+  for( UInt uiCUAddr = 0; uiCUAddr < m_pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( uiCUAddr );
+    xEncodeCUAlfCtrlFlag(pcCU, 0, 0);
+  }
+}
+
+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()->getWidth() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() ) )
+#else  
+  if( ( uiRPelX >= pcCU->getSlice()->getSPS()->getWidth() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() ) )
+#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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+#else
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+#endif      
+        xEncodeCUAlfCtrlFlag(pcCU, uiAbsPartIdx, uiDepth+1);
+    }
+    return;
+  }
+  
+  m_pcEntropyCoder->encodeAlfCtrlFlag(pcCU, uiAbsPartIdx);
+}
+#if MTK_NONCROSS_INLOOP_FILTER
+Void TEncAdaptiveLoopFilter::xCalcCorrelationFunc(Int ypos, Int xpos, Pel* pOrg, Pel* pCmp, Int iTap, Int iWidth, Int iHeight, Int iOrgStride, Int iCmpStride, Bool bSymmCopyBlockMatrix)
+#else
+Void TEncAdaptiveLoopFilter::xCalcCorrelationFunc(Pel* pOrg, Pel* pCmp, Int iTap, Int iWidth, Int iHeight, Int iOrgStride, Int iCmpStride)
+#endif
+{
+  //Patch should be extended before this point................
+  //ext_offset  = tap>>1;
+  
+#if TI_ALF_MAX_VSIZE_7
+  Int iTapV   = TComAdaptiveLoopFilter::ALFTapHToTapV(iTap);
+  Int N       = (iTap * iTapV + 1) >> 1;
+  Int offsetV = iTapV >> 1;
+#else
+  Int N      = (iTap*iTap+1)>>1;
+#endif
+  Int offset = iTap>>1;
+  
+  const Int* pFiltPos;
+  
+  switch(iTap)
+  {
+    case 5:
+      pFiltPos = m_aiSymmetricArray5x5;
+      break;
+    case 7:
+      pFiltPos = m_aiSymmetricArray7x7;
+      break;
+    case 9:
+#if TI_ALF_MAX_VSIZE_7
+      pFiltPos = m_aiSymmetricArray9x7;
+#else
+      pFiltPos = m_aiSymmetricArray9x9;
+#endif
+      break;
+    default:
+#if TI_ALF_MAX_VSIZE_7
+      pFiltPos = m_aiSymmetricArray9x7;
+#else
+      pFiltPos = m_aiSymmetricArray9x9;
+#endif
+      assert(0);
+      break;
+  }
+  
+  Pel* pTerm = new Pel[N];
+  
+  Int i, j;
+#if MTK_NONCROSS_INLOOP_FILTER
+  for (Int y = ypos; y < ypos + iHeight; y++)
+  {
+    for (Int x = xpos; x < xpos + iWidth; x++)
+    {
+#else    
+  for (Int y = 0; y < iHeight; y++)
+  {
+    for (Int x = 0; x < iWidth; x++)
+    {
+#endif
+      i = 0;
+      ::memset(pTerm, 0, sizeof(Pel)*N);
+#if TI_ALF_MAX_VSIZE_7
+      for (Int yy = y - offsetV; yy <= y + offsetV; yy++)
+#else
+      for(Int yy=y-offset; yy<=y+offset; yy++)
+#endif
+      {
+        for(Int xx=x-offset; xx<=x+offset; xx++)
+        {
+          pTerm[pFiltPos[i]] += pCmp[xx + yy*iCmpStride];
+          i++;
+        }
+      }
+      
+      for(j=0; j<N; j++)
+      {
+        m_ppdAlfCorr[j][j] += pTerm[j]*pTerm[j];
+        for(i=j+1; i<N; i++)
+          m_ppdAlfCorr[j][i] += pTerm[j]*pTerm[i];
+        
+        // DC offset
+        m_ppdAlfCorr[j][N]   += pTerm[j];
+        m_ppdAlfCorr[j][N+1] += pOrg[x+y*iOrgStride]*pTerm[j];
+      }
+      // DC offset
+      for(i=0; i<N; i++)
+        m_ppdAlfCorr[N][i] += pTerm[i];
+      m_ppdAlfCorr[N][N]   += 1;
+      m_ppdAlfCorr[N][N+1] += pOrg[x+y*iOrgStride];
+    }
+  }
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(bSymmCopyBlockMatrix)
+  {
+#endif
+  for(j=0; j<N-1; j++)
+  {
+    for(i=j+1; i<N; i++)
+      m_ppdAlfCorr[i][j] = m_ppdAlfCorr[j][i];
+  }
+#if MTK_NONCROSS_INLOOP_FILTER
+  }
+#endif
+
+  delete[] pTerm;
+  pTerm = NULL;
+}
+
+#if IBDI_DISTORTION
+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;;
+}
+#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
+
+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;
+  
+  switch(tap)
+  {
+    case 5:
+      pFiltMag = m_aiSymmetricMag5x5;
+      break;
+    case 7:
+      pFiltMag = m_aiSymmetricMag7x7;
+      break;
+    case 9:
+#if TI_ALF_MAX_VSIZE_7
+      pFiltMag = m_aiSymmetricMag9x7;
+#else
+      pFiltMag = m_aiSymmetricMag9x9;
+#endif
+      break;
+    default:
+#if TI_ALF_MAX_VSIZE_7
+      pFiltMag = m_aiSymmetricMag9x7;
+#else
+      pFiltMag = m_aiSymmetricMag9x9;
+#endif
+      assert(0);
+      break;
+  }
+  
+#if TI_ALF_MAX_VSIZE_7
+  Int tapV = TComAdaptiveLoopFilter::ALFTapHToTapV(tap);
+  N = (tap * tapV + 1) >> 1;
+#else
+  N = (tap*tap+1)>>1;
+#endif
+  
+  dh = new Double[N];
+  nc = new Int[N];
+  
+  max_value =   (1<<(1+ALF_NUM_BIT_SHIFT))-1;
+  min_value = 0-(1<<(1+ALF_NUM_BIT_SHIFT));
+  
+  dbl_total_gain=0.0;
+  q_total_gain=0;
+  for(i=0; i<N; i++)
+  {
+    if(h[i]>=0.0)
+      qh[i] =  (Int)( h[i]*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+    else
+      qh[i] = -(Int)(-h[i]*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+    
+    dh[i] = (Double)qh[i]/(Double)(1<<ALF_NUM_BIT_SHIFT) - h[i];
+    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
+  total_gain = (Int)(dbl_total_gain*(1<<ALF_NUM_BIT_SHIFT)+0.5);
+  
+  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]));
+  }
+  
+  // DC offset
+  //  max_value = Min(  (1<<(3+Max(img_bitdepth_luma,img_bitdepth_chroma)))-1, (1<<14)-1);
+  //  min_value = Max( -(1<<(3+Max(img_bitdepth_luma,img_bitdepth_chroma))),  -(1<<14)  );
+  max_value = Min(  (1<<(3+g_uiBitDepth + g_uiBitIncrement))-1, (1<<14)-1);
+  min_value = Max( -(1<<(3+g_uiBitDepth + g_uiBitIncrement)),  -(1<<14)  );
+  
+  qh[N] =  (h[N]>=0.0)? (Int)( h[N]*(1<<(ALF_NUM_BIT_SHIFT-bit_depth+8)) + 0.5) : -(Int)(-h[N]*(1<<(ALF_NUM_BIT_SHIFT-bit_depth+8)) + 0.5);
+  qh[N] = Max(min_value,Min(max_value, qh[N]));
+  
+  delete[] dh;
+  dh = NULL;
+  
+  delete[] nc;
+  nc = NULL;
+}
+
+Void TEncAdaptiveLoopFilter::xClearFilterCoefInt(Int* qh, Int N)
+{
+  // clear
+  memset( qh, 0, sizeof( Int ) * N );
+  
+  // center pos
+  qh[N-2]  = 1<<ALF_NUM_BIT_SHIFT;
+}
+
+Void TEncAdaptiveLoopFilter::xCalcRDCost(ALFParam* pAlfParam, UInt64& ruiRate, UInt64 uiDist, Double& rdCost)
+{
+  if(pAlfParam != NULL)
+  {
+    Int* piTmpCoef;
+    piTmpCoef = new Int[ALF_MAX_NUM_COEF];
+    
+    memcpy(piTmpCoef, pAlfParam->coeff, sizeof(Int)*pAlfParam->num_coeff);
+    
+    predictALFCoeff(pAlfParam);
+    
+    m_pcEntropyCoder->resetEntropy();
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeAlfParam(pAlfParam);
+    
+    if(pAlfParam->cu_control_flag)
+    {
+#if TSB_ALF_HEADER
+      m_pcEntropyCoder->encodeAlfCtrlParam(pAlfParam);
+#else
+      xEncodeCUAlfCtrlFlags();
+#endif
+    }
+    ruiRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+    memcpy(pAlfParam->coeff, piTmpCoef, sizeof(int)*pAlfParam->num_coeff);
+    delete[] piTmpCoef;
+    piTmpCoef = NULL;
+  }
+  else
+  {
+    ruiRate = 1;
+  }
+  
+  rdCost      = (Double)(ruiRate) * m_dLambdaLuma + (Double)(uiDist);
+}
+
+Void TEncAdaptiveLoopFilter::xCalcRDCost(TComPicYuv* pcPicOrg, TComPicYuv* pcPicCmp, ALFParam* pAlfParam, UInt64& ruiRate, UInt64& ruiDist, Double& rdCost)
+{
+  if(pAlfParam != NULL)
+  {
+    Int* piTmpCoef;
+    piTmpCoef = new Int[ALF_MAX_NUM_COEF];
+    
+    memcpy(piTmpCoef, pAlfParam->coeff, sizeof(Int)*pAlfParam->num_coeff);
+    
+    predictALFCoeff(pAlfParam);
+    
+    m_pcEntropyCoder->resetEntropy();
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeAlfParam(pAlfParam);
+    
+    if(pAlfParam->cu_control_flag)
+    {
+#if TSB_ALF_HEADER
+      m_pcEntropyCoder->encodeAlfCtrlParam(pAlfParam);
+#else
+      xEncodeCUAlfCtrlFlags();
+#endif
+    }
+    ruiRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+    memcpy(pAlfParam->coeff, piTmpCoef, sizeof(int)*pAlfParam->num_coeff);
+    delete[] piTmpCoef;
+    piTmpCoef = NULL;
+  }
+  else
+  {
+    ruiRate = 1;
+  }
+  
+  ruiDist     = xCalcSSD(pcPicOrg->getLumaAddr(), pcPicCmp->getLumaAddr(), pcPicOrg->getWidth(), pcPicOrg->getHeight(), pcPicOrg->getStride());
+  rdCost      = (Double)(ruiRate) * m_dLambdaLuma + (Double)(ruiDist);
+}
+
+Void TEncAdaptiveLoopFilter::xCalcRDCostChroma(TComPicYuv* pcPicOrg, TComPicYuv* pcPicCmp, ALFParam* pAlfParam, UInt64& ruiRate, UInt64& ruiDist, Double& rdCost)
+{
+  if(pAlfParam->chroma_idc)
+  {
+    Int* piTmpCoef;
+    piTmpCoef = new Int[ALF_MAX_NUM_COEF_C];
+    
+    memcpy(piTmpCoef, pAlfParam->coeff_chroma, sizeof(Int)*pAlfParam->num_coeff_chroma);
+    
+    predictALFCoeffChroma(pAlfParam);
+    
+    m_pcEntropyCoder->resetEntropy();
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeAlfParam(pAlfParam);
+    
+    if(pAlfParam->cu_control_flag)
+    {
+#if TSB_ALF_HEADER
+      m_pcEntropyCoder->encodeAlfCtrlParam(pAlfParam);
+#else
+      xEncodeCUAlfCtrlFlags();
+#endif
+    }
+    ruiRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+    memcpy(pAlfParam->coeff_chroma, piTmpCoef, sizeof(int)*pAlfParam->num_coeff_chroma);
+    delete[] piTmpCoef;
+    piTmpCoef = NULL;
+  }
+  ruiDist = 0;
+  ruiDist += xCalcSSD(pcPicOrg->getCbAddr(), pcPicCmp->getCbAddr(), (pcPicOrg->getWidth()>>1), (pcPicOrg->getHeight()>>1), pcPicOrg->getCStride());
+  ruiDist += xCalcSSD(pcPicOrg->getCrAddr(), pcPicCmp->getCrAddr(), (pcPicOrg->getWidth()>>1), (pcPicOrg->getHeight()>>1), pcPicOrg->getCStride());
+  rdCost  = (Double)(ruiRate) * m_dLambdaChroma + (Double)(ruiDist);
+}
+
+Void TEncAdaptiveLoopFilter::xFilteringFrameChroma(TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest)
+{
+  Int    i, tap, N, err_code;
+  Int* qh;
+  
+  tap  = m_pcTempAlfParam->tap_chroma;
+  N    = m_pcTempAlfParam->num_coeff_chroma;
+  qh   = m_pcTempAlfParam->coeff_chroma;
+  
+  // initialize correlation
+  for(i=0; i<N; i++)
+    memset(m_ppdAlfCorr[i], 0, sizeof(Double)*(N+1));
+  
+  if ((m_pcTempAlfParam->chroma_idc>>1)&0x01)
+  {
+    Pel* pOrg = pcPicOrg->getCbAddr();
+    Pel* pCmp = pcPicDec->getCbAddr();
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(!m_bUseNonCrossALF)
+      xCalcCorrelationFunc(0, 0, pOrg, pCmp, tap, (pcPicOrg->getWidth()>>1), (pcPicOrg->getHeight()>>1), pcPicOrg->getCStride(), pcPicDec->getCStride(), true);
+    else
+      xCalcCorrelationFuncforChromaSlices(ALF_Cb, pOrg, pCmp, tap, pcPicOrg->getCStride(), pcPicDec->getCStride());
+#else        
+    xCalcCorrelationFunc(pOrg, pCmp, tap, (pcPicOrg->getWidth()>>1), (pcPicOrg->getHeight()>>1), pcPicOrg->getCStride(), pcPicDec->getCStride());
+#endif
+  }
+  if ((m_pcTempAlfParam->chroma_idc)&0x01)
+  {
+    Pel* pOrg = pcPicOrg->getCrAddr();
+    Pel* pCmp = pcPicDec->getCrAddr();
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(!m_bUseNonCrossALF)
+      xCalcCorrelationFunc(0, 0, pOrg, pCmp, tap, (pcPicOrg->getWidth()>>1), (pcPicOrg->getHeight()>>1), pcPicOrg->getCStride(), pcPicDec->getCStride(), true);
+    else
+      xCalcCorrelationFuncforChromaSlices(ALF_Cr, pOrg, pCmp, tap, pcPicOrg->getCStride(), pcPicDec->getCStride());
+#else
+    xCalcCorrelationFunc(pOrg, pCmp, tap, (pcPicOrg->getWidth()>>1), (pcPicOrg->getHeight()>>1), pcPicOrg->getCStride(), pcPicDec->getCStride());
+#endif
+  }
+  
+  err_code = xGauss(m_ppdAlfCorr, N);
+  
+  if(err_code)
+  {
+    xClearFilterCoefInt(qh, N);
+  }
+  else
+  {
+    for(i=0; i<N; i++)
+      m_pdDoubleAlfCoeff[i] = m_ppdAlfCorr[i][N];
+    
+    xQuantFilterCoef(m_pdDoubleAlfCoeff, qh, tap, g_uiBitDepth + g_uiBitIncrement);
+  }
+  
+  
+  if ((m_pcTempAlfParam->chroma_idc>>1)&0x01)
+  {
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(! m_bUseNonCrossALF)
+      xFrameChroma(0, 0, (pcPicRest->getHeight() >> 1), (pcPicRest->getWidth() >>1), pcPicDec, pcPicRest, qh, tap, 0);
+    else
+      xFrameChromaforSlices(ALF_Cb, pcPicDec, pcPicRest, qh, tap);
+#else
+    xFrameChroma(pcPicDec, pcPicRest, qh, tap, 0);
+#endif
+  }
+  if ((m_pcTempAlfParam->chroma_idc)&0x01)
+  {
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(! m_bUseNonCrossALF)
+      xFrameChroma(0, 0, (pcPicRest->getHeight() >> 1), (pcPicRest->getWidth() >>1), pcPicDec, pcPicRest, qh, tap, 1);
+    else
+      xFrameChromaforSlices(ALF_Cr, pcPicDec, pcPicRest, qh, tap);
+#else
+    xFrameChroma(pcPicDec, pcPicRest, qh, tap, 1);
+#endif
+  }
+  
+  if(m_pcTempAlfParam->chroma_idc<3)
+  {
+    if(m_pcTempAlfParam->chroma_idc==1)
+    {
+      pcPicDec->copyToPicCb(pcPicRest);
+    }
+    if(m_pcTempAlfParam->chroma_idc==2)
+    {
+      pcPicDec->copyToPicCr(pcPicRest);
+    }
+  }
+  
+}
+
+Void TEncAdaptiveLoopFilter::xCopyDecToRestCUs(TComPicYuv* pcPicDec, TComPicYuv* pcPicRest)
+{
+  for( UInt uiCUAddr = 0; uiCUAddr < m_pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( uiCUAddr );
+    xCopyDecToRestCU(pcCU, 0, 0, pcPicDec, pcPicRest);
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xCopyDecToRestCU(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest)
+{
+  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()->getWidth() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() ) )
+  {
+    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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )      
+        xCopyDecToRestCU(pcCU, uiAbsPartIdx, uiDepth+1, pcPicDec, pcPicRest);
+    }
+    return;
+  }
+  
+  if (!pcCU->getAlfCtrlFlag(uiAbsPartIdx))
+  {
+    UInt uiCUAddr = pcCU->getAddr();
+    
+    Int iWidth = pcCU->getWidth(uiAbsPartIdx);
+    Int iHeight = pcCU->getHeight(uiAbsPartIdx);
+    
+    Pel* pRec = pcPicDec->getLumaAddr(uiCUAddr, uiAbsPartIdx);
+    Pel* pFilt = pcPicRest->getLumaAddr(uiCUAddr, uiAbsPartIdx);
+    
+    Int iRecStride = pcPicDec->getStride();
+    Int iFiltStride = pcPicRest->getStride();
+    
+    for (Int y = 0; y < iHeight; y++)
+    {
+      for (Int x = 0; x < iWidth; x++)
+      {
+        pFilt[x] = pRec[x];
+      }
+      pRec += iRecStride;
+      pFilt += iFiltStride;
+    }
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xcollectStatCodeFilterCoeffForce0(int **pDiffQFilterCoeffIntPP, int fl, int sqrFiltLength, 
+                                                               int filters_per_group, int bitsVarBin[])
+{
+  int i, k, kMin, kStart, minBits, ind, scanPos, maxScanVal, coeffVal, 
+  *pDepthInt=NULL, kMinTab[MAX_SQR_FILT_LENGTH], bitsCoeffScan[MAX_SCAN_VAL][MAX_EXP_GOLOMB],
+  minKStart, minBitsKStart, bitsKStart;
+  
+  pDepthInt=pDepthIntTab[fl-2];
+  
+  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=0; 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=0; 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;
+  }
+  
+  for(ind=0; ind<filters_per_group; ++ind)
+  {
+    bitsVarBin[ind]=0;
+    for(i = 0; i < sqrFiltLength; i++)
+    {
+      scanPos=pDepthInt[i]-1;
+      bitsVarBin[ind] += lengthGolomb(abs(pDiffQFilterCoeffIntPP[ind][i]), kMinTab[scanPos]);
+    }
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xdecideCoeffForce0(int codedVarBins[NO_VAR_BINS], double errorForce0Coeff[], double errorForce0CoeffTab[NO_VAR_BINS][2], int bitsVarBin[NO_VAR_BINS], double lambda, int filters_per_fr)
+{
+  int filtNo;
+  double lagrangianDiff;
+  int ind;
+  
+  errorForce0Coeff[0]=errorForce0Coeff[1]=0;
+  for (ind=0; ind<16; ind++) codedVarBins[ind]=0;
+  
+  for(filtNo=0; filtNo<filters_per_fr; filtNo++)
+  {
+    // No coeffcient prediction bits used
+#if ENABLE_FORCECOEFF0
+    lagrangianDiff=errorForce0CoeffTab[filtNo][0]-(errorForce0CoeffTab[filtNo][1]+lambda*bitsVarBin[filtNo]);
+    codedVarBins[filtNo]=(lagrangianDiff>0)? 1 : 0;
+    errorForce0Coeff[0]+=errorForce0CoeffTab[filtNo][codedVarBins[filtNo]];
+    errorForce0Coeff[1]+=errorForce0CoeffTab[filtNo][1];
+#else
+    lagrangianDiff=errorForce0CoeffTab[filtNo][0]-(errorForce0CoeffTab[filtNo][1]+lambda*bitsVarBin[filtNo]);
+    codedVarBins[filtNo]= 1;
+    errorForce0Coeff[0]+=errorForce0CoeffTab[filtNo][codedVarBins[filtNo]];
+    errorForce0Coeff[1]+=errorForce0CoeffTab[filtNo][1];
+#endif
+  }   
+}
+
+double TEncAdaptiveLoopFilter::xfindBestCoeffCodMethod(int codedVarBins[NO_VAR_BINS], int *forceCoeff0, 
+                                                       int **filterCoeffSymQuant, int fl, int sqrFiltLength, 
+                                                       int filters_per_fr, double errorForce0CoeffTab[NO_VAR_BINS][2], 
+                                                       double *errorQuant, double lambda)
+
+{
+  int bitsVarBin[NO_VAR_BINS], createBistream, coeffBits, coeffBitsForce0;
+  double errorForce0Coeff[2], lagrangianForce0, lagrangian;
+  
+  xcollectStatCodeFilterCoeffForce0(filterCoeffSymQuant, fl, sqrFiltLength,  
+                                    filters_per_fr, bitsVarBin);
+  
+  xdecideCoeffForce0(codedVarBins, errorForce0Coeff, errorForce0CoeffTab, bitsVarBin, lambda, filters_per_fr);
+  
+  coeffBitsForce0 = xsendAllFiltersPPPredForce0(filterCoeffSymQuant, fl, sqrFiltLength, 
+                                                filters_per_fr, codedVarBins, createBistream=0, m_tempALFp);
+  
+  coeffBits = xsendAllFiltersPPPred(filterCoeffSymQuant, fl, sqrFiltLength, filters_per_fr, 
+                                    createBistream=0, m_tempALFp);
+  
+  lagrangianForce0=errorForce0Coeff[0]+lambda*coeffBitsForce0;
+  lagrangian=errorForce0Coeff[1]+lambda*coeffBits;
+  if (lagrangianForce0<lagrangian)
+  {
+    *errorQuant=errorForce0Coeff[0];
+    *forceCoeff0=1;
+    return(lagrangianForce0);
+  }
+  else
+  {
+    *errorQuant=errorForce0Coeff[1];
+    *forceCoeff0=0;
+    return(lagrangian);
+  }
+}
+
+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;
+  
+  bit_ct0 = xcodeFilterCoeff(FilterCoeffQuant, 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];
+    }
+  }
+  
+  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(FilterCoeffQuant, 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->forceCoeff0 = 0;
+  ALFp->filters_per_group_diff = filters_per_group;
+  ALFp->filters_per_group = filters_per_group;
+  ALFp->predMethod = predMethod;
+  ALFp->num_coeff = sqrFiltLength;
+  if (ALFp->num_coeff == SQR_FILT_LENGTH_5SYM)
+    ALFp->realfiltNo=2;
+  else if (ALFp->num_coeff == SQR_FILT_LENGTH_7SYM)
+    ALFp->realfiltNo=1;
+  else
+    ALFp->realfiltNo=0;
+  
+  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] = FilterCoeffQuant[ind][i];
+    }
+  }
+  m_pcDummyEntropyCoder->codeFiltCountBit(ALFp, &Newbit_ct);
+  
+  
+  //  return(bit_ct);
+  return ((Int)Newbit_ct);
+}
+
+
+Int TEncAdaptiveLoopFilter::xsendAllFiltersPPPredForce0(int **FilterCoeffQuant, int fl, int sqrFiltLength, int filters_per_group, 
+                                                        int codedVarBins[NO_VAR_BINS], int createBistream, ALFParam* ALFp)
+{
+  int ind, bit_ct=0, bit_ct0, i, j;
+  int filters_per_group_temp, filters_per_group_diff;
+  int chosenPred = 0;
+  int force0 = 1;
+  Int64 Newbit_ct;
+  
+  i = 0;
+  for(ind = 0; ind < filters_per_group; ind++)
+  {
+    if(codedVarBins[ind] == 1)
+    {
+      for(j = 0; j < sqrFiltLength; j++)
+        m_FilterCoeffQuantTemp[i][j]=FilterCoeffQuant[ind][j];
+      i++;
+    }
+  }
+  filters_per_group_diff = filters_per_group_temp = i;
+  
+  for(ind = 0; ind < filters_per_group; ++ind)
+  {
+    if(ind == 0)
+    {
+      for(i = 0; i < sqrFiltLength; i++)
+        m_diffFilterCoeffQuant[ind][i] = m_FilterCoeffQuantTemp[ind][i];
+    }
+    else
+    {
+      for(i = 0; i < sqrFiltLength; i++)
+        m_diffFilterCoeffQuant[ind][i] = m_FilterCoeffQuantTemp[ind][i] - m_FilterCoeffQuantTemp[ind-1][i];
+    }
+  }
+  
+  if(!((filters_per_group_temp == 0) && (filters_per_group == 1)))
+  {
+    bit_ct0 = xcodeFilterCoeff(m_FilterCoeffQuantTemp, fl, sqrFiltLength, filters_per_group_temp, 0);
+    
+    if(xcodeFilterCoeff(m_diffFilterCoeffQuant, fl, sqrFiltLength, filters_per_group_diff, 0) >= bit_ct0)
+    {
+      chosenPred = 0;
+      bit_ct += lengthPredFlags(force0, chosenPred, codedVarBins, filters_per_group, createBistream);
+      bit_ct += xcodeFilterCoeff(m_FilterCoeffQuantTemp, fl, sqrFiltLength, filters_per_group_temp, createBistream);
+    }
+    else
+    {
+      chosenPred = 1;
+      bit_ct += lengthPredFlags(force0, chosenPred, codedVarBins, filters_per_group, createBistream);
+      bit_ct += xcodeFilterCoeff(m_diffFilterCoeffQuant, fl, sqrFiltLength, filters_per_group_temp, createBistream);
+    }
+  }
+  ALFp->forceCoeff0 = 1;
+  ALFp->predMethod = chosenPred;
+  ALFp->filters_per_group_diff = filters_per_group_diff;
+  ALFp->filters_per_group = filters_per_group;
+  ALFp->num_coeff = sqrFiltLength;
+  if (ALFp->num_coeff == SQR_FILT_LENGTH_5SYM)
+    ALFp->realfiltNo=2;
+  else if (ALFp->num_coeff == SQR_FILT_LENGTH_7SYM)
+    ALFp->realfiltNo=1;
+  else
+    ALFp->realfiltNo=0;
+  
+  for(ind = 0; ind < filters_per_group; ++ind)
+  {
+    ALFp->codedVarBins[ind] = codedVarBins[ind];
+  }
+  for(ind = 0; ind < filters_per_group_diff; ++ind)
+  {
+    for(i = 0; i < sqrFiltLength; i++)
+    {
+      if (chosenPred) ALFp->coeffmulti[ind][i] = m_diffFilterCoeffQuant[ind][i];
+      else ALFp->coeffmulti[ind][i] = m_FilterCoeffQuantTemp[ind][i];
+    }
+  }
+  m_pcDummyEntropyCoder->codeFiltCountBit(ALFp, &Newbit_ct);
+  
+  return ((Int)Newbit_ct);
+}
+
+//filtNo==-1/realfiltNo, noFilters=filters_per_frames, realfiltNo=filtNo
+Int TEncAdaptiveLoopFilter::xcodeAuxInfo(int filtNo, int noFilters, int varIndTab[NO_VAR_BINS], int frNo, int createBitstream,int realfiltNo, ALFParam* ALFp)
+{
+  int i, filterPattern[NO_VAR_BINS], startSecondFilter=0, bitCt=0, codePrediction;
+  Int64 NewbitCt;
+  
+  codePrediction = 0;
+  
+  //send realfiltNo (tap related)
+  ALFp->realfiltNo = realfiltNo;
+  ALFp->filtNo = filtNo;
+  
+  if(filtNo >= 0)
+  {
+    // decide startSecondFilter and filterPattern
+    if(noFilters > 1)
+    {
+      memset(filterPattern, 0, NO_VAR_BINS * sizeof(int)); 
+      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;
+    }
+    
+    //send noFilters (filters_per_frame)
+    //0: filters_per_frame = 1
+    //1: filters_per_frame = 2
+    //2: filters_per_frame > 2 (exact number from filterPattern)
+
+    ALFp->noFilters = min(noFilters-1,2);
+    if (noFilters<=0) printf("error\n");
+  }
+  m_pcDummyEntropyCoder->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_SQR_FILT_LENGTH], bitsCoeffScan[MAX_SCAN_VAL][MAX_EXP_GOLOMB],
+  minKStart, minBitsKStart, bitsKStart;
+  
+  pDepthInt = pDepthIntTab[fl-2];
+  
+  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 = 0; 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 = 0; 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);
+  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;
+      bit_cnt += lengthGolomb(abs(FilterCoeff[ind][i]), kMinTab[scanPos]);
+    }
+  }
+  return bit_cnt;
+}
+
+Void   TEncAdaptiveLoopFilter::xEncALFLuma_qc ( TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiMinRate, UInt64& ruiMinDist, Double& rdMinCost )
+{
+  //pcPicDec: extended decoded
+  //pcPicRest: original decoded: filtered signal will be stored
+  
+  UInt64  uiRate;
+  UInt64  uiDist;
+  Double dCost;
+#if !MQT_ALF_NPASS
+  Int    Height = pcPicOrg->getHeight();
+  Int    Width = pcPicOrg->getWidth();
+#endif
+  Int    LumaStride = pcPicOrg->getStride();
+  imgpel* pOrg = (imgpel*) pcPicOrg->getLumaAddr();
+  imgpel* pRest = (imgpel*) pcPicRest->getLumaAddr();
+  imgpel* pDec = (imgpel*) pcPicDec->getLumaAddr();
+
+  Int tap               = ALF_MIN_NUM_TAP;
+  m_pcTempAlfParam->tap = tap;
+#if TI_ALF_MAX_VSIZE_7
+  m_pcTempAlfParam->tapV = TComAdaptiveLoopFilter::ALFTapHToTapV(m_pcTempAlfParam->tap);
+  m_pcTempAlfParam->num_coeff = TComAdaptiveLoopFilter::ALFTapHToNumCoeff(m_pcTempAlfParam->tap);
+#else
+  m_pcTempAlfParam->num_coeff = (Int)tap*tap/4 + 2; 
+#endif
+
+#if MQT_BA_RA
+
+#if MQT_ALF_NPASS
+
+  static Bool   bFirst = true;
+  static Int*   apiVarIndTabBest[NUM_ALF_CLASS_METHOD];
+  static Int**  appiBestCoeffSet[NUM_ALF_CLASS_METHOD];
+
+  static Double***  adBestySym;
+  static Double**** adBestESym;
+  static Double**   adBestpixAcc;  
+
+  if(bFirst)
+  {
+    if(m_iALFEncodePassReduction)
+    {
+      initMatrix4D_double(&adBestESym,NUM_ALF_CLASS_METHOD,  NO_VAR_BINS, MAX_SQR_FILT_LENGTH, MAX_SQR_FILT_LENGTH);
+      initMatrix3D_double(&adBestySym,NUM_ALF_CLASS_METHOD,  NO_VAR_BINS, MAX_SQR_FILT_LENGTH); 
+      initMatrix_double  (&adBestpixAcc,NUM_ALF_CLASS_METHOD,  NO_VAR_BINS );
+
+      for(Int i=0; i< NUM_ALF_CLASS_METHOD; i++)
+      {
+
+        apiVarIndTabBest[i] = new Int[NO_VAR_BINS];
+        appiBestCoeffSet[i] = new Int*[NO_VAR_BINS];
+        for(Int j=0; j< NO_VAR_BINS; j++)
+        {
+          appiBestCoeffSet[i][j]= new Int[MAX_SQR_FILT_LENGTH];
+        }
+      }
+    }
+
+    bFirst = false;
+  }
+
+  Int         ibestfiltNo[NUM_ALF_CLASS_METHOD];
+  Int         ibestfilters_per_fr[NUM_ALF_CLASS_METHOD];
+  Int64       iDist;
+  Int64       iMinMethodDist = MAX_INT;
+  UInt64      uiMinMethodRate;
+  Double      dMinMethodCost = MAX_DOUBLE;
+#endif
+  Int       iBestClassMethod = ALF_RA;
+  Double    adExtraCostReduction[NUM_ALF_CLASS_METHOD];
+  ALFParam  cFrmAlfParam        [NUM_ALF_CLASS_METHOD];
+  ALFParam* pcAlfParam = NULL;
+
+  for(Int i=0; i< NUM_ALF_CLASS_METHOD; i++)
+  {
+    pcAlfParam = &(cFrmAlfParam[i]);
+    allocALFParam(pcAlfParam);
+
+    pcAlfParam->alf_flag        = 1;
+    pcAlfParam->chroma_idc      = 0;
+    pcAlfParam->cu_control_flag = 0;
+    pcAlfParam->tap = tap;
+#if TI_ALF_MAX_VSIZE_7
+    pcAlfParam->tapV = TComAdaptiveLoopFilter::ALFTapHToTapV(pcAlfParam->tap);
+    pcAlfParam->num_coeff = TComAdaptiveLoopFilter::ALFTapHToNumCoeff(pcAlfParam->tap);
+#else
+    pcAlfParam->num_coeff = (Int)tap*tap/4 + 2; 
+#endif
+
+    switch(i)
+    {
+    case ALF_RA:
+      {
+        adExtraCostReduction[i] = (double)(m_im_height * m_im_width) * m_dLambdaLuma * 2.0 / 4096.0;
+      }
+      break;
+    default:
+      {
+        adExtraCostReduction[i] = 0.0;
+      }
+      break;
+    }
+
+  }
+
+  for(Int i=0; i< NUM_ALF_CLASS_METHOD; i++)
+  {
+    pcAlfParam       = &(cFrmAlfParam[i]);
+    m_varImg         = m_varImgMethods[i];
+    m_uiVarGenMethod = pcAlfParam->alf_pcr_region_flag = i;
+#if MQT_ALF_NPASS
+    if(m_iALFEncodePassReduction)
+    {
+      m_aiFilterCoeffSaved = m_aiFilterCoeffSavedMethods[m_uiVarGenMethod];
+    }
+    setInitialMask(pcPicOrg, pcPicDec);
+#else
+    for (Int i=0; i<Height; i++)
+    {
+      for (Int j=0; j<Width; j++)
+      {
+        m_maskImg[i][j] = 1;
+      }
+    }
+#if MTK_NONCROSS_INLOOP_FILTER
+    if(!m_bUseNonCrossALF)
+      calcVar(0, 0, m_varImg, pDec, 9/2, VAR_SIZE, Height, Width, LumaStride);
+    else
+      calcVarforSlices(m_varImg, pDec, 9/2, VAR_SIZE, LumaStride);
+#else
+    calcVar(m_varImg, pDec, 9/2, VAR_SIZE, Height, Width, LumaStride);
+#endif
+#endif
+
+#if MQT_ALF_NPASS
+    if(m_iALFEncodePassReduction)
+    {
+      xFirstEstimateFilteringFrameLumaAllTap(pOrg, pDec, LumaStride, 
+        pcAlfParam, apiVarIndTabBest[i], appiBestCoeffSet[i],
+        ibestfiltNo[i], ibestfilters_per_fr[i], 
+        adBestySym[i], adBestESym[i], adBestpixAcc[i],
+        uiRate, iDist, dCost);
+
+    }
+    else
+    {
+#endif
+      xFirstFilteringFrameLuma(pOrg, pDec, (imgpel*)m_pcPicYuvTmp->getLumaAddr(), pcAlfParam, pcAlfParam->tap, LumaStride); 
+#if MQT_ALF_NPASS
+    }
+#endif
+
+#if MQT_ALF_NPASS
+    if(!m_iALFEncodePassReduction)
+    {
+#endif
+      xCalcRDCost(pcPicOrg, m_pcPicYuvTmp, pcAlfParam, uiRate, uiDist, dCost); 
+#if MQT_ALF_NPASS
+      iDist = (Int64)uiDist;
+    }
+#endif
+
+    dCost -= adExtraCostReduction[i];
+
+    if(dCost < dMinMethodCost)
+    {
+      iBestClassMethod = i;
+      dMinMethodCost = dCost;
+      uiMinMethodRate= uiRate;
+      iMinMethodDist = iDist;
+#if MQT_ALF_NPASS
+      if(!m_iALFEncodePassReduction)
+      {
+#endif
+        m_pcPicYuvTmp->copyToPicLuma(pcPicRest);
+#if MQT_ALF_NPASS
+      }
+#endif
+
+    }  
+
+  }
+
+  dMinMethodCost += adExtraCostReduction[iBestClassMethod];
+
+
+  m_varImg= m_varImgMethods[iBestClassMethod];
+
+  m_uiVarGenMethod = iBestClassMethod;
+
+#if MQT_ALF_NPASS
+  if(m_iALFEncodePassReduction)
+  {
+
+    m_aiFilterCoeffSaved = m_aiFilterCoeffSavedMethods[iBestClassMethod];
+
+    setInitialMask(pcPicOrg, pcPicDec);
+
+    m_pcBestAlfParam->alf_flag = 1;
+    m_pcBestAlfParam->cu_control_flag = 0;
+    m_pcBestAlfParam->chroma_idc = 0;
+    m_pcBestAlfParam->alf_pcr_region_flag = iBestClassMethod;
+
+    m_pcBestAlfParam->tap = cFrmAlfParam[iBestClassMethod].tap;
+#if TI_ALF_MAX_VSIZE_7
+    m_pcBestAlfParam->tapV = TComAdaptiveLoopFilter::ALFTapHToTapV(pcAlfParam->tap);
+    m_pcBestAlfParam->num_coeff = TComAdaptiveLoopFilter::ALFTapHToNumCoeff(pcAlfParam->tap);
+#else
+    m_pcBestAlfParam->num_coeff = (Int)tap*tap/4 + 2; 
+#endif
+
+    xFirstFilteringFrameLuma(pOrg, pDec, pRest, m_pcBestAlfParam, m_pcBestAlfParam->tap, LumaStride); 
+
+
+
+    xCalcRDCost(pcPicOrg, pcPicRest, m_pcBestAlfParam, uiMinMethodRate, uiDist, dMinMethodCost);
+    iMinMethodDist = (Int64)uiDist;
+  }
+  else
+  {
+#endif
+    copyALFParam(m_pcBestAlfParam, &cFrmAlfParam[iBestClassMethod]); 
+#if MQT_ALF_NPASS
+
+  }
+#endif
+
+  ruiMinRate = uiMinMethodRate;
+  ruiMinDist = (UInt64)iMinMethodDist;
+  rdMinCost =  dMinMethodCost;
+
+
+  for(Int i=0; i< NUM_ALF_CLASS_METHOD; i++)
+  {
+    freeALFParam(&cFrmAlfParam[i]);
+  }
+
+#else  
+
+#if MQT_ALF_NPASS
+  setInitialMask(pcPicOrg, pcPicDec);
+#else
+  for (Int i=0; i<Height; i++)
+  {
+    for (Int j=0; j<Width; j++)
+    {
+      m_maskImg[i][j] = 1;
+    }
+  }
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(!m_bUseNonCrossALF)
+    calcVar(0, 0, m_varImg, pDec, 9/2, VAR_SIZE, Height, Width, LumaStride);
+  else
+    calcVarforSlices(m_varImg, pDec, 9/2, VAR_SIZE, LumaStride);
+#else
+  calcVar(m_varImg, pDec, 9/2, VAR_SIZE, Height, Width, LumaStride);
+#endif
+#endif
+
+#if MQT_ALF_NPASS
+  if(m_iALFEncodePassReduction)
+  {
+    xFirstFilteringFrameLumaAllTap(pOrg, pDec, pRest, LumaStride);
+  }
+  else
+#endif
+    xFirstFilteringFrameLuma(pOrg, pDec, pRest, m_pcTempAlfParam, m_pcTempAlfParam->tap, LumaStride); 
+
+  xCalcRDCost(pcPicOrg, pcPicRest, m_pcTempAlfParam, uiRate, uiDist, dCost); // change this function final coding 
+  
+  if( dCost < rdMinCost)
+  {
+    ruiMinRate = uiRate;
+    ruiMinDist = uiDist;
+    rdMinCost = dCost;
+    copyALFParam(m_pcBestAlfParam, m_pcTempAlfParam); 
+  } 
+
+#endif
+}
+
+Void   TEncAdaptiveLoopFilter::xFirstFilteringFrameLuma(imgpel* ImgOrg, imgpel* ImgDec, imgpel* ImgRest, ALFParam* ALFp, Int tap, Int Stride)
+{
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(!m_bUseNonCrossALF)
+    xstoreInBlockMatrix(0, 0, m_im_height, m_im_width, true, true, ImgOrg, ImgDec, tap, Stride);
+  else
+    xstoreInBlockMatrixforSlices(ImgOrg, ImgDec, tap, Stride);
+#else
+  xstoreInBlockMatrix(ImgOrg, ImgDec, tap, Stride);
+#endif
+
+
+  xFilteringFrameLuma_qc(ImgOrg, ImgDec, ImgRest, ALFp, tap, Stride);
+}
+
+
+#if MTK_NONCROSS_INLOOP_FILTER
+Void   TEncAdaptiveLoopFilter::xstoreInBlockMatrix(Int ypos, Int xpos, Int iheight, Int iwidth, Bool bResetBlockMatrix, Bool bSymmCopyBlockMatrix, imgpel* ImgOrg, imgpel* ImgDec, Int tap, Int Stride)
+#else
+Void   TEncAdaptiveLoopFilter::xstoreInBlockMatrix(imgpel* ImgOrg, imgpel* ImgDec, Int tap, Int Stride)
+#endif
+{
+#if MQT_BA_RA
+  Int var_step_size_w = VAR_SIZE_W;
+  Int var_step_size_h = VAR_SIZE_H;
+#endif
+
+  Int i,j,k,l,varInd,ii,jj;
+  Int x, y;
+  Int fl =tap/2;
+#if TI_ALF_MAX_VSIZE_7
+  Int flV = TComAdaptiveLoopFilter::ALFFlHToFlV(fl);
+  Int sqrFiltLength = TComAdaptiveLoopFilter::ALFTapHToNumCoeff(tap);
+#else
+  Int sqrFiltLength=(((tap*tap)/4 + 1) + 1);
+#endif
+  Int fl2=9/2; //extended size at each side of the frame
+  Int ELocal[MAX_SQR_FILT_LENGTH];
+  Int yLocal;
+  Int *p_pattern;
+  Int filtNo =2; 
+  double **E,*yy;
+#if MTK_NONCROSS_INLOOP_FILTER
+  static Int count_valid;
+#else
+  Int count_valid=0;
+#endif
+  if (tap==9)
+    filtNo =0;
+  else if (tap==7)
+    filtNo =1;
+  
+  p_pattern= m_patternTab[filtNo];
+  
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(bResetBlockMatrix)
+  {
+    count_valid = 0;
+#endif
+  memset( m_pixAcc, 0,sizeof(double)*NO_VAR_BINS);
+  for (varInd=0; varInd<NO_VAR_BINS; varInd++)
+  {
+    memset(m_yGlobalSym[filtNo][varInd],0,sizeof(double)*MAX_SQR_FILT_LENGTH);
+    for (k=0; k<sqrFiltLength; k++)
+    {
+      memset(m_EGlobalSym[filtNo][varInd][k],0,sizeof(double)*MAX_SQR_FILT_LENGTH);
+    }
+  }
+  for (i = fl2; i < m_im_height+fl2; i++)
+  {
+    for (j = fl2; j < m_im_width+fl2; j++)
+    {
+      if (m_maskImg[i-fl2][j-fl2] == 1)
+      {
+        count_valid++;
+      }
+    }
+  }
+#if MTK_NONCROSS_INLOOP_FILTER
+  }
+#endif
+
+  {
+#if MTK_NONCROSS_INLOOP_FILTER
+    x = y = fl2; //cytsai: shall x, y  be removed ?
+
+    for (i= ypos; i< ypos + iheight; i++)
+    {
+      for (j= xpos; j< xpos + iwidth; j++)
+      {
+#else
+    for (i=0,y=fl2; i<m_im_height; i++,y++)
+    {
+      for (j=0,x=fl2; j<m_im_width; j++,x++)
+      {
+#endif
+#if MQT_ALF_NPASS
+        Int condition = (m_maskImg[i][j] == 1);
+        if (m_iDesignCurrentFilter)
+        {
+          condition = (m_maskImg[i][j] == 0 && count_valid > 0);
+        }
+        if(!condition)
+        {
+#else
+        if (m_maskImg[i][j] == 0 && count_valid > 0)
+        {
+
+        }
+        else
+        {
+#endif
+#if MQT_BA_RA
+          varInd = m_varImg[i/var_step_size_h][j/var_step_size_w];
+#else
+          varInd=min(m_varImg[i][j], NO_VAR_BINS-1);
+#endif
+          k=0; 
+          memset(ELocal, 0, sqrFiltLength*sizeof(int));
+#if TI_ALF_MAX_VSIZE_7
+          for (ii = -flV; ii < 0; ii++)
+#else
+          for (ii=-fl; ii<0; ii++)
+#endif
+          {
+            for (jj=-fl-ii; jj<=fl+ii; jj++)
+            {  
+              ELocal[p_pattern[k++]]+=(ImgDec[(i+ii)*Stride + (j+jj)]+ImgDec[(i-ii)*Stride + (j-jj)]);
+            }
+          }
+          for (jj=-fl; jj<0; jj++)
+            ELocal[p_pattern[k++]]+=(ImgDec[(i)*Stride + (j+jj)]+ImgDec[(i)*Stride + (j-jj)]);
+          ELocal[p_pattern[k++]]+=ImgDec[(i)*Stride + (j)];
+          ELocal[sqrFiltLength-1]=1;
+          yLocal=ImgOrg[(i)*Stride + (j)];
+
+          m_pixAcc[varInd]+=(yLocal*yLocal);
+          E= m_EGlobalSym[filtNo][varInd];
+          yy= m_yGlobalSym[filtNo][varInd];
+
+          for (k=0; k<sqrFiltLength; k++)
+          {
+            for (l=k; l<sqrFiltLength; l++)
+              E[k][l]+=(double)(ELocal[k]*ELocal[l]);
+            yy[k]+=(double)(ELocal[k]*yLocal);
+          }
+        }
+      }
+    }
+  }
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(bSymmCopyBlockMatrix)
+  {
+#endif
+
+  // Matrix EGlobalSeq is symmetric, only part of it is calculated
+  for (varInd=0; varInd<NO_VAR_BINS; varInd++)
+  {
+    double **pE = m_EGlobalSym[filtNo][varInd];
+    for (k=1; k<sqrFiltLength; k++)
+    {
+      for (l=0; l<k; l++)
+      {
+        pE[k][l]=pE[l][k];
+      }
+    }
+  }
+#if MTK_NONCROSS_INLOOP_FILTER
+  }
+#endif
+
+}
+
+Void   TEncAdaptiveLoopFilter::xFilteringFrameLuma_qc(imgpel* ImgOrg, imgpel* imgY_pad, imgpel* ImgFilt, ALFParam* ALFp, Int tap, Int Stride)
+{
+  int  filtNo,filters_per_fr;
+  static double **ySym, ***ESym;
+  int lambda_val = (Int) m_dLambdaLuma;
+  lambda_val = lambda_val * (1<<(2*g_uiBitIncrement));
+  if (tap==9)
+    filtNo =0;
+  else if (tap==7)
+    filtNo =1;
+  else
+    filtNo=2;
+  
+  ESym=m_EGlobalSym[filtNo];  
+  ySym=m_yGlobalSym[filtNo];
+  
+  xfindBestFilterVarPred(ySym, ESym, m_pixAcc, m_filterCoeffSym, m_filterCoeffSymQuant, filtNo, &filters_per_fr,
+                         m_varIndTab, NULL, m_varImg, m_maskImg, NULL, lambda_val);
+  
+  // g_filterCoeffPrevSelected = g_filterCoeffSym
+  xcalcPredFilterCoeff(filtNo);
+  
+  //filter the frame with g_filterCoeffPrevSelected
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(!m_bUseNonCrossALF)
+    xfilterFrame_en(0, 0, m_im_height, m_im_width, imgY_pad, ImgFilt, filtNo, Stride);
+  else
+    xfilterSlices_en(imgY_pad, ImgFilt, filtNo, Stride);
+#else
+  xfilterFrame_en(imgY_pad, ImgFilt, filtNo, Stride);
+#endif
+
+  xcodeFiltCoeff(m_filterCoeffSymQuant, filtNo, m_varIndTab, filters_per_fr,0, ALFp);
+}
+
+#if MTK_NONCROSS_INLOOP_FILTER
+Void TEncAdaptiveLoopFilter::xfilterFrame_en(int ypos, int xpos, int iheight, int iwidth, imgpel* ImgDec, imgpel* ImgRest,int filtNo, int Stride)
+#else
+Void TEncAdaptiveLoopFilter::xfilterFrame_en(imgpel* ImgDec, imgpel* ImgRest,int filtNo, int Stride)
+#endif
+{
+#if MQT_BA_RA
+  imgpel *imgY_rec = ImgDec;
+  imgpel *p_imgY_pad, *p_imgY_pad0;
+  int var_step_size_w = VAR_SIZE_W;
+  int var_step_size_h = VAR_SIZE_H;
+  int i,j,y,x;
+#else
+  int i,j,ii,jj,y,x;
+#endif
+  int  *pattern; 
+  int fl, fl_temp, sqrFiltLength;
+  int pixelInt;
+  int offset = (1<<(NUM_BITS - 2));
+  
+  pattern=m_patternTab_filt[filtNo];
+  fl_temp=m_flTab[filtNo];
+#if !MQT_BA_RA
+#if TI_ALF_MAX_VSIZE_7
+  Int fl_tempV = TComAdaptiveLoopFilter::ALFFlHToFlV(fl_temp);
+#endif
+#endif
+  sqrFiltLength=MAX_SQR_FILT_LENGTH;  fl=FILTER_LENGTH/2;
+  
+#if MTK_NONCROSS_INLOOP_FILTER
+  for (y= ypos, i = fl+ ypos; i < ypos+ iheight+ fl; i++, y++)
+  {
+    for (x= xpos, j = fl+ xpos; j < xpos+ iwidth+ fl; j++, x++)
+    {
+#else
+  for (y=0, i = fl; i < m_im_height+fl; i++, y++)
+  {
+    for (x=0, j = fl; j < m_im_width+fl; j++, x++)
+    {
+#endif
+#if MQT_BA_RA
+      int varInd=m_varImg[y/var_step_size_h][x/var_step_size_w];
+#else
+      int varInd=m_varImg[i-fl][j-fl];
+      imgpel *im1,*im2;
+#endif
+      int *coef = m_filterCoeffPrevSelected[varInd];
+      pattern=m_patternTab_filt[filtNo];
+      pixelInt= m_filterCoeffPrevSelected[varInd][sqrFiltLength-1]; 
+
+#if MQT_BA_RA
+      if (filtNo == 2) //5x5
+      {
+        pixelInt += coef[22]* (imgY_rec[(i-fl+2)*Stride + j-fl]+imgY_rec[(i-fl-2)*Stride + j-fl]);
+
+        pixelInt += coef[30]* (imgY_rec[(i-fl+1)*Stride + j-fl+1]+imgY_rec[(i-fl-1)*Stride + j-fl-1]);
+        pixelInt += coef[31]* (imgY_rec[(i-fl+1)*Stride + j-fl]  +imgY_rec[(i-fl-1)*Stride + j-fl]);
+        pixelInt += coef[32]* (imgY_rec[(i-fl+1)*Stride + j-fl-1]+imgY_rec[(i-fl-1)*Stride + j-fl+1]);
+
+        pixelInt += coef[38]* (imgY_rec[(i-fl)*Stride + j-fl-2]+imgY_rec[(i-fl)*Stride + j-fl+2]);
+        pixelInt += coef[39]* (imgY_rec[(i-fl)*Stride + j-fl-1]+imgY_rec[(i-fl)*Stride + j-fl+1]);
+        pixelInt += coef[40]* (imgY_rec[(i-fl)*Stride + j-fl]);
+      }
+      else if (filtNo == 1) //7x7
+      {
+        pixelInt += coef[13]* (imgY_rec[(i-fl+3)*Stride + j-fl]+imgY_rec[(i-fl-3)*Stride + j-fl]);
+
+        p_imgY_pad = imgY_rec + (i-fl+2)*Stride;
+        p_imgY_pad0 = imgY_rec + (i-fl-2)*Stride;
+        pixelInt += coef[21]* (p_imgY_pad[j-fl+1]+p_imgY_pad0[j-fl-1]);
+        pixelInt += coef[22]* (p_imgY_pad[j-fl]+p_imgY_pad0[j-fl]);
+        pixelInt += coef[23]* (p_imgY_pad[j-fl-1]+p_imgY_pad0[j-fl+1]);
+
+        p_imgY_pad = imgY_rec + (i-fl+1)*Stride;
+        p_imgY_pad0 = imgY_rec + (i-fl-1)*Stride;
+        pixelInt += coef[29]* (p_imgY_pad[j-fl+2]+p_imgY_pad0[j-fl-2]);
+        pixelInt += coef[30]* (p_imgY_pad[j-fl+1]+p_imgY_pad0[j-fl-1]);
+        pixelInt += coef[31]* (p_imgY_pad[j-fl]+p_imgY_pad0[j-fl]);
+        pixelInt += coef[32]* (p_imgY_pad[j-fl-1]+p_imgY_pad0[j-fl+1]);
+        pixelInt += coef[33]* (p_imgY_pad[j-fl-2]+p_imgY_pad0[j-fl+2]);
+
+        p_imgY_pad = imgY_rec + (i-fl)*Stride;
+        pixelInt += coef[37]* (p_imgY_pad[j-fl+3]+p_imgY_pad[j-fl-3]);
+        pixelInt += coef[38]* (p_imgY_pad[j-fl+2]+p_imgY_pad[j-fl-2]);
+        pixelInt += coef[39]* (p_imgY_pad[j-fl+1]+p_imgY_pad[j-fl-1]);
+        pixelInt += coef[40]* (p_imgY_pad[j-fl]);
+
+      }
+      else
+      {
+#if !TI_ALF_MAX_VSIZE_7
+        pixelInt += coef[4]* (imgY_rec[(i-fl+4)*Stride + j-fl]+imgY_rec[(i-fl-4)*Stride + j-fl]);
+#endif          
+        p_imgY_pad = imgY_rec + (i-fl+3)*Stride;
+        p_imgY_pad0 = imgY_rec + (i-fl-3)*Stride;
+        pixelInt += coef[12]* (p_imgY_pad[j-fl+1]+p_imgY_pad0[j-fl-1]);
+        pixelInt += coef[13]* (p_imgY_pad[j-fl]+p_imgY_pad0[j-fl]);
+        pixelInt += coef[14]* (p_imgY_pad[j-fl-1]+p_imgY_pad0[j-fl+1]);
+
+        p_imgY_pad = imgY_rec + (i-fl+2)*Stride;
+        p_imgY_pad0 = imgY_rec + (i-fl-2)*Stride;
+        pixelInt += coef[20]* (p_imgY_pad[j-fl+2]+p_imgY_pad0[j-fl-2]);
+        pixelInt += coef[21]* (p_imgY_pad[j-fl+1]+p_imgY_pad0[j-fl-1]);
+        pixelInt += coef[22]* (p_imgY_pad[j-fl]+p_imgY_pad0[j-fl]);
+        pixelInt += coef[23]* (p_imgY_pad[j-fl-1]+p_imgY_pad0[j-fl+1]);
+        pixelInt += coef[24]* (p_imgY_pad[j-fl-2]+p_imgY_pad0[j-fl+2]);
+
+        p_imgY_pad = imgY_rec + (i-fl+1)*Stride;
+        p_imgY_pad0 = imgY_rec + (i-fl-1)*Stride;
+        pixelInt += coef[28]* (p_imgY_pad[j-fl+3]+p_imgY_pad0[j-fl-3]);
+        pixelInt += coef[29]* (p_imgY_pad[j-fl+2]+p_imgY_pad0[j-fl-2]);
+        pixelInt += coef[30]* (p_imgY_pad[j-fl+1]+p_imgY_pad0[j-fl-1]);
+        pixelInt += coef[31]* (p_imgY_pad[j-fl]+p_imgY_pad0[j-fl]);
+        pixelInt += coef[32]* (p_imgY_pad[j-fl-1]+p_imgY_pad0[j-fl+1]);
+        pixelInt += coef[33]* (p_imgY_pad[j-fl-2]+p_imgY_pad0[j-fl+2]);
+        pixelInt += coef[34]* (p_imgY_pad[j-fl-3]+p_imgY_pad0[j-fl+3]);
+
+        p_imgY_pad = imgY_rec + (i-fl)*Stride;
+        pixelInt += coef[36]* (p_imgY_pad[j-fl+4]+p_imgY_pad[j-fl-4]);
+        pixelInt += coef[37]* (p_imgY_pad[j-fl+3]+p_imgY_pad[j-fl-3]);
+        pixelInt += coef[38]* (p_imgY_pad[j-fl+2]+p_imgY_pad[j-fl-2]);
+        pixelInt += coef[39]* (p_imgY_pad[j-fl+1]+p_imgY_pad[j-fl-1]);
+        pixelInt += coef[40]* (p_imgY_pad[j-fl]);
+
+      }
+#else
+
+#if TI_ALF_MAX_VSIZE_7
+      for (ii = -fl_tempV; ii < 0; ii++)
+#else
+      for (ii=-fl_temp; ii<0; ii++)
+#endif
+      {
+        im1= &(ImgDec[(y+ii)*Stride + x-fl_temp-ii]);
+        im2= &(ImgDec[(y-ii)*Stride + x+fl_temp+ii]);
+        for (jj=-fl_temp-ii; jj<=fl_temp+ii; jj++,im1++,im2--)
+          pixelInt+=((*im1+ *im2)*coef[*(pattern++)]);
+      }
+      im1= &(ImgDec[y*Stride + x-fl_temp]);
+      im2= &(ImgDec[y*Stride + x+fl_temp]);
+      for (jj=-fl_temp; jj<0; jj++,im1++,im2--)
+        pixelInt+=((*im1+ *im2)*coef[*(pattern++)]);
+      pixelInt+=(ImgDec[y*Stride + x]*coef[*(pattern++)]);
+#endif  
+
+      pixelInt=(int)((pixelInt+offset) >> (NUM_BITS - 1));
+      ImgRest[y*Stride + x] = Clip3(0, g_uiIBDI_MAX, pixelInt);
+    }
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xfindBestFilterVarPred(double **ySym, double ***ESym, double *pixAcc, int **filterCoeffSym, int **filterCoeffSymQuant, int filtNo, int *filters_per_fr_best, int varIndTab[], imgpel **imgY_rec, imgpel **varImg, imgpel **maskImg, imgpel **imgY_pad, double lambda_val)
+{
+  int filters_per_fr, firstFilt, coded, forceCoeff0,
+  interval[NO_VAR_BINS][2], intervalBest[NO_VAR_BINS][2];
+  int i, k, varInd;
+  static double ***E_temp, **y_temp, *pixAcc_temp;
+  static int **FilterCoeffQuantTemp;
+  double  error, lambda, lagrangian, lagrangianMin;
+  
+  int sqrFiltLength;
+  int *pattern, *patternMap, *weights;
+  int numBits, coeffBits;
+  double errorForce0CoeffTab[NO_VAR_BINS][2];
+  int  codedVarBins[NO_VAR_BINS], createBistream /*, forceCoeff0 */;
+  int  usePrevFilt[NO_VAR_BINS], usePrevFiltDefault[NO_VAR_BINS];
+  static int first=0;
+  
+  for (i = 0; i < NO_VAR_BINS; i++)
+    usePrevFiltDefault[i]=usePrevFilt[i]=1;
+  lambda = lambda_val;
+  sqrFiltLength=MAX_SQR_FILT_LENGTH;
+  
+  if (first==0)
+  {
+    initMatrix3D_double(&E_temp, NO_VAR_BINS, MAX_SQR_FILT_LENGTH, MAX_SQR_FILT_LENGTH);
+    initMatrix_double(&y_temp, NO_VAR_BINS, MAX_SQR_FILT_LENGTH); 
+    pixAcc_temp = (double *) calloc(NO_VAR_BINS, sizeof(double));
+    initMatrix_int(&FilterCoeffQuantTemp, NO_VAR_BINS, MAX_SQR_FILT_LENGTH);
+    first=1;
+  }
+  
+  sqrFiltLength=m_sqrFiltLengthTab[filtNo];   
+  Int fl = m_flTab[filtNo];
+  weights=m_weightsTab[filtNo];               
+  patternMap=m_patternMapTab[filtNo];  
+  pattern=m_patternTab[filtNo];
+  
+  memcpy(pixAcc_temp,pixAcc,sizeof(double)*NO_VAR_BINS);
+  for (varInd=0; varInd<NO_VAR_BINS; varInd++)
+  {
+    memcpy(y_temp[varInd],ySym[varInd],sizeof(double)*sqrFiltLength);
+    for (k=0; k<sqrFiltLength; k++)
+      memcpy(E_temp[varInd][k],ESym[varInd][k],sizeof(double)*sqrFiltLength);
+  }
+  
+  // 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)*MAX_SQR_FILT_LENGTH);
+    memset(filterCoeffSymQuant[i],0,sizeof(int)*MAX_SQR_FILT_LENGTH);
+  }
+  
+  firstFilt=1;  lagrangianMin=0;
+  filters_per_fr=NO_FILTERS;
+  
+  while(filters_per_fr>=1)
+  {
+    findFilterGroupingError(E_temp, y_temp, pixAcc_temp, interval, sqrFiltLength, filters_per_fr);
+    findFilterCoeff(E_temp, y_temp, pixAcc_temp, filterCoeffSym, filterCoeffSymQuant, interval,
+                    varIndTab, sqrFiltLength, filters_per_fr, weights, numBits=NUM_BITS,  errorForce0CoeffTab);
+    lagrangian=xfindBestCoeffCodMethod(codedVarBins, &forceCoeff0, filterCoeffSymQuant, fl, 
+                                       sqrFiltLength, filters_per_fr, errorForce0CoeffTab, &error, lambda);
+    
+    if (lagrangian<lagrangianMin || firstFilt==1)
+    {
+      firstFilt=0;
+      lagrangianMin=lagrangian;
+
+      (*filters_per_fr_best)=filters_per_fr;
+      memcpy(intervalBest, interval, NO_VAR_BINS*2*sizeof(int));
+    }
+    filters_per_fr--;
+  }
+  
+  findFilterCoeff(E_temp, y_temp, pixAcc_temp, filterCoeffSym, filterCoeffSymQuant, intervalBest,
+                  varIndTab, sqrFiltLength, (*filters_per_fr_best), weights, numBits=NUM_BITS, errorForce0CoeffTab);
+  
+  xfindBestCoeffCodMethod(codedVarBins, &forceCoeff0, filterCoeffSymQuant, fl, sqrFiltLength, 
+                          (*filters_per_fr_best), errorForce0CoeffTab, &error, lambda);
+  
+  coded=1;
+  if (forceCoeff0==1 && (*filters_per_fr_best)==1)
+  {
+    coded=0;
+    coeffBits = xcodeAuxInfo(-1, (*filters_per_fr_best), varIndTab, 0, createBistream=0,filtNo, m_tempALFp);
+  }
+  else
+  {
+    coeffBits = xcodeAuxInfo(filtNo, (*filters_per_fr_best), varIndTab, 0, createBistream=0,filtNo, m_tempALFp);
+  }
+
+  if (forceCoeff0==0)
+  {
+    coeffBits += xsendAllFiltersPPPred(filterCoeffSymQuant, fl, sqrFiltLength, 
+      (*filters_per_fr_best), createBistream=0, m_tempALFp);
+  }
+  else
+  {
+    if ((*filters_per_fr_best)==1)
+    {
+      for(varInd=0; varInd<(*filters_per_fr_best); varInd++)
+      {
+        memset(filterCoeffSym[varInd],0,sizeof(int)*MAX_SQR_FILT_LENGTH);
+        memset(filterCoeffSymQuant[varInd],0,sizeof(int)*MAX_SQR_FILT_LENGTH);
+      }
+    }
+    else
+    {
+      coeffBits += xsendAllFiltersPPPredForce0(filterCoeffSymQuant, fl, sqrFiltLength, 
+        (*filters_per_fr_best), codedVarBins, createBistream=0, m_tempALFp);
+
+      for(varInd=0; varInd<(*filters_per_fr_best); varInd++)
+      {
+        if (codedVarBins[varInd]==0)
+        {
+          memset(filterCoeffSym[varInd],0,sizeof(int)*MAX_SQR_FILT_LENGTH);
+          memset(filterCoeffSymQuant[varInd],0,sizeof(int)*MAX_SQR_FILT_LENGTH);
+        }
+      }
+    }
+  }
+}
+
+
+Void TEncAdaptiveLoopFilter::xcalcPredFilterCoeff(int filtNo)
+{
+  int *patternMap, varInd, i, k;
+  
+  patternMap=m_patternMapTab[filtNo];
+  for(varInd=0; varInd<NO_VAR_BINS; ++varInd)
+  {
+    k=0;
+    for(i = 0; i < MAX_SQR_FILT_LENGTH; i++)
+    {
+      if (patternMap[i]>0)
+      {
+        m_filterCoeffPrevSelected[varInd][i]=m_filterCoeffSym[m_varIndTab[varInd]][k];
+        k++;
+      }
+      else
+      {
+        m_filterCoeffPrevSelected[varInd][i]=0;
+      }
+#if MQT_ALF_NPASS
+      if (m_iALFEncodePassReduction && (!m_iUsePreviousFilter || !m_iDesignCurrentFilter))
+      {
+        if((m_iCurrentPOC%m_iGOPSize) == 0)
+        {
+          m_aiFilterCoeffSaved[0][varInd][i] = m_aiFilterCoeffSaved[m_iGOPSize][varInd][i]; 
+          m_aiFilterCoeffSaved[m_iGOPSize][varInd][i] = m_filterCoeffPrevSelected[varInd][i]; 
+        }
+        else
+        {
+          m_aiFilterCoeffSaved[m_iCurrentPOC%m_iGOPSize][varInd][i] = m_filterCoeffPrevSelected[varInd][i];
+        }
+      }
+#endif
+    }
+  }
+}
+
+#if MQT_ALF_NPASS
+UInt TEncAdaptiveLoopFilter::xcodeFiltCoeff(int **filterCoeffSymQuant, int filtNo, int varIndTab[], int filters_per_fr_best, int frNo, ALFParam* ALFp)
+#else
+Void TEncAdaptiveLoopFilter::xcodeFiltCoeff(int **filterCoeffSymQuant, int filtNo, int varIndTab[], int filters_per_fr_best, int frNo, ALFParam* ALFp)
+#endif
+{
+  int varInd, forceCoeff0, codedVarBins[NO_VAR_BINS], coeffBits, createBistream,   sqrFiltLength=m_sqrFiltLengthTab[filtNo], 
+  fl=m_flTab[filtNo], coded;
+  
+  ALFp->filters_per_group_diff = filters_per_fr_best;
+  ALFp->filters_per_group = filters_per_fr_best;
+  
+  for(varInd=0; varInd<filters_per_fr_best; varInd++)
+  {
+    codedVarBins[varInd] = 1;
+  }
+  memcpy (ALFp->codedVarBins, codedVarBins, sizeof(int)*NO_VAR_BINS);
+  forceCoeff0=0;
+  for(varInd=0; varInd<filters_per_fr_best; varInd++)
+  {
+    if (codedVarBins[varInd] == 0)
+    {
+      forceCoeff0=1;
+      break;
+    }
+  }
+
+  coded=1;
+  if (forceCoeff0==1 && filters_per_fr_best==1)
+  {
+    coded=0;
+    coeffBits = xcodeAuxInfo(-1, filters_per_fr_best, varIndTab, frNo, createBistream=1,filtNo, ALFp);
+  }
+  else
+  {
+    coeffBits = xcodeAuxInfo(filtNo, filters_per_fr_best, varIndTab, frNo, createBistream=1,filtNo, ALFp);
+  }
+  
+  ALFp->forceCoeff0 = forceCoeff0;
+  ALFp->predMethod = 0;
+  ALFp->num_coeff = sqrFiltLength;
+  ALFp->realfiltNo=filtNo;
+  if (filters_per_fr_best <= 1)
+  {
+    ALFp->forceCoeff0 = 0;
+    ALFp->predMethod = 0;
+  }
+  
+  if (forceCoeff0==0) 
+  {
+    coeffBits += xsendAllFiltersPPPred(filterCoeffSymQuant, fl, sqrFiltLength, 
+                                       filters_per_fr_best, createBistream=1, ALFp);
+  }
+  else if (filters_per_fr_best>1)
+  {
+    coeffBits += xsendAllFiltersPPPredForce0(filterCoeffSymQuant, fl, sqrFiltLength, 
+                                             filters_per_fr_best, codedVarBins, createBistream=1, ALFp);
+  }
+
+#if MQT_ALF_NPASS
+  return (UInt)coeffBits;
+#endif
+}
+
+
+
+#if TSB_ALF_HEADER
+Void TEncAdaptiveLoopFilter::xSetCUAlfCtrlFlags_qc(UInt uiAlfCtrlDepth, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiDist, ALFParam *pAlfParam)
+#else
+Void TEncAdaptiveLoopFilter::xSetCUAlfCtrlFlags_qc(UInt uiAlfCtrlDepth, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiDist)
+#endif
+{
+  ruiDist = 0;
+#if TSB_ALF_HEADER
+  pAlfParam->num_alf_cu_flag = 0;
+#endif
+  
+  for( UInt uiCUAddr = 0; uiCUAddr < m_pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+  {
+    TComDataCU* pcCU = m_pcPic->getCU( uiCUAddr );
+#if TSB_ALF_HEADER
+    xSetCUAlfCtrlFlag_qc(pcCU, 0, 0, uiAlfCtrlDepth, pcPicOrg, pcPicDec, pcPicRest, ruiDist, pAlfParam);
+#else
+    xSetCUAlfCtrlFlag_qc(pcCU, 0, 0, uiAlfCtrlDepth, pcPicOrg, pcPicDec, pcPicRest, ruiDist);
+#endif
+  }
+}
+
+#if TSB_ALF_HEADER
+Void TEncAdaptiveLoopFilter::xSetCUAlfCtrlFlag_qc(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiAlfCtrlDepth, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiDist, ALFParam *pAlfParam)
+#else
+Void TEncAdaptiveLoopFilter::xSetCUAlfCtrlFlag_qc(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiAlfCtrlDepth, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiDist)
+#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()->getWidth() ) || ( uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() ) )
+  {
+    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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+#if TSB_ALF_HEADER
+        xSetCUAlfCtrlFlag_qc(pcCU, uiAbsPartIdx, uiDepth+1, uiAlfCtrlDepth, pcPicOrg, pcPicDec, pcPicRest, ruiDist, pAlfParam);
+#else
+      xSetCUAlfCtrlFlag_qc(pcCU, uiAbsPartIdx, uiDepth+1, uiAlfCtrlDepth, pcPicOrg, pcPicDec, pcPicRest, ruiDist);
+#endif
+    }
+    return;
+  }
+  
+  if( uiDepth > uiAlfCtrlDepth && !pcCU->isFirstAbsZorderIdxInDepth(uiAbsPartIdx, uiAlfCtrlDepth))
+  {
+    return;
+  }
+  
+  UInt uiCUAddr = pcCU->getAddr();
+  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()->getWidth() )
+    {
+      iWidth = pcCU->getSlice()->getSPS()->getWidth() - uiLPelX;
+    }
+    
+    if( uiBPelY >= pcCU->getSlice()->getSPS()->getHeight() )
+    {
+      iHeight = pcCU->getSlice()->getSPS()->getHeight() - uiTPelY;
+    }
+    
+    uiSetDepth = uiAlfCtrlDepth;
+  }
+  else
+  {
+    iWidth = pcCU->getWidth(uiAbsPartIdx);
+    iHeight = pcCU->getHeight(uiAbsPartIdx);
+    uiSetDepth = uiDepth;
+  }
+  
+  Pel* pOrg = pcPicOrg->getLumaAddr(uiCUAddr, uiAbsPartIdx);
+  Pel* pRec = pcPicDec->getLumaAddr(uiCUAddr, uiAbsPartIdx);
+  Pel* pFilt = pcPicRest->getLumaAddr(uiCUAddr, uiAbsPartIdx);
+  
+  uiRecSSD  += xCalcSSD( pOrg, pRec,  iWidth, iHeight, pcPicOrg->getStride() );
+  uiFiltSSD += xCalcSSD( pOrg, pFilt, iWidth, iHeight, pcPicOrg->getStride() );
+  
+  if (uiFiltSSD < uiRecSSD)
+  {
+    ruiDist += uiFiltSSD;
+    pcCU->setAlfCtrlFlagSubParts(1, uiAbsPartIdx, uiSetDepth);
+#if TSB_ALF_HEADER
+    pAlfParam->alf_cu_flag[pAlfParam->num_alf_cu_flag]=1;
+#endif
+    for (int i=uiTPelY ;i<=min(uiBPelY,(unsigned int)(pcPicOrg->getHeight()-1))  ;i++)
+    {
+      for (int j=uiLPelX ;j<=min(uiRPelX,(unsigned int)(pcPicOrg->getWidth()-1)) ;j++)
+      { 
+        m_maskImg[i][j]=1;
+      }
+    }
+  }
+  else
+  {
+    ruiDist += uiRecSSD;
+    pcCU->setAlfCtrlFlagSubParts(0, uiAbsPartIdx, uiSetDepth);
+#if TSB_ALF_HEADER
+    pAlfParam->alf_cu_flag[pAlfParam->num_alf_cu_flag]=0;
+#endif
+    for (int i=uiTPelY ;i<=min(uiBPelY,(unsigned int)(pcPicOrg->getHeight()-1))  ;i++)
+    {
+      for (int j=uiLPelX ;j<=min(uiRPelX,(unsigned int)(pcPicOrg->getWidth()-1)) ;j++)
+      { 
+        m_maskImg[i][j]=0;
+      }
+    }
+  }
+#if TSB_ALF_HEADER
+  pAlfParam->num_alf_cu_flag++;
+#endif
+}
+
+Void TEncAdaptiveLoopFilter::xReDesignFilterCoeff_qc(TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Bool bReadCorr)
+{
+  
+  Int tap = m_pcTempAlfParam->tap;
+  Int    LumaStride = pcPicOrg->getStride();
+  imgpel* pOrg = (imgpel*)pcPicOrg->getLumaAddr();
+  imgpel* pDec = (imgpel*)pcPicDec->getLumaAddr();
+  imgpel* pRest = (imgpel*)pcPicRest->getLumaAddr();
+  xFirstFilteringFrameLuma(pOrg, pDec, pRest, m_pcTempAlfParam, tap, LumaStride); 
+  
+}
+Void TEncAdaptiveLoopFilter::xCUAdaptiveControl_qc(TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiMinRate, UInt64& ruiMinDist, Double& rdMinCost)
+{
+#if MQT_ALF_NPASS
+  imgpel** maskImgTemp;
+
+  if(m_iALFEncodePassReduction == 2)
+  {
+    get_mem2Dpel(&maskImgTemp, m_im_height, m_im_width);
+  }
+#endif
+
+  m_pcEntropyCoder->setAlfCtrl(true);
+  
+  UInt uiBestDepth = 0;
+  
+  ALFParam cFrmAlfParam;
+  allocALFParam(&cFrmAlfParam);
+  copyALFParam(&cFrmAlfParam, m_pcBestAlfParam);
+  
+  for (UInt uiDepth = 0; uiDepth < g_uiMaxCUDepth; uiDepth++)
+  {
+    m_pcEntropyCoder->setMaxAlfCtrlDepth(uiDepth);
+    pcPicRest->copyToPicLuma(m_pcPicYuvTmp);
+    copyALFParam(m_pcTempAlfParam, &cFrmAlfParam);
+    m_pcTempAlfParam->cu_control_flag = 1;
+    
+#if MQT_ALF_NPASS
+    for (UInt uiRD = 0; uiRD <= m_iALFNumOfRedesign; uiRD++)
+#else
+    for (UInt uiRD = 0; uiRD <= ALF_NUM_OF_REDESIGN; uiRD++)
+#endif
+    {
+      if (uiRD)
+      {
+        // re-design filter coefficients
+        xReDesignFilterCoeff_qc(pcPicOrg, pcPicDec, m_pcPicYuvTmp, true); //use filtering of mine
+      }
+      
+      UInt64 uiRate, uiDist;
+      Double dCost;
+     //m_pcPicYuvTmp: filtered signal, pcPicDec: orig reconst
+#if TSB_ALF_HEADER
+      xSetCUAlfCtrlFlags_qc(uiDepth, pcPicOrg, pcPicDec, m_pcPicYuvTmp, uiDist, m_pcTempAlfParam); //set up varImg here
+#else
+      xSetCUAlfCtrlFlags_qc(uiDepth, pcPicOrg, pcPicDec, m_pcPicYuvTmp, uiDist); //set up varImg here
+#endif
+      
+      xCalcRDCost(m_pcTempAlfParam, uiRate, uiDist, dCost);
+      
+      if (dCost < rdMinCost)
+      {
+        uiBestDepth = uiDepth;
+        rdMinCost = dCost;
+        ruiMinDist = uiDist;
+        ruiMinRate = uiRate;
+        m_pcPicYuvTmp->copyToPicLuma(m_pcPicYuvBest);
+        copyALFParam(m_pcBestAlfParam, m_pcTempAlfParam);
+        //save maskImg
+        xCopyTmpAlfCtrlFlagsFrom();
+#if MQT_ALF_NPASS
+        if(m_iALFEncodePassReduction == 2)
+        {
+          ::memcpy(maskImgTemp[0], m_maskImg[0], sizeof(imgpel)*m_im_height* m_im_width);
+        }
+#endif
+      }
+    }
+  }
+  
+  if (m_pcBestAlfParam->cu_control_flag)
+  {
+#if MQT_ALF_NPASS
+    if(m_iALFEncodePassReduction == 2)
+    {
+      UInt uiDepth = uiBestDepth;
+      ::memcpy(m_maskImg[0], maskImgTemp[0], sizeof(imgpel)*m_im_height* m_im_width);
+      xCopyTmpAlfCtrlFlagsTo();
+  
+      copyALFParam(&cFrmAlfParam, m_pcBestAlfParam);
+
+      m_pcEntropyCoder->setAlfCtrl(true);
+      m_pcEntropyCoder->setMaxAlfCtrlDepth(uiDepth);
+      copyALFParam(m_pcTempAlfParam, &cFrmAlfParam);
+
+      xReDesignFilterCoeff_qc(pcPicOrg, pcPicDec, m_pcPicYuvTmp, true); //use filtering of mine
+
+      UInt64 uiRate, uiDist;
+      Double dCost;
+
+#if TSB_ALF_HEADER
+      xSetCUAlfCtrlFlags_qc(uiDepth, pcPicOrg, pcPicDec, m_pcPicYuvTmp, uiDist, m_pcTempAlfParam); //set up varImg here
+#else
+      xSetCUAlfCtrlFlags_qc(uiDepth, pcPicOrg, pcPicDec, m_pcPicYuvTmp, uiDist); //set up varImg here
+#endif
+
+      xCalcRDCost(m_pcTempAlfParam, uiRate, uiDist, dCost);
+
+      if (dCost < rdMinCost)
+      {
+        rdMinCost = dCost;
+        ruiMinDist = uiDist;
+        ruiMinRate = uiRate;
+        m_pcPicYuvTmp->copyToPicLuma(m_pcPicYuvBest);
+        copyALFParam(m_pcBestAlfParam, m_pcTempAlfParam);
+        xCopyTmpAlfCtrlFlagsFrom();
+      }
+    }
+#endif
+
+    m_pcEntropyCoder->setAlfCtrl(true);
+    m_pcEntropyCoder->setMaxAlfCtrlDepth(uiBestDepth);
+    xCopyTmpAlfCtrlFlagsTo();
+    m_pcPicYuvBest->copyToPicLuma(pcPicRest);//copy m_pcPicYuvBest to pcPicRest
+    xCopyDecToRestCUs(pcPicDec, pcPicRest); //pcPicRest = pcPicDec
+  }
+  else
+  {
+    m_pcEntropyCoder->setAlfCtrl(false);
+    m_pcEntropyCoder->setMaxAlfCtrlDepth(0);
+  }
+  freeALFParam(&cFrmAlfParam);
+
+#if MQT_ALF_NPASS
+  if(m_iALFEncodePassReduction == 2)
+  {
+    free_mem2Dpel(maskImgTemp);
+  }
+#endif
+}
+
+
+Void TEncAdaptiveLoopFilter::xFilterTapDecision_qc(TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiMinRate, UInt64& ruiMinDist, Double& rdMinCost)
+{
+#if MQT_ALF_NPASS
+  if(m_iALFEncodePassReduction)
+  {
+    return;  // filter tap has been decided in xEncALFLuma_qc
+  }
+#endif
+
+  // restriction for non-referenced B-slice
+  if (m_eSliceType == B_SLICE && m_iPicNalReferenceIdc == 0)
+  {
+    return;
+  }
+  
+  UInt64 uiRate, uiDist;
+  Double dCost;
+  
+  if (m_pcBestAlfParam->cu_control_flag)
+  {
+    xCopyTmpAlfCtrlFlagsFrom();
+  }
+  
+  Bool bChanged = false;
+  for (Int iTap = ALF_MIN_NUM_TAP; iTap <= ALF_MAX_NUM_TAP; iTap += 2)
+  {
+    copyALFParam(m_pcTempAlfParam, m_pcBestAlfParam);
+    m_pcTempAlfParam->tap = iTap;
+#if TI_ALF_MAX_VSIZE_7
+    m_pcTempAlfParam->tapV = TComAdaptiveLoopFilter::ALFTapHToTapV(m_pcTempAlfParam->tap);
+    m_pcTempAlfParam->num_coeff = TComAdaptiveLoopFilter::ALFTapHToNumCoeff(m_pcTempAlfParam->tap); 
+#else
+    m_pcTempAlfParam->num_coeff = (Int)(iTap*iTap/4) + 2; 
+#endif
+    
+    if (m_pcTempAlfParam->cu_control_flag)
+    {
+      xReDesignFilterCoeff_qc(pcPicOrg, pcPicDec, m_pcPicYuvTmp, false);
+#if TSB_ALF_HEADER
+      xSetCUAlfCtrlFlags_qc(m_pcEntropyCoder->getMaxAlfCtrlDepth(), pcPicOrg, pcPicDec, m_pcPicYuvTmp, uiDist, m_pcTempAlfParam);
+#else
+      xSetCUAlfCtrlFlags_qc(m_pcEntropyCoder->getMaxAlfCtrlDepth(), pcPicOrg, pcPicDec, m_pcPicYuvTmp, uiDist);
+#endif
+      xCalcRDCost(m_pcTempAlfParam, uiRate, uiDist, dCost);
+    }
+
+    else
+    {
+      Int    Height = pcPicOrg->getHeight();
+      Int    Width = pcPicOrg->getWidth();
+      for (Int i=0; i<Height; i++)
+      {
+        for (Int j=0; j<Width; j++)
+        {
+          m_maskImg[i][j] = 1;
+        }
+      }
+      xReDesignFilterCoeff_qc(pcPicOrg, pcPicDec, m_pcPicYuvTmp, false);
+
+      xCalcRDCost(pcPicOrg, m_pcPicYuvTmp, m_pcTempAlfParam, uiRate, uiDist, dCost);
+    }
+
+    if (dCost < rdMinCost)
+    {
+      rdMinCost = dCost;
+      ruiMinDist = uiDist;
+      ruiMinRate = uiRate;
+      m_pcPicYuvTmp->copyToPicLuma(m_pcPicYuvBest);
+      copyALFParam(m_pcBestAlfParam, m_pcTempAlfParam);
+      bChanged = true;
+      if (m_pcTempAlfParam->cu_control_flag)
+      {
+        xCopyTmpAlfCtrlFlagsFrom();
+      }
+    }
+  }
+  
+  if (m_pcBestAlfParam->cu_control_flag)
+  {
+    xCopyTmpAlfCtrlFlagsTo();
+    if (bChanged)
+    {
+      m_pcPicYuvBest->copyToPicLuma(pcPicRest);
+      xCopyDecToRestCUs(pcPicDec, pcPicRest);
+    }
+  }
+  else if (m_pcBestAlfParam->tap > ALF_MIN_NUM_TAP)
+  {
+    m_pcPicYuvBest->copyToPicLuma(pcPicRest);
+  }
+  
+  copyALFParam(m_pcTempAlfParam, m_pcBestAlfParam);
+}
+
+
+#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[MAX_SQR_FILT_LENGTH][MAX_SQR_FILT_LENGTH], int noEq)
+{ 
+  int 
+  i, j, k;     /* Looping Variables */
+  double 
+  scale;       /* scaling factor for each row */
+  double 
+  invDiag[MAX_SQR_FILT_LENGTH];  /* 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[MAX_SQR_FILT_LENGTH][MAX_SQR_FILT_LENGTH], 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[MAX_SQR_FILT_LENGTH][MAX_SQR_FILT_LENGTH], double z[MAX_SQR_FILT_LENGTH], 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)
+{ 
+  double aux[MAX_SQR_FILT_LENGTH];     /* Auxiliary vector */
+  double U[MAX_SQR_FILT_LENGTH][MAX_SQR_FILT_LENGTH];    /* 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);
+    /* Solve  U'*aux = rhs for aux */  
+    gnsTransposeBacksubstitution(U, rhs, aux, noEq);   
+    
+    /* Solve U*x = aux for x */
+    gnsBacksubstitution(U, aux, noEq, x);
+  }  
+  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[MAX_SQR_FILT_LENGTH];
+  
+  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);
+}
+
+
+
+double TEncAdaptiveLoopFilter::findFilterGroupingError(double ***EGlobalSeq, double **yGlobalSeq, double *pixAccGlobalSeq, int intervalBest[NO_VAR_BINS][2], int sqrFiltLength, int filters_per_fr)
+{
+  double error;
+  
+  // find best filters for each frame group
+  error = 0;
+  error += mergeFiltersGreedy(yGlobalSeq, EGlobalSeq, pixAccGlobalSeq, intervalBest, sqrFiltLength, filters_per_fr);
+  
+  return(error);
+}
+
+
+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, int bit_depth)
+{
+  double error;
+  
+  int factor = (1<<(bit_depth-1)), 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;
+    }
+  }
+  
+  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, int bit_depth, 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, bit_depth);
+    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);
+}
+
+#if MQT_ALF_NPASS
+Void TEncAdaptiveLoopFilter::setALFEncodingParam(TComPic *pcPic)
+{
+  if(m_iALFEncodePassReduction)
+  {
+    m_iALFNumOfRedesign = 0;
+    m_iCurrentPOC = m_pcPic->getPOC();
+
+    if((m_eSliceType == I_SLICE) || (m_iGOPSize==8 && (m_iCurrentPOC % 4 == 0)))
+    {
+      m_iUsePreviousFilter = 0;
+    }
+    else
+    {
+      m_iUsePreviousFilter = 1;
+    }
+  }
+  else
+  {
+    m_iALFNumOfRedesign = ALF_NUM_OF_REDESIGN;
+  }
+  m_iDesignCurrentFilter = 1;
+
+}
+
+Void TEncAdaptiveLoopFilter::xcalcPredFilterCoeffPrev(Int filtNo)
+{
+  int varInd, i;
+
+  for(varInd=0; varInd<NO_VAR_BINS; ++varInd)
+  {
+    for(i = 0; i < MAX_SQR_FILT_LENGTH; i++)
+    {
+      m_filterCoeffPrevSelected[varInd][i]=m_aiFilterCoeffSaved[m_iFilterIdx][varInd][i];
+    }
+  }
+}
+
+Void TEncAdaptiveLoopFilter::setFilterIdx(Int index)
+{
+  if (m_iGOPSize == 8)
+  {
+    if ((m_iCurrentPOC % m_iGOPSize) == 0)
+    {
+      Int FiltTable[2] = {0, m_iGOPSize};
+      m_iFilterIdx = FiltTable[index]; 
+    }
+    if ((m_iCurrentPOC % m_iGOPSize) == 4)
+    {
+      Int FiltTable[2] = {0, m_iGOPSize};
+      m_iFilterIdx = FiltTable[index]; 
+    }
+    if ((m_iCurrentPOC % m_iGOPSize) == 2)
+    {
+      Int FiltTable[2] = {0, 4};
+      m_iFilterIdx = FiltTable[index]; 
+    }
+    if ((m_iCurrentPOC % m_iGOPSize) == 6)
+    {
+      Int FiltTable[2] = {4, m_iGOPSize};
+      m_iFilterIdx = FiltTable[index]; 
+    }
+    if ((m_iCurrentPOC % m_iGOPSize) == 1)
+    {
+      Int FiltTable[2] = {0, 2};
+      m_iFilterIdx = FiltTable[index]; 
+    }
+    if ((m_iCurrentPOC % m_iGOPSize) == 3)
+    {
+      Int FiltTable[2] = {2, 4};
+      m_iFilterIdx = FiltTable[index]; 
+    }
+    if ((m_iCurrentPOC % m_iGOPSize) == 5)
+    {
+      Int FiltTable[2] = {4, 6};
+      m_iFilterIdx = FiltTable[index]; 
+    }
+    if ((m_iCurrentPOC % m_iGOPSize) == 7)
+    {
+      Int FiltTable[2] = {6, m_iGOPSize};
+      m_iFilterIdx = FiltTable[index]; 
+    }
+  }
+  else
+  {
+    Int FiltTable[2] = {0, m_iGOPSize};
+    m_iFilterIdx = FiltTable[index]; 
+  }
+}
+
+Void TEncAdaptiveLoopFilter::setInitialMask(TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec)
+{
+  Int Height = pcPicOrg->getHeight();
+  Int Width = pcPicOrg->getWidth();
+  Int LumaStride = pcPicOrg->getStride();
+  imgpel* pDec = (imgpel*)pcPicDec->getLumaAddr();
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(!m_bUseNonCrossALF)
+    calcVar(0, 0, m_varImg, pDec, 9/2, VAR_SIZE, Height, Width, LumaStride);
+  else
+    calcVarforSlices(m_varImg, pDec, 9/2, VAR_SIZE, LumaStride);
+#else
+  calcVar(m_varImg, pDec, 9/2, VAR_SIZE, Height, Width, LumaStride);
+#endif
+
+  if(!m_iALFEncodePassReduction || !m_iUsePreviousFilter)
+  {
+    for(Int y=0; y<Height; y++)
+    {
+      for(Int x=0; x<Width; x++)
+      {
+        m_maskImg[y][x] = 1;
+      }
+    }
+  }
+  else
+  {
+    Int uiBestDepth=0;
+    UInt64 uiRate, uiDist, uiMinRate, uiMinDist;
+    Double dCost, dMinCost = MAX_DOUBLE;
+    //imgpel* pOrg = (imgpel*)pcPicOrg->getLumaAddr();
+    imgpel* pRest = (imgpel*)m_pcPicYuvTmp->getLumaAddr();
+
+    Int iTap = 9;
+    Int filtNo = 0;
+    m_pcTempAlfParam->cu_control_flag = 0;
+    m_pcTempAlfParam->tap = iTap;
+#if TI_ALF_MAX_VSIZE_7
+    m_pcTempAlfParam->tapV      = TComAdaptiveLoopFilter::ALFTapHToTapV(iTap);
+    m_pcTempAlfParam->num_coeff = TComAdaptiveLoopFilter::ALFTapHToNumCoeff(iTap);
+#else
+    m_pcTempAlfParam->num_coeff = iTap*iTap/4 + 2;
+#endif
+
+    for (Int index=0; index<2; index++)
+    {
+      setFilterIdx(index);
+      xcalcPredFilterCoeffPrev(filtNo);
+#if MTK_NONCROSS_INLOOP_FILTER
+      if(!m_bUseNonCrossALF)
+        xfilterFrame_en(0, 0, Height, Width, pDec, pRest, filtNo, LumaStride);
+      else
+        xfilterSlices_en(pDec, pRest, filtNo, LumaStride);
+#else
+      xfilterFrame_en(pDec, pRest, filtNo, LumaStride);
+#endif
+      xCalcRDCost(pcPicOrg, m_pcPicYuvTmp, NULL, uiRate, uiDist, dCost);
+      if (dCost < dMinCost)
+      {
+        dMinCost  = dCost;
+        uiMinDist = uiDist;
+        uiMinRate = uiRate;
+        m_pcPicYuvTmp->copyToPicLuma(m_pcPicYuvBest);
+        copyALFParam(m_pcBestAlfParam, m_pcTempAlfParam);
+      }
+    }
+    m_pcPicYuvBest->copyToPicLuma(m_pcPicYuvTmp);
+
+    m_pcEntropyCoder->setAlfCtrl(true);
+    Int maxDepth = g_uiMaxCUDepth;
+    if (pcPicOrg->getWidth() < 1000) maxDepth = 2;
+    for (UInt uiDepth = 0; uiDepth < maxDepth; uiDepth++)
+    {
+      m_pcEntropyCoder->setMaxAlfCtrlDepth(uiDepth);
+      copyALFParam(m_pcTempAlfParam, m_pcBestAlfParam);
+      m_pcTempAlfParam->cu_control_flag = 1;
+
+#if TSB_ALF_HEADER
+      xSetCUAlfCtrlFlags_qc(uiDepth, pcPicOrg, pcPicDec, m_pcPicYuvTmp, uiDist, m_pcTempAlfParam); //set up varImg here
+#else
+      xSetCUAlfCtrlFlags_qc(uiDepth, pcPicOrg, pcPicDec, m_pcPicYuvTmp, uiDist); //set up varImg here
+#endif
+      m_pcEntropyCoder->resetEntropy();
+      m_pcEntropyCoder->resetBits();
+      xEncodeCUAlfCtrlFlags();
+      uiRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+      dCost  = (Double)(uiRate) * m_dLambdaLuma + (Double)(uiDist);
+
+      if (dCost < dMinCost)
+      {
+        uiBestDepth = uiDepth;
+        dMinCost    = dCost;
+        uiMinDist   = uiDist;
+        uiMinRate   = uiRate;
+        copyALFParam(m_pcBestAlfParam, m_pcTempAlfParam);
+        //save maskImg
+        xCopyTmpAlfCtrlFlagsFrom();
+      }
+    }
+
+    copyALFParam(m_pcTempAlfParam, m_pcBestAlfParam);
+    m_iDesignCurrentFilter = 0; // design filter for subsequent slices
+    xReDesignFilterCoeff_qc(pcPicOrg, pcPicDec, m_pcPicYuvTmp, true);
+    m_iDesignCurrentFilter = 1;
+
+    if (m_pcBestAlfParam->cu_control_flag)
+    {
+      m_pcEntropyCoder->setAlfCtrl(true);
+      m_pcEntropyCoder->setMaxAlfCtrlDepth(uiBestDepth);
+      xCopyTmpAlfCtrlFlagsTo();
+    }
+    else
+    {
+      m_pcEntropyCoder->setAlfCtrl(false);
+      m_pcEntropyCoder->setMaxAlfCtrlDepth(0);
+      for(Int y=0; y<Height; y++)
+      {
+        for(Int x=0; x<Width; x++)
+        {
+          m_maskImg[y][x] = 1;
+        }
+      }
+    }
+  }
+}
+
+#if MQT_BA_RA
+Void  TEncAdaptiveLoopFilter::xFirstEstimateFilteringFrameLumaAllTap(imgpel* ImgOrg, imgpel* ImgDec, Int Stride, 
+                                                                     ALFParam* pcAlfSaved,
+                                                                     Int* aiVarIndTabBest,
+                                                                     Int** ppiBestCoeffSet,
+                                                                     Int& ibestfiltNo,
+                                                                     Int& ibestfilters_per_fr,
+                                                                     Double**  ppdBesty,
+                                                                     Double*** pppdBestE,
+                                                                     Double*   pdBestpixAcc,
+                                                                     UInt64& ruiRate,
+                                                                     Int64& riDist,
+                                                                     Double& rdCost
+                                                                     )
+#else
+Void   TEncAdaptiveLoopFilter::xFirstFilteringFrameLumaAllTap(imgpel* ImgOrg, imgpel* ImgDec, imgpel* ImgRest, Int Stride)
+#endif
+{
+#if !MQT_BA_RA
+  static Bool bFirst = true;
+  static Int  aiVarIndTabBest[NO_VAR_BINS];
+#endif
+  static Double **ySym, ***ESym;
+#if !MQT_BA_RA
+  static Int**  ppiBestCoeffSet;
+
+  if(bFirst)
+  {
+    initMatrix_int(&ppiBestCoeffSet, NO_VAR_BINS, MAX_SQR_FILT_LENGTH);
+    bFirst = false;
+  }
+#endif
+
+  Int    lambda_val = ((Int) m_dLambdaLuma) * (1<<(2*g_uiBitIncrement));
+#if MQT_BA_RA
+  Int    filtNo, filters_per_fr;
+#else
+  Int    filtNo, ibestfiltNo=0, filters_per_fr, ibestfilters_per_fr=0;
+#endif
+  Int64  iEstimatedDist;
+  UInt64 uiRate;
+  Double dEstimatedCost, dEstimatedMinCost = MAX_DOUBLE;;
+  Bool   bMatrixBaseReady  = false;
+  m_iMatrixBaseFiltNo = 0; 
+#if MQT_BA_RA
+  m_pcTempAlfParam->alf_flag = 1;
+  m_pcTempAlfParam->cu_control_flag = 0;
+  m_pcTempAlfParam->chroma_idc = 0;
+#endif
+  for(Int iTap = ALF_MAX_NUM_TAP; iTap>=ALF_MIN_NUM_TAP; iTap -= 2)
+  {
+    m_pcTempAlfParam->tap = iTap;
+#if TI_ALF_MAX_VSIZE_7
+    m_pcTempAlfParam->tapV      = TComAdaptiveLoopFilter::ALFTapHToTapV(iTap);
+    m_pcTempAlfParam->num_coeff = TComAdaptiveLoopFilter::ALFTapHToNumCoeff(iTap);
+#else
+    m_pcTempAlfParam->num_coeff = iTap*iTap/4 + 2;
+#endif
+    if (iTap==9)
+    {
+      filtNo = 0;
+    }
+    else if (iTap==7)
+    {
+      filtNo = 1;
+    }
+    else
+    {
+      filtNo = 2;
+    }
+
+    ESym     = m_EGlobalSym     [filtNo];
+    ySym     = m_yGlobalSym     [filtNo];
+
+    if( bMatrixBaseReady )
+    {
+      xretriveBlockMatrix(m_pcTempAlfParam->num_coeff, m_iTapPosTabIn9x9Sym[filtNo], 
+                          m_EGlobalSym[m_iMatrixBaseFiltNo], ESym, 
+                          m_yGlobalSym[m_iMatrixBaseFiltNo], ySym);
+
+    }
+    else
+#if MTK_NONCROSS_INLOOP_FILTER
+    {
+      if(!m_bUseNonCrossALF)
+        xstoreInBlockMatrix(0, 0, m_im_height, m_im_width, true, true, ImgOrg, ImgDec, iTap, Stride);
+      else
+        xstoreInBlockMatrixforSlices(ImgOrg, ImgDec, iTap, Stride);
+    }
+#else
+    xstoreInBlockMatrix(ImgOrg, ImgDec, iTap, Stride);
+#endif
+    if(filtNo == m_iMatrixBaseFiltNo)
+    {
+      bMatrixBaseReady = true;
+    }
+
+    xfindBestFilterVarPred(ySym, ESym, m_pixAcc, m_filterCoeffSym, m_filterCoeffSymQuant, filtNo, &filters_per_fr, 
+                           m_varIndTab, NULL, m_varImg, m_maskImg, NULL, lambda_val);
+
+    uiRate         = xcodeFiltCoeff(m_filterCoeffSymQuant, filtNo, m_varIndTab, filters_per_fr,0, m_pcTempAlfParam);
+    iEstimatedDist = xEstimateFiltDist(filters_per_fr, m_varIndTab, ESym, ySym, m_filterCoeffSym, m_pcTempAlfParam->num_coeff);
+    dEstimatedCost = (Double)(uiRate) * m_dLambdaLuma + (Double)(iEstimatedDist);
+
+    if(dEstimatedCost < dEstimatedMinCost)
+    {
+      dEstimatedMinCost   = dEstimatedCost;
+      ibestfiltNo         = filtNo;
+      ibestfilters_per_fr = filters_per_fr;
+#if MQT_BA_RA
+      ruiRate = uiRate;
+      riDist  = iEstimatedDist;
+      rdCost  = dEstimatedMinCost;
+
+      copyALFParam(pcAlfSaved, m_pcTempAlfParam); 
+#else
+      copyALFParam(m_pcBestAlfParam, m_pcTempAlfParam); 
+#endif
+      ::memcpy(aiVarIndTabBest, m_varIndTab, sizeof(Int)*NO_VAR_BINS);
+      for(Int i=0; i< ibestfilters_per_fr; i++ )
+      {
+        ::memcpy( ppiBestCoeffSet[i], m_filterCoeffSym[i], sizeof(Int) * m_pcTempAlfParam->num_coeff);
+      }
+    }
+  }
+
+  filtNo         = ibestfiltNo;
+  filters_per_fr = ibestfilters_per_fr;
+  ::memcpy(m_varIndTab, aiVarIndTabBest, sizeof(Int)*NO_VAR_BINS);
+  for(Int i=0; i< filters_per_fr; i++ )
+  {
+#if MQT_BA_RA
+    ::memcpy(m_filterCoeffSym[i], ppiBestCoeffSet[i], sizeof(Int) * pcAlfSaved->num_coeff);
+#else
+    ::memcpy(m_filterCoeffSym[i], ppiBestCoeffSet[i], sizeof(Int) * m_pcTempAlfParam->num_coeff);
+#endif
+  }
+
+  xcalcPredFilterCoeff(filtNo);
+
+#if MQT_BA_RA
+
+
+  ::memset( pdBestpixAcc, 0,sizeof(double)*NO_VAR_BINS);
+  for (Int varInd=0; varInd<NO_VAR_BINS; varInd++)
+  {
+    ::memset(ppdBesty[varInd],0,sizeof(double)*MAX_SQR_FILT_LENGTH);
+    for (Int k=0; k< pcAlfSaved->num_coeff; k++)
+    {
+      ::memset(pppdBestE[varInd][k],0,sizeof(double)*MAX_SQR_FILT_LENGTH);
+    }
+  }
+  ESym     = m_EGlobalSym     [filtNo];
+  ySym     = m_yGlobalSym     [filtNo];
+
+  ::memcpy( pdBestpixAcc, m_pixAcc ,sizeof(double)*NO_VAR_BINS);
+  for (Int varInd=0; varInd<NO_VAR_BINS; varInd++)
+  {
+    ::memcpy(ppdBesty[varInd],ySym[varInd],sizeof(double)*MAX_SQR_FILT_LENGTH);
+    for (Int k=0; k< pcAlfSaved->num_coeff; k++)
+    {
+      ::memcpy(pppdBestE[varInd][k],ESym[varInd][k],sizeof(double)*MAX_SQR_FILT_LENGTH);
+    }
+  }
+
+
+#else
+
+  filtNo         = ibestfiltNo;
+  filters_per_fr = ibestfilters_per_fr;
+  copyALFParam(m_pcTempAlfParam, m_pcBestAlfParam);
+  ::memcpy(m_varIndTab, aiVarIndTabBest, sizeof(Int)*NO_VAR_BINS);
+  for(Int i=0; i< filters_per_fr; i++ )
+  {
+    ::memcpy(m_filterCoeffSym[i], ppiBestCoeffSet[i], sizeof(Int) * m_pcTempAlfParam->num_coeff);
+  }
+
+  xcalcPredFilterCoeff(filtNo);
+#if MTK_NONCROSS_INLOOP_FILTER
+  if(!m_bUseNonCrossALF)
+    xfilterFrame_en(0, 0, m_im_height, m_im_width, ImgDec, ImgRest, filtNo, Stride);
+  else
+    xfilterSlices_en(ImgDec, ImgRest, filtNo, Stride);
+#else
+  xfilterFrame_en(ImgDec, ImgRest, filtNo, Stride);
+#endif
+
+#endif
+}
+
+Void TEncAdaptiveLoopFilter::xretriveBlockMatrix(Int iNumTaps, 
+                                                 Int* piTapPosInMaxFilter, 
+                                                 Double*** pppdEBase, Double*** pppdETarget, 
+                                                 Double**  ppdyBase,  Double** ppdyTarget )
+{
+  Int varInd;
+  Int i, j, r, c;
+
+  Double** ppdSrcE;
+  Double** ppdDstE;
+  Double*  pdSrcy;
+  Double*  pdDsty;
+
+  for (varInd=0; varInd< NO_VAR_BINS; varInd++)
+  {
+    ppdSrcE = pppdEBase  [varInd];
+    ppdDstE = pppdETarget[varInd];
+    pdSrcy  = ppdyBase   [varInd];
+    pdDsty  = ppdyTarget [varInd];
+
+    for(j=0; j< iNumTaps; j++)
+    {
+      r = piTapPosInMaxFilter[j];
+
+      for(i=j; i< iNumTaps; i++)
+      {
+        c = piTapPosInMaxFilter[i];
+
+        //auto-correlation retrieval
+        ppdDstE[j][i] = ppdSrcE[r][c];
+
+      }
+
+      //cross-correlation retrieval
+      pdDsty[j] = pdSrcy[r];
+
+    }
+
+    //symmetric copy
+    for(j=1; j< iNumTaps; j++)
+      for(i=0; i< j; i++)
+        ppdDstE[j][i] = ppdDstE[i][j];
+
+  }
+
+}
+
+Int64 TEncAdaptiveLoopFilter::xFastFiltDistEstimation(Double** ppdE, Double* pdy, Int* piCoeff, Int iFiltLength)
+{
+  //static memory
+  static Bool     bFirst = true;
+  static Double*  pdcoeff;
+  if(bFirst)
+  {
+    pdcoeff= new Double[MAX_SQR_FILT_LENGTH];        
+    bFirst= false;
+  }
+
+  //variable
+  Int    i,j;
+  Int64  iDist;
+  Double dDist, dsum;
+
+
+  for(i=0; i< iFiltLength; i++)
+    pdcoeff[i]= (Double)piCoeff[i] / (Double)(1<< (NUM_BITS - 1) );
+
+
+  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;
+
+}
+
+Int64 TEncAdaptiveLoopFilter::xEstimateFiltDist(Int filters_per_fr, Int* VarIndTab, 
+                                                Double*** pppdE, Double** ppdy, 
+                                                Int** ppiCoeffSet, Int iFiltLength)
+
+{
+  Int64     iDist;
+  Double**  ppdDstE;
+  Double**  ppdSrcE;
+  Double*   pdDsty;  
+  Double*   pdSrcy;
+  Int       f, j, i, varInd;
+  Int*      piCoeff;
+
+  //clean m_E_merged & m_y_merged
+  for(f=0; f< filters_per_fr; f++)
+  {
+    for(j =0; j < iFiltLength; j++)
+    {
+      //clean m_E_merged one line
+      for(i=0; i < iFiltLength; i++)
+        m_E_merged[f][j][i] = 0;
+
+      //clean m_y_merged
+      m_y_merged[f][j] = 0;
+    }
+  }
+
+
+  //merge correlation values
+  for (varInd=0; varInd< NO_VAR_BINS; varInd++)
+  {
+    ppdSrcE = pppdE[varInd];
+    ppdDstE = m_E_merged[ VarIndTab[varInd] ];
+
+    pdSrcy  = ppdy[varInd];
+    pdDsty  = m_y_merged[ VarIndTab[varInd] ];
+
+    for(j=0; j< iFiltLength; j++)
+    {
+      for(i=0; i< iFiltLength; i++)
+        ppdDstE[j][i] += ppdSrcE[j][i];
+
+      pdDsty[j] += pdSrcy[j];
+    }
+  }
+
+  //estimate distortion reduction by using FFDE (JCTVC-C143)
+  iDist = 0;
+  for(f=0; f< filters_per_fr; f++)
+  {
+    piCoeff = ppiCoeffSet[f];
+    ppdDstE = m_E_merged [f];
+    pdDsty  = m_y_merged [f];
+
+    iDist += xFastFiltDistEstimation(ppdDstE, pdDsty, piCoeff, iFiltLength);
+  }
+
+
+  return iDist;
+
+}
+#endif
+
+#if MTK_NONCROSS_INLOOP_FILTER
+
+Void TEncAdaptiveLoopFilter::calcVarforSlices(imgpel **varmap, imgpel *imgY_Dec, Int pad_size, Int fl, Int img_stride)
+{
+#if MQT_BA_RA
+  if(m_uiVarGenMethod == ALF_RA)
+  {
+    return;
+  }
+#endif
+
+  Pel* pPicSrc   = (Pel *)imgY_Dec;
+  Pel* pPicSlice = m_pcSliceYuvTmp->getLumaAddr();
+
+  for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    CAlfSlice* pSlice = &(m_pSlice[s]);
+
+    pSlice->copySliceLuma(pPicSlice, pPicSrc, img_stride);
+    pSlice->extendSliceBorderLuma(pPicSlice, img_stride, (UInt)EXTEND_NUM_PEL);
+    calcVarforOneSlice(pSlice, varmap, (imgpel*)pPicSlice, pad_size, fl, img_stride);
+  }
+}
+
+
+
+Void TEncAdaptiveLoopFilter::xfilterSlices_en(imgpel* ImgDec, imgpel* ImgRest,int filtNo, int iStride)
+{
+  Pel* pPicSrc   = (Pel *)ImgDec;
+  Pel* pPicSlice = m_pcSliceYuvTmp->getLumaAddr();
+
+  for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    CAlfSlice* pSlice = &(m_pSlice[s]);
+
+    pSlice->copySliceLuma(pPicSlice, pPicSrc, iStride);
+    pSlice->extendSliceBorderLuma(pPicSlice, iStride, EXTEND_NUM_PEL);
+
+    xfilterOneSlice_en(pSlice, (imgpel*)pPicSlice, ImgRest, filtNo, iStride);
+  }
+}
+
+
+Void TEncAdaptiveLoopFilter::xfilterOneSlice_en(CAlfSlice* pSlice, imgpel* ImgDec, imgpel* ImgRest,int filtNo, int iStride)
+{
+  UInt uiNumLCUs = pSlice->getNumLCUs();
+
+  Int iHeight, iWidth;
+  Int ypos, xpos;
+
+  for(UInt i=0; i< uiNumLCUs; i++)
+  {
+    CAlfCU* pcAlfCU = &((*pSlice)[i]);
+
+    ypos    = pcAlfCU->getCU()->getCUPelY();
+    xpos    = pcAlfCU->getCU()->getCUPelX();
+    iHeight = pcAlfCU->getHeight();
+    iWidth  = pcAlfCU->getWidth();
+
+    xfilterFrame_en(ypos, xpos, iHeight, iWidth, ImgDec, ImgRest, filtNo, iStride);
+  }
+}
+
+
+
+Void   TEncAdaptiveLoopFilter::xstoreInBlockMatrixforSlices(imgpel* ImgOrg, imgpel* ImgDec, Int tap, Int iStride)
+{
+  Pel* pPicSrc   = (Pel *)ImgDec;
+  Pel* pPicSlice = m_pcSliceYuvTmp->getLumaAddr();
+
+  for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    CAlfSlice* pSlice = &(m_pSlice[s]);
+    pSlice->copySliceLuma(pPicSlice, pPicSrc, iStride);
+    pSlice->extendSliceBorderLuma(pPicSlice, iStride, (UInt)EXTEND_NUM_PEL);
+    xstoreInBlockMatrixforOneSlice(pSlice, ImgOrg, (imgpel*)pPicSlice, tap, iStride, (s==0), (s== m_uiNumSlicesInPic-1));
+  }
+}
+
+Void   TEncAdaptiveLoopFilter::xstoreInBlockMatrixforOneSlice(CAlfSlice* pSlice, 
+                                                              imgpel* ImgOrg, imgpel* ImgDec, 
+                                                              Int tap, Int iStride, 
+                                                              Bool bFirstSlice, 
+                                                              Bool bLastSlice
+                                                              )
+{
+
+
+  UInt uiNumLCUs = pSlice->getNumLCUs();
+
+  Int iHeight, iWidth;
+  Int ypos, xpos;
+  Bool bFirstLCU, bLastLCU;
+
+  for(UInt i=0; i< uiNumLCUs; i++)
+  {
+    bFirstLCU = (i==0);
+    bLastLCU  = (i== uiNumLCUs -1);
+
+    CAlfCU* pcAlfCU = &((*pSlice)[i]);
+    ypos    = pcAlfCU->getCU()->getCUPelY();
+    xpos    = pcAlfCU->getCU()->getCUPelX();
+    iHeight = pcAlfCU->getHeight();
+    iWidth  = pcAlfCU->getWidth();
+
+    xstoreInBlockMatrix(ypos, xpos, iHeight, iWidth, 
+      (bFirstSlice && bFirstLCU),(bLastSlice && bLastLCU),
+      ImgOrg, ImgDec,tap, iStride);
+  }
+}
+
+
+
+Void TEncAdaptiveLoopFilter::xCalcCorrelationFuncforChromaSlices(Int ComponentID, Pel* pOrg, Pel* pCmp, Int iTap, Int iOrgStride, Int iCmpStride)
+{
+
+  assert(iOrgStride == iCmpStride);
+
+  Pel* pPicSrc   = pCmp;
+  Pel* pPicSlice = (ComponentID == ALF_Cb)?(m_pcSliceYuvTmp->getCbAddr()):(m_pcSliceYuvTmp->getCrAddr());
+
+  for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    CAlfSlice* pSlice = &(m_pSlice[s]);
+
+    pSlice->copySliceChroma(pPicSlice, pPicSrc, iCmpStride);
+    pSlice->extendSliceBorderChroma(pPicSlice, iCmpStride, (UInt)EXTEND_NUM_PEL_C);
+
+    xCalcCorrelationFuncforChromaOneSlice(pSlice, pOrg, pPicSlice, iTap, iCmpStride,(s==m_uiNumSlicesInPic-1));
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xCalcCorrelationFuncforChromaOneSlice(CAlfSlice* pSlice, Pel* pOrg, Pel* pCmp, Int iTap, Int iStride, Bool bLastSlice)
+{
+  UInt uiNumLCUs = pSlice->getNumLCUs();
+
+  Int iHeight, iWidth;
+  Int ypos, xpos;
+  Bool bLastLCU;
+
+  for(UInt i=0; i< uiNumLCUs; i++)
+  {
+    bLastLCU  = (i== uiNumLCUs -1);
+
+    CAlfCU* pcAlfCU = &((*pSlice)[i]);
+    ypos    = ( pcAlfCU->getCU()->getCUPelY() >> 1 );
+    xpos    = ( pcAlfCU->getCU()->getCUPelX() >> 1 );
+    iHeight = (Int)( pcAlfCU->getHeight() >> 1);
+    iWidth  = (Int)( pcAlfCU->getWidth() >> 1);
+
+    xCalcCorrelationFunc(ypos, xpos, pOrg, pCmp, iTap, iWidth, iHeight, iStride, iStride, (bLastSlice && bLastLCU ) );
+  }
+}
+
+Void TEncAdaptiveLoopFilter::xFrameChromaforSlices(Int ComponentID, TComPicYuv* pcPicDecYuv, TComPicYuv* pcPicRestYuv, Int *qh, Int iTap )
+{
+  Pel* pPicDec   = (ComponentID == ALF_Cb)?(    pcPicDecYuv->getCbAddr()):(    pcPicDecYuv->getCrAddr());
+  //  Pel* pPicRest  = (ComponentID == ALF_Cb)?(   pcPicRestYuv->getCbAddr()):(   pcPicRestYuv->getCrAddr());
+  Pel* pPicSlice = (ComponentID == ALF_Cb)?(m_pcSliceYuvTmp->getCbAddr()):(m_pcSliceYuvTmp->getCrAddr());
+
+  Int iStride = pcPicDecYuv->getCStride();
+
+  assert(iStride == pcPicRestYuv->getCStride());
+
+  for(UInt s=0; s< m_uiNumSlicesInPic; s++)
+  {
+    CAlfSlice* pSlice = &(m_pSlice[s]);
+
+    pSlice->copySliceChroma(pPicSlice, pPicDec, iStride);
+    pSlice->extendSliceBorderChroma(pPicSlice, iStride, (UInt)EXTEND_NUM_PEL_C);
+
+    xFrameChromaforOneSlice(pSlice, ComponentID, m_pcSliceYuvTmp, pcPicRestYuv, qh, iTap);
+  }
+}
+
+#endif
+
+
+#if MTK_SAO
+inline Double xRoundIbdi2(Double x)
+{
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(g_uiBitIncrement-1)))/(1<<g_uiBitIncrement)) : ((Int)(((Int)(x)-(1<<(g_uiBitIncrement-1)))/(1<<g_uiBitIncrement)));
+}
+
+inline Double xRoundIbdi(Double x)
+{
+  return (g_uiBitIncrement >0 ? xRoundIbdi2((x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+}
+
+/** run QAO One Part.
+ * \param  pQAOOnePart, iPartIdx
+ */
+Void TEncSampleAdaptiveOffset::xQAOOnePart(SAOQTPart* pQAOOnePart, Int iPartIdx)
+{
+  Int iTypeIdx;
+  Int iNumTotalType = MAX_NUM_SAO_TYPE;
+
+  Int64 iEstDist;
+  Int64 iOffsetOrg;
+  Int64 iOffset;
+  Int64 iCount;
+  Int iClassIdx;
+  Int uiShift = g_uiBitIncrement << 1;
+  Double dAreaWeight =  (pQAOOnePart->part_xe - pQAOOnePart->part_xs + 1) * (pQAOOnePart->part_ye - pQAOOnePart->part_ys + 1);
+  Double dComplexityCost = 0;
+  Int    iQaoPara1 = SAO_RDCO;
+
+  UInt uiDepth = pQAOOnePart->PartLevel;
+
+  //   m_iDistOrg [iPartIdx] = 0;
+
+  m_iDistOrg [iPartIdx] =  (Int64)((Double)(iQaoPara1)/10000 * m_dLambdaLuma * dAreaWeight);
+
+  for (iTypeIdx=-1; iTypeIdx<iNumTotalType; iTypeIdx++)
+  {
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]); // pcCU->getDepth(0) ==> m_puhDepth[uiIdx]
+      m_pcRDGoOnSbacCoder->resetBits();
+    }
+    else
+    {
+      m_pcEntropyCoder->resetEntropy();
+      m_pcEntropyCoder->resetBits();
+    }
+
+    iEstDist = 0;
+
+    m_pcEntropyCoder->m_pcEntropyCoderIf->codeAoUvlc(iTypeIdx+1);
+
+    if (iTypeIdx>=0)
+    {
+
+      for(iClassIdx=1; iClassIdx < m_iNumClass[iTypeIdx]+1; iClassIdx++)
+      {
+        if(m_iCount [iPartIdx][iTypeIdx][iClassIdx])
+        {
+          m_iOffset[iPartIdx][iTypeIdx][iClassIdx]    = (Int64) xRoundIbdi((Double)(m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx]<<m_uiAoBitDepth) / (Double)m_iCount [iPartIdx][iTypeIdx][iClassIdx]);
+        }
+        else
+        {
+          m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx] = 0;
+          m_iOffset[iPartIdx][iTypeIdx][iClassIdx] = 0;
+        }
+
+        iCount     =  m_iCount [iPartIdx][iTypeIdx][iClassIdx];
+        iOffset    =  m_iOffset[iPartIdx][iTypeIdx][iClassIdx] << (g_uiBitIncrement-m_uiAoBitDepth);
+        iOffsetOrg =  m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx];
+        iEstDist   += (( iCount*iOffset*iOffset-iOffsetOrg*iOffset*2 ) >> uiShift);
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeAoSvlc((Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx]);
+      }
+      m_iDist[iPartIdx][iTypeIdx] = iEstDist;
+      m_iRate[iPartIdx][iTypeIdx] = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+      m_dCost[iPartIdx][iTypeIdx] = (Double)((Double)m_iDist[iPartIdx][iTypeIdx] + m_dLambdaLuma * (Double) m_iRate[iPartIdx][iTypeIdx]);
+      dComplexityCost = (Double)(iQaoPara1)/10000 * m_dLambdaLuma * (Double)m_iWeightAO[iTypeIdx] * dAreaWeight;
+      m_dCost[iPartIdx][iTypeIdx] = (Double)((Double)m_iDist[iPartIdx][iTypeIdx] + m_dLambdaLuma * (Double) m_iRate[iPartIdx][iTypeIdx]) + dComplexityCost;
+
+      //       printf("\n%3d:%10.f, %10.0f, %10.0f",iPartIdx,(Double)m_iDist[iPartIdx][iTypeIdx], dComplexityCost);
+
+      // printf("\n%d, %d, %6d, %6d, %f", iPartIdx, iTypeIdx, (Int)m_iDist[iPartIdx][iTypeIdx], (Int)m_iRate[iPartIdx][iTypeIdx], m_dCost[iPartIdx][iTypeIdx]);
+      if(m_dCost[iPartIdx][iTypeIdx] < m_dCostPartBest[iPartIdx])
+      {
+        m_iDistOrg [iPartIdx] = (Int64)dComplexityCost;
+        m_dCostPartBest[iPartIdx] = m_dCost[iPartIdx][iTypeIdx];
+        m_iTypePartBest[iPartIdx] = iTypeIdx;
+        if( m_bUseSBACRD )
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pQAOOnePart->PartLevel][CI_TEMP_BEST] );
+      }
+    }
+    else
+    {
+
+      if(m_iDistOrg[iPartIdx] < m_dCostPartBest[iPartIdx] )
+      {
+        m_dCostPartBest[iPartIdx] = (Double) m_iDistOrg[iPartIdx] + m_pcEntropyCoder->getNumberOfWrittenBits()*m_dLambdaLuma ; 
+        m_iTypePartBest[iPartIdx] = -1;
+        if( m_bUseSBACRD )
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pQAOOnePart->PartLevel][CI_TEMP_BEST] );
+      }
+    }
+  }
+
+  pQAOOnePart->bProcessed = true;
+  pQAOOnePart->bSplit     = false;
+  pQAOOnePart->iMinDist   =        m_iTypePartBest[iPartIdx] >= 0 ? m_iDist[iPartIdx][m_iTypePartBest[iPartIdx]] : m_iDistOrg[iPartIdx];
+  pQAOOnePart->iMinRate   = (Int) (m_iTypePartBest[iPartIdx] >= 0 ? m_iRate[iPartIdx][m_iTypePartBest[iPartIdx]] : 0);
+  pQAOOnePart->dMinCost   = pQAOOnePart->iMinDist + m_dLambdaLuma * pQAOOnePart->iMinRate;
+  pQAOOnePart->iBestType  = m_iTypePartBest[iPartIdx];
+  if (pQAOOnePart->iBestType != -1)
+  {
+    pQAOOnePart->bEnableFlag =  1;
+    pQAOOnePart->iLength = m_iNumClass[m_psQAOPart[iPartIdx].iBestType];
+    for (Int i=0; i<pQAOOnePart->iLength ; i++)
+      pQAOOnePart->iOffset[i] = (Int) m_iOffset[iPartIdx][pQAOOnePart->iBestType][i+1];
+  }
+  else
+  {
+    pQAOOnePart->bEnableFlag =  0;
+    pQAOOnePart->iLength     =  0;
+  }
+
+}
+
+/** run Part Tree Disable.
+ * \param  pQAOOnePart, iPartIdx
+ */
+Void TEncSampleAdaptiveOffset::xPartTreeDisable(Int iPartIdx)
+{
+  SAOQTPart*  pQAOPart= &(m_psQAOPart[iPartIdx]);
+
+  pQAOPart->bEnableFlag = false;
+  pQAOPart->bSplit      = false;
+  pQAOPart->iLength     =  0;
+  pQAOPart->iBestType   = -1;
+
+  if (pQAOPart->PartLevel < m_uiMaxSplitLevel)
+  {
+    for (Int i=0; i<NUM_DOWN_PART; i++)
+    {
+      xPartTreeDisable(pQAOPart->DownPartsIdx[i]);
+    }
+  }
+
+}
+
+/** run QuadTree Decision Function.
+ * \param  iPartIdx, pcPicOrg, pcPicDec, pcPicRest, &dCostFinal
+ */
+Void TEncSampleAdaptiveOffset::xQuadTreeDecisionFunc(Int iPartIdx, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Double &dCostFinal)
+{
+  SAOQTPart*  pQAOPart= &(m_psQAOPart[iPartIdx]);
+  UInt uiDepth = pQAOPart->PartLevel;
+  UInt uhNextDepth = uiDepth+1;
+
+  if (iPartIdx == 0)
+  {
+    dCostFinal = 0;
+  }
+
+  //QAO for this part
+  if(!pQAOPart->bProcessed)
+  {
+    xQAOOnePart (pQAOPart, iPartIdx);
+  }
+
+  //QAO for sub 4 parts
+  if (pQAOPart->PartLevel < m_uiMaxSplitLevel)
+  {
+    Double      dCostNotSplit = m_dLambdaLuma + pQAOPart->dMinCost;
+    Double      dCostSplit    = m_dLambdaLuma;
+
+    for (Int i=0; i< NUM_DOWN_PART ;i++)
+    {
+      if( m_bUseSBACRD )  
+      {
+        if ( 0 == iPartIdx) //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]);
+      }  
+      xQuadTreeDecisionFunc(pQAOPart->DownPartsIdx[i], pcPicOrg, pcPicDec, pcPicRest, dCostFinal);
+      dCostSplit += dCostFinal;
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+      }
+    }
+
+
+    if(dCostSplit < dCostNotSplit)
+    {
+      dCostFinal = dCostSplit;
+      pQAOPart->bSplit      = true;
+      pQAOPart->bEnableFlag = false;
+      pQAOPart->iLength     =  0;
+      pQAOPart->iBestType   = -1;
+    }
+    else
+    {
+      dCostFinal = dCostNotSplit;
+      pQAOPart->bSplit = false;
+      for (Int i=0; i<NUM_DOWN_PART; i++)
+      {
+        xPartTreeDisable(pQAOPart->DownPartsIdx[i]);
+      }
+    }
+  }
+  else
+  {
+    dCostFinal = pQAOPart->dMinCost;
+  }
+}
+/** destory TEncSampleAdaptiveOffset class.
+ * \param  
+ */
+Void TEncSampleAdaptiveOffset::destoryEncBuffer()
+{
+
+    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;
+    }
+
+
+}
+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_QAO_CLASS]; 
+        m_iOffset[i][j] = new Int64 [MAX_NUM_QAO_CLASS]; 
+        m_iOffsetOrg[i][j]=  new Int64 [MAX_NUM_QAO_CLASS]; 
+      }
+    }
+
+}
+
+/** 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_pppcRDSbacCoder = pppcRDSbacCoder;
+  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]);
+  }
+
+  m_bSaoFlag = 0;
+  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_QAO_CLASS;k++)
+      {
+        m_iCount [i][j][k] = 0;
+        m_iOffset[i][j][k] = 0;
+        m_iOffsetOrg[i][j][k] = 0;
+      }  
+    }
+  }
+
+  for(Int i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
+  {
+    m_psQAOPart[i].bEnableFlag   =  0;
+    m_psQAOPart[i].iBestType     = -1;
+    m_psQAOPart[i].iLength       =  0;
+    m_psQAOPart[i].bSplit        =  false; 
+    m_psQAOPart[i].bProcessed    = false;
+    m_psQAOPart[i].dMinCost      = MAX_DOUBLE;
+    m_psQAOPart[i].iMinDist      = MAX_INT;
+    m_psQAOPart[i].iMinRate      = MAX_INT;
+
+    for (Int j=0;j<MAX_NUM_QAO_CLASS;j++)
+    {
+      m_psQAOPart[i].iOffset[j] = 0;
+    }
+  }
+
+  for(Int i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
+  {
+    m_psQAOPart[i].bEnableFlag   =  0;
+    m_psQAOPart[i].iBestType     = -1;
+    m_psQAOPart[i].iLength       =  0;
+    for (Int j=0;j<MAX_NUM_QAO_CLASS;j++)
+    {
+      m_psQAOPart[i].iOffset[j] = 0;
+    }
+  }
+
+}
+
+/** end Sao Encoder.
+ * \param 
+ */
+Void TEncSampleAdaptiveOffset::endSaoEnc()
+{
+  m_pcPic = NULL;
+  m_pcEntropyCoder = NULL;
+}
+
+inline int xSign(int x)
+{
+  return ((x >> 31) | ((int)( (((unsigned int) -x)) >> 31)));
+}
+/** calculate Ao Stats Cu
+ * \param iAddr, iPartIdx
+ */
+Void TEncSampleAdaptiveOffset::calcAoStatsCu(Int iAddr, Int iPartIdx)
+{
+  Int x,y;
+  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
+  TComSPS *pTmpSPS =  m_pcPic->getSlice(0)->getSPS();
+
+
+  Pel* pOrg      ;
+  Pel* pRec      ;
+  Int iStride    =  m_pcPic->getStride();
+  Int iLcuWidth  = pTmpSPS->getMaxCUHeight();
+  Int iLcuHeight = pTmpSPS->getMaxCUWidth();
+  Int iPicWidth  = pTmpSPS->getWidth();
+  Int iPicHeight = pTmpSPS->getHeight();
+  UInt uiLPelX   = pTmpCu->getCUPelX();
+  UInt uiRPelX   = uiLPelX + iLcuWidth;
+  UInt uiTPelY   = pTmpCu->getCUPelY();
+  UInt uiBPelY   = uiTPelY + iLcuHeight;
+  uiRPelX    = uiRPelX > iPicWidth ? iPicWidth : uiRPelX;
+  uiBPelY    = uiBPelY > iPicHeight? iPicHeight: uiBPelY;
+  iLcuWidth  = uiRPelX - uiLPelX;
+  iLcuHeight = uiBPelY - uiTPelY;
+  Int64* iStats ;
+  Int64* iCount ;
+  Int iClassIdx;
+
+
+  //   if(m_iAoType == BO_0 || m_iAoType == BO_1)
+  {
+    iStats = m_iOffsetOrg[iPartIdx][SAO_BO_0];
+    iCount = m_iCount    [iPartIdx][SAO_BO_0];
+
+    pOrg      = m_pcPic->getPicYuvOrg()->getLumaAddr(iAddr);
+    pRec      = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+
+    for (y=0; y<iLcuHeight; y++)
+    {
+      for (x=0; x<iLcuWidth; x++)
+      {
+        iClassIdx =  m_ppLumaTableBo0[pRec[x]];
+        if (iClassIdx)
+        {
+          iStats[iClassIdx] += (pOrg[x] - pRec[x]); 
+          iCount[iClassIdx] ++;
+        }
+      }
+      pOrg += iStride;
+      pRec += iStride;
+    }
+
+    iStats = m_iOffsetOrg[iPartIdx][SAO_BO_1];
+    iCount = m_iCount    [iPartIdx][SAO_BO_1];
+
+    pOrg      = m_pcPic->getPicYuvOrg()->getLumaAddr(iAddr);
+    pRec      = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+
+    for (y=0; y<iLcuHeight; y++)
+    {
+      for (x=0; x<iLcuWidth; x++)
+      {
+        iClassIdx =  m_ppLumaTableBo1[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 (m_iAoType == EO_0  || m_iAoType == EO_1 || m_iAoType == EO_2 || m_iAoType == EO_3)
+  {
+    //     if (m_iAoType == EO_0  )
+    {
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_0];
+      iCount = m_iCount    [iPartIdx][SAO_EO_0];
+
+      pOrg      = m_pcPic->getPicYuvOrg()->getLumaAddr(iAddr);
+      pRec      = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+      for (y=0; y<iLcuHeight; y++)
+      {
+        iSignLeft  = xSign(pRec[1] - pRec[0]);
+        for (x=1; x<iLcuWidth-1; 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 (m_iAoType == EO_1  )
+    {
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_1];
+      iCount = m_iCount    [iPartIdx][SAO_EO_1];
+
+      pOrg      = m_pcPic->getPicYuvOrg()->getLumaAddr(iAddr);
+      pRec      = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+      pOrg += iStride;
+      pRec += iStride;
+
+      for (x=0; x< iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride]);
+      }
+
+      for (y=1; y<iLcuHeight-1; 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 (m_iAoType == EO_2  )
+    {
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_2];
+      iCount = m_iCount    [iPartIdx][SAO_EO_2];
+
+      pOrg      = m_pcPic->getPicYuvOrg()->getLumaAddr(iAddr);
+      pRec      = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+      pOrg += iStride;
+      pRec += iStride;
+      for (x=1; x<iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride-1]);
+      }
+      for (y=1; y<iLcuHeight-1; y++)
+      {
+        iSignDown2 = xSign(pRec[iStride] - pRec[0]);
+        for (x=1; x<iLcuWidth-1; 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[1] = iSignDown2;
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pRec += iStride;
+        pOrg += iStride;
+      }
+    } 
+    //     if (m_iAoType == EO_3  )
+    {
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_3];
+      iCount = m_iCount    [iPartIdx][SAO_EO_3];
+
+      pOrg      = m_pcPic->getPicYuvOrg()->getLumaAddr(iAddr);
+      pRec      = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+      pOrg += iStride;
+      pRec += iStride;
+      for (x=0; x<iLcuWidth-1; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride+1]);
+      }
+
+      for (y=1; y<iLcuHeight-1; y++)
+      {
+        for (x=1; x<iLcuWidth-1; 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[iLcuWidth-2] = xSign(pRec[iLcuWidth-2 + iStride] - pRec[iLcuWidth-1]);
+
+        pRec += iStride;
+        pOrg += iStride;
+      } 
+    } 
+  }
+
+}
+
+/** run get QAO Stats
+ * \param pcPicYuvOrg, pcPicYuvRec, pcPicYuvExt
+ */
+Void TEncSampleAdaptiveOffset::xGetQAOStats(TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvRec, TComPicYuv* pcPicYuvExt)
+{
+  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;
+
+  if (m_uiMaxSplitLevel == 0)
+  {
+    iPartIdx = 0;
+    for (LcuIdxY = m_psQAOPart[iPartIdx].StartCUY; LcuIdxY<= m_psQAOPart[iPartIdx].EndCUY; LcuIdxY++)
+    {
+      for (LcuIdxX = m_psQAOPart[iPartIdx].StartCUX; LcuIdxX<= m_psQAOPart[iPartIdx].EndCUX; LcuIdxX++)
+      {
+        iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+        calcAoStatsCu(iAddr, iPartIdx);
+      }
+    }
+
+  }
+  else
+  {
+    for(iPartIdx=m_aiNumCulPartsLevel[m_uiMaxSplitLevel-1]; iPartIdx<m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; iPartIdx++)
+    {
+      for (LcuIdxY = m_psQAOPart[iPartIdx].StartCUY; LcuIdxY<= m_psQAOPart[iPartIdx].EndCUY; LcuIdxY++)
+      {
+        for (LcuIdxX = m_psQAOPart[iPartIdx].StartCUX; LcuIdxX<= m_psQAOPart[iPartIdx].EndCUX; LcuIdxX++)
+        {
+          iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+          calcAoStatsCu(iAddr, iPartIdx);
+        }
+      }
+    }
+    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++)
+      {
+        for (i=0; i<NUM_DOWN_PART; i++)
+        {
+          iDownPartIdx = m_psQAOPart[iPartIdx].DownPartsIdx[i];
+          for (iTypeIdx=0; iTypeIdx<iNumTotalType; iTypeIdx++)
+          {
+            for (iClassIdx=0; iClassIdx<m_iNumClass[iTypeIdx]+1; iClassIdx++)
+            {
+              m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx] += m_iOffsetOrg[iDownPartIdx][iTypeIdx][iClassIdx];
+              m_iCount [iPartIdx][iTypeIdx][iClassIdx]    += m_iCount [iDownPartIdx][iTypeIdx][iClassIdx];
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+/** Sample adaptive offset Process
+ * \param dLambda
+ */
+Void TEncSampleAdaptiveOffset::SAOProcess( Double dLambda)
+{
+  // set lambda
+  TComPicYuv* pcPicYuvOrg = m_pcPic->getPicYuvOrg();
+  TComPicYuv* pcPicYuvRec = m_pcPic->getPicYuvRec();
+
+  TComPicYuv* pcPicYuvExt = NULL;
+
+  m_eSliceType           =  m_pcPic->getSlice(0)->getSliceType();
+  m_iPicNalReferenceIdc  = (m_pcPic->getSlice(0)->isReferenced() ? 1 :0);
+
+  m_dLambdaLuma    = dLambda;
+  m_dLambdaChroma  = dLambda;
+
+  if (g_uiBitIncrement>1)
+  {
+    m_uiAoBitDepth = 1;
+  }
+  else
+  {
+    m_uiAoBitDepth = 0;
+  }
+
+  Double dCostFinal = 0;
+
+  xGetQAOStats(pcPicYuvOrg, pcPicYuvRec, pcPicYuvExt);
+  xQuadTreeDecisionFunc(0, pcPicYuvOrg, pcPicYuvRec, pcPicYuvExt, dCostFinal);
+  m_bSaoFlag = dCostFinal < m_iDistOrg[0] ? 1:0;
+
+
+  if(m_bSaoFlag)
+  {
+    xProcessQuadTreeAo( 0, pcPicYuvRec,  pcPicYuvExt);
+  }
+
+}
+
+
+#endif
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncAdaptiveLoopFilter.h	(revision 19)
@@ -0,0 +1,348 @@
+/* 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     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"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+#if MTK_SAO
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+private:
+  Double            m_dLambdaLuma;
+  Double            m_dLambdaChroma;
+
+  TEncEntropy*      m_pcEntropyCoder;
+  TEncSbac***       m_pppcRDSbacCoder;
+  TEncSbac*         m_pcRDGoOnSbacCoder;
+
+  Int64  ***m_iCount ;     //[MAX_NUM_QAO_PART][MAX_NUM_QAO_TYPE][MAX_NUM_QAO_CLASS]; 
+  Int64  ***m_iOffset;     //[MAX_NUM_QAO_PART][MAX_NUM_QAO_TYPE][MAX_NUM_QAO_CLASS]; 
+  Int64  ***m_iOffsetOrg  ;      //[MAX_NUM_QAO_PART][MAX_NUM_QAO_TYPE]; 
+  Int64  **m_iRate  ;      //[MAX_NUM_QAO_PART][MAX_NUM_QAO_TYPE]; 
+  Int64  **m_iDist  ;      //[MAX_NUM_QAO_PART][MAX_NUM_QAO_TYPE]; 
+  Double **m_dCost  ;      //[MAX_NUM_QAO_PART][MAX_NUM_QAO_TYPE]; 
+  Double *m_dCostPartBest ;//[MAX_NUM_QAO_PART]; 
+  Int64  *m_iDistOrg;      //[MAX_NUM_QAO_PART]; 
+  Int    *m_iTypePartBest ;//[MAX_NUM_QAO_PART]; 
+
+  Bool    m_bUseSBACRD;
+
+public:
+  Void startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder);
+  Void endSaoEnc();
+  Void SAOProcess(Double dLambda);
+  Void xQuadTreeDecisionFunc(Int iPartIdx, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Double &dCostFinal);
+  Void xQAOOnePart(SAOQTPart* pQAOOnePart, Int iPartIdx);
+  Void xPartTreeDisable(Int iPartIdx);
+  Void xGetQAOStats(TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest);
+  Void calcAoStatsCu(Int iAddr, Int iPartIdx);
+  Void destoryEncBuffer();
+  Void createEncBuffer();
+};
+#endif
+
+/// estimation part of adaptive loop filter class
+class TEncAdaptiveLoopFilter : public TComAdaptiveLoopFilter
+{
+private:
+  static const Int m_aiSymmetricArray9x9[81];     ///< scan index for 9x9 filter
+  static const Int m_aiSymmetricArray7x7[49];     ///< scan index for 7x7 filter
+  static const Int m_aiSymmetricArray5x5[25];     ///< scan index for 5x5 filter
+#if TI_ALF_MAX_VSIZE_7
+  static const Int m_aiSymmetricArray9x7[63];     ///< scan index for 9x7 filter
+#endif
+  
+  Double** m_ppdAlfCorr;
+  Double* m_pdDoubleAlfCoeff;
+  
+  SliceType m_eSliceType;
+  Int m_iPicNalReferenceIdc;
+  
+  Double m_dLambdaLuma;
+  Double m_dLambdaChroma;
+  
+  TEncEntropy* m_pcEntropyCoder;
+  
+  TComPic* m_pcPic;
+  ALFParam* m_pcBestAlfParam;
+  ALFParam* m_pcTempAlfParam;
+  
+  TComPicYuv* m_pcPicYuvBest;
+  TComPicYuv* m_pcPicYuvTmp;
+  
+  UInt m_uiNumSCUInCU;
+  
+  Int m_varIndTab[NO_VAR_BINS];
+  double ***m_yGlobalSym;
+  double ****m_EGlobalSym;
+  double *m_pixAcc;
+  Int **m_filterCoeffSymQuant;
+  imgpel **m_varImg;
+  imgpel **m_maskImg;
+  Int m_im_width;
+  Int m_im_height;
+  ALFParam *m_tempALFp;
+  TEncEntropy* m_pcDummyEntropyCoder;
+  
+  double **m_y_merged;
+  double ***m_E_merged;
+  double *m_pixAcc_merged;
+  double *m_y_temp;
+  double **m_E_temp;
+  
+  Int *m_filterCoeffQuantMod;
+  double *m_filterCoeff;
+  Int *m_filterCoeffQuant;
+  Int **m_diffFilterCoeffQuant;
+  Int **m_FilterCoeffQuantTemp;
+  
+#if MQT_ALF_NPASS
+  Int  m_iUsePreviousFilter;
+  Int  m_iDesignCurrentFilter;
+  Int  m_iFilterIdx;
+#if MQT_BA_RA
+  Int***   m_aiFilterCoeffSavedMethods[NUM_ALF_CLASS_METHOD];
+  Int***   m_aiFilterCoeffSaved;
+#else
+  Int  m_aiFilterCoeffSaved[9][NO_VAR_BINS][MAX_SQR_FILT_LENGTH];
+#endif
+  Int  m_iGOPSize;
+  Int  m_iCurrentPOC;
+  Int  m_iALFEncodePassReduction;
+  Int  m_iALFNumOfRedesign;
+  Int  m_iMatrixBaseFiltNo;
+
+#if TI_ALF_MAX_VSIZE_7
+  static Int  m_aiTapPos9x9_In9x9Sym[21];
+#else
+  static Int  m_aiTapPos9x9_In9x9Sym[22];
+#endif
+  static Int  m_aiTapPos7x7_In9x9Sym[14];
+  static Int  m_aiTapPos5x5_In9x9Sym[8];
+  static Int* m_iTapPosTabIn9x9Sym[NO_TEST_FILT];
+#endif
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  TComPicYuv* m_pcSliceYuvTmp;
+#endif
+
+private:
+  // init / uninit internal variables
+  Void xInitParam      ();
+  Void xUninitParam    ();
+  
+  // create/destroy/copy/set functions of ALF control flags
+  Void xCreateTmpAlfCtrlFlags   ();
+  Void xDestroyTmpAlfCtrlFlags  ();
+  Void xCopyTmpAlfCtrlFlagsTo   ();
+  Void xCopyTmpAlfCtrlFlagsFrom ();
+  
+  // encoder ALF control flags
+  Void xEncodeCUAlfCtrlFlags  ();
+  Void xEncodeCUAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+  
+  // functions related to correlation computation
+#if MTK_NONCROSS_INLOOP_FILTER
+  Void xCalcCorrelationFunc   ( Int ypos, Int xpos, Pel* pOrg, Pel* pCmp, Int iTap, Int iWidth, Int iHeight, Int iOrgStride, Int iCmpStride, Bool bSymmCopyBlockMatrix);
+#else
+  Void xCalcCorrelationFunc   ( Pel* pOrg, Pel* pCmp, Int iTap, Int iWidth, Int iHeight, Int iOrgStride, Int iCmpStride);
+#endif
+
+  // 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 );
+  Void xClearFilterCoefInt    ( Int* qh, Int N );
+  Void xCopyDecToRestCUs      ( TComPicYuv* pcPicDec, TComPicYuv* pcPicRest );
+  Void xCopyDecToRestCU       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest );
+  Void xFilteringFrameChroma  ( TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest );
+  
+  // distortion / misc functions
+  UInt64 xCalcSSD             ( Pel* pOrg, Pel* pCmp, Int iWidth, Int iHeight, Int iStride );
+  Void   xCalcRDCost          ( TComPicYuv* pcPicOrg, TComPicYuv* pcPicCmp, ALFParam* pAlfParam, UInt64& ruiRate, UInt64& ruiDist, Double& rdCost );
+  Void   xCalcRDCostChroma    ( TComPicYuv* pcPicOrg, TComPicYuv* pcPicCmp, ALFParam* pAlfParam, UInt64& ruiRate, UInt64& ruiDist, Double& rdCost );
+  Void   xCalcRDCost          ( ALFParam* pAlfParam, UInt64& ruiRate, UInt64 uiDist, Double& rdCost );
+  Int    xGauss               ( Double **a, Int N );
+  
+#if MQT_ALF_NPASS
+  Void  xretriveBlockMatrix    (Int iNumTaps, Int* piTapPosInMaxFilter, Double*** pppdEBase, Double*** pppdETarget, Double** ppdyBase, Double** ppdyTarget );
+  Void  xcalcPredFilterCoeffPrev(Int filtNo);
+  Void  setALFEncodingParam(TComPic *pcPic);
+  Void  setFilterIdx(Int index);
+  Void  setInitialMask(TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec);
+#if MQT_BA_RA
+  Void  xFirstEstimateFilteringFrameLumaAllTap(imgpel* ImgOrg, imgpel* ImgDec, Int Stride, ALFParam* pcAlfSaved,Int* aiVarIndTabBest,Int** ppiBestCoeffSet, Int& ibestfiltNo,Int& ibestfilters_per_fr, Double** ppdBesty,Double*** pppdBestE,Double* pdBestpixAcc,UInt64& ruiRate,Int64& riDist,Double& rdCost);  
+#else
+  Void  xFirstFilteringFrameLumaAllTap(imgpel* ImgOrg, imgpel* ImgDec, imgpel* ImgRest, Int Stride);
+#endif
+  Int64 xFastFiltDistEstimation(Double** ppdE, Double* pdy, Int* piCoeff, Int iFiltLength);
+  Int64 xEstimateFiltDist      (Int filters_per_fr, Int* VarIndTab, Double*** pppdE, Double** ppdy, Int** ppiCoeffSet, Int iFiltLength);
+#endif
+
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  Void xstoreInBlockMatrixforSlices  (imgpel* ImgOrg, imgpel* ImgDec, Int tap, Int iStride);
+  Void xstoreInBlockMatrixforOneSlice(CAlfSlice* pSlice, imgpel* ImgOrg, imgpel* ImgDec, Int tap, Int iStride, Bool bFirstSlice, Bool bLastSlice);
+  Void xfilterSlices_en              (imgpel* ImgDec, imgpel* ImgRest,int filtNo, int Stride);
+  Void xfilterOneSlice_en            (CAlfSlice* pSlice, imgpel* ImgDec, imgpel* ImgRest,int filtNo, int iStride);
+  Void calcVarforSlices              (imgpel **varmap, imgpel *imgY_pad, Int pad_size, Int fl, Int img_stride);
+
+  //only for chroma
+  Void xCalcCorrelationFuncforChromaSlices  (Int ComponentID, Pel* pOrg, Pel* pCmp, Int iTap, Int iOrgStride, Int iCmpStride);
+  Void xCalcCorrelationFuncforChromaOneSlice(CAlfSlice* pSlice, Pel* pOrg, Pel* pCmp, Int iTap, Int iStride, Bool bLastSlice);
+  Void xFrameChromaforSlices                (Int ComponentID, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, Int *qh, Int iTap);
+#endif
+
+
+protected:
+  /// do ALF for chroma
+  Void xEncALFChroma          ( UInt64 uiLumaRate, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiDist, UInt64& ruiBits );
+public:
+  TEncAdaptiveLoopFilter          ();
+  virtual ~TEncAdaptiveLoopFilter () {}
+  
+  /// allocate temporal memory
+  Void startALFEnc(TComPic* pcPic, TEncEntropy* pcEntropyCoder);
+  
+  /// destroy temporal memory
+  Void endALFEnc();
+  
+  /// estimate ALF parameters
+  Void ALFProcess(ALFParam* pcAlfParam, Double dLambda, UInt64& ruiDist, UInt64& ruiBits, UInt& ruiMaxAlfCtrlDepth );
+  /// test ALF for luma
+  Void xEncALFLuma_qc                  ( TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiMinRate, 
+                                         UInt64& ruiMinDist, Double& rdMinCost );
+  Void xCUAdaptiveControl_qc           ( TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiMinRate, 
+                                         UInt64& ruiMinDist, Double& rdMinCost );
+#if TSB_ALF_HEADER
+  Void xSetCUAlfCtrlFlags_qc            (UInt uiAlfCtrlDepth, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, 
+                                         UInt64& ruiDist, ALFParam *pAlfParam);
+  Void xSetCUAlfCtrlFlag_qc             (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiAlfCtrlDepth, TComPicYuv* pcPicOrg,
+                                         TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiDist, ALFParam *pAlfParam);
+#else
+  Void xSetCUAlfCtrlFlags_qc            (UInt uiAlfCtrlDepth, TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, 
+                                         UInt64& ruiDist);
+  Void xSetCUAlfCtrlFlag_qc             (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiAlfCtrlDepth, TComPicYuv* pcPicOrg,
+                                         TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiDist);
+#endif
+  Void xReDesignFilterCoeff_qc          (TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec,  TComPicYuv* pcPicRest, Bool bReadCorr);
+  Void xFilterTapDecision_qc            (TComPicYuv* pcPicOrg, TComPicYuv* pcPicDec, TComPicYuv* pcPicRest, UInt64& ruiMinRate, 
+                                         UInt64& ruiMinDist, Double& rdMinCost);
+  Void xFirstFilteringFrameLuma         (imgpel* ImgOrg, imgpel* ImgDec, imgpel* ImgRest, ALFParam* ALFp, Int tap,  Int Stride);
+#if MTK_NONCROSS_INLOOP_FILTER
+  Void xstoreInBlockMatrix(Int ypos, Int xpos, Int iheight, Int iwidth, Bool bResetBlockMatrix, Bool bSymmCopyBlockMatrix, imgpel* ImgOrg, imgpel* ImgDec, Int tap, Int Stride);
+#else
+  Void xstoreInBlockMatrix(imgpel* ImgOrg, imgpel* ImgDec, Int tap, Int Stride);
+#endif
+  Void xFilteringFrameLuma_qc(imgpel* ImgOrg, imgpel* imgY_pad, imgpel* ImgFilt, ALFParam* ALFp, Int tap, Int Stride);
+#if MTK_NONCROSS_INLOOP_FILTER
+  Void xfilterFrame_en(int ypos, int xpos, int iheight, int iwidth, imgpel* ImgDec, imgpel* ImgRest,int filtNo, int Stride);
+#else
+  Void xfilterFrame_en(imgpel* ImgDec, imgpel* ImgRest,int filtNo, int Stride);
+#endif
+  Void xcalcPredFilterCoeff(Int filtNo);
+#if MQT_ALF_NPASS  
+  UInt xcodeFiltCoeff(Int **filterCoeffSymQuant, Int filtNo, Int varIndTab[], Int filters_per_fr_best, Int frNo, ALFParam* ALFp);
+#else
+  Void xcodeFiltCoeff(Int **filterCoeffSymQuant, Int filtNo, Int varIndTab[], Int filters_per_fr_best, Int frNo, ALFParam* ALFp);
+#endif
+  Void xfindBestFilterVarPred(double **ySym, double ***ESym, double *pixAcc, Int **filterCoeffSym, Int **filterCoeffSymQuant,
+                              Int filtNo, Int *filters_per_fr_best, Int varIndTab[], imgpel **imgY_rec, imgpel **varImg, 
+                              imgpel **maskImg, imgpel **imgY_pad, double lambda_val);
+  double xfindBestCoeffCodMethod(int codedVarBins[NO_VAR_BINS], int *forceCoeff0, 
+                                 int **filterCoeffSymQuant, int fl, int sqrFiltLength, 
+                                 int filters_per_fr, double errorForce0CoeffTab[NO_VAR_BINS][2], 
+                                 double *errorQuant, double lambda);
+  Void xcollectStatCodeFilterCoeffForce0(int **pDiffQFilterCoeffIntPP, int fl, int sqrFiltLength, int filters_per_group, 
+                                         int bitsVarBin[]);
+  Void xdecideCoeffForce0(int codedVarBins[NO_VAR_BINS], double errorForce0Coeff[], double errorForce0CoeffTab[NO_VAR_BINS][2], 
+                          int bitsVarBin[NO_VAR_BINS], double lambda, int filters_per_fr);
+  Int xsendAllFiltersPPPredForce0(int **FilterCoeffQuant, int fl, int sqrFiltLength, int filters_per_group, 
+                                  int codedVarBins[NO_VAR_BINS], int createBistream, ALFParam* ALFp);
+  Int xsendAllFiltersPPPred(int **FilterCoeffQuant, int fl, int sqrFiltLength, 
+                            int filters_per_group, int createBistream, ALFParam* ALFp);
+  Int xcodeAuxInfo(int filtNo, int noFilters, int varIndTab[NO_VAR_BINS], int frNo, int createBitstream,int realfiltNo, ALFParam* ALFp);
+  Int xcodeFilterCoeff(int **pDiffQFilterCoeffIntPP, int fl, 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);
+  //cholesky related
+  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, int bit_depth, double errorTabForce0Coeff[NO_VAR_BINS][2]);
+  Double QuantizeIntegerFilterPP(double *filterCoeff, int *filterCoeffQuant, double **E, double *y, 
+                                 int sqrFiltLength, int *weights, int bit_depth);
+  Void roundFiltCoeff(int *FilterCoeffQuan, double *FilterCoeff, int sqrFiltLength, int factor);
+  double findFilterGroupingError(double ***EGlobalSeq, double **yGlobalSeq, double *pixAccGlobalSeq, 
+                                 int intervalBest[NO_VAR_BINS][2], int sqrFiltLength, int filters_per_fr);
+  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[MAX_SQR_FILT_LENGTH][MAX_SQR_FILT_LENGTH], double z[MAX_SQR_FILT_LENGTH], 
+                            int R_size, double A[MAX_SQR_FILT_LENGTH]);
+  Void gnsTransposeBacksubstitution(double U[MAX_SQR_FILT_LENGTH][MAX_SQR_FILT_LENGTH], double rhs[], double x[],
+                                    int order);
+  Int gnsCholeskyDec(double **inpMatr, double outMatr[MAX_SQR_FILT_LENGTH][MAX_SQR_FILT_LENGTH], int noEq);
+#if MQT_ALF_NPASS
+  Void  setGOPSize(Int val) { m_iGOPSize = val; }
+  Void  setALFEncodePassReduction (Int iVal) {m_iALFEncodePassReduction = iVal;}
+
+#if MQT_BA_RA
+  Void createAlfGlobalBuffers(Int iALFEncodePassReduction);
+  Void destroyAlfGlobalBuffers();
+#endif
+#endif
+};
+#endif
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 19)
@@ -0,0 +1,152 @@
+/* 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     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"
+
+// ====================================================================================================================
+// 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: /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 19)
@@ -0,0 +1,74 @@
+/* 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     TEncBinCoder.h
+    \brief    binary entropy encoder interface
+*/
+
+#ifndef __TENC_BIN_CODER__
+#define __TENC_BIN_CODER__
+
+#include "../TLibCommon/ContextModel.h"
+#include "../TLibCommon/TComBitStream.h"
+
+
+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  resetBits         ()                                          = 0;
+  virtual UInt  getNumWrittenBits ()                                          = 0;
+
+  virtual Void  encodeBin         ( UInt  uiBin,  ContextModel& rcCtxModel )  = 0;
+  virtual Void  encodeBinEP       ( UInt  uiBin                            )  = 0;
+  virtual Void  encodeBinTrm      ( UInt  uiBin                            )  = 0;
+
+  virtual TEncBinCABAC*   getTEncBinCABAC   ()  { return 0; }
+  
+  virtual ~TEncBinIf() {}
+};
+
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 19)
@@ -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-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     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABAC.h"
+
+
+TEncBinCABAC::TEncBinCABAC()
+: m_pcTComBitIf( 0 )
+, m_bBinCountingEnabled(0)
+{
+}
+
+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_uiBitsToFollow  = 0;
+  m_uiByte          = 0;
+  m_uiBitsLeft      = 9;
+}
+
+Void
+TEncBinCABAC::finish()
+{
+  xWriteBitAndBitsToFollow( ( m_uiLow >> 9 ) & 1 );
+  xWriteBit               ( ( m_uiLow >> 8 ) & 1 );
+  // xWriteBit               ( 1 ); // stop bit, already written in TEncGOP::compressGOP
+  if( 8 - m_uiBitsLeft != 0 )
+  {
+    m_pcTComBitIf->write  ( m_uiByte, 8 - m_uiBitsLeft );
+  }
+}
+
+Void
+TEncBinCABAC::copyState( TEncBinIf* pcTEncBinIf )
+{
+  TEncBinCABAC* pcTEncBinCABAC = pcTEncBinIf->getTEncBinCABAC();
+  m_uiLow           = pcTEncBinCABAC->m_uiLow;
+  m_uiRange         = pcTEncBinCABAC->m_uiRange;
+  m_uiBitsToFollow  = pcTEncBinCABAC->m_uiBitsToFollow;
+  m_uiByte          = pcTEncBinCABAC->m_uiByte;
+  m_uiBitsLeft      = pcTEncBinCABAC->m_uiBitsLeft;
+}
+
+Void  
+TEncBinCABAC::resetBits()
+{
+  m_uiLow          &= 255;
+  m_uiBitsToFollow  = 0;
+  m_uiByte          = 0;
+  m_uiBitsLeft      = 9;
+}
+
+UInt
+TEncBinCABAC::getNumWrittenBits()
+{
+  return m_pcTComBitIf->getNumberOfWrittenBits() + 8 + m_uiBitsToFollow - m_uiBitsLeft + 1;
+}
+
+Void
+TEncBinCABAC::encodeBin( UInt uiBin, ContextModel &rcCtxModel )
+{
+  {
+    DTRACE_CABAC_V( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tstate=" )
+    DTRACE_CABAC_V( ( rcCtxModel.getState() << 1 ) + rcCtxModel.getMps() )
+    DTRACE_CABAC_T( "\tsymbol=" )
+    DTRACE_CABAC_V( uiBin )
+    DTRACE_CABAC_T( "\n" )
+  }
+  if (m_bBinCountingEnabled) 
+  {
+    m_uiBinsCoded++;
+  }
+  UInt  uiLPS   = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) & 3 ];
+  m_uiRange    -= uiLPS;
+  if( uiBin != rcCtxModel.getMps() )
+  {
+    m_uiLow    += m_uiRange;
+    m_uiRange   = uiLPS;
+    rcCtxModel.updateLPS();
+  }
+  else
+  {
+    rcCtxModel.updateMPS();
+  }
+  while( m_uiRange < 256 )
+  {
+    if( m_uiLow >= 512 )
+    {
+      xWriteBitAndBitsToFollow( 1 );
+      m_uiLow -= 512;
+    }
+    else if( m_uiLow < 256 )
+    {
+      xWriteBitAndBitsToFollow( 0 );
+    }
+    else
+    {
+      m_uiBitsToFollow++;
+      m_uiLow         -= 256;
+    }
+    m_uiLow   <<= 1;
+    m_uiRange <<= 1;
+  }
+}
+
+Void
+TEncBinCABAC::encodeBinEP( UInt uiBin )
+{
+  {
+    DTRACE_CABAC_V( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tEPsymbol=" )
+    DTRACE_CABAC_V( uiBin )
+    DTRACE_CABAC_T( "\n" )
+  }
+  if (m_bBinCountingEnabled)
+  {
+    m_uiBinsCoded++;
+  }
+  m_uiLow <<= 1;
+  if( uiBin )
+  {
+    m_uiLow += m_uiRange;
+  }
+  if( m_uiLow >= 1024 )
+  {
+    xWriteBitAndBitsToFollow( 1 );
+    m_uiLow -= 1024;
+  }
+  else if( m_uiLow < 512 )
+  {
+    xWriteBitAndBitsToFollow( 0 );
+  }
+  else
+  {
+    m_uiBitsToFollow++;
+    m_uiLow         -= 512;
+  }
+}
+
+Void
+TEncBinCABAC::encodeBinTrm( UInt uiBin )
+{
+  if (m_bBinCountingEnabled)
+  {
+    m_uiBinsCoded++;
+  }
+  m_uiRange -= 2;
+  if( uiBin )
+  {
+    m_uiLow  += m_uiRange;
+    m_uiRange = 2;
+  }
+  while( m_uiRange < 256 )
+  {
+    if( m_uiLow >= 512 )
+    {
+      xWriteBitAndBitsToFollow( 1 );
+      m_uiLow -= 512;
+    }
+    else if( m_uiLow < 256 )
+    {
+      xWriteBitAndBitsToFollow( 0 );
+    }
+    else
+    {
+      m_uiBitsToFollow++;
+      m_uiLow         -= 256;
+    }
+    m_uiLow   <<= 1;
+    m_uiRange <<= 1;
+  }
+}
+
+Void  
+TEncBinCABAC::xWriteBit( UInt uiBit )
+{
+  m_uiByte += m_uiByte + uiBit;
+  if( ! --m_uiBitsLeft )
+  {
+    m_pcTComBitIf->write( m_uiByte, 8 );
+    m_uiBitsLeft  = 8;
+    m_uiByte      = 0;
+  }
+}
+
+Void  
+TEncBinCABAC::xWriteBitAndBitsToFollow( UInt uiBit )
+{
+  xWriteBit( uiBit );
+  uiBit = 1 - uiBit;
+  while( m_uiBitsToFollow > 0 )
+  {
+    m_uiBitsToFollow--;
+    xWriteBit( uiBit );
+  }
+}
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 19)
@@ -0,0 +1,90 @@
+/* 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     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"
+
+
+class TEncBinCABAC : public TEncBinIf
+{
+public:
+  TEncBinCABAC ();
+  virtual ~TEncBinCABAC();
+  
+  Void  init              ( TComBitIf* pcTComBitIf );
+  Void  uninit            ();
+  
+  Void  start             ();
+  Void  finish            ();
+  Void  copyState         ( TEncBinIf* pcTEncBinIf );
+  
+  Void  resetBits         ();
+  UInt  getNumWrittenBits ();
+  
+  Void  encodeBin         ( UInt  uiBin,  ContextModel& rcCtxModel );
+  Void  encodeBinEP       ( UInt  uiBin                            );
+  Void  encodeBinTrm      ( UInt  uiBin                            );
+  
+  TEncBinCABAC* getTEncBinCABAC()  { return this; }
+  
+  Void  setBinsCoded              ( UInt uiVal )  { m_uiBinsCoded = uiVal;          }
+  UInt  getBinsCoded              ()              { return m_uiBinsCoded;           }
+  Void  setBinCountingEnableFlag  ( Bool bFlag )  { m_bBinCountingEnabled = bFlag;  }
+  Bool  getBinCountingEnableFlag  ()              { return m_bBinCountingEnabled;   }
+protected:
+  Void  xWriteBit               ( UInt uiBit );
+  Void  xWriteBitAndBitsToFollow( UInt uiBit );
+  
+private:
+  TComBitIf*          m_pcTComBitIf;
+  UInt                m_uiLow;
+  UInt                m_uiRange;
+  UInt                m_uiBitsToFollow;
+  UInt                m_uiByte;
+  UInt                m_uiBitsLeft;
+  UInt                m_uiBinsCoded;
+  Bool                m_bBinCountingEnabled;
+};
+
+
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 19)
@@ -0,0 +1,3548 @@
+/* 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     TEncCavlc.cpp
+    \brief    CAVLC encoder class
+*/
+
+#include "TEncCavlc.h"
+#include "SEIwrite.h"
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncCavlc::TEncCavlc()
+{
+  m_pcBitIf           = NULL;
+  m_bRunLengthCoding  = false;   //  m_bRunLengthCoding  = !rcSliceHeader.isIntra();
+  m_uiCoeffCost       = 0;
+  m_bAlfCtrl = false;
+  m_uiMaxAlfCtrlDepth = 0;
+
+  m_bAdaptFlag        = true;    // adaptive VLC table
+}
+
+TEncCavlc::~TEncCavlc()
+{
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncCavlc::resetEntropy()
+{
+  m_bRunLengthCoding = ! m_pcSlice->isIntra();
+  m_uiRun = 0;
+#if !CAVLC_COEF_LRG_BLK
+  ::memcpy(m_uiLPTableE8, g_auiLPTableE8, 10*128*sizeof(UInt));
+  ::memcpy(m_uiLPTableD8, g_auiLPTableD8, 10*128*sizeof(UInt));
+#endif
+  ::memcpy(m_uiLPTableE4, g_auiLPTableE4, 3*32*sizeof(UInt));
+  ::memcpy(m_uiLPTableD4, g_auiLPTableD4, 3*32*sizeof(UInt));
+  ::memcpy(m_uiLastPosVlcIndex, g_auiLastPosVlcIndex, 10*sizeof(UInt));
+
+#if LCEC_INTRA_MODE
+#if MTK_DCM_MPM
+  ::memcpy(m_uiIntraModeTableD17[0], g_auiIntraModeTableD17[0], 16*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableE17[0], g_auiIntraModeTableE17[0], 16*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableD17[1], g_auiIntraModeTableD17[1], 16*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableE17[1], g_auiIntraModeTableE17[1], 16*sizeof(UInt));
+
+  ::memcpy(m_uiIntraModeTableD34[0], g_auiIntraModeTableD34[0], 33*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableE34[0], g_auiIntraModeTableE34[0], 33*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableD34[1], g_auiIntraModeTableD34[1], 33*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableE34[1], g_auiIntraModeTableE34[1], 33*sizeof(UInt));
+#else
+  ::memcpy(m_uiIntraModeTableD17, g_auiIntraModeTableD17, 16*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableE17, g_auiIntraModeTableE17, 16*sizeof(UInt));
+
+  ::memcpy(m_uiIntraModeTableD34, g_auiIntraModeTableD34, 33*sizeof(UInt));
+  ::memcpy(m_uiIntraModeTableE34, g_auiIntraModeTableE34, 33*sizeof(UInt));
+#endif
+#endif
+
+#if CAVLC_RQT_CBP
+  ::memcpy(m_uiCBP_YUV_TableE, g_auiCBP_YUV_TableE, 4*8*sizeof(UInt));
+  ::memcpy(m_uiCBP_YUV_TableD, g_auiCBP_YUV_TableD, 4*8*sizeof(UInt));
+  ::memcpy(m_uiCBP_YS_TableE,  g_auiCBP_YS_TableE,  2*4*sizeof(UInt));
+  ::memcpy(m_uiCBP_YS_TableD,  g_auiCBP_YS_TableD,  2*4*sizeof(UInt));
+  ::memcpy(m_uiCBP_YCS_TableE, g_auiCBP_YCS_TableE, 2*8*sizeof(UInt));
+  ::memcpy(m_uiCBP_YCS_TableD, g_auiCBP_YCS_TableD, 2*8*sizeof(UInt));
+  ::memcpy(m_uiCBP_4Y_TableE,  g_auiCBP_4Y_TableE,  2*15*sizeof(UInt));
+  ::memcpy(m_uiCBP_4Y_TableD,  g_auiCBP_4Y_TableD,  2*15*sizeof(UInt));
+  m_uiCBP_4Y_VlcIdx = 0;
+#else
+  ::memcpy(m_uiCBPTableE, g_auiCBPTableE, 2*8*sizeof(UInt));
+  ::memcpy(m_uiCBPTableD, g_auiCBPTableD, 2*8*sizeof(UInt));
+  m_uiCbpVlcIdx[0] = 0;
+  m_uiCbpVlcIdx[1] = 0;
+  ::memcpy(m_uiBlkCBPTableE, g_auiBlkCBPTableE, 2*15*sizeof(UInt));
+  ::memcpy(m_uiBlkCBPTableD, g_auiBlkCBPTableD, 2*15*sizeof(UInt));
+  m_uiBlkCbpVlcIdx = 0;
+#endif
+
+#if UNIFY_INTER_TABLE
+  ::memcpy(m_uiMI1TableE, g_auiComMI1TableE, 9*sizeof(UInt));
+  ::memcpy(m_uiMI1TableD, g_auiComMI1TableD, 9*sizeof(UInt));
+#else
+  ::memcpy(m_uiMI1TableE, g_auiMI1TableE, 8*sizeof(UInt));
+  ::memcpy(m_uiMI1TableD, g_auiMI1TableD, 8*sizeof(UInt));
+  ::memcpy(m_uiMI2TableE, g_auiMI2TableE, 15*sizeof(UInt));
+  ::memcpy(m_uiMI2TableD, g_auiMI2TableD, 15*sizeof(UInt));
+
+#if DCM_COMB_LIST
+  if ( m_pcSlice->getNoBackPredFlag() || m_pcSlice->getNumRefIdx(REF_PIC_LIST_C)>0)
+#else
+  if ( m_pcSlice->getNoBackPredFlag() )
+#endif
+  {
+    ::memcpy(m_uiMI1TableE, g_auiMI1TableENoL1, 8*sizeof(UInt));
+    ::memcpy(m_uiMI1TableD, g_auiMI1TableDNoL1, 8*sizeof(UInt));
+    ::memcpy(m_uiMI2TableE, g_auiMI2TableENoL1, 15*sizeof(UInt));
+    ::memcpy(m_uiMI2TableD, g_auiMI2TableDNoL1, 15*sizeof(UInt));
+  }
+#if MS_LCEC_ONE_FRAME
+  if ( m_pcSlice->getNumRefIdx(REF_PIC_LIST_0) <= 1 && m_pcSlice->getNumRefIdx(REF_PIC_LIST_1) <= 1 )
+  {
+    if ( m_pcSlice->getNoBackPredFlag() || ( m_pcSlice->getNumRefIdx(REF_PIC_LIST_C) > 0 && m_pcSlice->getNumRefIdx(REF_PIC_LIST_C) <= 1 ) )
+    {
+      ::memcpy(m_uiMI1TableE, g_auiMI1TableEOnly1RefNoL1, 8*sizeof(UInt));
+      ::memcpy(m_uiMI1TableD, g_auiMI1TableDOnly1RefNoL1, 8*sizeof(UInt));
+    }
+    else
+    {
+      ::memcpy(m_uiMI1TableE, g_auiMI1TableEOnly1Ref, 8*sizeof(UInt));
+      ::memcpy(m_uiMI1TableD, g_auiMI1TableDOnly1Ref, 8*sizeof(UInt));
+    }
+  }
+#endif
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  if (m_pcSlice->getNumRefIdx(REF_PIC_LIST_C)>0)
+  {
+    m_uiMI1TableE[8] = 8;
+    m_uiMI1TableD[8] = 8;
+  }
+  else  // GPB case
+  {
+    m_uiMI1TableD[8] = m_uiMI1TableD[6];
+    m_uiMI1TableD[6] = 8;
+
+    m_uiMI1TableE[m_uiMI1TableD[8]] = 8;
+    m_uiMI1TableE[m_uiMI1TableD[6]] = 6;
+  }
+#endif
+#endif
+
+#if QC_LCEC_INTER_MODE
+  ::memcpy(m_uiSplitTableE, g_auiInterModeTableE, 4*7*sizeof(UInt));
+  ::memcpy(m_uiSplitTableD, g_auiInterModeTableD, 4*7*sizeof(UInt));
+#endif
+
+  m_uiMITableVlcIdx = 0;
+
+#if CAVLC_COUNTER_ADAPT
+#if CAVLC_RQT_CBP
+  ::memset(m_ucCBP_YUV_TableCounter,   0,        4*4*sizeof(UChar));
+  ::memset(m_ucCBP_4Y_TableCounter,    0,        2*2*sizeof(UChar));
+  ::memset(m_ucCBP_YCS_TableCounter,   0,        2*4*sizeof(UChar));
+  ::memset(m_ucCBP_YS_TableCounter,    0,        2*3*sizeof(UChar));
+#else
+  ::memset(m_ucCBFTableCounter,        0,        2*4*sizeof(UChar));
+  ::memset(m_ucBlkCBPTableCounter,     0,        2*2*sizeof(UChar));
+#endif
+
+  ::memset(m_ucMI1TableCounter,        0,          4*sizeof(UChar));
+  ::memset(m_ucSplitTableCounter,      0,        4*4*sizeof(UChar));
+
+#if CAVLC_RQT_CBP
+  m_ucCBP_YUV_TableCounterSum[0] = m_ucCBP_YUV_TableCounterSum[1] = m_ucCBP_YUV_TableCounterSum[2] = m_ucCBP_YUV_TableCounterSum[3] = 0;
+  m_ucCBP_4Y_TableCounterSum[0] = m_ucCBP_4Y_TableCounterSum[1] = 0;
+  m_ucCBP_YCS_TableCounterSum[0] = m_ucCBP_YCS_TableCounterSum[1] = 0;
+  m_ucCBP_YS_TableCounterSum[0] = m_ucCBP_YS_TableCounterSum[1] = 0;
+#else
+  m_ucCBFTableCounterSum[0] = m_ucCBFTableCounterSum[1] = 0;
+  m_ucBlkCBPTableCounterSum[0] = m_ucBlkCBPTableCounterSum[1] = 0;
+#endif
+  m_ucSplitTableCounterSum[0] = m_ucSplitTableCounterSum[1] = m_ucSplitTableCounterSum[2]= m_ucSplitTableCounterSum[3] = 0;
+  m_ucMI1TableCounterSum = 0;
+#endif
+}
+
+#if !CAVLC_COEF_LRG_BLK
+UInt* TEncCavlc::GetLP8Table()
+{
+  return &m_uiLPTableE8[0][0];
+}
+#endif
+
+UInt* TEncCavlc::GetLP4Table()
+{
+  return &m_uiLPTableE4[0][0];
+}
+
+#if QC_MOD_LCEC
+UInt* TEncCavlc::GetLastPosVlcIndexTable()
+{
+  return &m_uiLastPosVlcIndex[0];
+}
+#endif
+
+/**
+ * marshall the SEI message @sei.
+ */
+void TEncCavlc::codeSEI(const SEI& sei)
+{
+  codeNALUnitHeader(NAL_UNIT_SEI, NAL_REF_IDC_PRIORITY_LOWEST);
+  writeSEImessage(*m_pcBitIf, sei);
+}
+
+Void TEncCavlc::codePPS( TComPPS* pcPPS )
+{
+  // uiFirstByte
+  codeNALUnitHeader( NAL_UNIT_PPS, NAL_REF_IDC_PRIORITY_HIGHEST );
+
+  xWriteUvlc( pcPPS->getPPSId() );
+  xWriteUvlc( pcPPS->getSPSId() );
+#if CONSTRAINED_INTRA_PRED
+  xWriteFlag( pcPPS->getConstrainedIntraPred() ? 1 : 0 );
+#endif
+#ifdef WEIGHT_PRED
+  xWriteCode( pcPPS->getUseWP(), 1);        // Use of Weighting Prediction (P_SLICE)
+  xWriteCode( pcPPS->getWPBiPredIdc(), 2);  // Use of Weighting Bi-Prediction (B_SLICE)
+#endif
+  return;
+}
+
+Void TEncCavlc::codeNALUnitHeader( NalUnitType eNalUnitType, NalRefIdc eNalRefIdc, UInt TemporalId, Bool bOutputFlag )
+{
+  // uiFirstByte
+  xWriteCode( 0, 1);            // forbidden_zero_flag
+  xWriteCode( eNalRefIdc, 2);   // nal_ref_idc
+  xWriteCode( eNalUnitType, 5); // nal_unit_type
+
+  if ( (eNalUnitType == NAL_UNIT_CODED_SLICE) || (eNalUnitType == NAL_UNIT_CODED_SLICE_IDR) || (eNalUnitType == NAL_UNIT_CODED_SLICE_CDR) )
+  {
+    xWriteCode( TemporalId, 3);   // temporal_id
+    xWriteFlag( bOutputFlag );    // output_flag
+    xWriteCode( 1, 4);            // reseved_one_4bits
+  }
+}
+
+Void TEncCavlc::codeSPS( TComSPS* pcSPS )
+{
+  // uiFirstByte
+  codeNALUnitHeader( NAL_UNIT_SPS, NAL_REF_IDC_PRIORITY_HIGHEST );
+
+  // Structure
+  xWriteUvlc  ( pcSPS->getSPSId() );
+  xWriteUvlc  ( pcSPS->getWidth () );
+  xWriteUvlc  ( pcSPS->getHeight() );
+
+  xWriteUvlc  ( pcSPS->getPad (0) );
+  xWriteUvlc  ( pcSPS->getPad (1) );
+
+  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
+  xWriteUvlc  ( pcSPS->getMaxCUWidth()   );
+  xWriteUvlc  ( pcSPS->getMaxCUDepth()-g_uiAddCUDepth );
+
+  xWriteUvlc( pcSPS->getQuadtreeTULog2MinSize() - 2 );
+  xWriteUvlc( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize() );
+  xWriteUvlc( pcSPS->getQuadtreeTUMaxDepthInter() - 1 );
+  xWriteUvlc( pcSPS->getQuadtreeTUMaxDepthIntra() - 1 );
+
+  xWriteUvlc( pcSPS->getCodedPictureBufferSize() );
+
+  // Tools
+  xWriteFlag  ( (pcSPS->getUseALF ()) ? 1 : 0 );
+  xWriteFlag  ( (pcSPS->getUseDQP ()) ? 1 : 0 );
+#if !HHI_NO_LowDelayCoding
+  xWriteFlag  ( (pcSPS->getUseLDC ()) ? 1 : 0 );
+#endif
+  xWriteFlag  ( (pcSPS->getUseMRG ()) ? 1 : 0 ); // SOPH:
+
+#if LM_CHROMA
+  xWriteFlag  ( (pcSPS->getUseLMChroma ()) ? 1 : 0 );
+#endif
+
+#if HHI_RMP_SWITCH
+  xWriteFlag  ( (pcSPS->getUseRMP()) ? 1 : 0 );
+#endif
+
+  // AMVP mode for each depth
+  for (Int i = 0; i < pcSPS->getMaxCUDepth(); i++)
+  {
+    xWriteFlag( pcSPS->getAMVPMode(i) ? 1 : 0);
+  }
+
+  // Bit-depth information
+#if FULL_NBIT
+  xWriteUvlc( pcSPS->getBitDepth() - 8 );
+#else
+#if ENABLE_IBDI
+  xWriteUvlc( pcSPS->getBitDepth() - 8 );
+#endif
+  xWriteUvlc( pcSPS->getBitIncrement() );
+#endif
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  xWriteFlag( pcSPS->getLFCrossSliceBoundaryFlag()?1 : 0);
+#endif
+#if MTK_SAO
+  xWriteFlag( pcSPS->getUseSAO() ? 1 : 0);
+#endif
+
+  if( pcSPS->getViewId() || pcSPS->isDepth() )
+  {
+    xWriteFlag( 0 ); // inverse of RBSP stop bit (for backwards compatible extension)
+    if( pcSPS->isDepth() )
+    {
+      xWriteFlag( 1 ); // depth
+      xWriteUvlc( pcSPS->getViewId() );
+      xWriteSvlc( pcSPS->getViewOrderIdx() );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      xWriteFlag( pcSPS->getUseDMM() ? 1 : 0 );
+#endif
+#if HHI_MPI
+      xWriteFlag( pcSPS->getUseMVI() ? 1 : 0 );
+#endif
+    }
+    else
+    {
+      xWriteFlag( 0 ); // not depth
+      xWriteUvlc( pcSPS->getViewId() - 1 );
+      xWriteSvlc( pcSPS->getViewOrderIdx() );
+      xWriteUvlc( pcSPS->getCamParPrecision() );
+      xWriteFlag( pcSPS->hasCamParInSliceHeader() ? 1 : 0 );
+      if( !pcSPS->hasCamParInSliceHeader() )
+      {
+        for( UInt uiId = 0; uiId < pcSPS->getViewId(); uiId++ )
+        {
+          xWriteSvlc( pcSPS->getCodedScale    ()[ uiId ] );
+          xWriteSvlc( pcSPS->getCodedOffset   ()[ uiId ] );
+          xWriteSvlc( pcSPS->getInvCodedScale ()[ uiId ] + pcSPS->getCodedScale ()[ uiId ] );
+          xWriteSvlc( pcSPS->getInvCodedOffset()[ uiId ] + pcSPS->getCodedOffset()[ uiId ] );
+        }
+      }
+#if DEPTH_MAP_GENERATION
+      xWriteUvlc( pcSPS->getPredDepthMapGeneration() );
+      if( pcSPS->getPredDepthMapGeneration() )
+      {
+        xWriteUvlc  ( pcSPS->getPdmPrecision() );
+        for( UInt uiId = 0; uiId < pcSPS->getViewId(); uiId++ )
+        {
+          xWriteSvlc( pcSPS->getPdmScaleNomDelta()[ uiId ] );
+          xWriteSvlc( pcSPS->getPdmOffset       ()[ uiId ] );
+        }
+#if HHI_INTER_VIEW_MOTION_PRED
+        xWriteUvlc  ( pcSPS->getMultiviewMvPredMode() );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        xWriteFlag  ( pcSPS->getMultiviewResPredMode() );
+#endif
+      }
+#endif
+    }
+  }
+}
+
+Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
+{
+  // here someone can add an appropriated NalRefIdc type
+#if DCM_DECODING_REFRESH
+  codeNALUnitHeader (pcSlice->getNalUnitType(), NAL_REF_IDC_PRIORITY_HIGHEST, 1, true);
+#else
+  codeNALUnitHeader (NAL_UNIT_CODED_SLICE, NAL_REF_IDC_PRIORITY_HIGHEST);
+#endif
+
+  Bool bEntropySlice = false;
+  if (pcSlice->isNextSlice())
+  {
+    xWriteFlag( 0 ); // Entropy slice flag
+  }
+  else
+  {
+    bEntropySlice = true;
+    xWriteFlag( 1 ); // Entropy slice flag
+  }
+  if (!bEntropySlice)
+  {
+    assert( pcSlice->getPPS()->getPPSId() == pcSlice->getPPSId() );
+    xWriteUvlc  ( pcSlice->getPPSId() );
+    xWriteCode  (pcSlice->getPOC(), 10 );   //  9 == SPS->Log2MaxFrameNum
+    xWriteUvlc  (pcSlice->getSliceType() );
+    xWriteSvlc  (pcSlice->getSliceQp() );
+  }
+  if (pcSlice->isNextSlice())
+  {
+    xWriteUvlc(pcSlice->getSliceCurStartCUAddr());        // start CU addr for slice
+  }
+  else
+  {
+    xWriteUvlc(pcSlice->getEntropySliceCurStartCUAddr()); // start CU addr for entropy slice
+  }
+  if (!bEntropySlice)
+  {
+    xWriteFlag  (pcSlice->getSymbolMode() > 0 ? 1 : 0);
+
+    if (!pcSlice->isIntra())
+    {
+      xWriteFlag  (pcSlice->isReferenced() ? 1 : 0);
+  #if !HIGH_ACCURACY_BI
+  #ifdef ROUNDING_CONTROL_BIPRED
+      xWriteFlag  (pcSlice->isRounding() ? 1 : 0);
+  #endif
+  #endif
+    }
+
+    xWriteFlag  (pcSlice->getLoopFilterDisable());
+
+    if (!pcSlice->isIntra())
+    {
+      xWriteCode  ((pcSlice->getNumRefIdx( REF_PIC_LIST_0 )), 3 );
+    }
+    else
+    {
+      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
+    }
+    if (pcSlice->isInterB())
+    {
+      xWriteCode  ((pcSlice->getNumRefIdx( REF_PIC_LIST_1 )), 3 );
+    }
+    else
+    {
+      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+    }
+
+    if (!pcSlice->isIntra())
+    {
+
+      for(Int i = 0; i<pcSlice->getNumRefIdx(REF_PIC_LIST_0);i++)
+      {
+        const bool bInterViewRef = pcSlice->getViewIdx() != pcSlice->getRefPic( REF_PIC_LIST_0,i )->getViewIdx();
+        xWriteFlag( bInterViewRef );
+        if( bInterViewRef )
+        {
+          xWriteUvlc( pcSlice->getRefPic( REF_PIC_LIST_0,i )->getViewIdx() );
+        }
+        else
+        {
+          xWriteSvlc(pcSlice->getPOC()-pcSlice->getRefPOC(REF_PIC_LIST_0,i));
+        }
+      }
+
+    }
+    if( pcSlice->isInterB())
+    {
+      for(Int i = 0; i<pcSlice->getNumRefIdx(REF_PIC_LIST_1);i++)
+      {
+        const bool bInterViewRef = pcSlice->getViewIdx() != pcSlice->getRefPic( REF_PIC_LIST_1,i )->getViewIdx();
+        xWriteFlag( bInterViewRef );
+        if( bInterViewRef )
+        {
+          xWriteUvlc( pcSlice->getRefPic( REF_PIC_LIST_1,i )->getViewIdx() );
+        }
+        else
+        {
+          xWriteSvlc(pcSlice->getPOC()-pcSlice->getRefPOC(REF_PIC_LIST_1,i));
+        }
+      }
+    }
+
+
+  #if DCM_COMB_LIST
+    if (pcSlice->isInterB())
+    {
+      xWriteFlag  (pcSlice->getRefPicListCombinationFlag() ? 1 : 0 );
+      if(pcSlice->getRefPicListCombinationFlag())
+      {
+        xWriteUvlc( pcSlice->getNumRefIdx(REF_PIC_LIST_C)-1);
+
+        xWriteFlag  (pcSlice->getRefPicListModificationFlagLC() ? 1 : 0 );
+        if(pcSlice->getRefPicListModificationFlagLC())
+        {
+          for (UInt i=0;i<pcSlice->getNumRefIdx(REF_PIC_LIST_C);i++)
+          {
+            xWriteFlag( pcSlice->getListIdFromIdxOfLC(i));
+            xWriteUvlc( pcSlice->getRefIdxFromIdxOfLC(i));
+          }
+        }
+      }
+    }
+  #endif
+
+  #if 0
+    xWriteFlag  (pcSlice->getDRBFlag() ? 1 : 0 );
+    if ( !pcSlice->getDRBFlag() )
+    {
+      xWriteCode  (pcSlice->getERBIndex(), 2);
+    }
+  #endif
+
+  #if AMVP_NEIGH_COL
+    if ( pcSlice->getSliceType() == B_SLICE )
+    {
+      xWriteFlag( pcSlice->getColDir() );
+    }
+  #endif
+
+#ifdef WEIGHT_PRED
+    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPredIdc()==1 && pcSlice->getSliceType()==B_SLICE) )
+    {
+      codeWeightPredTable( pcSlice );
+    }
+#endif
+    if( pcSlice->getSPS()->hasCamParInSliceHeader() )
+    {
+      for( UInt uiId = 0; uiId < pcSlice->getSPS()->getViewId(); uiId++ )
+      {
+        xWriteSvlc( pcSlice->getCodedScale    ()[ uiId ] );
+        xWriteSvlc( pcSlice->getCodedOffset   ()[ uiId ] );
+        xWriteSvlc( pcSlice->getInvCodedScale ()[ uiId ] + pcSlice->getCodedScale ()[ uiId ] );
+        xWriteSvlc( pcSlice->getInvCodedOffset()[ uiId ] + pcSlice->getCodedOffset()[ uiId ] );
+      }
+    }
+  }
+}
+
+Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
+{
+}
+
+Void TEncCavlc::codeSliceFinish ()
+{
+  if ( m_bRunLengthCoding && m_uiRun)
+  {
+    xWriteUvlc(m_uiRun);
+  }
+}
+
+Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  Int iSymbol = pcCU->getMVPIdx(eRefList, uiAbsPartIdx);
+  Int iNum    = pcCU->getMVPNum(eRefList, uiAbsPartIdx);
+
+  xWriteUnaryMaxSymbol(iSymbol, iNum-1);
+}
+#if QC_LCEC_INTER_MODE
+Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if ( pcCU->getSlice()->isIntra() && pcCU->isIntra( uiAbsPartIdx ) )
+  {
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+    if( uiDepth == (g_uiMaxCUDepth - g_uiAddCUDepth))
+#endif
+      xWriteFlag( pcCU->getPartitionSize(uiAbsPartIdx ) == SIZE_2Nx2N? 1 : 0 );
+    return;
+  }
+
+
+#if MTK_DISABLE_INTRA_NxN_SPLIT && HHI_DISABLE_INTER_NxN_SPLIT
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+  {
+    if ((pcCU->getPartitionSize(uiAbsPartIdx ) == SIZE_NxN) || pcCU->isIntra( uiAbsPartIdx ))
+    {
+      UInt uiIntraFlag = ( pcCU->isIntra(uiAbsPartIdx));
+      if (pcCU->getPartitionSize(uiAbsPartIdx ) == SIZE_2Nx2N)
+      {
+        xWriteFlag(1);
+      }
+      else
+      {
+        xWriteFlag(0);
+#if MTK_DISABLE_INTRA_NxN_SPLIT && !HHI_DISABLE_INTER_NxN_SPLIT
+        if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#elif !MTK_DISABLE_INTRA_NxN_SPLIT && HHI_DISABLE_INTER_NxN_SPLIT
+        if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+        xWriteFlag( uiIntraFlag? 1 : 0 );
+      }
+
+      return;
+    }
+  }
+}
+#else
+Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
+
+  if ( pcCU->getSlice()->isInterB() && pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    xWriteFlag( 0 );
+#if HHI_RMP_SWITCH
+    if( pcCU->getSlice()->getSPS()->getUseRMP() )
+#endif
+    {
+      xWriteFlag( 0 );
+      xWriteFlag( 0 );
+    }
+#if HHI_DISABLE_INTER_NxN_SPLIT
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      xWriteFlag( 0 );
+    }
+#else
+    xWriteFlag( 0 );
+#endif
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+    {
+      xWriteFlag( (eSize == SIZE_2Nx2N? 0 : 1) );
+    }
+    return;
+  }
+
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+    {
+      xWriteFlag( eSize == SIZE_2Nx2N? 1 : 0 );
+    }
+    return;
+  }
+
+  switch(eSize)
+  {
+    case SIZE_2Nx2N:
+    {
+      xWriteFlag( 1 );
+      break;
+    }
+    case SIZE_2NxN:
+    {
+      xWriteFlag( 0 );
+      xWriteFlag( 1 );
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      xWriteFlag( 0 );
+      xWriteFlag( 0 );
+      xWriteFlag( 1 );
+      break;
+    }
+    case SIZE_NxN:
+    {
+#if HHI_DISABLE_INTER_NxN_SPLIT
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+      {
+        xWriteFlag( 0 );
+#if HHI_RMP_SWITCH
+        if( pcCU->getSlice()->getSPS()->getUseRMP())
+#endif
+        {
+          xWriteFlag( 0 );
+          xWriteFlag( 0 );
+        }
+        if (pcCU->getSlice()->isInterB())
+        {
+          xWriteFlag( 1 );
+        }
+      }
+      break;
+    }
+    default:
+    {
+      assert(0);
+    }
+  }
+}
+#endif
+
+/** code prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \returns Void
+ */
+Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if QC_LCEC_INTER_MODE
+  codeInterModeFlag(pcCU, uiAbsPartIdx,(UInt)pcCU->getDepth(uiAbsPartIdx),2);
+  return;
+#else
+  // get context function is here
+  Int iPredMode = pcCU->getPredictionMode( uiAbsPartIdx );
+  if ( pcCU->getSlice()->isInterB() )
+  {
+    return;
+  }
+  xWriteFlag( iPredMode == MODE_INTER ? 0 : 1 );
+#endif
+}
+
+/** code merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \returns Void
+ */
+Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if QC_LCEC_INTER_MODE
+  if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N )
+     return;
+#endif
+  UInt uiSymbol = pcCU->getMergeFlag( uiAbsPartIdx ) ? 1 : 0;
+  xWriteFlag( uiSymbol );
+}
+
+
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+Void 
+TEncCavlc::codeMergeIndexMV( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiNumCand  = 0;
+  UInt uiMergeIdx = pcCU->getMergeIndex( uiAbsPartIdx );
+#if HHI_MPI
+  const Bool bMVIAvailable = pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE;
+  const UInt uiMviMergePos = bMVIAvailable ? HHI_MPI_MERGE_POS : MRG_MAX_NUM_CANDS;
+  if( bMVIAvailable )
+  {
+    uiNumCand++;
+    const Bool bUseMVI = pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1;
+    if( bUseMVI )
+      uiMergeIdx = HHI_MPI_MERGE_POS;
+    else if( uiMergeIdx >= HHI_MPI_MERGE_POS )
+      uiMergeIdx++;
+  }
+  UInt uiUnaryIdx = uiMergeIdx;
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS; uiIdx++ )
+  {
+    if( uiIdx < uiMviMergePos )
+    {
+      if( pcCU->getNeighbourCandIdx( uiIdx, uiAbsPartIdx ) == uiIdx + 1 )
+      {
+        uiNumCand++;
+      }
+      else if( uiIdx < uiMergeIdx )
+      {
+        uiUnaryIdx--;
+      }
+    }
+    else if( uiIdx > uiMviMergePos )
+    {
+      if( pcCU->getNeighbourCandIdx( uiIdx - 1, uiAbsPartIdx ) == uiIdx )
+      {
+        uiNumCand++;
+      }
+      else if( uiIdx < uiMergeIdx )
+      {
+        uiUnaryIdx--;
+      }
+    }
+  }
+#else
+  UInt uiUnaryIdx = uiMergeIdx;
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS; uiIdx++ )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIdx, uiAbsPartIdx ) == uiIdx + 1 )
+    {
+      uiNumCand++;
+    }
+    else if( uiIdx < uiMergeIdx )
+    {
+      uiUnaryIdx--;
+    }
+  }
+#endif
+  AOF( uiNumCand > 1 );
+  for( UInt ui = 0; ui < uiNumCand - 1; ui++ )
+  {
+    const UInt uiSymbol = ( ui == uiUnaryIdx ? 0 : 1 );
+    xWriteFlag( uiSymbol );
+    if( uiSymbol == 0 )
+    {
+      break;
+    }
+  }
+}
+#endif
+
+
+/** code merge index
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \returns Void
+ */
+Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+#if HHI_INTER_VIEW_MOTION_PRED && HHI_MPI
+  if( ( pcCU->getSlice()->getSPS()->getViewId() > 0 && ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) == PDM_USE_FOR_MERGE ) ||
+      ( pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N ) )
+#elif HHI_MPI
+  if( pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+#else
+  if( pcCU->getSlice()->getSPS()->getViewId() > 0 && ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) == PDM_USE_FOR_MERGE )
+#endif
+  {
+    codeMergeIndexMV( pcCU, uiAbsPartIdx );
+    return;
+  }
+#endif
+
+  Bool bLeftInvolved = false;
+  Bool bAboveInvolved = false;
+  Bool bCollocatedInvolved = false;
+  Bool bCornerInvolved = false;
+  UInt uiNumCand = 0;
+  for( UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; ++uiIter )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == uiIter + 1 )
+    {
+      uiNumCand++;
+      if( uiIter == 0 )
+      {
+        bLeftInvolved = true;
+      }
+      else if( uiIter == 1 )
+      {
+        bAboveInvolved = true;
+      }
+      else if( uiIter == 2 )
+      {
+        bCollocatedInvolved = true;
+      }
+      else if( uiIter == 3 )
+      {
+        bCornerInvolved = true;
+      }
+    }
+  }
+  assert( uiNumCand > 1 );
+  UInt uiUnaryIdx = pcCU->getMergeIndex( uiAbsPartIdx );
+  if( !bCornerInvolved && uiUnaryIdx > 3 )
+  {
+    --uiUnaryIdx;
+  }
+  if( !bCollocatedInvolved && uiUnaryIdx > 2 )
+  {
+    --uiUnaryIdx;
+  }
+  if( !bAboveInvolved && uiUnaryIdx > 1 )
+  {
+    --uiUnaryIdx;
+  }
+  if( !bLeftInvolved && uiUnaryIdx > 0 )
+  {
+    --uiUnaryIdx;
+  }
+  for( UInt ui = 0; ui < uiNumCand - 1; ++ui )
+  {
+    const UInt uiSymbol = ui == uiUnaryIdx ? 0 : 1;
+    xWriteFlag( uiSymbol );
+    if( uiSymbol == 0 )
+    {
+      break;
+    }
+  }
+}
+
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+Void 
+TEncCavlc::codeResPredFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiSymbol = ( pcCU->getResPredFlag( uiAbsPartIdx ) ? 1 : 0 );
+  xWriteFlag( uiSymbol );
+}
+#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::codeAlfCtrlDepth()
+{
+  if (!m_bAlfCtrl)
+    return;
+
+  UInt uiDepth = m_uiMaxAlfCtrlDepth;
+
+  xWriteUnaryMaxSymbol(uiDepth, g_uiMaxCUDepth-1);
+}
+#if QC_LCEC_INTER_MODE
+Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
+{
+  Bool bHasSplit = ( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )? 0 : 1;
+  UInt uiSplitFlag = ( pcCU->getDepth( uiAbsPartIdx ) > uiDepth ) ? 1 : 0;
+  UInt uiMode=0,uiControl=0;
+  UInt uiTableDepth = uiDepth;
+  if ( !bHasSplit )
+  {
+    uiTableDepth = 3;
+  }
+  if(!uiSplitFlag || !bHasSplit)
+  {
+    uiMode = 1;
+    uiControl = 1;
+    if (!pcCU->isSkipped(uiAbsPartIdx ))
+    {
+      uiControl = 2;
+      uiMode = 6;
+      if (pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER)
+      {
+        if(pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N)
+          uiMode=pcCU->getMergeFlag(uiAbsPartIdx) ? 2 : 3;
+        else
+          uiMode=3+(UInt)pcCU->getPartitionSize(uiAbsPartIdx);
+      }
+    }
+  }
+  if (uiEncMode != uiControl )
+    return;
+  UInt uiEndSym = bHasSplit ? 7 : 6;
+  uiDepth = uiTableDepth;
+  UInt uiLength = m_uiSplitTableE[uiDepth][uiMode] + 1;
+  if (uiLength == uiEndSym)
+  {
+    xWriteCode( 0, uiLength - 1);
+  }
+  else
+  {
+    xWriteCode( 1, uiLength );
+  }
+  UInt x = uiMode;
+  UInt cx = m_uiSplitTableE[uiDepth][x];
+  /* Adapt table */
+  if ( m_bAdaptFlag)
+  {
+#if CAVLC_COUNTER_ADAPT
+    adaptCodeword(cx, m_ucSplitTableCounter[uiDepth],  m_ucSplitTableCounterSum[uiDepth],   m_uiSplitTableD[uiDepth],  m_uiSplitTableE[uiDepth], 4);
+#else
+    if(cx>0)
+    {
+      UInt cy = Max(0,cx-1);
+      UInt y = m_uiSplitTableD[uiDepth][cy];
+      m_uiSplitTableD[uiDepth][cy] = x;
+      m_uiSplitTableD[uiDepth][cx] = y;
+      m_uiSplitTableE[uiDepth][x] = cy;
+      m_uiSplitTableE[uiDepth][y] = cx;
+    }
+#endif
+  }
+  return;
+}
+#endif
+Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if QC_LCEC_INTER_MODE
+  codeInterModeFlag(pcCU,uiAbsPartIdx,(UInt)pcCU->getDepth(uiAbsPartIdx),1);
+  return;
+#else
+  // get context function is here
+  UInt uiSymbol = pcCU->isSkipped( uiAbsPartIdx ) ? 1 : 0;
+  xWriteFlag( uiSymbol );
+#endif
+}
+
+Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    return;
+#if QC_LCEC_INTER_MODE
+  if (!pcCU->getSlice()->isIntra())
+  {
+    codeInterModeFlag(pcCU,uiAbsPartIdx,uiDepth,0);
+    return;
+  }
+#endif
+  UInt uiCurrSplitFlag = ( pcCU->getDepth( uiAbsPartIdx ) > uiDepth ) ? 1 : 0;
+
+  xWriteFlag( uiCurrSplitFlag );
+  return;
+}
+
+Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  xWriteFlag( uiSymbol );
+}
+
+Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  UInt uiCbf = pcCU->getCbf( uiAbsPartIdx, eType, uiTrDepth );
+  xWriteFlag( uiCbf );
+}
+
+Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiCbf = pcCU->getQtRootCbf( uiAbsPartIdx );
+  xWriteFlag( uiCbf ? 1 : 0 );
+}
+
+#if LCEC_INTRA_MODE
+#if MTK_DCM_MPM
+Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDir         = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+#if ADD_PLANAR_MODE
+  UInt planarFlag    = 0;
+  if (iDir == PLANAR_IDX)
+  {
+    iDir = 2;
+    planarFlag = 1;
+  }
+#endif
+
+  Int uiPreds[2] = {-1, -1};
+  Int uiPredNum = pcCU->getIntraDirLumaPredictor(uiAbsPartIdx, uiPreds);
+
+  Int uiPredIdx = -1;
+
+  for(UInt i = 0; i < uiPredNum; i++)
+  {
+    if(iDir == uiPreds[i])
+    {
+      uiPredIdx = i;
+    }
+  }
+
+  if ( g_aucIntraModeBitsAng[iIntraIdx] < 5 )
+  {
+    if(uiPredIdx != -1)
+    {
+      xWriteFlag(1);
+      if(uiPredNum == 2)
+      {
+        xWriteFlag((UInt)uiPredIdx);
+      }
+    }
+    else
+    {
+      xWriteFlag(0);
+      for(Int i = (uiPredNum - 1); i >= 0; i--)
+      {
+        iDir = iDir > uiPreds[i] ? iDir - 1 : iDir;
+      }
+
+
+      xWriteFlag( iDir & 0x01 ? 1 : 0 );
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) { xWriteFlag( iDir & 0x02 ? 1 : 0 ); }
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) { xWriteFlag( iDir & 0x04 ? 1 : 0 ); }
+    }
+
+  }
+  else
+  {
+     UInt uiCode, uiLength;
+     Int iRankIntraMode, iRankIntraModeLarger, iDirLarger;
+
+     const UInt *huff;
+     const UInt *lengthHuff;
+     UInt  *m_uiIntraModeTableD;
+     UInt  *m_uiIntraModeTableE;
+
+     if ( g_aucIntraModeBitsAng[iIntraIdx] == 5 )
+     {
+       huff = huff17_2[uiPredNum - 1];
+       lengthHuff = lengthHuff17_2[uiPredNum - 1];
+       m_uiIntraModeTableD = m_uiIntraModeTableD17[uiPredNum - 1];
+       m_uiIntraModeTableE = m_uiIntraModeTableE17[uiPredNum - 1];
+     }
+     else
+     {
+       huff = huff34_2[uiPredNum - 1];
+       lengthHuff = lengthHuff34_2[uiPredNum - 1];
+       m_uiIntraModeTableD = m_uiIntraModeTableD34[uiPredNum - 1];
+       m_uiIntraModeTableE = m_uiIntraModeTableE34[uiPredNum - 1];
+     }
+
+     if(uiPredIdx != -1)
+     {
+       uiCode=huff[0];
+       uiLength=lengthHuff[0];
+       xWriteCode(uiCode, uiLength);
+
+       if(uiPredNum == 2)
+       {
+         xWriteFlag((UInt)uiPredIdx);
+       }
+     }
+     else
+     {
+       for(Int i = (uiPredNum - 1); i >= 0; i--)
+       {
+         iDir = iDir > uiPreds[i] ? iDir - 1 : iDir;
+       }
+       iRankIntraMode=m_uiIntraModeTableE[iDir];
+
+       uiCode=huff[iRankIntraMode+1];
+       uiLength=lengthHuff[iRankIntraMode+1];
+
+       xWriteCode(uiCode, uiLength);
+
+       if ( m_bAdaptFlag )
+       {
+         iRankIntraModeLarger = Max(0,iRankIntraMode-1);
+         iDirLarger = m_uiIntraModeTableD[iRankIntraModeLarger];
+
+         m_uiIntraModeTableD[iRankIntraModeLarger] = iDir;
+         m_uiIntraModeTableD[iRankIntraMode] = iDirLarger;
+         m_uiIntraModeTableE[iDir] = iRankIntraModeLarger;
+         m_uiIntraModeTableE[iDirLarger] = iRankIntraMode;
+       }
+     }
+  }
+#if ADD_PLANAR_MODE
+  iDir = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  if ( (iDir == PLANAR_IDX) || (iDir == 2) )
+  {
+    xWriteFlag( planarFlag );
+  }
+#endif
+}
+#else
+Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDir         = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  Int iMostProbable = pcCU->getMostProbableIntraDirLuma( uiAbsPartIdx );
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+  UInt uiCode, uiLength;
+  Int iRankIntraMode, iRankIntraModeLarger, iDirLarger;
+#if ADD_PLANAR_MODE
+  UInt planarFlag    = 0;
+  if (iDir == PLANAR_IDX)
+  {
+    iDir = 2;
+    planarFlag = 1;
+  }
+#endif
+
+  UInt ind=(pcCU->getLeftIntraDirLuma( uiAbsPartIdx )==pcCU->getAboveIntraDirLuma( uiAbsPartIdx ))? 0 : 1;
+
+  const UInt *huff17=huff17_2[ind];
+  const UInt *lengthHuff17=lengthHuff17_2[ind];
+  const UInt *huff34=huff34_2[ind];
+  const UInt *lengthHuff34=lengthHuff34_2[ind];
+
+  if ( g_aucIntraModeBitsAng[iIntraIdx] < 5 )
+  {
+    if (iDir == iMostProbable)
+      xWriteFlag( 1 );
+    else{
+      if (iDir>iMostProbable)
+        iDir--;
+      xWriteFlag( 0 );
+      xWriteFlag( iDir & 0x01 ? 1 : 0 );
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) xWriteFlag( iDir & 0x02 ? 1 : 0 );
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) xWriteFlag( iDir & 0x04 ? 1 : 0 );
+    }
+  }
+  else if ( g_aucIntraModeBitsAng[iIntraIdx] == 5 )
+  {
+
+    if (iDir==iMostProbable)
+    {
+      uiCode=huff17[0];
+      uiLength=lengthHuff17[0];
+    }
+    else
+    {
+      if (iDir>iMostProbable)
+      {
+        iDir--;
+      }
+      iRankIntraMode=m_uiIntraModeTableE17[iDir];
+
+      uiCode=huff17[iRankIntraMode+1];
+      uiLength=lengthHuff17[iRankIntraMode+1];
+
+      if ( m_bAdaptFlag )
+      {
+        iRankIntraModeLarger = Max(0,iRankIntraMode-1);
+        iDirLarger = m_uiIntraModeTableD17[iRankIntraModeLarger];
+
+        m_uiIntraModeTableD17[iRankIntraModeLarger] = iDir;
+        m_uiIntraModeTableD17[iRankIntraMode] = iDirLarger;
+        m_uiIntraModeTableE17[iDir] = iRankIntraModeLarger;
+        m_uiIntraModeTableE17[iDirLarger] = iRankIntraMode;
+      }
+    }
+    xWriteCode(uiCode, uiLength);
+  }
+  else{
+    if (iDir==iMostProbable)
+    {
+      uiCode=huff34[0];
+      uiLength=lengthHuff34[0];
+    }
+    else{
+      if (iDir>iMostProbable)
+      {
+        iDir--;
+      }
+      iRankIntraMode=m_uiIntraModeTableE34[iDir];
+
+      uiCode=huff34[iRankIntraMode+1];
+      uiLength=lengthHuff34[iRankIntraMode+1];
+
+      if ( m_bAdaptFlag )
+      {
+        iRankIntraModeLarger = Max(0,iRankIntraMode-1);
+        iDirLarger = m_uiIntraModeTableD34[iRankIntraModeLarger];
+
+        m_uiIntraModeTableD34[iRankIntraModeLarger] = iDir;
+        m_uiIntraModeTableD34[iRankIntraMode] = iDirLarger;
+        m_uiIntraModeTableE34[iDir] = iRankIntraModeLarger;
+        m_uiIntraModeTableE34[iDirLarger] = iRankIntraMode;
+      }
+    }
+
+    xWriteCode(uiCode, uiLength);
+  }
+
+#if ADD_PLANAR_MODE
+  iDir = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  if ( (iDir == PLANAR_IDX) || (iDir == 2) )
+  {
+    xWriteFlag( planarFlag );
+  }
+#endif
+
+}
+#endif
+#else
+
+Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiDir         = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  Int  iMostProbable = pcCU->getMostProbableIntraDirLuma( uiAbsPartIdx );
+#if ADD_PLANAR_MODE
+  UInt planarFlag    = 0;
+  if (uiDir == PLANAR_IDX)
+  {
+    uiDir = 2;
+    planarFlag = 1;
+  }
+#endif
+
+  if (uiDir == iMostProbable)
+  {
+    xWriteFlag( 1 );
+  }
+  else
+  {
+    xWriteFlag( 0 );
+    uiDir = uiDir > iMostProbable ? uiDir - 1 : uiDir;
+    Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+    if ( g_aucIntraModeBitsAng[iIntraIdx] < 6 )
+    {
+      xWriteFlag( uiDir & 0x01 ? 1 : 0 );
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) xWriteFlag( uiDir & 0x02 ? 1 : 0 );
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) xWriteFlag( uiDir & 0x04 ? 1 : 0 );
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 4 ) xWriteFlag( uiDir & 0x08 ? 1 : 0 );
+    }
+    else
+    {
+      if (uiDir < 31)
+      { // uiDir is here 0...32, 5 bits for uiDir 0...30, 31 is an escape code for coding one more bit for 31 and 32
+        xWriteFlag( uiDir & 0x01 ? 1 : 0 );
+        xWriteFlag( uiDir & 0x02 ? 1 : 0 );
+        xWriteFlag( uiDir & 0x04 ? 1 : 0 );
+        xWriteFlag( uiDir & 0x08 ? 1 : 0 );
+        xWriteFlag( uiDir & 0x10 ? 1 : 0 );
+      }
+      else
+      {
+        xWriteFlag( 1 );
+        xWriteFlag( 1 );
+        xWriteFlag( 1 );
+        xWriteFlag( 1 );
+        xWriteFlag( 1 );
+        xWriteFlag( uiDir == 32 ? 1 : 0 );
+      }
+    }
+  }
+
+#if ADD_PLANAR_MODE
+  uiDir = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  if ( (uiDir == PLANAR_IDX) || (uiDir == 2) )
+  {
+    xWriteFlag( planarFlag );
+  }
+#endif
+
+}
+#endif
+
+Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiIntraDirChroma = pcCU->getChromaIntraDir   ( uiAbsPartIdx );
+#if ADD_PLANAR_MODE
+  UInt planarFlag       = 0;
+  if (uiIntraDirChroma == PLANAR_IDX)
+  {
+    uiIntraDirChroma = 2;
+    planarFlag = 1;
+  }
+#endif
+
+#if CHROMA_CODEWORD
+  UInt uiMode = pcCU->getLumaIntraDir(uiAbsPartIdx);
+#if ADD_PLANAR_MODE
+  if ( (uiMode == 2 ) || (uiMode == PLANAR_IDX) )
+  {
+    uiMode = 4;
+  }
+#endif
+#if LM_CHROMA
+  Bool bUseLMFlag = pcCU->getSlice()->getSPS()->getUseLMChroma();
+
+  Int  iMaxMode = bUseLMFlag ? 3 : 4;
+
+  Int  iMax = uiMode < iMaxMode ? 3 : 4;
+
+  //switch codeword
+  if (uiIntraDirChroma == 4)
+  {
+    uiIntraDirChroma = 0;
+  }
+  else if (uiIntraDirChroma == 3 && bUseLMFlag )
+  {
+    uiIntraDirChroma = 1;
+  }
+  else
+  {
+    if (uiIntraDirChroma < uiMode)
+      uiIntraDirChroma++;
+
+    if (bUseLMFlag)
+      uiIntraDirChroma++;
+#if CHROMA_CODEWORD_SWITCH
+    uiIntraDirChroma = ChromaMapping[iMax-3][uiIntraDirChroma];
+#endif
+  }
+
+  xWriteUnaryMaxSymbol( uiIntraDirChroma, iMax);
+
+#else //<--LM_CHROMA
+  Int  iMax = uiMode < 4 ? 3 : 4;
+
+  //switch codeword
+  if (uiIntraDirChroma == 4)
+  {
+    uiIntraDirChroma = 0;
+  }
+#if CHROMA_CODEWORD_SWITCH
+  else
+  {
+    if (uiIntraDirChroma < uiMode)
+    {
+      uiIntraDirChroma++;
+    }
+    uiIntraDirChroma = ChromaMapping[iMax-3][uiIntraDirChroma];
+  }
+#else
+  else if (uiIntraDirChroma < uiMode)
+  {
+    uiIntraDirChroma++;
+  }
+#endif
+  xWriteUnaryMaxSymbol( uiIntraDirChroma, iMax);
+#endif //<-- LM_CHROMA
+
+#else // CHROMA_CODEWORD
+  if ( 0 == uiIntraDirChroma )
+  {
+    xWriteFlag( 0 );
+  }
+  else
+  {
+    xWriteFlag( 1 );
+    xWriteUnaryMaxSymbol( uiIntraDirChroma - 1, 3 );
+  }
+#endif
+
+#if ADD_PLANAR_MODE
+  uiIntraDirChroma = pcCU->getChromaIntraDir( uiAbsPartIdx );
+#if CHROMA_CODEWORD
+  uiMode = pcCU->getLumaIntraDir(uiAbsPartIdx);
+  mapPlanartoDC( uiIntraDirChroma );
+  mapPlanartoDC( uiMode );
+  if ( (uiIntraDirChroma == 2) && (uiMode != 2) )
+#else
+  if ( (uiIntraDirChroma == PLANAR_IDX) || (uiIntraDirChroma == 2) )
+#endif
+  {
+    xWriteFlag( planarFlag );
+  }
+#endif
+  return;
+}
+
+Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiInterDir = pcCU->getInterDir   ( uiAbsPartIdx );
+  uiInterDir--;
+
+#if UNIFY_INTER_TABLE
+#if DCM_COMB_LIST
+  UInt uiNumRefIdxOfLC = pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C);
+#endif
+  #define min(a, b) (((a) < (b)) ? (a) : (b))
+#if DCM_COMB_LIST
+  UInt uiValNumRefIdxOfLC = min(4,pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C));
+#endif
+  UInt uiValNumRefIdxOfL0 = min(2,pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0));
+  UInt uiValNumRefIdxOfL1 = min(2,pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1));
+
+  if ( pcCU->getSlice()->getRefIdxCombineCoding() )
+  {
+#if CAVLC_COUNTER_ADAPT
+    Int x,cx;
+#else
+    Int x,cx,y,cy;
+#endif
+    Int iRefFrame0,iRefFrame1;
+    UInt uiIndex = 0;
+
+    UInt *m_uiMITableE;
+    UInt *m_uiMITableD;
+
+    m_uiMITableE = m_uiMI1TableE;
+    m_uiMITableD = m_uiMI1TableD;
+
+    UInt uiMaxVal;
+#if DCM_COMB_LIST
+    if (uiNumRefIdxOfLC > 0)
+    {
+      uiMaxVal = uiValNumRefIdxOfLC + uiValNumRefIdxOfL0*uiValNumRefIdxOfL1;
+    }
+    else
+#endif
+    if (m_pcSlice->getNoBackPredFlag())
+    {
+      uiMaxVal = uiValNumRefIdxOfL0 + uiValNumRefIdxOfL0*uiValNumRefIdxOfL1;
+    }
+    else
+    {
+      uiMaxVal = uiValNumRefIdxOfL0 + uiValNumRefIdxOfL1 + uiValNumRefIdxOfL0*uiValNumRefIdxOfL1;
+    }
+
+    if (uiInterDir==0)
+    {
+#if DCM_COMB_LIST
+      if(uiNumRefIdxOfLC > 0)
+      {
+        iRefFrame0 = pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx ));
+      }
+      else
+#endif
+      {
+        iRefFrame0 = pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx );
+      }
+      uiIndex = iRefFrame0;
+#if DCM_COMB_LIST
+      if(uiNumRefIdxOfLC > 0)
+      {
+        if ( iRefFrame0 >= 4 )
+        {
+          uiIndex = uiMaxVal;
+        }
+      }
+      else
+#endif
+      {
+        if ( iRefFrame0 > 1 )
+        {
+          uiIndex = uiMaxVal;
+        }
+      }
+    }
+    else if (uiInterDir==1)
+    {
+#if DCM_COMB_LIST
+      if(uiNumRefIdxOfLC > 0)
+      {
+        iRefFrame1 = pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx ));
+        uiIndex = iRefFrame1;
+      }
+      else
+#endif
+      {
+        iRefFrame1 = pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx );
+        uiIndex = uiValNumRefIdxOfL0 + iRefFrame1;
+      }
+#if DCM_COMB_LIST
+      if(uiNumRefIdxOfLC > 0)
+      {
+        if ( iRefFrame1 >= 4 )
+        {
+          uiIndex = uiMaxVal;
+        }
+      }
+      else
+#endif
+      {
+        if ( iRefFrame1 > 1 )
+        {
+          uiIndex = uiMaxVal;
+        }
+      }
+    }
+    else
+    {
+      iRefFrame0 = pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx );
+      iRefFrame1 = pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx );
+      if ( iRefFrame0 >= 2 || iRefFrame1 >= 2 )
+      {
+        uiIndex = uiMaxVal;
+      }
+      else
+      {
+  #if DCM_COMB_LIST
+        if(uiNumRefIdxOfLC > 0)
+        {
+          uiIndex = uiValNumRefIdxOfLC + iRefFrame0*uiValNumRefIdxOfL1 + iRefFrame1;
+        }
+        else
+  #endif
+        if (m_pcSlice->getNoBackPredFlag())
+        {
+          uiMaxVal = uiValNumRefIdxOfL0 + iRefFrame0*uiValNumRefIdxOfL1 + iRefFrame1;
+        }
+        else
+        {
+          uiIndex = uiValNumRefIdxOfL0 + uiValNumRefIdxOfL1 + iRefFrame0*uiValNumRefIdxOfL1 + iRefFrame1;
+        }
+      }
+    }
+
+    x = uiIndex;
+
+    cx = m_uiMITableE[x];
+
+    /* Adapt table */
+    if ( m_bAdaptFlag )
+    {
+#if CAVLC_COUNTER_ADAPT
+      adaptCodeword(cx, m_ucMI1TableCounter,  m_ucMI1TableCounterSum,   m_uiMITableD,  m_uiMITableE, 4);
+#else
+      cy = Max(0,cx-1);
+      y = m_uiMITableD[cy];
+      m_uiMITableD[cy] = x;
+      m_uiMITableD[cx] = y;
+      m_uiMITableE[x] = cy;
+      m_uiMITableE[y] = cx;
+      m_uiMITableVlcIdx += cx == m_uiMITableVlcIdx ? 0 : (cx < m_uiMITableVlcIdx ? -1 : 1);
+#endif
+    }
+
+    xWriteUnaryMaxSymbol( cx, uiMaxVal );
+
+    if ( x<uiMaxVal )
+    {
+      return;
+    }
+  }
+
+#else //UNIFY_INTER_TABLE
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  if ( pcCU->getSlice()->getRefIdxCombineCoding() )
+#else
+  if(pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 2 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 2)
+#endif
+  {
+#if CAVLC_COUNTER_ADAPT
+    Int x,cx;
+#else
+    Int x,cx,y,cy;
+#endif
+    Int iRefFrame0,iRefFrame1;
+    UInt uiIndex;
+
+    UInt *m_uiMITableE;
+    UInt *m_uiMITableD;
+    {
+      m_uiMITableE = m_uiMI1TableE;
+      m_uiMITableD = m_uiMI1TableD;
+      if (uiInterDir==0)
+      {
+#if DCM_COMB_LIST
+        if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+        {
+          iRefFrame0 = pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx ));
+        }
+        else
+        {
+          iRefFrame0 = pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx );
+        }
+#else
+        iRefFrame0 = pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx );
+#endif
+        uiIndex = iRefFrame0;
+
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+        if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+        {
+          if ( iRefFrame0 >= 4 )
+          {
+            uiIndex = 8;
+          }
+        }
+        else
+        {
+          if ( iRefFrame0 > MS_LCEC_UNI_EXCEPTION_THRES )
+          {
+            uiIndex = 8;
+          }
+        }
+#endif
+      }
+      else if (uiInterDir==1)
+      {
+#if DCM_COMB_LIST
+        if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+        {
+          iRefFrame1 = pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx ));
+          uiIndex = iRefFrame1;
+        }
+        else
+        {
+          iRefFrame1 = pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx );
+          uiIndex = 2 + iRefFrame1;
+        }
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+        if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+        {
+          if ( iRefFrame1 >= 4 )
+          {
+            uiIndex = 8;
+          }
+        }
+        else
+        {
+          if ( iRefFrame1 > MS_LCEC_UNI_EXCEPTION_THRES )
+          {
+            uiIndex = 8;
+          }
+        }
+#endif
+#else
+        iRefFrame1 = pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx );
+        uiIndex = 2 + iRefFrame1;
+#endif
+      }
+      else
+      {
+        iRefFrame0 = pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx );
+        iRefFrame1 = pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx );
+        uiIndex = 4 + 2*iRefFrame0 + iRefFrame1;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+        if ( iRefFrame0 >= 2 || iRefFrame1 >= 2 )
+        {
+          uiIndex = 8;
+        }
+#endif
+      }
+    }
+
+    x = uiIndex;
+
+    cx = m_uiMITableE[x];
+
+    /* Adapt table */
+#if !MS_LCEC_LOOKUP_TABLE_MAX_VALUE
+    UInt vlcn = g_auiMITableVlcNum[m_uiMITableVlcIdx];
+#endif
+    if ( m_bAdaptFlag )
+    {
+#if CAVLC_COUNTER_ADAPT
+      adaptCodeword(cx, m_ucMI1TableCounter,  m_ucMI1TableCounterSum,   m_uiMITableD,  m_uiMITableE, 4);
+#else
+      cy = Max(0,cx-1);
+      y = m_uiMITableD[cy];
+      m_uiMITableD[cy] = x;
+      m_uiMITableD[cx] = y;
+      m_uiMITableE[x] = cy;
+      m_uiMITableE[y] = cx;
+      m_uiMITableVlcIdx += cx == m_uiMITableVlcIdx ? 0 : (cx < m_uiMITableVlcIdx ? -1 : 1);
+#endif
+    }
+
+    {
+#if MS_LCEC_LOOKUP_TABLE_MAX_VALUE
+      UInt uiMaxVal = 7;
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+      uiMaxVal = 8;
+#endif
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 1 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 1 )
+      {
+        if ( pcCU->getSlice()->getNoBackPredFlag() || ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 1 ) )
+        {
+          uiMaxVal = 1;
+        }
+        else
+        {
+          uiMaxVal = 2;
+        }
+      }
+      else if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 2 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 2 )
+      {
+        if ( pcCU->getSlice()->getNoBackPredFlag() || ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 2 ) )
+        {
+          uiMaxVal = 5;
+        }
+        else
+        {
+          uiMaxVal = 7;
+        }
+      }
+      else if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0 ) // GPB case
+      {
+        uiMaxVal = 4+1+MS_LCEC_UNI_EXCEPTION_THRES;
+      }
+
+      xWriteUnaryMaxSymbol( cx, uiMaxVal );
+#else
+      xWriteVlc( vlcn, cx );
+#endif
+    }
+
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+    if ( x<8 )
+#endif
+    {
+      return;
+    }
+  }
+#endif //UNIFY_INTER_TABLE
+
+  xWriteFlag( ( uiInterDir == 2 ? 1 : 0 ));
+  if ( pcCU->getSlice()->getNoBackPredFlag() )
+  {
+    assert( uiInterDir != 1 );
+    return;
+  }
+#if DCM_COMB_LIST
+  if ( uiInterDir < 2 && pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0)
+#else
+  if ( uiInterDir < 2 )
+#endif
+  {
+    xWriteFlag( uiInterDir );
+  }
+
+  return;
+}
+
+Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+#if DCM_COMB_LIST
+  Int iRefFrame;
+  RefPicList eRefListTemp;
+
+  if( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C)>0)
+  {
+    if ( pcCU->getInterDir( uiAbsPartIdx ) != 3)
+    {
+      eRefListTemp = REF_PIC_LIST_C;
+      iRefFrame = pcCU->getSlice()->getRefIdxOfLC(eRefList, pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx ));
+    }
+    else
+    {
+      eRefListTemp = eRefList;
+      iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
+    }
+  }
+  else
+  {
+    eRefListTemp = eRefList;
+    iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
+  }
+#else
+  Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
+#endif
+
+  if (pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) <= 2 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) <= 2 && pcCU->getSlice()->isInterB())
+  {
+    return;
+  }
+
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  if ( pcCU->getSlice()->getRefIdxCombineCoding() && pcCU->getInterDir(uiAbsPartIdx)==3 &&
+      pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx ) < 2 &&
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx ) < 2 )
+  {
+    return;
+  }
+  else if ( pcCU->getSlice()->getRefIdxCombineCoding() && pcCU->getInterDir(uiAbsPartIdx)==1 &&
+           ( ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C)>0  && pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_0, pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx )) < 4 ) ||
+            ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C)<=0 && pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx ) <= MS_LCEC_UNI_EXCEPTION_THRES ) ) )
+  {
+    return;
+  }
+  else if ( pcCU->getSlice()->getRefIdxCombineCoding() && pcCU->getInterDir(uiAbsPartIdx)==2 && pcCU->getSlice()->getRefIdxOfLC(REF_PIC_LIST_1, pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx )) < 4 )
+  {
+    return;
+  }
+
+  UInt uiRefFrmIdxMinus = 0;
+  if ( pcCU->getSlice()->getRefIdxCombineCoding() )
+  {
+    if ( pcCU->getInterDir( uiAbsPartIdx ) != 3 )
+    {
+      if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 )
+      {
+        uiRefFrmIdxMinus = 4;
+        assert( iRefFrame >=4 );
+      }
+      else
+      {
+        uiRefFrmIdxMinus = MS_LCEC_UNI_EXCEPTION_THRES+1;
+        assert( iRefFrame > MS_LCEC_UNI_EXCEPTION_THRES );
+      }
+
+    }
+    else if ( eRefList == REF_PIC_LIST_1 && pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx ) < 2 )
+    {
+      uiRefFrmIdxMinus = 2;
+      assert( iRefFrame >= 2 );
+    }
+  }
+
+  if ( pcCU->getSlice()->getNumRefIdx( eRefListTemp ) - uiRefFrmIdxMinus <= 1 )
+  {
+    return;
+  }
+  xWriteFlag( ( iRefFrame - uiRefFrmIdxMinus == 0 ? 0 : 1 ) );
+#else
+  xWriteFlag( ( iRefFrame == 0 ? 0 : 1 ) );
+#endif
+
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  if ( iRefFrame - uiRefFrmIdxMinus > 0 )
+#else
+  if ( iRefFrame > 0 )
+#endif
+  {
+    {
+#if DCM_COMB_LIST
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+      xWriteUnaryMaxSymbol( iRefFrame - 1 - uiRefFrmIdxMinus, pcCU->getSlice()->getNumRefIdx( eRefListTemp )-2 - uiRefFrmIdxMinus );
+#else
+      xWriteUnaryMaxSymbol( iRefFrame - 1, pcCU->getSlice()->getNumRefIdx( eRefListTemp )-2 );
+#endif
+#else
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+      xWriteUnaryMaxSymbol( iRefFrame - 1 - uiRefFrmIdxMinus, pcCU->getSlice()->getNumRefIdx( eRefList )-2 - uiRefFrmIdxMinus );
+#else
+      xWriteUnaryMaxSymbol( iRefFrame - 1, pcCU->getSlice()->getNumRefIdx( eRefList )-2 );
+#endif
+#endif
+    }
+  }
+  return;
+}
+
+Void TEncCavlc::codeViewIdx(Int iViewIdx)
+{
+  xWriteUnaryMaxSymbol(iViewIdx, MAX_NUMBER_VIEWS   );
+}
+
+Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  TComCUMvField* pcCUMvField = pcCU->getCUMvField( eRefList );
+  Int iHor = pcCUMvField->getMvd( uiAbsPartIdx ).getHor();
+  Int iVer = pcCUMvField->getMvd( uiAbsPartIdx ).getVer();
+
+  UInt uiAbsPartIdxL, uiAbsPartIdxA;
+  Int iHorPred, iVerPred;
+
+  TComDataCU* pcCUL   = pcCU->getPULeft ( uiAbsPartIdxL, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  TComDataCU* pcCUA   = pcCU->getPUAbove( uiAbsPartIdxA, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+
+  TComCUMvField* pcCUMvFieldL = ( pcCUL == NULL || pcCUL->isIntra( uiAbsPartIdxL ) ) ? NULL : pcCUL->getCUMvField( eRefList );
+  TComCUMvField* pcCUMvFieldA = ( pcCUA == NULL || pcCUA->isIntra( uiAbsPartIdxA ) ) ? NULL : pcCUA->getCUMvField( eRefList );
+  iHorPred = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsHor() ) +
+  ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsHor() );
+  iVerPred = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsVer() ) +
+  ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsVer() );
+
+  xWriteSvlc( iHor );
+  xWriteSvlc( iVer );
+
+  return;
+}
+
+Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getSlice()->getSliceQp();
+
+  if ( iDQp == 0 )
+  {
+    xWriteFlag( 0 );
+  }
+  else
+  {
+    xWriteFlag( 1 );
+    xWriteSvlc( iDQp );
+  }
+
+  return;
+}
+
+#if CAVLC_RQT_CBP
+/** Function for coding cbf and split flag
+* \param pcCU pointer to CU
+* \param uiAbsPartIdx CU index
+* \param uiDepth CU Depth
+* \returns
+* This function performs coding of cbf and split flag
+*/
+Void TEncCavlc::codeCbfTrdiv( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt n,cx;
+  UInt uiTrDepth = uiDepth - pcCU->getDepth(uiAbsPartIdx);
+  UInt uiCBFY = pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, uiTrDepth);
+  UInt uiCBFU = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth);
+  UInt uiCBFV = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth);
+  UInt uiQPartNumParent  = pcCU->getPic()->getNumPartInCU() >> ((uiDepth-1) << 1);
+  UInt uiQPartNumCurr    = pcCU->getPic()->getNumPartInCU() >> ((uiDepth) << 1);
+
+  const UInt uiSubdiv = pcCU->getTransformIdx( uiAbsPartIdx ) + pcCU->getDepth( uiAbsPartIdx ) > uiDepth;
+  UInt uiFlagPattern = xGetFlagPattern( pcCU, uiAbsPartIdx, uiDepth );
+  n = pcCU->isIntra( uiAbsPartIdx ) ? 0 : 1;
+
+  if(uiFlagPattern < 8)
+  {
+    UInt uiFullDepth = pcCU->getDepth(uiAbsPartIdx) + uiTrDepth;
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    if( uiLog2TrSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      UInt uiCBFU_Parent = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth-1);
+      UInt uiCBFV_Parent = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth-1);
+      if(uiCBFU_Parent)
+      {
+        xWriteFlag(uiCBFU);
+      }
+      if(uiCBFV_Parent)
+      {
+        xWriteFlag(uiCBFV);
+      }
+    }
+
+    if(uiFlagPattern & 0x01)
+    {
+      codeTransformSubdivFlag( uiSubdiv, 0);
+    }
+  }
+  else
+  {
+    if(uiFlagPattern == 8)
+    {
+      if (uiAbsPartIdx % uiQPartNumParent ==0)
+      {
+        codeBlockCbf(pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrDepth, uiQPartNumCurr);
+      }
+    }
+    else if(uiFlagPattern == 9)
+    {
+      bool bNeedToCode = true;
+      if ( n==1 && (uiAbsPartIdx%uiQPartNumParent) / uiQPartNumCurr == 3 )
+      {
+        UInt uiTempAbsPartIdx = uiAbsPartIdx/uiQPartNumParent*uiQPartNumParent;
+        if ( pcCU->getCbf( uiTempAbsPartIdx + uiQPartNumCurr*0, TEXT_LUMA, uiTrDepth ) ||
+          pcCU->getCbf( uiTempAbsPartIdx + uiQPartNumCurr*1, TEXT_LUMA, uiTrDepth ) ||
+          pcCU->getCbf( uiTempAbsPartIdx + uiQPartNumCurr*2, TEXT_LUMA, uiTrDepth ) )
+        {
+          bNeedToCode = true;
+        }
+        else
+        {
+          bNeedToCode = false;
+          xWriteFlag( uiSubdiv );
+        }
+      }
+      if ( bNeedToCode )
+      {
+        cx = m_uiCBP_YS_TableE[n][(uiCBFY<<1)+uiSubdiv];
+        xWriteUnaryMaxSymbol(cx,n?2:3);//intra 3; inter 2
+
+        if ( m_bAdaptFlag )
+        {
+          adaptCodeword(cx, m_ucCBP_YS_TableCounter[n],  m_ucCBP_YS_TableCounterSum[n],  m_uiCBP_YS_TableD[n],  m_uiCBP_YS_TableE[n], 3);
+        }
+      }
+    }
+    else if( uiFlagPattern == 14)
+    {
+      UInt  uiIdx = uiTrDepth? (2 + n) : n;
+      cx = m_uiCBP_YUV_TableE[uiIdx][(uiCBFV<<0) + (uiCBFU<<1) + (uiCBFY<<2)];
+      xWriteUnaryMaxSymbol(cx,7);
+
+      if ( m_bAdaptFlag )
+      {
+        adaptCodeword(cx,  m_ucCBP_YUV_TableCounter[uiIdx],  m_ucCBP_YUV_TableCounterSum[uiIdx],  m_uiCBP_YUV_TableD[uiIdx],  m_uiCBP_YUV_TableE[uiIdx], 4);
+      }
+    }
+    else if ( uiFlagPattern == 11 || uiFlagPattern == 13 || uiFlagPattern == 15 )
+    {
+      cx = m_uiCBP_YCS_TableE[n][(uiCBFY<<2)+((uiCBFU||uiCBFV?1:0)<<1)+uiSubdiv];
+      xWriteCode(g_auiCBP_YCS_Table[n][cx], g_auiCBP_YCS_TableLen[n][cx]);
+
+      if ( m_bAdaptFlag )
+      {
+        adaptCodeword(cx, m_ucCBP_YCS_TableCounter[n],  m_ucCBP_YCS_TableCounterSum[n],  m_uiCBP_YCS_TableD[n],  m_uiCBP_YCS_TableE[n], 4);
+      }
+
+      //U and V
+      if ( uiFlagPattern == 15)
+      {
+        UInt uiCBFUV = (uiCBFU<<1) + uiCBFV;
+        if(uiCBFUV > 0)
+        {
+          xWriteUnaryMaxSymbol(n? (uiCBFUV - 1) : (3-uiCBFUV), 2);
+        }
+      }
+    }
+    else if (uiFlagPattern == 10 || uiFlagPattern == 12)
+    {
+      xWriteUnaryMaxSymbol(g_auiCBP_YC_TableE[n][(uiCBFY<<1)+(uiCBFU||uiCBFV?1:0)],3);//intra 3; inter 2
+    }
+  }
+  return;
+}
+
+
+/** Function for parsing cbf and split
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU Depth
+ * \returns flag pattern
+ * This function gets flagpattern for cbf and split flag
+ */
+UInt TEncCavlc::xGetFlagPattern( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
+  UInt uiTrDepth =  uiDepth - pcCU->getDepth( uiAbsPartIdx );
+  UInt patternYUV, patternDiv;
+  UInt bY, bU, bV;
+
+  UInt uiFullDepth = uiDepth;
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  if(uiTrDepth == 0)
+  {
+    patternYUV = 7;
+  }
+  else if( uiLog2TrSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    bY = pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, uiTrDepth - 1)?1:0;
+    bU = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1)?1:0;
+    bV = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1)?1:0;
+    patternYUV = (bY<<2) + (bU<<1) + bV;
+  }
+  else
+  {
+    bY = pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, uiTrDepth - 1)?1:0;
+    patternYUV = bY<<2;
+  }
+
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    patternDiv = 0;
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    patternDiv = 0;
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    patternDiv = 0;
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    patternDiv = 0;
+  }
+  else
+  {
+    patternDiv = 1;
+  }
+  return ((patternYUV<<1)+patternDiv);
+}
+#endif
+
+Void TEncCavlc::codeCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  if (eType == TEXT_ALL)
+  {
+#if CAVLC_COUNTER_ADAPT
+    Int n,x,cx;
+#else
+    Int n,x,cx,y,cy;
+#endif
+
+    UInt uiCBFY = pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, 0);
+    UInt uiCBFU = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, 0);
+    UInt uiCBFV = pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, 0);
+    UInt uiCBP = (uiCBFV<<2) + (uiCBFU<<1) + (uiCBFY<<0);
+
+    /* Start adaptation */
+    n = pcCU->isIntra( uiAbsPartIdx ) ? 0 : 1;
+    x = uiCBP;
+#if CAVLC_RQT_CBP
+    cx = m_uiCBP_YUV_TableE[n][x];
+    UInt vlcn = 0;
+#else
+    cx = m_uiCBPTableE[n][x];
+    UInt vlcn = g_auiCbpVlcNum[n][m_uiCbpVlcIdx[n]];
+#endif
+
+    if ( m_bAdaptFlag )
+    {
+#if CAVLC_COUNTER_ADAPT
+#if CAVLC_RQT_CBP
+      adaptCodeword(cx, m_ucCBP_YUV_TableCounter[n], m_ucCBP_YUV_TableCounterSum[n], m_uiCBP_YUV_TableD[n], m_uiCBP_YUV_TableE[n], 4);
+#else
+      adaptCodeword(cx, m_ucCBFTableCounter[n],  m_ucCBFTableCounterSum[n],  m_uiCBPTableD[n],  m_uiCBPTableE[n], 4);
+#endif
+#else
+      cy = Max(0,cx-1);
+      y = m_uiCBPTableD[n][cy];
+      m_uiCBPTableD[n][cy] = x;
+      m_uiCBPTableD[n][cx] = y;
+      m_uiCBPTableE[n][x] = cy;
+      m_uiCBPTableE[n][y] = cx;
+      m_uiCbpVlcIdx[n] += cx == m_uiCbpVlcIdx[n] ? 0 : (cx < m_uiCbpVlcIdx[n] ? -1 : 1);
+#endif
+    }
+    xWriteVlc( vlcn, cx );
+  }
+}
+
+Void TEncCavlc::codeBlockCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiQPartNum, Bool bRD )
+{
+  UInt uiCbf0 = pcCU->getCbf   ( uiAbsPartIdx, eType, uiTrDepth );
+  UInt uiCbf1 = pcCU->getCbf   ( uiAbsPartIdx + uiQPartNum, eType, uiTrDepth );
+  UInt uiCbf2 = pcCU->getCbf   ( uiAbsPartIdx + uiQPartNum*2, eType, uiTrDepth );
+  UInt uiCbf3 = pcCU->getCbf   ( uiAbsPartIdx + uiQPartNum*3, eType, uiTrDepth );
+  UInt uiCbf = (uiCbf0<<3) | (uiCbf1<<2) | (uiCbf2<<1) | uiCbf3;
+
+  assert(uiTrDepth > 0);
+
+  if(bRD && uiCbf==0)
+  {
+    xWriteCode(0, 4);
+    return;
+  }
+
+  assert(uiCbf > 0);
+
+  uiCbf --;
+
+#if CAVLC_COUNTER_ADAPT
+  Int x,cx;
+#else
+  Int x,cx,y,cy;
+#endif
+
+  UInt n = (pcCU->isIntra(uiAbsPartIdx) && eType == TEXT_LUMA)? 0:1;
+  x = uiCbf;
+
+#if CAVLC_RQT_CBP
+  cx = m_uiCBP_4Y_TableE[n][uiCbf];
+  UInt vlcn = (n==0)?g_auiCBP_4Y_VlcNum[m_uiCBP_4Y_VlcIdx]:11;
+#else
+  cx = m_uiBlkCBPTableE[n][uiCbf];
+  UInt vlcn = (n==0)?g_auiBlkCbpVlcNum[m_uiBlkCbpVlcIdx]:11;
+#endif
+
+
+  if ( m_bAdaptFlag )
+  {
+
+#if CAVLC_COUNTER_ADAPT
+#if CAVLC_RQT_CBP
+    adaptCodeword(cx, m_ucCBP_4Y_TableCounter[n],  m_ucCBP_4Y_TableCounterSum[n],  m_uiCBP_4Y_TableD[n],  m_uiCBP_4Y_TableE[n], 2);
+#else
+    adaptCodeword(cx, m_ucBlkCBPTableCounter[n],  m_ucBlkCBPTableCounterSum[n],  m_uiBlkCBPTableD[n],  m_uiBlkCBPTableE[n], 2);
+#endif
+#else
+    cy = Max(0,cx-1);
+    y = m_uiBlkCBPTableD[n][cy];
+    m_uiBlkCBPTableD[n][cy] = x;
+    m_uiBlkCBPTableD[n][cx] = y;
+    m_uiBlkCBPTableE[n][x] = cy;
+    m_uiBlkCBPTableE[n][y] = cx;
+#endif
+
+#if CAVLC_RQT_CBP
+    if(n==0)
+      m_uiCBP_4Y_VlcIdx += cx == m_uiCBP_4Y_VlcIdx ? 0 : (cx < m_uiCBP_4Y_VlcIdx ? -1 : 1);
+#else
+    if(n==0)
+      m_uiBlkCbpVlcIdx += cx == m_uiBlkCbpVlcIdx ? 0 : (cx < m_uiBlkCbpVlcIdx ? -1 : 1);
+#endif
+  }
+
+  xWriteVlc( vlcn, cx );
+  return;
+}
+
+Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType, Bool bRD )
+{
+  if ( uiWidth > m_pcSlice->getSPS()->getMaxTrSize() )
+  {
+    uiWidth  = m_pcSlice->getSPS()->getMaxTrSize();
+    uiHeight = m_pcSlice->getSPS()->getMaxTrSize();
+  }
+  UInt uiSize   = uiWidth*uiHeight;
+
+  // point to coefficient
+  TCoeff* piCoeff = pcCoef;
+  UInt uiNumSig = 0;
+  UInt uiScanning;
+
+  // compute number of significant coefficients
+  UInt  uiPart = 0;
+  xCheckCoeff(piCoeff, uiWidth, 0, uiNumSig, uiPart );
+
+  if ( bRD )
+  {
+    UInt uiTempDepth = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+    pcCU->setCbfSubParts( ( uiNumSig ? 1 : 0 ) << uiTempDepth, eTType, uiAbsPartIdx, uiDepth );
+    codeCbf( pcCU, uiAbsPartIdx, eTType, uiTempDepth );
+  }
+
+  if ( uiNumSig == 0 )
+  {
+    return;
+  }
+
+  // initialize scan
+  const UInt*  pucScan;
+
+#if CAVLC_COEF_LRG_BLK
+  UInt maxBlSize = (eTType==TEXT_LUMA)?32:8;
+  UInt uiBlSize = Min(maxBlSize,uiWidth);
+  UInt uiConvBit = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth :uiBlSize];
+  UInt uiNoCoeff = uiBlSize*uiBlSize;
+#else
+  //UInt uiConvBit = g_aucConvertToBit[ Min(8,uiWidth)    ];
+  UInt uiConvBit = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : Min(8,uiWidth)    ];
+#endif
+  pucScan        = g_auiFrameScanXY [ uiConvBit + 1 ];
+
+#if QC_MDCS
+  UInt uiBlkPos;
+#if CAVLC_COEF_LRG_BLK
+  UInt uiLog2BlkSize = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : uiBlSize] + 2;
+#else
+  UInt uiLog2BlkSize = g_aucConvertToBit[ pcCU->isIntra( uiAbsPartIdx ) ? uiWidth : Min(8,uiWidth)    ] + 2;
+#endif
+  const UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+#endif //QC_MDCS
+
+#if CAVLC_COEF_LRG_BLK
+  static TCoeff scoeff[1024];
+#else
+  TCoeff scoeff[64];
+#endif
+  Int iBlockType;
+  UInt uiCodeDCCoef = 0;
+  TCoeff dcCoeff = 0;
+  if (pcCU->isIntra(uiAbsPartIdx))
+  {
+    UInt uiAbsPartIdxL, uiAbsPartIdxA;
+    TComDataCU* pcCUL   = pcCU->getPULeft (uiAbsPartIdxL, pcCU->getZorderIdxInCU() + uiAbsPartIdx);
+    TComDataCU* pcCUA   = pcCU->getPUAbove(uiAbsPartIdxA, pcCU->getZorderIdxInCU() + uiAbsPartIdx);
+    if (pcCUL == NULL && pcCUA == NULL)
+    {
+      uiCodeDCCoef = 1;
+      xWriteVlc((eTType == TEXT_LUMA ? 3 : 1) , abs(piCoeff[0]));
+      if (piCoeff[0] != 0)
+      {
+        UInt sign = (piCoeff[0] < 0) ? 1 : 0;
+        xWriteFlag(sign);
+      }
+      dcCoeff = piCoeff[0];
+      piCoeff[0] = 1;
+    }
+  }
+
+  if( uiSize == 2*2 )
+  {
+    // hack: re-use 4x4 coding
+    ::memset( scoeff, 0, 16*sizeof(TCoeff) );
+    for (uiScanning=0; uiScanning<4; uiScanning++)
+    {
+#if QC_MDCS
+      uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+      scoeff[15-uiScanning] = piCoeff[ uiBlkPos ];
+#else
+      scoeff[15-uiScanning] = piCoeff[ pucScan[ uiScanning ] ];
+#endif //QC_MDCS
+    }
+#if QC_MOD_LCEC
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+#else
+    iBlockType = pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType();
+#endif
+
+#if CAVLC_COEF_LRG_BLK
+    xCodeCoeff( scoeff, iBlockType, 4 );
+#else
+    xCodeCoeff4x4( scoeff, iBlockType );
+#endif
+  }
+  else if ( uiSize == 4*4 )
+  {
+    for (uiScanning=0; uiScanning<16; uiScanning++)
+    {
+#if QC_MDCS
+      uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+      scoeff[15-uiScanning] = piCoeff[ uiBlkPos ];
+#else
+      scoeff[15-uiScanning] = piCoeff[ pucScan[ uiScanning ] ];
+#endif //QC_MDCS
+    }
+#if QC_MOD_LCEC
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+#else
+    iBlockType = pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType();
+#endif
+
+#if CAVLC_COEF_LRG_BLK
+    xCodeCoeff( scoeff, iBlockType, 4 );
+#else
+    xCodeCoeff4x4( scoeff, iBlockType );
+#endif
+  }
+  else if ( uiSize == 8*8 )
+  {
+    for (uiScanning=0; uiScanning<64; uiScanning++)
+    {
+#if QC_MDCS
+      uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+      scoeff[63-uiScanning] = piCoeff[ uiBlkPos ];
+#else
+      scoeff[63-uiScanning] = piCoeff[ pucScan[ uiScanning ] ];
+#endif //QC_MDCS
+    }
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+      iBlockType = eTType-2;
+    else
+      iBlockType = 2 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+
+#if CAVLC_COEF_LRG_BLK
+    xCodeCoeff( scoeff, iBlockType, 8 );
+#else
+    xCodeCoeff8x8( scoeff, iBlockType );
+#endif
+  }
+  else
+  {
+    if(!pcCU->isIntra( uiAbsPartIdx ))
+    {
+#if CAVLC_COEF_LRG_BLK
+      UInt uiBlSizeInBit = g_aucConvertToBit[uiBlSize] + 2;
+      UInt uiWidthInBit = g_aucConvertToBit[uiWidth] + 2;
+      for (uiScanning=0; uiScanning<uiNoCoeff; uiScanning++)
+      {
+#if QC_MDCS
+        uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+        uiBlkPos = ((uiBlkPos>>uiBlSizeInBit) <<uiWidthInBit) + (uiBlkPos&(uiBlSize-1));
+        scoeff[uiNoCoeff-uiScanning-1] = piCoeff[ uiBlkPos ];
+#else
+        scoeff[uiNoCoeff-uiScanning-1] = piCoeff[((pucScan[uiScanning]>>uiBlSizeInBit)<<uiWidthInBit) + (pucScan[uiScanning]&(uiBlSize-1))];
+#endif
+      }
+#else
+      for (uiScanning=0; uiScanning<64; uiScanning++)
+      {
+#if QC_MDCS
+      uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+      uiBlkPos = (uiBlkPos/8) * uiWidth + uiBlkPos%8;
+      scoeff[63-uiScanning] = piCoeff[ uiBlkPos ];
+#else
+        scoeff[63-uiScanning] = piCoeff[(pucScan[uiScanning]/8)*uiWidth + (pucScan[uiScanning]%8)];
+#endif //QC_MDCS
+      }
+      if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+        iBlockType = eTType-2;
+      else
+        iBlockType = 5 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+      xCodeCoeff8x8( scoeff, iBlockType );
+      return;
+#endif
+    }
+
+    if(pcCU->isIntra( uiAbsPartIdx ))
+    {
+#if CAVLC_COEF_LRG_BLK
+      for (uiScanning=0; uiScanning<uiNoCoeff; uiScanning++)
+      {
+#if QC_MDCS
+        uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+        scoeff[uiNoCoeff-uiScanning-1] = piCoeff[ uiBlkPos ];
+#else
+        scoeff[uiNoCoeff-uiScanning-1] = piCoeff[ pucScan[ uiScanning ] ];
+#endif
+      }
+#else
+      for (uiScanning=0; uiScanning<64; uiScanning++)
+      {
+#if QC_MDCS
+      uiBlkPos = g_auiSigLastScan[uiScanIdx][uiLog2BlkSize-1][uiScanning];
+      scoeff[63-uiScanning] = piCoeff[ uiBlkPos ];
+#else
+        scoeff[63-uiScanning] = piCoeff[ pucScan[ uiScanning ] ];
+#endif //QC_MDCS
+      }
+
+      if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+        iBlockType = eTType-2;
+      else
+        iBlockType = 5 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+      xCodeCoeff8x8( scoeff, iBlockType );
+#endif
+    }
+
+#if CAVLC_COEF_LRG_BLK
+    if (eTType==TEXT_CHROMA_U || eTType==TEXT_CHROMA_V)
+    {
+      iBlockType = eTType-2;
+    }
+    else
+    {
+      iBlockType = 5 + ( pcCU->isIntra(uiAbsPartIdx) ? 0 : pcCU->getSlice()->getSliceType() );
+    }
+    xCodeCoeff( scoeff, iBlockType, uiBlSize);
+#endif
+
+    //#endif
+  }
+
+  if (uiCodeDCCoef == 1)
+  {
+    piCoeff[0] = dcCoeff;
+  }
+}
+
+Void TEncCavlc::codeAlfFlag( UInt uiCode )
+{
+
+  xWriteFlag( uiCode );
+}
+
+#if TSB_ALF_HEADER
+Void TEncCavlc::codeAlfFlagNum( UInt uiCode, UInt minValue )
+{
+  UInt uiLength = 0;
+  UInt maxValue = (minValue << (this->getMaxAlfCtrlDepth()*2));
+  assert((uiCode>=minValue)&&(uiCode<=maxValue));
+  UInt temp = maxValue - minValue;
+  for(UInt i=0; i<32; i++)
+  {
+    if(temp&0x1)
+    {
+      uiLength = i+1;
+    }
+    temp = (temp >> 1);
+  }
+  if(uiLength)
+  {
+    xWriteCode( uiCode - minValue, uiLength );
+  }
+}
+
+Void TEncCavlc::codeAlfCtrlFlag( UInt uiSymbol )
+{
+  xWriteFlag( uiSymbol );
+}
+#endif
+
+Void TEncCavlc::codeAlfUvlc( UInt uiCode )
+{
+  xWriteUvlc( uiCode );
+}
+
+Void TEncCavlc::codeAlfSvlc( Int iCode )
+{
+  xWriteSvlc( iCode );
+}
+#if MTK_SAO
+Void TEncCavlc::codeAoFlag( UInt uiCode )
+{
+
+  xWriteFlag( uiCode );
+#if LCEC_STAT
+  if (m_bAdaptFlag)
+    m_uiBitAlfFlag += 1;
+#endif
+}
+
+Void TEncCavlc::codeAoUvlc( UInt uiCode )
+{
+#if LCEC_STAT
+  if (m_bAdaptFlag)
+    m_uiBitAlfUvlc += xWriteUvlc( uiCode );
+  else
+#endif
+    xWriteUvlc( uiCode );
+}
+
+Void TEncCavlc::codeAoSvlc( Int iCode )
+{
+#if LCEC_STAT
+  if (m_bAdaptFlag)
+    m_uiBitAlfSvlc += xWriteSvlc( iCode );
+  else
+#endif
+    xWriteSvlc( iCode );
+}
+
+#endif
+
+Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, UInt uiCTXIdx, 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 );
+}
+
+Void TEncCavlc::xWriteSvlc     ( Int iCode )
+{
+  UInt uiCode;
+
+  uiCode = xConvertToUInt( iCode );
+  xWriteUvlc( uiCode );
+}
+
+Void TEncCavlc::xWriteFlag( UInt uiCode )
+{
+  m_pcBitIf->write( uiCode, 1 );
+}
+
+Void TEncCavlc::xCheckCoeff( TCoeff* pcCoef, UInt uiSize, UInt uiDepth, UInt& uiNumofCoeff, UInt& uiPart )
+{
+  UInt ui = uiSize>>uiDepth;
+  if( uiPart == 0 )
+  {
+    if( ui <= 4 )
+    {
+      UInt x, y;
+      TCoeff* pCeoff = pcCoef;
+      for( y=0 ; y<ui ; y++ )
+      {
+        for( x=0 ; x<ui ; x++ )
+        {
+          if( pCeoff[x] != 0 )
+          {
+            uiNumofCoeff++;
+          }
+        }
+        pCeoff += uiSize;
+      }
+    }
+    else
+    {
+      xCheckCoeff( pcCoef,                            uiSize, uiDepth+1, uiNumofCoeff, uiPart ); uiPart++; //1st Part
+      xCheckCoeff( pcCoef             + (ui>>1),      uiSize, uiDepth+1, uiNumofCoeff, uiPart ); uiPart++; //2nd Part
+      xCheckCoeff( pcCoef + (ui>>1)*uiSize,           uiSize, uiDepth+1, uiNumofCoeff, uiPart ); uiPart++; //3rd Part
+      xCheckCoeff( pcCoef + (ui>>1)*uiSize + (ui>>1), uiSize, uiDepth+1, uiNumofCoeff, uiPart );           //4th Part
+    }
+  }
+  else
+  {
+    UInt x, y;
+    TCoeff* pCeoff = pcCoef;
+    for( y=0 ; y<ui ; y++ )
+    {
+      for( x=0 ; x<ui ; x++ )
+      {
+        if( pCeoff[x] != 0 )
+        {
+          uiNumofCoeff++;
+        }
+      }
+      pCeoff += uiSize;
+    }
+  }
+}
+
+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;
+}
+
+#if !QC_MOD_LCEC_RDOQ
+UInt TEncCavlc::xLeadingZeros(UInt uiCode)
+{
+  UInt uiCount = 0;
+  Int iDone = 0;
+
+  if (uiCode)
+  {
+    while (!iDone)
+    {
+      uiCode >>= 1;
+      if (!uiCode) iDone = 1;
+      else uiCount++;
+    }
+  }
+  return uiCount;
+}
+#endif
+
+Void TEncCavlc::xWriteVlc(UInt uiTableNumber, UInt uiCodeNumber)
+{
+#if CAVLC_COEF_LRG_BLK
+  assert( uiTableNumber<=13 );
+#else
+  assert( uiTableNumber<=11 );
+#endif
+
+  UInt uiTemp;
+  UInt uiLength = 0;
+  UInt uiCode = 0;
+
+  if ( uiTableNumber < 5 )
+  {
+    if ((Int)uiCodeNumber < (6 * (1 << uiTableNumber)))
+    {
+      uiTemp = 1<<uiTableNumber;
+      uiCode = uiTemp+uiCodeNumber%uiTemp;
+      uiLength = 1+uiTableNumber+(uiCodeNumber>>uiTableNumber);
+    }
+    else
+    {
+      uiCode = uiCodeNumber - (6 * (1 << uiTableNumber)) + (1 << uiTableNumber);
+      uiLength = (6-uiTableNumber)+1+2*xLeadingZeros(uiCode);
+    }
+  }
+  else if (uiTableNumber < 8)
+  {
+    uiTemp = 1<<(uiTableNumber-4);
+    uiCode = uiTemp+uiCodeNumber%uiTemp;
+    uiLength = 1+(uiTableNumber-4)+(uiCodeNumber>>(uiTableNumber-4));
+  }
+  else if (uiTableNumber == 8)
+  {
+    assert( uiCodeNumber<=2 );
+    if (uiCodeNumber == 0)
+    {
+      uiCode = 1;
+      uiLength = 1;
+    }
+    else if (uiCodeNumber == 1)
+    {
+      uiCode = 1;
+      uiLength = 2;
+    }
+    else if (uiCodeNumber == 2)
+    {
+      uiCode = 0;
+      uiLength = 2;
+    }
+  }
+  else if (uiTableNumber == 9)
+  {
+    if (uiCodeNumber == 0)
+    {
+      uiCode = 4;
+      uiLength = 3;
+    }
+    else if (uiCodeNumber == 1)
+    {
+      uiCode = 10;
+      uiLength = 4;
+    }
+    else if (uiCodeNumber == 2)
+    {
+      uiCode = 11;
+      uiLength = 4;
+    }
+    else if (uiCodeNumber < 11)
+    {
+      uiCode = uiCodeNumber+21;
+      uiLength = 5;
+    }
+    else
+    {
+      uiTemp = 1<<4;
+      uiCode = uiTemp+(uiCodeNumber+5)%uiTemp;
+      uiLength = 5+((uiCodeNumber+5)>>4);
+    }
+  }
+  else if (uiTableNumber == 10)
+  {
+    uiCode = uiCodeNumber+1;
+    uiLength = 1+2*xLeadingZeros(uiCode);
+  }
+  else if (uiTableNumber == 11)
+  {
+    if (uiCodeNumber == 0)
+    {
+      uiCode = 0;
+      uiLength = 3;
+    }
+    else
+    {
+      uiCode = uiCodeNumber + 1;
+      uiLength = 4;
+    }
+  }
+#if CAVLC_COEF_LRG_BLK
+  else if (uiTableNumber == 12)
+  {
+    uiCode = 64+(uiCodeNumber&0x3f);
+    uiLength = 7+(uiCodeNumber>>6);
+    if (uiLength>32)
+    {
+      xWriteCode(0, uiLength-32);
+      uiLength  = 32;
+    }
+  }
+  else if (uiTableNumber == 13)
+  {
+    uiTemp = 1<<4;
+    uiCode = uiTemp+(uiCodeNumber&0x0f);
+    uiLength = 5+(uiCodeNumber>>4);
+  }
+#endif
+
+  xWriteCode(uiCode, uiLength);
+}
+
+#if CAVLC_COEF_LRG_BLK
+/** Function for encoding a block of transform coeffcients in CAVLC.
+ * \param scoeff pointer to transform coefficient buffer
+ * \param n block type information, e.g. luma, chroma, intra, inter, etc.
+ * \param blSize block size
+ * \returns
+ * This function performs encoding for a block of transform coefficient in CAVLC.
+ */
+Void TEncCavlc::xCodeCoeff( TCoeff* scoeff, Int n, Int blSize)
+{
+  static const int switch_thr[10] = {49,49,0,49,49,0,49,49,49,49};
+  int i, noCoeff = blSize*blSize;
+  unsigned int cn;
+  int level,vlc,sign,done,last_pos,start;
+  int run_done,maxrun,run,lev;
+  int tmprun,vlc_adaptive=0;
+  static const int atable[5] = {4,6,14,28,0xfffffff};
+  int sum_big_coef = 0;
+  Int tr1;
+
+  /* Do the last coefficient first */
+  i = 0;
+  done = 0;
+  while (!done && i < noCoeff)
+  {
+    if (scoeff[i])
+    {
+      done = 1;
+    }
+    else
+    {
+      i++;
+    }
+  }
+  if (i == noCoeff)
+  {
+    return;
+  }
+
+  last_pos = noCoeff-i-1;
+  level = abs(scoeff[i]);
+  lev = (level == 1) ? 0 : 1;
+
+  if(blSize >= 8)
+  {
+    cn = xLastLevelInd(lev, last_pos, blSize);
+    // ADAPT_VLC_NUM
+    vlc = g_auiLastPosVlcNum[n][Min(16,m_uiLastPosVlcIndex[n])];
+    xWriteVlc( vlc, cn );
+
+    if ( m_bAdaptFlag ){
+      // ADAPT_VLC_NUM
+      cn = (blSize==8)? cn:(cn>>2);
+      m_uiLastPosVlcIndex[n] += cn == m_uiLastPosVlcIndex[n] ? 0 : (cn < m_uiLastPosVlcIndex[n] ? -1 : 1);
+    }
+  }
+  else
+  {
+    int x,y,cx,cy;
+    int nTab = max(0,n-2);
+
+    x = (lev<<4) + last_pos;
+    cx = m_uiLPTableE4[nTab][x];
+    xWriteVlc( 2, cx );
+
+    if ( m_bAdaptFlag )
+    {
+      cy = Max( 0, cx-1 );
+      y = m_uiLPTableD4[nTab][cy];
+      m_uiLPTableD4[nTab][cy] = x;
+      m_uiLPTableD4[nTab][cx] = y;
+      m_uiLPTableE4[nTab][x] = cy;
+      m_uiLPTableE4[nTab][y] = cx;
+    }
+  }
+
+  sign = (scoeff[i++] < 0) ? 1 : 0;
+  if (level > 1)
+  {
+    xWriteVlc( 0, ((level-2)<<1)+sign );
+    tr1=0;
+  }
+  else
+  {
+    xWriteFlag( sign );
+    tr1=1;
+  }
+
+  if (i < noCoeff)
+  {
+    /* Go into run mode */
+    run_done = 0;
+    const UInt *vlcTable = (n==2||n==5)? ((blSize<=8)? g_auiVlcTable8x8Intra:g_auiVlcTable16x16Intra):
+      ((blSize<=8)? g_auiVlcTable8x8Inter:g_auiVlcTable16x16Inter);
+    const UInt **pLumaRunTr1 = (blSize==4)? g_pLumaRunTr14x4:g_pLumaRunTr18x8;
+    while ( !run_done )
+    {
+      maxrun = noCoeff-i-1;
+      tmprun = Min(maxrun, 28);
+
+      vlc = vlcTable[tmprun];
+      run = 0;
+      done = 0;
+      while (!done)
+      {
+        if (!scoeff[i])
+        {
+          run++;
+        }
+        else
+        {
+          level = abs(scoeff[i]);
+          lev = (level == 1) ? 0 : 1;
+
+          if(n == 2 || n == 5)
+          {
+            cn = xRunLevelInd(lev, run, maxrun, pLumaRunTr1[tr1][tmprun]);
+          }
+          else
+          {
+            cn = xRunLevelIndInter(lev, run, maxrun);
+          }
+
+          xWriteVlc( vlc, cn );
+
+          if (tr1==0 || level>=2)
+          {
+            tr1=0;
+          }
+          else if (tr1 < MAX_TR1)
+          {
+            tr1++;
+          }
+
+          sign = (scoeff[i] < 0) ? 1 : 0;
+          if (level > 1)
+          {
+            xWriteVlc( 0, ((level-2)<<1)+sign );
+
+            sum_big_coef += level;
+            if (blSize == 4 || i > switch_thr[n] || sum_big_coef > 2)
+            {
+              run_done = 1;
+            }
+          }
+          else
+          {
+            xWriteFlag( sign );
+          }
+          run = 0;
+          done = 1;
+        }
+        if (i == (noCoeff-1))
+        {
+          done = 1;
+          run_done = 1;
+          if (run)
+          {
+            if(n == 2 || n == 5)
+            {
+              cn = xRunLevelInd(0, run, maxrun, pLumaRunTr1[tr1][tmprun]);
+            }
+            else
+            {
+              cn = xRunLevelIndInter(0, run, maxrun);
+            }
+
+            xWriteVlc( vlc, cn );
+          }
+        }
+        i++;
+      }
+    }
+  }
+
+  /* Code the rest in level mode */
+  start = i;
+  for ( i=start; i<noCoeff; i++ )
+  {
+    int tmp = abs(scoeff[i]);
+
+    xWriteVlc( vlc_adaptive, tmp );
+    if (scoeff[i])
+    {
+      xWriteFlag( (scoeff[i] < 0) ? 1 : 0 );
+      if (tmp > atable[vlc_adaptive])
+      {
+        vlc_adaptive++;
+      }
+    }
+  }
+
+  return;
+}
+
+#else
+Void TEncCavlc::xCodeCoeff4x4(TCoeff* scoeff, Int n )
+{
+  Int i;
+  UInt cn;
+  Int level,vlc,sign,done,last_pos,start;
+  Int run_done,maxrun,run,lev;
+#if QC_MOD_LCEC
+  Int vlc_adaptive=0;
+#else
+  Int tmprun, vlc_adaptive=0;
+#endif
+  static const int atable[5] = {4,6,14,28,0xfffffff};
+  Int tmp;
+#if QC_MOD_LCEC
+  Int nTab = max(0,n-2);
+  Int tr1;
+#endif
+
+  /* Do the last coefficient first */
+  i = 0;
+  done = 0;
+
+  while (!done && i < 16)
+  {
+    if (scoeff[i])
+    {
+      done = 1;
+    }
+    else
+    {
+      i++;
+    }
+  }
+  if (i == 16)
+  {
+    return;
+  }
+
+  last_pos = 15-i;
+  level = abs(scoeff[i]);
+  lev = (level == 1) ? 0 : 1;
+
+#if QC_MOD_LCEC
+  if (level>1)
+  {
+    tr1=0;
+  }
+  else
+  {
+    tr1=1;
+  }
+#endif
+
+  {
+    int x,y,cx,cy,vlcNum;
+    int vlcTable[3] = {2,2,2};
+
+    x = 16*lev + last_pos;
+
+#if QC_MOD_LCEC
+    cx = m_uiLPTableE4[nTab][x];
+    vlcNum = vlcTable[nTab];
+#else
+    cx = m_uiLPTableE4[n][x];
+    vlcNum = vlcTable[n];
+#endif
+
+    xWriteVlc( vlcNum, cx );
+
+    if ( m_bAdaptFlag )
+    {
+      cy = Max( 0, cx-1 );
+#if QC_MOD_LCEC
+      y = m_uiLPTableD4[nTab][cy];
+      m_uiLPTableD4[nTab][cy] = x;
+      m_uiLPTableD4[nTab][cx] = y;
+      m_uiLPTableE4[nTab][x] = cy;
+      m_uiLPTableE4[nTab][y] = cx;
+#else
+      y = m_uiLPTableD4[n][cy];
+      m_uiLPTableD4[n][cy] = x;
+      m_uiLPTableD4[n][cx] = y;
+      m_uiLPTableE4[n][x] = cy;
+      m_uiLPTableE4[n][y] = cx;
+#endif
+    }
+  }
+
+  sign = (scoeff[i] < 0) ? 1 : 0;
+  if (level > 1)
+  {
+    xWriteVlc( 0, 2*(level-2)+sign );
+  }
+  else
+  {
+    xWriteFlag( sign );
+  }
+  i++;
+
+  if (i < 16)
+  {
+    /* Go into run mode */
+    run_done = 0;
+    while (!run_done)
+    {
+      maxrun = 15-i;
+#if QC_MOD_LCEC
+      if ( n == 2 )
+        vlc = g_auiVlcTable8x8Intra[maxrun];
+      else
+        vlc = g_auiVlcTable8x8Inter[maxrun];
+#else
+      tmprun = maxrun;
+      if (maxrun > 27)
+      {
+        vlc = 3;
+        tmprun = 28;
+      }
+      else
+      {
+        vlc = g_auiVlcTable8x8[maxrun];
+      }
+#endif
+
+      run = 0;
+      done = 0;
+      while (!done)
+      {
+        if (!scoeff[i])
+        {
+          run++;
+        }
+        else
+        {
+          level = abs(scoeff[i]);
+          lev = (level == 1) ? 0 : 1;
+#if QC_MOD_LCEC
+          if ( n == 2 ){
+            cn = xRunLevelInd(lev, run, maxrun, g_auiLumaRunTr14x4[tr1][maxrun]);
+          }
+          else{
+#if RUNLEVEL_TABLE_CUT
+            cn = xRunLevelIndInter(lev, run, maxrun);
+#else
+            cn = g_auiLumaRun8x8[maxrun][lev][run];
+#endif
+          }
+#else
+          if (maxrun > 27)
+          {
+            cn = g_auiLumaRun8x8[28][lev][run];
+          }
+          else
+          {
+            cn = g_auiLumaRun8x8[maxrun][lev][run];
+          }
+#endif
+            xWriteVlc( vlc, cn );
+
+#if QC_MOD_LCEC
+          if (tr1>0 && tr1 < MAX_TR1)
+          {
+            tr1++;
+          }
+#endif
+          sign = (scoeff[i] < 0) ? 1 : 0;
+          if (level > 1)
+          {
+            xWriteVlc( 0, 2*(level-2)+sign );
+            run_done = 1;
+          }
+          else
+          {
+            xWriteFlag( sign );
+          }
+
+          run = 0;
+          done = 1;
+        }
+        if (i == 15)
+        {
+          done = 1;
+          run_done = 1;
+          if (run)
+          {
+#if QC_MOD_LCEC
+            if (n==2){
+              cn=xRunLevelInd(0, run, maxrun, g_auiLumaRunTr14x4[tr1][maxrun]);
+            }
+            else{
+#if RUNLEVEL_TABLE_CUT
+              cn = xRunLevelIndInter(0, run, maxrun);
+#else
+              cn = g_auiLumaRun8x8[maxrun][0][run];
+#endif
+            }
+#else
+            if (maxrun > 27)
+            {
+              cn = g_auiLumaRun8x8[28][0][run];
+            }
+            else
+            {
+              cn = g_auiLumaRun8x8[maxrun][0][run];
+            }
+#endif
+            xWriteVlc( vlc, cn );
+          }
+        }
+        i++;
+      }
+    }
+  }
+
+  /* Code the rest in level mode */
+  start = i;
+  for ( i=start; i<16; i++ )
+  {
+    tmp = abs(scoeff[i]);
+    xWriteVlc( vlc_adaptive, tmp );
+    if (scoeff[i])
+    {
+      sign = (scoeff[i] < 0) ? 1 : 0;
+      xWriteFlag( sign );
+    }
+    if ( tmp > atable[vlc_adaptive] )
+    {
+      vlc_adaptive++;
+    }
+  }
+  return;
+}
+
+Void TEncCavlc::xCodeCoeff8x8( TCoeff* scoeff, Int n )
+{
+  int i;
+  unsigned int cn;
+  int level,vlc,sign,done,last_pos,start;
+  int run_done,maxrun,run,lev;
+#if QC_MOD_LCEC
+  int vlc_adaptive=0;
+#else
+  int tmprun,vlc_adaptive=0;
+#endif
+  static const int atable[5] = {4,6,14,28,0xfffffff};
+  int tmp;
+#if QC_MOD_LCEC
+  Int tr1;
+#endif
+
+  static const int switch_thr[10] = {49,49,0,49,49,0,49,49,49,49};
+  int sum_big_coef = 0;
+
+
+  /* Do the last coefficient first */
+  i = 0;
+  done = 0;
+  while (!done && i < 64)
+  {
+    if (scoeff[i])
+    {
+      done = 1;
+    }
+    else
+    {
+      i++;
+    }
+  }
+  if (i == 64)
+  {
+    return;
+  }
+
+  last_pos = 63-i;
+  level = abs(scoeff[i]);
+  lev = (level == 1) ? 0 : 1;
+
+  {
+    int x,y,cx,cy,vlcNum;
+    x = 64*lev + last_pos;
+
+    cx = m_uiLPTableE8[n][x];
+    // ADAPT_VLC_NUM
+    vlcNum = g_auiLastPosVlcNum[n][Min(16,m_uiLastPosVlcIndex[n])];
+    xWriteVlc( vlcNum, cx );
+
+    if ( m_bAdaptFlag )
+    {
+      // ADAPT_VLC_NUM
+      m_uiLastPosVlcIndex[n] += cx == m_uiLastPosVlcIndex[n] ? 0 : (cx < m_uiLastPosVlcIndex[n] ? -1 : 1);
+      cy = Max(0,cx-1);
+      y = m_uiLPTableD8[n][cy];
+      m_uiLPTableD8[n][cy] = x;
+      m_uiLPTableD8[n][cx] = y;
+      m_uiLPTableE8[n][x] = cy;
+      m_uiLPTableE8[n][y] = cx;
+    }
+  }
+
+  sign = (scoeff[i] < 0) ? 1 : 0;
+  if (level > 1)
+  {
+    xWriteVlc( 0, 2*(level-2)+sign );
+  }
+  else
+  {
+    xWriteFlag( sign );
+  }
+  i++;
+#if QC_MOD_LCEC
+  if (level>1){
+    tr1=0;
+  }
+  else
+  {
+    tr1=1;
+  }
+#endif
+
+  if (i < 64)
+  {
+    /* Go into run mode */
+    run_done = 0;
+    while ( !run_done )
+    {
+      maxrun = 63-i;
+#if QC_MOD_LCEC
+      if(n == 2 || n == 5)
+        vlc = g_auiVlcTable8x8Intra[Min(maxrun,28)];
+      else
+        vlc = g_auiVlcTable8x8Inter[Min(maxrun,28)];
+#else
+      tmprun = maxrun;
+      if (maxrun > 27)
+      {
+        vlc = 3;
+        tmprun = 28;
+      }
+      else
+      {
+        vlc = g_auiVlcTable8x8[maxrun];
+      }
+#endif
+
+      run = 0;
+      done = 0;
+      while (!done)
+      {
+        if (!scoeff[i])
+        {
+          run++;
+        }
+        else
+        {
+          level = abs(scoeff[i]);
+          lev = (level == 1) ? 0 : 1;
+#if QC_MOD_LCEC
+          if(n == 2 || n == 5)
+            cn = xRunLevelInd(lev, run, maxrun, g_auiLumaRunTr18x8[tr1][min(maxrun,28)]);
+          else
+#if RUNLEVEL_TABLE_CUT
+            cn = xRunLevelIndInter(lev, run, maxrun);
+#else
+            cn = g_auiLumaRun8x8[min(maxrun,28)][lev][run];
+#endif
+#else
+          if (maxrun > 27)
+          {
+            cn = g_auiLumaRun8x8[28][lev][run];
+          }
+          else
+          {
+            cn = g_auiLumaRun8x8[maxrun][lev][run];
+          }
+#endif
+          xWriteVlc( vlc, cn );
+
+#if QC_MOD_LCEC
+          if (tr1==0 || level >=2)
+          {
+            tr1=0;
+          }
+          else if (tr1 < MAX_TR1)
+          {
+            tr1++;
+          }
+#endif
+          sign = (scoeff[i] < 0) ? 1 : 0;
+          if (level > 1)
+          {
+            xWriteVlc( 0, 2*(level-2)+sign );
+
+            sum_big_coef += level;
+            if (i > switch_thr[n] || sum_big_coef > 2)
+            {
+              run_done = 1;
+            }
+          }
+          else
+          {
+            xWriteFlag( sign );
+          }
+          run = 0;
+          done = 1;
+        }
+        if (i == 63)
+        {
+          done = 1;
+          run_done = 1;
+          if (run)
+          {
+#if QC_MOD_LCEC
+            if(n == 2 || n == 5)
+              cn=xRunLevelInd(0, run, maxrun, g_auiLumaRunTr18x8[tr1][min(maxrun,28)]);
+            else
+#if RUNLEVEL_TABLE_CUT
+              cn = xRunLevelIndInter(0, run, maxrun);
+#else
+              cn = g_auiLumaRun8x8[min(maxrun,28)][0][run];
+#endif
+#else
+            if (maxrun > 27)
+            {
+              cn = g_auiLumaRun8x8[28][0][run];
+            }
+            else
+            {
+              cn = g_auiLumaRun8x8[maxrun][0][run];
+            }
+#endif
+            xWriteVlc( vlc, cn );
+          }
+        }
+        i++;
+      }
+    }
+  }
+
+  /* Code the rest in level mode */
+  start = i;
+  for ( i=start; i<64; i++ )
+  {
+    tmp = abs(scoeff[i]);
+    xWriteVlc( vlc_adaptive, tmp );
+    if (scoeff[i])
+    {
+      sign = (scoeff[i] < 0) ? 1 : 0;
+      xWriteFlag( sign );
+    }
+    if (tmp>atable[vlc_adaptive])
+    {
+      vlc_adaptive++;
+    }
+  }
+
+  return;
+}
+#endif
+
+#ifdef WEIGHT_PRED
+Void TEncCavlc::codeWeightPredTable( TComSlice* pcSlice )
+{
+  wpScalingParam  *wp;
+  Bool            bChroma     = true; // color always present in HEVC ?
+  Int             nbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
+  Bool            denomCoded  = false;
+
+  for ( Int numRef=0 ; numRef<nbRef ; numRef++ ) {
+    RefPicList  eRefPicList = ( numRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) {
+      pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+      if ( !denomCoded ) {
+        // code luma_log2_weight_denom :
+        xWriteUvlc( wp[0].uiLog2WeightDenom );    // ue(v): luma_log2_weight_denom
+        if( bChroma )
+          xWriteUvlc( wp[1].uiLog2WeightDenom );  // ue(v): chroma_log2_weight_denom
+        denomCoded = true;
+      }
+
+      xWriteFlag( wp[0].bPresentFlag );           // u(1): luma_weight_l0_flag
+      if ( wp[0].bPresentFlag ) {
+        xWriteSvlc( wp[0].iWeight );  // se(v): luma_weight_l0[i]
+        xWriteSvlc( wp[0].iOffset );  // se(v): luma_offset_l0[i]
+      }
+      if ( bChroma ) {
+        xWriteFlag( wp[1].bPresentFlag );           // u(1): chroma_weight_l0_flag
+        if ( wp[1].bPresentFlag ) {
+          for ( Int j=1 ; j<3 ; j++ ) {
+            xWriteSvlc( wp[j].iWeight );  // se(v): chroma_weight_l0[i][j]
+            xWriteSvlc( wp[j].iOffset );  // se(v): chroma_offset_l0[i][j]
+          }
+        }
+      }
+    }
+  }
+
+}
+#endif
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncCavlc.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncCavlc.h	(revision 19)
@@ -0,0 +1,283 @@
+/* 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     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"
+#if QC_MOD_LCEC
+#include "../TLibCommon/TComRom.h"
+#endif
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CAVLC encoder class
+class TEncCavlc : public TEncEntropyIf
+{
+private:
+  Bool m_bAdaptFlag;
+  
+  
+public:
+  TEncCavlc();
+  virtual ~TEncCavlc();
+  
+protected:
+  TComBitIf*    m_pcBitIf;
+  TComSlice*    m_pcSlice;
+  UInt          m_uiCoeffCost;
+  Bool          m_bRunLengthCoding;
+  UInt          m_uiRun;
+  Bool          m_bAlfCtrl;
+  UInt          m_uiMaxAlfCtrlDepth;
+  UInt          m_uiLPTableE4[3][32];
+  UInt          m_uiLPTableD4[3][32];
+#if !CAVLC_COEF_LRG_BLK
+  UInt          m_uiLPTableE8[10][128];
+  UInt          m_uiLPTableD8[10][128];
+#endif
+  UInt          m_uiLastPosVlcIndex[10];
+  
+#if LCEC_INTRA_MODE
+ #if MTK_DCM_MPM
+  UInt          m_uiIntraModeTableD17[2][16];
+  UInt          m_uiIntraModeTableE17[2][16];
+
+  UInt          m_uiIntraModeTableD34[2][33];
+  UInt          m_uiIntraModeTableE34[2][33];
+#else
+  UInt          m_uiIntraModeTableD17[16];
+  UInt          m_uiIntraModeTableE17[16];
+
+  UInt          m_uiIntraModeTableD34[33];
+  UInt          m_uiIntraModeTableE34[33];
+#endif
+#endif
+  
+#if CAVLC_RQT_CBP
+  UInt          m_uiCBP_YUV_TableE[4][8];
+  UInt          m_uiCBP_YUV_TableD[4][8];
+  UInt          m_uiCBP_YS_TableE[2][4];
+  UInt          m_uiCBP_YS_TableD[2][4];
+  UInt          m_uiCBP_YCS_TableE[2][8];
+  UInt          m_uiCBP_YCS_TableD[2][8];
+  UInt          m_uiCBP_4Y_TableE[2][15];
+  UInt          m_uiCBP_4Y_TableD[2][15];
+  UInt          m_uiCBP_4Y_VlcIdx;
+#else
+  UInt          m_uiCBPTableE[2][8];
+  UInt          m_uiCBPTableD[2][8];
+  UInt          m_uiBlkCBPTableE[2][15];
+  UInt          m_uiBlkCBPTableD[2][15];
+  UInt          m_uiCbpVlcIdx[2];
+  UInt          m_uiBlkCbpVlcIdx;
+#endif
+
+
+  
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+  UInt          m_uiMI1TableE[9];
+  UInt          m_uiMI1TableD[9];
+#else
+  UInt          m_uiMI1TableE[8];
+  UInt          m_uiMI1TableD[8];
+#endif
+  UInt          m_uiMI2TableE[15];
+  UInt          m_uiMI2TableD[15];
+  
+  UInt          m_uiMITableVlcIdx;
+#if QC_LCEC_INTER_MODE
+  UInt          m_uiSplitTableE[4][7];
+  UInt          m_uiSplitTableD[4][7];
+#endif
+
+#if CAVLC_COUNTER_ADAPT
+#if CAVLC_RQT_CBP
+  UChar         m_ucCBP_YUV_TableCounter[4][4];
+  UChar         m_ucCBP_4Y_TableCounter[2][2];
+  UChar         m_ucCBP_YS_TableCounter[2][3];
+  UChar         m_ucCBP_YCS_TableCounter[2][4];
+  UChar         m_ucCBP_YUV_TableCounterSum[4];
+  UChar         m_ucCBP_4Y_TableCounterSum[2];
+  UChar         m_ucCBP_YS_TableCounterSum[2];
+  UChar         m_ucCBP_YCS_TableCounterSum[2];
+#else
+  UChar         m_ucCBFTableCounter    [2][4];
+  UChar         m_ucBlkCBPTableCounter [2][2];
+  UChar         m_ucCBFTableCounterSum[2];
+  UChar         m_ucBlkCBPTableCounterSum[2];
+#endif
+  UChar         m_ucMI1TableCounter       [4];
+  UChar         m_ucSplitTableCounter  [4][4];
+
+  UChar         m_ucSplitTableCounterSum[4];
+  UChar         m_ucMI1TableCounterSum;
+#endif
+
+  Void  xCheckCoeff( TCoeff* pcCoef, UInt uiSize, UInt uiDepth, UInt& uiNumofCoeff, UInt& uiPart );
+  
+  Void  xWriteCode            ( UInt uiCode, UInt uiLength );
+  Void  xWriteUvlc            ( UInt uiCode );
+  Void  xWriteSvlc            ( Int iCode   );
+  Void  xWriteFlag            ( UInt uiCode );
+  Void  xWriteEpExGolomb      ( UInt uiSymbol, UInt uiCount );
+  Void  xWriteExGolombLevel    ( UInt uiSymbol );
+  Void  xWriteUnaryMaxSymbol  ( UInt uiSymbol, UInt uiMaxSymbol );
+#if !QC_MOD_LCEC_RDOQ
+  UInt  xLeadingZeros         ( UInt uiCode );
+#endif
+  Void  xWriteVlc             ( UInt uiTableNumber, UInt uiCodeNumber );
+
+#if CAVLC_COEF_LRG_BLK
+  Void  xCodeCoeff             ( TCoeff* scoeff, Int n, Int blSize);
+#else
+  Void  xCodeCoeff4x4          ( TCoeff* scoeff, Int iTableNumber );
+  Void  xCodeCoeff8x8          ( TCoeff* scoeff, Int iTableNumber );
+#endif
+  
+  UInt  xConvertToUInt        ( Int iValue ) {  return ( iValue <= 0) ? -iValue<<1 : (iValue<<1)-1; }
+  
+public:
+  
+  Void  resetEntropy          ();
+
+#if !CAVLC_COEF_LRG_BLK
+  UInt* GetLP8Table();
+#endif
+  UInt* GetLP4Table();
+#if QC_MOD_LCEC
+  UInt* GetLastPosVlcIndexTable();
+#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;  }
+  
+  Void  codeNALUnitHeader       ( NalUnitType eNalUnitType, NalRefIdc eNalRefIdc, UInt TemporalId = 0, Bool bOutputFlag = true );
+  
+  Void  codeSPS                 ( TComSPS* pcSPS );
+  Void  codePPS                 ( TComPPS* pcPPS );
+  void codeSEI(const SEI&);
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast );
+  Void  codeSliceFinish         ();
+  
+  Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void codeAlfFlag       ( UInt uiCode );
+  Void codeAlfUvlc       ( UInt uiCode );
+  Void codeAlfSvlc       ( Int   iCode );
+  Void codeAlfCtrlDepth();
+#if MTK_SAO
+  Void codeAoFlag       ( UInt uiCode );
+  Void codeAoUvlc       ( UInt uiCode );
+  Void codeAoSvlc       ( Int   iCode );
+#endif
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+  Void codeMergeIndexMV  ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Void codeResPredFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if TSB_ALF_HEADER
+  Void codeAlfFlagNum    ( UInt uiCode, UInt minValue );
+  Void codeAlfCtrlFlag   ( UInt uiSymbol );
+#endif
+#if QC_LCEC_INTER_MODE
+  Void codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode );
+#endif  
+  Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  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 codeViewIdx       ( Int iViewIdx );
+#if CAVLC_RQT_CBP
+  Void codeCbfTrdiv      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  UInt xGetFlagPattern   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void codeCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeBlockCbf      ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiQPartNum, Bool bRD = false);
+  
+  Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType, Bool bRD = false );
+
+#ifdef WEIGHT_PRED
+  Void codeWeightPredTable( TComSlice* pcSlice );
+#endif
+  
+  Void estBit             (estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType);
+  
+  Bool  getAdaptFlag          ()          { return m_bAdaptFlag; }
+  Void  setAdaptFlag          ( Bool b )  { m_bAdaptFlag = b;     }
+};
+
+#endif // !defined(AFX_TENCCAVLC_H__EE8A0B30_945B_4169_B290_24D3AD52296F__INCLUDED_)
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncCfg.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncCfg.h	(revision 19)
@@ -0,0 +1,479 @@
+/* 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     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 "TEncSeqStructure.h"
+#include <assert.h>
+
+#include <vector>
+
+// ====================================================================================================================
+// 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_iFrameToBeEncoded;
+
+  //====== Coding Structure ========
+#if DCM_DECODING_REFRESH
+  UInt      m_uiDecodingRefreshType;            ///< the type of decoding refresh employed for the random access.
+#endif
+
+  UInt      m_uiCodedPictureStoreSize ;
+  Int       m_iGOPSize;
+  Int       m_iRateGOPSize;
+
+  std::string     m_cInputFormatString ;
+
+  Int       m_iQP;                              //  if (AdaptiveQP == OFF)
+
+  Int       m_aiTLayerQPOffset[MAX_TLAYER];
+  Int       m_aiPad[2];
+
+  //======= Transform =============
+  UInt      m_uiQuadtreeTULog2MaxSize;
+  UInt      m_uiQuadtreeTULog2MinSize;
+  UInt      m_uiQuadtreeTUMaxDepthInter;
+  UInt      m_uiQuadtreeTUMaxDepthIntra;
+
+  //====== B Slice ========
+
+  //====== Entropy Coding ========
+  Int       m_iSymbolMode;                      //  (CAVLC, CABAC)
+
+  //====== Loop/Deblock Filter ========
+  Bool      m_bLoopFilterDisable;
+  Int       m_iLoopFilterAlphaC0Offset;
+  Int       m_iLoopFilterBetaOffset;
+
+#if MTK_SAO
+  Bool      m_bUseSAO;
+#endif
+
+  //====== Motion search ========
+  Int       m_iFastSearch;                      //  0:Full search  1:Diamond  2:PMVFAST
+  Int       m_iSearchRange;                     //  0:Full frame
+  Int       m_bipredSearchRange;
+  Int       m_iMaxDeltaQP;                      //  Max. absolute delta QP (1:default)
+
+#if HHI_VSO
+  //====== View Synthesis Optimization ======
+  Bool      m_bForceLambdaScale;
+#if HHI_VSO_DIST_INT
+  Bool      m_bAllowNegDist;
+#endif
+  Double    m_dLambdaScaleVSO;
+  UInt      m_uiVSOMode;
+#endif
+
+  //====== Tool list ========
+  Bool      m_bUseSBACRD;
+  Bool      m_bUseALF;
+#if MQT_ALF_NPASS
+  Int       m_iALFEncodePassReduction;
+#endif
+  Bool      m_bUseASR;
+  Bool      m_bUseHADME;
+#if DCM_COMB_LIST
+  Bool      m_bUseLComb;
+  Bool      m_bLCMod;
+#endif
+  Bool      m_bUseRDOQ;
+#if !HHI_NO_LowDelayCoding
+  Bool      m_bUseLDC;
+#endif
+  Bool      m_bUsePAD;
+  Bool      m_bUseFastEnc;
+
+#if HHI_VSO
+  Bool      m_bUseVSO;
+#endif  
+  Bool      m_bUseMRG; // SOPH:
+#if LM_CHROMA
+  Bool      m_bUseLMChroma;
+#endif
+
+  Int*      m_aidQP;
+  UInt      m_uiDeltaQpRD;
+
+#if HHI_RMP_SWITCH
+  Bool      m_bUseRMP;
+#endif
+#ifdef ROUNDING_CONTROL_BIPRED
+  Bool m_useRoundingControlBipred;
+#endif
+#if CONSTRAINED_INTRA_PRED
+  Bool      m_bUseConstrainedIntraPred;
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool m_bUseDMM;
+#endif
+#if HHI_MPI
+  Bool m_bUseMVI;
+#endif
+
+  //====== Slice ========
+  Int       m_iSliceMode;
+  Int       m_iSliceArgument;
+  //====== Entropy Slice ========
+  Int       m_iEntropySliceMode;
+  Int       m_iEntropySliceArgument;
+#if MTK_NONCROSS_INLOOP_FILTER
+  Bool      m_bLFCrossSliceBoundaryFlag;
+#endif
+
+  bool m_pictureDigestEnabled; ///< enable(1)/disable(0) md5 computation and SEI signalling
+
+#ifdef WEIGHT_PRED
+  //====== Weighted Prediction ========
+  Bool      m_bUseWeightPred;       // Use of Weighting Prediction (P_SLICE)
+  UInt      m_uiBiPredIdc;          // Use of Bi-Directional Weighting Prediction (B_SLICE)
+#endif
+
+  TEncSeqStructure m_cSequenceStructure;
+  //std::vector<int>  m_aiLayerQPOffset;
+
+  UInt        m_uiViewId;
+  Int         m_iViewOrderIdx;
+  Bool        m_bIsDepth;
+  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 HHI_INTER_VIEW_MOTION_PRED
+  UInt        m_uiMultiviewMvPredMode;
+  UInt        m_uiMultiviewMvRegMode;
+  Double      m_dMultiviewMvRegLambdaScale;
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  UInt        m_uiMultiviewResPredMode;
+#endif
+
+  PicOrderCnt m_iQpChangeFrame;
+  Int         m_iQpChangeOffsetVideo;
+  Int         m_iQpChangeOffsetDepth;
+#if HHI_INTERVIEW_SKIP
+  UInt        m_uiInterViewSkip;
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  Double      m_dInterViewSkipLambdaScale;
+#endif
+#endif
+
+public:
+  TEncCfg()          {}
+  virtual ~TEncCfg() {}
+
+  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      setFrameToBeEncoded             ( Int   i )      { m_iFrameToBeEncoded = i; }
+
+  //====== Coding Structure ========
+#if DCM_DECODING_REFRESH
+  Void      setDecodingRefreshType          ( Int   i )      { m_uiDecodingRefreshType = (UInt)i; }
+#endif
+  Void      setCPSSize                      ( Int   i )      { m_uiCodedPictureStoreSize = (UInt) i ;}
+  Void      setGOPSize                      ( Int   i )      { m_iGOPSize = i; }
+  Void      setRateGOPSize                  ( Int   i )      { m_iRateGOPSize = i; }
+
+  Void      setViewId                       ( UInt  u )      { m_uiViewId               = u; }
+  Void      setViewOrderIdx                 ( Int   i )      { m_iViewOrderIdx          = i; }
+  Void      setIsDepth                      ( Bool  b )      { m_bIsDepth               = b; }
+  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 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 HHI_INTER_VIEW_MOTION_PRED
+  Void      setMultiviewMvPredMode          ( UInt  u )      { m_uiMultiviewMvPredMode      = u; }
+  Void      setMultiviewMvRegMode           ( UInt  u )      { m_uiMultiviewMvRegMode       = u; }
+  Void      setMultiviewMvRegLambdaScale    ( Double d)      { m_dMultiviewMvRegLambdaScale = d; }
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Void      setMultiviewResPredMode         ( UInt  u )      { m_uiMultiviewResPredMode     = u; }
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  Void      setInterViewSkip            ( UInt  u )       { m_uiInterViewSkip         = u; }
+  Bool      getInterViewSkip            ( )       { return (m_uiInterViewSkip?true:false) ;}
+#if HHI_INTERVIEW_SKIP_LAMBDA_SCALE
+  Void      setInterViewSkipLambdaScale ( UInt  u )       { m_dInterViewSkipLambdaScale = u; }
+  Double      getInterViewSkipLambdaScale ()                { return m_dInterViewSkipLambdaScale; }
+#endif
+#endif
+
+  Bool      isDepthCoder                    ()               { return m_bIsDepth; }
+
+  Void      setSeqStructure( std::string s )                 { m_cSequenceStructure.init( s ); }
+
+  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]; }
+
+  //======== 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; }
+
+  //====== b; Slice ========
+
+  //====== Entropy Coding ========
+  Void      setSymbolMode                   ( Int   i )      { m_iSymbolMode = i; }
+
+  //====== Loop/Deblock Filter ========
+  Void      setLoopFilterDisable            ( Bool  b )      { m_bLoopFilterDisable       = b; }
+  Void      setLoopFilterAlphaC0Offset      ( Int   i )      { m_iLoopFilterAlphaC0Offset = i; }
+  Void      setLoopFilterBetaOffset         ( Int   i )      { m_iLoopFilterBetaOffset    = i; }
+
+  //====== Motion search ========
+  Void      setFastSearch                   ( Int   i )      { m_iFastSearch = i; }
+  Void      setSearchRange                  ( Int   i )      { m_iSearchRange = i; }
+  Void      setBipredSearchRange            ( Int   i )      { m_bipredSearchRange = i; }
+  Void      setMaxDeltaQP                   ( Int   i )      { m_iMaxDeltaQP = i; }
+
+#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
+#endif
+
+  //====== Sequence ========
+  Int       getFrameRate                    ()      { return  m_iFrameRate; }
+  unsigned int getFrameSkip                 ()      { return  m_FrameSkip; }
+  Int       getSourceWidth                  ()      { return  m_iSourceWidth; }
+  Int       getSourceHeight                 ()      { return  m_iSourceHeight; }
+  Int       getFrameToBeEncoded             ()      { return  m_iFrameToBeEncoded; }
+
+  //==== Coding Structure ========
+#if DCM_DECODING_REFRESH
+  UInt      getDecodingRefreshType          ()      { return  m_uiDecodingRefreshType; }
+#endif
+  UInt getCodedPictureBufferSize            ()      { return m_uiCodedPictureStoreSize ;}
+
+  Int       getGOPSize                      ()      { return  m_iGOPSize; }
+  Int       getRateGOPSize                  ()      { return  m_iRateGOPSize; }
+
+  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; }
+
+  //==== b; Slice ========
+
+  //==== Entropy Coding ========
+  Int       getSymbolMode                   ()      { return  m_iSymbolMode; }
+
+  //==== Loop/Deblock Filter ========
+  Bool      getLoopFilterDisable            ()      { return  m_bLoopFilterDisable;       }
+  Int       getLoopFilterAlphaC0Offget      ()      { return  m_iLoopFilterAlphaC0Offset; }
+  Int       getLoopFilterBetaOffget         ()      { return  m_iLoopFilterBetaOffset;    }
+
+  //==== Motion search ========
+  Int       getFastSearch                   ()      { return  m_iFastSearch; }
+  Int       getSearchRange                  ()      { return  m_iSearchRange; }
+  Int       getMaxDeltaQP                   ()      { return  m_iMaxDeltaQP; }
+
+#if HHI_INTER_VIEW_MOTION_PRED
+  UInt      getMultiviewMvRegMode           ()      { return  m_uiMultiviewMvRegMode; }
+  Double    getMultiviewMvRegLambdaScale    ()      { return  m_dMultiviewMvRegLambdaScale; }
+#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
+#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; }
+#if DCM_COMB_LIST
+  Void      setUseLComb                     ( Bool  b )     { m_bUseLComb   = b; }
+  Void      setLCMod                        ( Bool  b )     { m_bLCMod   = b;    }
+#endif
+  Void      setUseRDOQ                      ( Bool  b )     { m_bUseRDOQ    = b; }
+#if !HHI_NO_LowDelayCoding
+  Void      setUseLDC                       ( Bool  b )     { m_bUseLDC     = b; }
+#endif
+  Void      setUsePAD                       ( Bool  b )     { m_bUsePAD     = b; }
+  Void      setUseFastEnc                   ( Bool  b )     { m_bUseFastEnc = b; }
+#if HHI_VSO
+  Void      setUseVSO                       ( Bool  b )     { m_bUseVSO     = b; }
+#endif
+  Void      setUseMRG                       ( Bool  b )     { m_bUseMRG     = b; } // SOPH:
+#if CONSTRAINED_INTRA_PRED
+  Void      setUseConstrainedIntraPred      ( Bool  b )     { m_bUseConstrainedIntraPred = b; }
+#endif
+  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;     }
+#if MQT_ALF_NPASS
+  Void      setALFEncodePassReduction       (Int i)  { m_iALFEncodePassReduction = i; }
+  Int       getALFEncodePassReduction       ()       { return m_iALFEncodePassReduction; }
+#endif
+#if DCM_COMB_LIST
+  Bool      getUseLComb                     ()      { return m_bUseLComb;   }
+  Bool      getLCMod                        ()      { return m_bLCMod; }
+#endif
+  Bool      getUseRDOQ                      ()      { return m_bUseRDOQ;    }
+#if !HHI_NO_LowDelayCoding
+  Bool      getUseLDC                       ()      { return m_bUseLDC;     }
+#endif
+  Bool      getUsePAD                       ()      { return m_bUsePAD;     }
+  Bool      getUseFastEnc                   ()      { return m_bUseFastEnc; }
+
+#if HHI_VSO
+  Bool      getUseVSO                       ()      { return m_bUseVSO;     }
+#endif
+  Bool      getUseMRG                       ()      { return m_bUseMRG;     } // SOPH:
+#if CONSTRAINED_INTRA_PRED
+  Bool      getUseConstrainedIntraPred      ()      { return m_bUseConstrainedIntraPred; }
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void setUseDMM( Bool b) { m_bUseDMM = b;    }
+  Bool getUseDMM()        { return m_bUseDMM; }
+#endif
+
+#if LM_CHROMA
+  Bool getUseLMChroma                       ()      { return m_bUseLMChroma;        }
+  Void setUseLMChroma                       ( Bool b ) { m_bUseLMChroma  = b;       }
+#endif
+
+  Int*      getdQPs                         ()      { return m_aidQP;       }
+  UInt      getDeltaQpRD                    ()      { return m_uiDeltaQpRD; }
+#if HHI_RMP_SWITCH
+  Void      setUseRMP                      ( Bool b ) { m_bUseRMP = b; }
+  Bool      getUseRMP                      ()      {return m_bUseRMP; }
+#endif
+#ifdef ROUNDING_CONTROL_BIPRED
+  Void setUseRoundingControlBipred(Bool b) { m_useRoundingControlBipred = b; }
+  Bool getUseRoundingControlBipred() { return m_useRoundingControlBipred; }
+#endif
+  //====== 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;}
+#if MTK_NONCROSS_INLOOP_FILTER
+  Void      setLFCrossSliceBoundaryFlag     ( Bool   bValue  )    { m_bLFCrossSliceBoundaryFlag = bValue; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                    { return m_bLFCrossSliceBoundaryFlag;   }
+#endif
+#if MTK_SAO
+  Void      setUseSAO                  (Bool bVal)     {m_bUseSAO = bVal;}
+  Bool      getUseSAO                  ()              {return m_bUseSAO;}
+#endif
+#if HHI_MPI
+  Void      setUseMVI                  (Bool bVal)     {m_bUseMVI = bVal;}
+#endif
+
+  void setPictureDigestEnabled(bool b) { m_pictureDigestEnabled = b; }
+  bool getPictureDigestEnabled() { return m_pictureDigestEnabled; }
+
+#ifdef WEIGHT_PRED
+  Void      setUseWP                        ( Bool  b )   { m_bUseWeightPred    = b;    }
+  Void      setWPBiPredIdc                  ( UInt u )    { m_uiBiPredIdc       = u;    }
+  Bool      getUseWP                        ()            { return m_bUseWeightPred;    }
+  UInt      getWPBiPredIdc                  ()            { return m_uiBiPredIdc;       }
+#endif
+
+  Void setQpChangeFrame( PicOrderCnt iPoc ) { m_iQpChangeFrame = iPoc; }
+  Int  getQpChangeFrame() { return (Int)m_iQpChangeFrame; }
+  Void setQpChangeOffsetVideo( Int iOffset ) { m_iQpChangeOffsetVideo = iOffset; }
+  Int  getQpChangeOffsetVideo() { return m_iQpChangeOffsetVideo; }
+  Void setQpChangeOffsetDepth( Int iOffset ) { m_iQpChangeOffsetDepth = iOffset; }
+  Int  getQpChangeOffsetDepth() { return m_iQpChangeOffsetDepth; }
+};
+
+#endif // !defined(AFX_TENCCFG_H__6B99B797_F4DA_4E46_8E78_7656339A6C41__INCLUDED_)
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncCu.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncCu.cpp	(revision 19)
@@ -0,0 +1,1612 @@
+/* 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     TEncCU.cpp
+    \brief    CU encoder class
+*/
+
+#include <stdio.h>
+#include "TEncTop.h"
+#include "TEncCu.h"
+#include "TEncAnalyze.h"
+
+// ====================================================================================================================
+// 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];
+  m_ppcResPredTmp  = new TComYuv*[m_uhTotalDepth-1];
+
+#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 );
+    m_ppcTempCU[i] = new TComDataCU; m_ppcTempCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false );
+
+    m_ppcPredYuvBest[i] = new TComYuv; m_ppcPredYuvBest[i]->create(uiWidth, uiHeight);
+    m_ppcResiYuvBest[i] = new TComYuv; m_ppcResiYuvBest[i]->create(uiWidth, uiHeight);
+    m_ppcRecoYuvBest[i] = new TComYuv; m_ppcRecoYuvBest[i]->create(uiWidth, uiHeight);
+
+    m_ppcPredYuvTemp[i] = new TComYuv; m_ppcPredYuvTemp[i]->create(uiWidth, uiHeight);
+    m_ppcResiYuvTemp[i] = new TComYuv; m_ppcResiYuvTemp[i]->create(uiWidth, uiHeight);
+    m_ppcRecoYuvTemp[i] = new TComYuv; m_ppcRecoYuvTemp[i]->create(uiWidth, uiHeight);
+
+    m_ppcOrigYuv    [i] = new TComYuv; m_ppcOrigYuv    [i]->create(uiWidth, uiHeight);
+
+    m_ppcResPredTmp [i] = new TComYuv; m_ppcResPredTmp [i]->create(uiWidth, uiHeight);
+  }
+
+  // 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 );
+}
+
+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(m_ppcResPredTmp[i])
+    {
+      m_ppcResPredTmp [i]->destroy(); delete m_ppcResPredTmp[i];  m_ppcResPredTmp[i] = NULL;
+    }
+  }
+  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(m_ppcResPredTmp)
+  {
+    delete [] m_ppcResPredTmp;
+    m_ppcResPredTmp = NULL;
+  }
+}
+
+/** \param    pcEncTop      pointer of encoder class
+ */
+Void TEncCu::init( TEncTop* pcEncTop )
+{
+  m_pcEncCfg           = pcEncTop;
+  m_pcEncTop           = 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 )
+{
+  // single-QP coding mode
+  if ( rpcCU->getSlice()->getSPS()->getUseDQP() == false )
+  {
+    // 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 );
+  }
+  // multiple-QP coding mode
+  else
+  {
+    Int iQP  = rpcCU->getSlice()->getSliceQp();
+    Int idQP = m_pcEncCfg->getMaxDeltaQP();
+    Int i;
+    Int iBestQP = iQP;
+    Double fBestCost = MAX_DOUBLE;
+
+    rpcCU->getSlice()->setSliceQp( iQP );
+    m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+    m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+    m_ppcBestCU[0]->setQPSubParts( iQP, 0, 0 );
+    m_ppcTempCU[0]->setQPSubParts( iQP, 0, 0 );
+
+    // first try
+    xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 );
+
+    // for non-zero residual case
+    if ( !( m_ppcBestCU[0]->isSkipped( 0 ) && m_ppcBestCU[0]->getDepth( 0 ) == 0 ) )
+    {
+      // add dQP bits
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeQP( m_ppcBestCU[0], 0, false );
+      m_ppcBestCU[0]->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+
+
+#if HHI_VSO
+      if ( m_pcRdCost->getUseLambdaScaleVSO() )
+      {
+        m_ppcBestCU[0]->getTotalCost() = m_pcRdCost->calcRdCostVSO( m_ppcBestCU[0]->getTotalBits(), m_ppcBestCU[0]->getTotalDistortion() );
+      }
+      else
+#endif
+      {
+        m_ppcBestCU[0]->getTotalCost()  = m_pcRdCost->calcRdCost( m_ppcBestCU[0]->getTotalBits(), m_ppcBestCU[0]->getTotalDistortion() );
+      }
+
+      fBestCost = m_ppcBestCU[0]->getTotalCost();
+
+      // try every case
+      for ( i=iQP-idQP; i<=iQP+idQP; i++ )
+      {
+        if ( i == iQP ) continue;
+
+        rpcCU->getSlice()->setSliceQp( i );
+        m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+        m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+        m_ppcBestCU[0]->setQPSubParts( i, 0, 0 );
+        m_ppcTempCU[0]->setQPSubParts( i, 0, 0 );
+
+        xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 );
+
+        // add dQP bits
+        rpcCU->getSlice()->setSliceQp( iQP );
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQP( m_ppcBestCU[0], 0, false );
+        m_ppcBestCU[0]->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+
+#if HHI_VSO
+        if (m_pcRdCost->getUseLambdaScaleVSO())
+        {
+          m_ppcBestCU[0]->getTotalCost()  = m_pcRdCost->calcRdCostVSO( m_ppcBestCU[0]->getTotalBits(), m_ppcBestCU[0]->getTotalDistortion() );
+        }
+        else
+#endif
+        {
+          m_ppcBestCU[0]->getTotalCost()  = m_pcRdCost->calcRdCost( m_ppcBestCU[0]->getTotalBits(), m_ppcBestCU[0]->getTotalDistortion() );
+        }
+
+        if ( fBestCost > m_ppcBestCU[0]->getTotalCost() )
+        {
+          fBestCost = m_ppcBestCU[0]->getTotalCost();
+          iBestQP   = i;
+        }
+      }
+
+      // perform best case
+      rpcCU->getSlice()->setSliceQp( iBestQP );
+      m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+      m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+      m_ppcBestCU[0]->setQPSubParts( iBestQP, 0, 0 );
+      m_ppcTempCU[0]->setQPSubParts( iBestQP, 0, 0 );
+
+      xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 );
+
+      // add dQP bits
+      rpcCU->getSlice()->setSliceQp( iQP );
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeQP( m_ppcBestCU[0], 0, false );
+      m_ppcBestCU[0]->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+
+#if HHI_VSO
+      if (m_pcRdCost->getUseLambdaScaleVSO())
+      {
+        m_ppcBestCU[0]->getTotalCost()  = m_pcRdCost->calcRdCostVSO( m_ppcBestCU[0]->getTotalBits(), m_ppcBestCU[0]->getTotalDistortion() );
+      }
+      else
+#endif
+      {
+        m_ppcBestCU[0]->getTotalCost()  = m_pcRdCost->calcRdCost( m_ppcBestCU[0]->getTotalBits(), m_ppcBestCU[0]->getTotalDistortion() );
+      }
+    }
+  }
+}
+
+/** \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 SNY_DQP
+  if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+  {
+    pcCU->setdQPFlag(true);
+  }
+#endif//SNY_DQP
+  // encode CU data
+  xEncodeCU( pcCU, 0, 0 );
+
+#if SNY_DQP
+  // dQP: only for LCU
+  if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+  {
+    if ( pcCU->isSkipped( 0 ) && pcCU->getDepth( 0 ) == 0 )
+    {
+    }
+    else if ( pcCU->getdQPFlag())// non-skip
+    {
+
+      m_pcEntropyCoder->encodeQP( pcCU, 0 );
+      pcCU->setdQPFlag(false);
+    }
+  }
+#else
+  // dQP: only for LCU
+  if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+  {
+    if ( pcCU->isSkipped( 0 ) && pcCU->getDepth( 0 ) == 0 )
+    {
+    }
+    else
+    {
+      m_pcEntropyCoder->encodeQP( pcCU, 0 );
+    }
+  }
+#endif//SNY_DQP
+
+  //--- write terminating bit ---
+  Bool bTerminateSlice = bForceTerminate;
+  UInt uiCUAddr = pcCU->getAddr();
+
+  if (uiCUAddr == (pcCU->getPic()->getNumCUsInFrame()-1) )
+    bTerminateSlice = true;
+
+  if (uiCUAddr == (pcCU->getSlice()->getSliceCurEndCUAddr()-1))
+    bTerminateSlice = true;
+
+  m_pcEntropyCoder->encodeTerminatingBit( bTerminateSlice ? 1 : 0 );
+
+  // Encode slice finish
+  if ( bTerminateSlice )
+  {
+    m_pcEntropyCoder->encodeSliceFinish();
+  }
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+{
+  TComPic* pcPic = rpcBestCU->getPic();
+
+  // get Original YUV data from picture
+  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+
+  // variables for fast encoder decision
+  TComDataCU* pcTempCU;
+  Bool    bEarlySkip  = false;
+  Bool    bTrySplit    = true;
+  Double  fRD_Skip    = MAX_DOUBLE;
+
+  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 ( 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
+  if( ( uiRPelX < rpcBestCU->getSlice()->getSPS()->getWidth() ) && ( uiBPelY < rpcBestCU->getSlice()->getSPS()->getHeight() ) )
+  {
+    // do inter modes
+    if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+    {
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      // check availability of residual prediction
+      Bool  bResPredAvailable   = false;
+      Bool  bResPredAllowed     =                    (!rpcBestCU->getSlice()->getSPS()->isDepth                () );
+      bResPredAllowed           = bResPredAllowed && ( rpcBestCU->getSlice()->getSPS()->getViewId              () );
+      bResPredAllowed           = bResPredAllowed && ( rpcBestCU->getSlice()->getSPS()->getMultiviewResPredMode() );
+      if( bResPredAllowed )
+      {
+        bResPredAvailable       = rpcBestCU->getResidualSamples( 0, m_ppcResPredTmp[uiDepth] );
+      }
+
+      for( UInt uiResPrdId = 0; uiResPrdId < ( bResPredAvailable ? 2 : 1 ); uiResPrdId++ )
+      {
+        Bool bResPredFlag  = ( uiResPrdId > 0 );
+#endif
+
+      // SKIP
+      pcTempCU = rpcTempCU;
+
+      if( pcPic->getSlice(0)->getSPS()->getUseMRG() )
+      {
+#if !HHI_MRG_SKIP
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+        xCheckRDCostAMVPSkip ( rpcBestCU, rpcTempCU );        rpcTempCU->initEstData();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, bFullyRenderedSec );            rpcTempCU->initEstData();
+#else
+        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU );            rpcTempCU->initEstData();
+#endif
+      }
+      else
+      {
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+        xCheckRDCostAMVPSkip ( rpcBestCU, rpcTempCU );        rpcTempCU->initEstData();
+      }
+
+      // 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;
+        }
+      }
+
+      // 2Nx2N, NxN
+      if ( !bEarlySkip )
+      {
+#if HHI_DISABLE_INTER_NxN_SPLIT
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+        xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFullyRenderedSec );  rpcTempCU->initEstData();
+#else
+        xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData();
+#endif
+        if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+        {
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+          rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFullyRenderedSec );  rpcTempCU->initEstData();
+#else
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );  rpcTempCU->initEstData();
+#endif
+        }
+#else
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+        xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFullyRenderedSec );  rpcTempCU->initEstData();
+#else
+        xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+        xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN, bFullyRenderedSec   );  rpcTempCU->initEstData();
+#else
+        xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );  rpcTempCU->initEstData();
+#endif
+#endif
+      }
+
+#if HHI_RMP_SWITCH
+      if( pcPic->getSlice(0)->getSPS()->getUseRMP() )
+#endif
+      { // 2NxN, Nx2N
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+        xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N, bFullyRenderedSec  );  rpcTempCU->initEstData();
+#else
+        xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N  );  rpcTempCU->initEstData();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+        rpcTempCU->setResPredIndicator( bResPredAvailable, bResPredFlag );
+#endif
+#if HHI_INTERVIEW_SKIP
+        xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN, bFullyRenderedSec  );  rpcTempCU->initEstData();
+#else
+        xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN  );  rpcTempCU->initEstData();
+#endif
+      }
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    } // uiResPrdId
+#endif
+    }
+
+    // do normal intra modes
+    if ( !bEarlySkip )
+    {
+      // 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 ) && !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     ) // avoid very complex intra if it is unlikely
+#endif
+      {
+        xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N ); rpcTempCU->initEstData();
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+        if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+        {
+          if( rpcTempCU->getWidth(0) > ( 1 << rpcTempCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() ) )
+          {
+            xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN   ); rpcTempCU->initEstData();
+          }
+        }
+      }
+    }
+
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
+    rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+
+#if HHI_VSO
+    if (m_pcRdCost->getUseLambdaScaleVSO())
+    {
+      rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
+    }
+    else
+#endif
+    {
+#if HHI_INTERVIEW_SKIP
+  if(  m_pcEncCfg->getInterViewSkip())
+      {
+        TComYuv*  pRec    = m_ppcRecoYuvBest[ uiDepth ];
+        TComYuv*  pOrg    = m_ppcOrigYuv    [ uiDepth ];
+        Pel*      pUsedY  = pcPic->getUsedPelsMap()->getLumaAddr( rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+        Pel*      pUsedU  = pcPic->getUsedPelsMap()->getCbAddr  ( rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+        Pel*      pUsedV  = pcPic->getUsedPelsMap()->getCrAddr  ( rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+        Int       iUStrdY = pcPic->getUsedPelsMap()->getStride  ();
+        Int       iUStrdC = pcPic->getUsedPelsMap()->getCStride ();
+        UInt      uiWdt   = rpcBestCU->getWidth ( 0 );
+        UInt      uiHgt   = rpcBestCU->getHeight( 0 );
+        UInt      uiDist  = ( m_pcRdCost->getDistPart( pRec->getLumaAddr(), pRec->getStride(),  pOrg->getLumaAddr(), pOrg->getStride(),  pUsedY, iUStrdY, uiWdt,      uiHgt      )
+                            + m_pcRdCost->getDistPart( pRec->getCbAddr(),   pRec->getCStride(), pOrg->getCbAddr(),   pOrg->getCStride(), pUsedU, iUStrdC, uiWdt >> 1, uiHgt >> 1 )
+                            + m_pcRdCost->getDistPart( pRec->getCrAddr(),   pRec->getCStride(), pOrg->getCrAddr(),   pOrg->getCStride(), pUsedV, iUStrdC, uiWdt >> 1, uiHgt >> 1 ) );
+//        printf("\nD(as is) = %d,   D(new) = %d,  diff = %d", rpcBestCU->getTotalDistortion(), uiDist, Int(rpcBestCU->getTotalDistortion()-uiDist) );
+        rpcBestCU->getTotalDistortion() = uiDist;
+      }
+#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 ] ++;
+      }
+    }
+#if HHI_MPI
+    if( rpcBestCU->getSlice()->getSPS()->getUseMVI() && rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+    {
+      xCheckRDCostMvInheritance( rpcBestCU, rpcTempCU, uiDepth, false, false ); rpcTempCU->initEstData();
+      rpcTempCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, 0, uiDepth );
+      rpcTempCU->setDepthSubParts( uiDepth, 0 );
+      xCheckRDCostMvInheritance( rpcBestCU, rpcTempCU, uiDepth, true, false );  rpcTempCU->initEstData();
+    }
+#endif
+  }
+  else
+  {
+    bBoundary = true;
+  }
+
+  // further split
+  if( bTrySplit && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+  {
+#if HHI_VSO
+    // reset Model
+    if( m_pcRdCost->getUseRenModel() )
+    {
+      UInt  uiWidth     = m_ppcBestCU[uiDepth]->getWidth ( 0 );
+      UInt  uiHeight    = m_ppcBestCU[uiDepth]->getHeight( 0 );
+      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( rpcBestCU, uiPartUnitIdx, uhNextDepth );           // clear sub partition datas or init.
+      pcSubTempPartCU->initSubCU( rpcBestCU, uiPartUnitIdx, uhNextDepth );           // clear sub partition datas or init.
+
+      if( ( pcSubBestPartCU->getCUPelX() < pcSubBestPartCU->getSlice()->getSPS()->getWidth() ) && ( pcSubBestPartCU->getCUPelY() < pcSubBestPartCU->getSlice()->getSPS()->getHeight() ) )
+      {
+        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]);
+          }
+        }
+
+        xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth );
+
+#if HHI_VSO
+        if( m_pcRdCost->getUseRenModel() )
+        {
+          UInt  uiWidth     = pcSubBestPartCU->getWidth ( 0 );
+          UInt  uiHeight    = pcSubBestPartCU->getHeight( 0 );
+          Pel*  piSrc       = m_ppcRecoYuvBest[pcSubBestPartCU->getDepth(0)]->getLumaAddr( 0 );
+          UInt  uiSrcStride = m_ppcRecoYuvBest[pcSubBestPartCU->getDepth(0)]->getStride();
+          m_pcRdCost->setRenModelData( pcSubBestPartCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+        }
+#endif
+        rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );         // Keep best part data to current temporary data.
+        xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
+      }
+    }
+
+    if( !bBoundary )
+    {
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeSplitFlag( rpcTempCU, 0, uiDepth, true );
+
+      rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+    }
+
+#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->getUseLambdaScaleVSO())
+    {
+      rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+    }
+    else
+#endif
+    {
+      rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+    }
+
+    if( m_bUseSBACRD )
+    {
+      m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+    }
+    xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth );                                          // RD compare current larger prediction
+
+#if HHI_VSO
+    if( m_pcRdCost->getUseRenModel() )
+    {
+      UInt  uiWidth     = rpcBestCU->getWidth ( 0 );
+      UInt  uiHeight    = rpcBestCU->getHeight( 0 );
+      Pel*  piSrc       = m_ppcRecoYuvBest[uiDepth]->getLumaAddr( 0 );
+      UInt  uiSrcStride = m_ppcRecoYuvBest[uiDepth]->getStride();
+      m_pcRdCost->setRenModelData( rpcBestCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+    }
+#endif
+  }                                                                                  // with sub partitioned prediction.
+
+  rpcBestCU->copyToPic(uiDepth);                                                     // Copy Best data to Picture for next partition prediction.
+
+  if( bBoundary )
+    return;
+
+  xCopyYuv2Pic( rpcBestCU->getPic(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU(), uiDepth );   // Copy Yuv data to picture Yuv
+
+  // 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 );
+}
+
+/** 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( ( uiRPelX < pcCU->getSlice()->getSPS()->getWidth() ) && ( uiBPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+  {
+#if HHI_MPI
+    if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 || uiDepth < pcCU->getTextureModeDepth( uiAbsPartIdx ) )
+#endif
+      m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  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 < pcCU->getSlice()->getSPS()->getWidth() ) && ( uiBPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+      m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+    if( !pcCU->getSlice()->isIntra() )
+    {
+      m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
+    }
+
+    if( pcCU->isSkipped( uiAbsPartIdx ) )
+    {
+#if HHI_MRG_SKIP
+      m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx, 0 );
+#else
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 ) //if ( ref. frame list0 has at least 1 entry )
+      {
+        m_pcEntropyCoder->encodeMVPIdx( pcCU, uiAbsPartIdx, REF_PIC_LIST_0);
+      }
+      if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 ) //if ( ref. frame list1 has at least 1 entry )
+      {
+        m_pcEntropyCoder->encodeMVPIdx( pcCU, uiAbsPartIdx, REF_PIC_LIST_1);
+      }
+#endif
+      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 );
+    xRestoreDepthWidthHeight( pcCU );
+  }
+#endif
+
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( 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()->getWidth() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getHeight() ) )
+        xEncodeCU( pcCU, uiAbsPartIdx, uiDepth+1 );
+    }
+    return;
+  }
+
+#if TSB_ALF_HEADER
+#else
+  m_pcEntropyCoder->encodeAlfCtrlFlag( pcCU, uiAbsPartIdx );
+#endif
+
+#if HHI_MPI
+  if( !pcCU->getSlice()->isIntra() && pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 )
+#else
+  if( !pcCU->getSlice()->isIntra() )
+#endif
+  {
+    m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
+  }
+
+  if( pcCU->isSkipped( uiAbsPartIdx ) )
+  {
+#if HHI_MRG_SKIP
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx, 0 );
+#else
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 ) //if ( ref. frame list0 has at least 1 entry )
+    {
+      m_pcEntropyCoder->encodeMVPIdx( pcCU, uiAbsPartIdx, REF_PIC_LIST_0);
+    }
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 ) //if ( ref. frame list1 has at least 1 entry )
+    {
+      m_pcEntropyCoder->encodeMVPIdx( pcCU, uiAbsPartIdx, REF_PIC_LIST_1);
+    }
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    m_pcEntropyCoder->encodeResPredFlag( pcCU, uiAbsPartIdx, 0 );
+#endif
+    return;
+  }
+#if HHI_MPI
+  if( pcCU->getTextureModeDepth( uiAbsPartIdx ) == -1 )
+  {
+#endif
+    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 HHI_INTER_VIEW_RESIDUAL_PRED
+    if( !pcCU->isIntra( uiAbsPartIdx ) )
+    {
+      m_pcEntropyCoder->encodeResPredFlag( pcCU, uiAbsPartIdx, 0 );
+    }
+#endif
+#if HHI_MPI
+  }
+#endif
+
+  // Encode Coefficients
+  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, pcCU->getWidth (uiAbsPartIdx), pcCU->getHeight(uiAbsPartIdx) );
+}
+
+Void TEncCu::xCheckRDCostSkip( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool bSkipRes )
+{
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = rpcTempCU->getWidth ( 0 );
+    UInt  uiHeight    = rpcTempCU->getHeight( 0 );
+    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
+    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+  rpcTempCU->setPredModeSubParts( MODE_SKIP,   0, uhDepth );
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N,  0, uhDepth );
+
+  m_pcPredSearch->predInterSkipSearch       ( rpcTempCU,
+                                             m_ppcOrigYuv    [uhDepth],
+                                             m_ppcPredYuvTemp[uhDepth],
+                                             m_ppcResiYuvTemp[uhDepth],
+                                             m_ppcRecoYuvTemp[uhDepth] );
+
+  m_pcPredSearch->encodeResAndCalcRdInterCU ( rpcTempCU,
+                                             m_ppcOrigYuv    [uhDepth],
+                                             m_ppcPredYuvTemp[uhDepth],
+                                             m_ppcResiYuvTemp[uhDepth],
+                                             m_ppcResiYuvBest[uhDepth],
+                                             m_ppcRecoYuvTemp[uhDepth],
+                                             m_ppcResPredTmp [uhDepth],
+                                             bSkipRes );
+
+  xCheckBestMode( rpcBestCU, rpcTempCU, uhDepth );
+}
+
+/** 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 );
+  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  UInt uiNeighbourCandIdx[MRG_MAX_NUM_CANDS]; //MVs with same idx => same cand
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Bool  bResPrdAvail  = rpcTempCU->getResPredAvail( 0 );
+  Bool  bResPrdFlag   = rpcTempCU->getResPredFlag ( 0 );
+#endif
+
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+  {
+    uhInterDirNeighbours[ui] = 0;
+    uiNeighbourCandIdx[ui] = 0;
+  }
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = rpcTempCU->getWidth ( 0 );
+    UInt  uiHeight    = rpcTempCU->getHeight( 0 );
+    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
+  rpcTempCU->getInterMergeCandidates( 0, 0, uhDepth, cMvFieldNeighbours,uhInterDirNeighbours, uiNeighbourCandIdx );
+
+  Bool bValidCands = false;
+  for( UInt uiMergeCand = 0; uiMergeCand < MRG_MAX_NUM_CANDS; ++uiMergeCand )
+  {
+    if( uiNeighbourCandIdx[uiMergeCand] == ( uiMergeCand + 1 ) )
+    {
+#if HHI_MRG_SKIP
+      TComYuv* pcPredYuvTemp = NULL;
+#if HHI_INTERVIEW_SKIP
+      for( UInt uiNoResidual = (bSkipRes ? 1:0); uiNoResidual < 2; ++uiNoResidual )
+#else
+      for( UInt uiNoResidual = 0; uiNoResidual < 2; ++uiNoResidual )
+#endif
+      {
+#endif
+      bValidCands = true;
+      // set MC parameters
+#if HHI_MRG_SKIP
+      rpcTempCU->setPredModeSubParts( MODE_SKIP, 0, uhDepth ); // interprets depth relative to LCU level
+#else
+      rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to LCU level
+#endif
+      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
+      rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to LCU level
+      for( UInt uiInner = 0; uiInner < MRG_MAX_NUM_CANDS; uiInner++ )
+      {
+        rpcTempCU->setNeighbourCandIdxSubParts( uiInner, uiNeighbourCandIdx[uiInner], 0, 0,uhDepth );
+      }
+      rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand].getMv(), cMvFieldNeighbours[0 + 2*uiMergeCand].getRefIdx(), SIZE_2Nx2N, 0, 0, 0 ); // interprets depth relative to rpcTempCU level
+      rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand].getMv(), cMvFieldNeighbours[1 + 2*uiMergeCand].getRefIdx(), SIZE_2Nx2N, 0, 0, 0 ); // interprets depth relative to rpcTempCU level
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      rpcTempCU->setResPredAvailSubParts( bResPrdAvail, 0, 0, uhDepth );
+      rpcTempCU->setResPredFlagSubParts ( bResPrdFlag,  0, 0, uhDepth );
+#endif
+
+#if HHI_MRG_SKIP
+      // do MC
+#if HHI_INTERVIEW_SKIP
+      if ( (uiNoResidual == 0) || bSkipRes ){
+#else
+      if ( uiNoResidual == 0 ){
+#endif
+        m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+        // 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     = rpcTempCU->getWidth ( 0 );
+        UInt  uiHeight    = rpcTempCU->getHeight( 0 );
+        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],
+                                                m_ppcResPredTmp [uhDepth],
+                                                (uiNoResidual? true:false) );
+      Bool bQtRootCbf = rpcTempCU->getQtRootCbf(0) == 1;
+#else
+      // do MC
+      m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+
+      // estimate residual and encode everything
+      m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+                                                 m_ppcOrigYuv    [uhDepth],
+                                                 m_ppcPredYuvTemp[uhDepth],
+                                                 m_ppcResiYuvTemp[uhDepth],
+                                                 m_ppcResiYuvBest[uhDepth],
+                                                 m_ppcRecoYuvTemp[uhDepth],
+                                                 m_ppcResPredTmp [uhDepth],
+                                                 false );
+#endif
+      xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth );
+
+      rpcTempCU->initEstData();
+#if HHI_MRG_SKIP
+      if (!bQtRootCbf)
+        break;
+      }
+#endif
+    }
+  }
+}
+
+#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
+{
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = rpcTempCU->getWidth ( 0 );
+    UInt  uiHeight    = rpcTempCU->getHeight( 0 );
+    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 HHI_INTER_VIEW_RESIDUAL_PRED
+  Bool  bResPrdAvail  = rpcTempCU->getResPredAvail( 0 );
+  Bool  bResPrdFlag   = rpcTempCU->getResPredFlag ( 0 );
+#endif
+  rpcTempCU->setPartSizeSubParts    ( SIZE_2Nx2N,   0,    uhDepth );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  rpcTempCU->setResPredAvailSubParts( bResPrdAvail, 0, 0, uhDepth );
+  rpcTempCU->setResPredFlagSubParts ( bResPrdFlag,  0, 0, uhDepth );
+#endif
+  rpcTempCU->setPartSizeSubParts    ( ePartSize,    0,    uhDepth );
+  rpcTempCU->setPredModeSubParts    ( MODE_INTER,   0,    uhDepth );
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  if( rpcTempCU->getResPredFlag( 0 ) )
+  { // subtract residual prediction from original in motion search
+    m_ppcOrigYuv[uhDepth]->add( m_ppcResPredTmp [uhDepth], rpcTempCU->getWidth( 0 ), rpcTempCU->getHeight( 0 ), true );
+  }
+#endif
+#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
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  if( rpcTempCU->getResPredFlag( 0 ) )
+  { // add residual prediction to original again
+    m_ppcOrigYuv[uhDepth]->add( m_ppcResPredTmp [uhDepth], rpcTempCU->getWidth( 0 ), rpcTempCU->getHeight( 0 ) );
+  }
+#endif
+
+#if PART_MRG
+  if (rpcTempCU->getWidth(0) > 8 && !rpcTempCU->getMergeFlag(0) && (ePartSize != SIZE_2Nx2N && ePartSize != SIZE_NxN))
+  {
+    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], m_ppcResPredTmp [uhDepth],bSkipRes );
+#else
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], m_ppcResPredTmp [uhDepth], 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() );
+  }
+
+  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     = rpcTempCU->getWidth ( 0 );
+    UInt  uiHeight    = rpcTempCU->getHeight( 0 );
+    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 );
+
+#if LM_CHROMA
+  m_ppcRecoYuvTemp[uiDepth]->copyToPicLuma(rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getAddr(), rpcTempCU->getZorderIdxInCU() );
+#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 );
+
+  // Encode Coefficients
+  m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, rpcTempCU->getWidth (0), rpcTempCU->getHeight(0) );
+
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+#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() );
+  }
+
+  xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth );
+}
+
+// check whether current try is the best
+Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UChar uhDepth )
+{
+  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
+  {
+    TComYuv* pcYuv;
+
+    // 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]);
+  }
+}
+
+Void TEncCu::xCheckRDCostAMVPSkip           ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
+{
+  UChar uhDepth = rpcTempCU->getDepth(0);
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Bool  bResPrdAvail  = rpcTempCU->getResPredAvail( 0 );
+  Bool  bResPrdFlag   = rpcTempCU->getResPredFlag ( 0 );
+#endif
+
+  AMVPInfo cAMVPInfo0;
+  cAMVPInfo0.iN = 0;
+
+  AMVPInfo cAMVPInfo1;
+  cAMVPInfo1.iN = 0;
+
+  if (rpcTempCU->getAMVPMode(0) == AM_EXPL)
+  {
+    rpcTempCU->setPredModeSubParts( MODE_SKIP, 0, uhDepth );
+    rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N,  0, uhDepth );
+
+    if ( rpcTempCU->getSlice()->isInterP() && rpcTempCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+    {
+      rpcTempCU->fillMvpCand(0, 0, REF_PIC_LIST_0, 0, &cAMVPInfo0);
+    }
+    else if ( rpcTempCU->getSlice()->isInterB() &&
+             rpcTempCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 &&
+             rpcTempCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0  )
+    {
+      rpcTempCU->fillMvpCand(0, 0, REF_PIC_LIST_0, 0, &cAMVPInfo0);
+      rpcTempCU->fillMvpCand(0, 0, REF_PIC_LIST_1, 0, &cAMVPInfo1);
+    }
+    else
+    {
+      assert( 0 );
+    }
+  }
+
+  Int iMVP0, iMVP1;
+
+  for (iMVP0 = (cAMVPInfo0.iN > 0? 0:-1); iMVP0 < cAMVPInfo0.iN; iMVP0++)
+  {
+    for (iMVP1 = (cAMVPInfo1.iN > 0? 0:-1); iMVP1 < cAMVPInfo1.iN; iMVP1++)
+    {
+      rpcTempCU->setPredModeSubParts( MODE_SKIP, 0, uhDepth );
+      rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N,  0, uhDepth );
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      rpcTempCU->setResPredAvailSubParts( bResPrdAvail, 0, 0, uhDepth );
+      rpcTempCU->setResPredFlagSubParts ( bResPrdFlag,  0, 0, uhDepth );
+#endif
+
+      if (rpcTempCU->getSlice()->isInterB())
+        rpcTempCU->setInterDirSubParts( 3, 0, 0, uhDepth );
+
+      rpcTempCU->setMVPIdxSubParts( iMVP0, REF_PIC_LIST_0, 0, 0, uhDepth );
+      rpcTempCU->setMVPIdxSubParts( iMVP1, REF_PIC_LIST_1, 0, 0, uhDepth );
+
+      rpcTempCU->setMVPNumSubParts( cAMVPInfo0.iN, REF_PIC_LIST_0, 0, 0, uhDepth );
+      rpcTempCU->setMVPNumSubParts( cAMVPInfo1.iN, REF_PIC_LIST_1, 0, 0, uhDepth );
+
+      xCopyAMVPInfo(&cAMVPInfo0, rpcTempCU->getCUMvField(REF_PIC_LIST_0)->getAMVPInfo());
+      xCopyAMVPInfo(&cAMVPInfo1, rpcTempCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo());
+      xCheckRDCostSkip ( rpcBestCU, rpcTempCU, true );      rpcTempCU->initEstData();
+    }
+  }
+}
+
+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 uiAbsZorderIdx, UInt uiDepth)
+{
+  m_ppcRecoYuvBest[uiDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsZorderIdx );
+}
+
+Void TEncCu::xCopyYuv2Tmp( UInt uiPartUnitIdx, UInt uiNextDepth )
+{
+  UInt uiCurrDepth = uiNextDepth - 1;
+  m_ppcRecoYuvBest[uiNextDepth]->copyToPartYuv( m_ppcRecoYuvTemp[uiCurrDepth], uiPartUnitIdx );
+}
+
+#if HHI_MPI
+Void TEncCu::xCheckRDCostMvInheritance( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UChar uhTextureModeDepth, Bool bSkipResidual, Bool bRecursiveCall )
+{
+  assert( rpcTempCU->getSlice()->getSPS()->isDepth() );
+  TComDataCU *pcTextureCU = rpcTempCU->getSlice()->getTexturePic()->getCU( rpcTempCU->getAddr() );
+
+  const UChar uhDepth  = rpcTempCU->getDepth( 0 );
+  assert( bRecursiveCall == ( uhDepth != uhTextureModeDepth ) );
+
+  if( uhDepth == uhTextureModeDepth )
+  {
+    for( UInt ui = 0; ui < rpcTempCU->getTotalNumPart(); ui++ )
+    {
+      if( pcTextureCU->isIntra( rpcTempCU->getZorderIdxInCU() + ui ) )
+      {
+        return;
+      }
+    }
+  }
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseRenModel() && !bRecursiveCall)
+  {
+    UInt  uiWidth     = m_ppcTempCU [uhDepth]->getWidth ( 0 );
+    UInt  uiHeight    = m_ppcTempCU [uhDepth]->getHeight( 0 );
+    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( 0 );
+    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+    m_pcRdCost->setRenModelData( m_ppcTempCU[uhDepth], 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( rpcBestCU, uiPartUnitIdx, uhNextDepth );           // clear sub partition datas or init.
+      pcSubTempPartCU->initSubCU( rpcBestCU, uiPartUnitIdx, uhNextDepth );           // clear sub partition datas or init.
+
+      if( ( pcSubBestPartCU->getCUPelX() < pcSubBestPartCU->getSlice()->getSPS()->getWidth() ) && ( pcSubBestPartCU->getCUPelY() < pcSubBestPartCU->getSlice()->getSPS()->getHeight() ) )
+      {
+        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 );
+      }
+    }
+
+    if( uhDepth == uhTextureModeDepth )
+    {
+      xAddMVISignallingBits( rpcTempCU );
+    }
+
+    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() );
+    rpcTempCU->setPartSizeSubParts( SIZE_NxN, 0, uhDepth );
+    for( UInt ui = 0; ui < rpcTempCU->getTotalNumPart(); ui++ )
+    {
+      assert( rpcTempCU->getInterDir( ui ) != 0 );
+      assert( rpcTempCU->getPredictionMode( ui ) != MODE_NONE );
+    }
+    rpcTempCU->setPredModeSubParts( bSkipResidual ? MODE_SKIP : MODE_INTER, 0, uhDepth );
+    m_pcPredSearch->motionCompensation( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+
+    // 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], m_ppcResPredTmp [uhDepth], bSkipResidual );
+
+    if( uhDepth == uhTextureModeDepth )
+    {
+      xAddMVISignallingBits( 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() );
+  }
+
+  xCheckBestMode( rpcBestCU, rpcTempCU, uhDepth );
+
+#if HHI_VSO
+  if( !bSplit && bRecursiveCall && m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = rpcBestCU->getWidth ( 0 );
+    UInt  uiHeight    = rpcBestCU->getHeight( 0 );
+    Pel*  piSrc       = m_ppcRecoYuvBest[uhDepth]->getLumaAddr( 0 );
+    UInt  uiSrcStride = m_ppcRecoYuvBest[uhDepth]->getStride();
+    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( 0, 0, 0, uhDepth );
+
+  {
+    TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+    UInt uiNeighbourCandIdx[MRG_MAX_NUM_CANDS]; //MVs with same idx => same cand
+
+    for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+    {
+      uhInterDirNeighbours[ui] = 0;
+      uiNeighbourCandIdx[ui] = 0;
+    }
+    pcCU->getInterMergeCandidates( 0, 0, uhDepth, cMvFieldNeighbours,uhInterDirNeighbours, uiNeighbourCandIdx );
+    for( UInt uiMergeCand = 0; uiMergeCand < MRG_MAX_NUM_CANDS; uiMergeCand++ )
+    {
+      pcCU->setNeighbourCandIdxSubParts( uiMergeCand, uiNeighbourCandIdx[uiMergeCand], 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 ) )
+  {
+#if HHI_MRG_SKIP
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, 0, 0, true );
+#else
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 ) //if ( ref. frame list0 has at least 1 entry )
+    {
+      m_pcEntropyCoder->encodeMVPIdx( pcCU, 0, REF_PIC_LIST_0, true );
+    }
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 ) //if ( ref. frame list1 has at least 1 entry )
+    {
+      m_pcEntropyCoder->encodeMVPIdx( pcCU, 0, REF_PIC_LIST_1, true );
+    }
+#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 );
+  }
+  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: /tags/0.2r1/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncCu.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncCu.h	(revision 19)
@@ -0,0 +1,162 @@
+/* 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     TEncCU.h
+    \brief    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"
+
+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
+  TComYuv**               m_ppcResPredTmp;  ///< Temporary residual prediction for each depth
+  
+  //  Data : encoder control
+  Int                     m_iQp;            ///< Last QP
+  
+  //  Access channel
+  TEncCfg*                m_pcEncCfg;
+  TEncTop*                m_pcEncTop;
+  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  );
+  
+  /// set QP value
+  Void  setQpLast           ( Int iQp ) { m_iQp = iQp; }
+  
+protected:
+  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
+  Void  xEncodeCU           ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
+  
+  Void  xCheckRDCostAMVPSkip( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU                      );
+  
+#if HHI_INTERVIEW_SKIP
+  Void xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool bFullyRendered ) ;
+#else
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU                  );
+#endif
+  
+  Void  xCheckRDCostSkip    ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool bBSkipRes      );
+#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  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+  Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UChar uhDepth       );
+  
+  Void  xCopyAMVPInfo       ( AMVPInfo* pSrc, AMVPInfo* pDst );
+  Void  xCopyYuv2Pic        ( TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void  xCopyYuv2Tmp        ( UInt uhPartUnitIdx, UInt uiDepth );
+  Void  xAddMVISignallingBits( TComDataCU* pcCU );
+#if HHI_MPI
+  Void  xCheckRDCostMvInheritance( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UChar uhTextureModeDepth, Bool bSkipResidual, Bool bRecursiveCall );
+  Void  xSaveDepthWidthHeight( TComDataCU* pcCU );
+  Void  xRestoreDepthWidthHeight( TComDataCU* pcCU );
+#endif
+};
+
+
+#endif // __TENCMB__
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 19)
@@ -0,0 +1,1725 @@
+/* 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     TEncEntropy.cpp
+    \brief    entropy encoder class
+*/
+
+#include "TEncEntropy.h"
+
+Void TEncEntropy::setEntropyCoder ( TEncEntropyIf* e, TComSlice* pcSlice )
+{
+  m_pcEntropyCoderIf = e;
+  m_pcEntropyCoderIf->setSlice ( pcSlice );
+}
+
+Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
+{
+  m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
+  return;
+}
+
+Void TEncEntropy::encodeTerminatingBit      ( UInt uiIsLast )
+{
+  m_pcEntropyCoderIf->codeTerminatingBit( uiIsLast );
+  
+  return;
+}
+
+Void TEncEntropy::encodeSliceFinish()
+{
+  m_pcEntropyCoderIf->codeSliceFinish();
+}
+
+void TEncEntropy::encodeSEI(const SEI& sei)
+{
+  m_pcEntropyCoderIf->codeSEI(sei);
+  return;
+}
+
+Void TEncEntropy::encodePPS( TComPPS* pcPPS )
+{
+  m_pcEntropyCoderIf->codePPS( pcPPS );
+  return;
+}
+
+Void TEncEntropy::encodeSPS( TComSPS* pcSPS )
+{
+  m_pcEntropyCoderIf->codeSPS( pcSPS );
+  return;
+}
+
+Void TEncEntropy::encodeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+  if( bRD )
+    uiAbsPartIdx = 0;
+  m_pcEntropyCoderIf->codeSkipFlag( pcCU, uiAbsPartIdx );
+}
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComAdaptiveLoopFilter.h"
+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)
+{
+#if ENABLE_FORCECOEFF0
+  if (pAlfParam->filtNo>=0) m_pcEntropyCoderIf->codeAlfFlag(1);
+  else m_pcEntropyCoderIf->codeAlfFlag(0);
+#endif
+  Int FiltTab[3] = {9, 7, 5};
+  Int Tab = FiltTab[pAlfParam->realfiltNo];
+  //  m_pcEntropyCoderIf->codeAlfUvlc(pAlfParam->realfiltNo); 
+
+#if MQT_BA_RA  
+  m_pcEntropyCoderIf->codeAlfFlag(pAlfParam->alf_pcr_region_flag);
+#endif
+
+  m_pcEntropyCoderIf->codeAlfUvlc((Tab-5)/2); 
+  
+  if (pAlfParam->filtNo>=0)
+  {
+    if(pAlfParam->realfiltNo >= 0)
+    {
+      // filters_per_fr
+      m_pcEntropyCoderIf->codeAlfUvlc(pAlfParam->noFilters);
+
+      if(pAlfParam->noFilters == 1)
+      {
+        m_pcEntropyCoderIf->codeAlfUvlc(pAlfParam->startSecondFilter);
+      }
+      else if (pAlfParam->noFilters == 2)
+      {
+        for (int i=1; i<NO_VAR_BINS; 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_diff;
+  int sqrFiltLength = ALFp->num_coeff;
+  int filtNo = ALFp->realfiltNo;
+  int flTab[]={9/2, 7/2, 5/2};
+  int fl = flTab[filtNo];
+  int i, k, kMin, kStart, minBits, ind, scanPos, maxScanVal, coeffVal, len = 0,
+  *pDepthInt=NULL, kMinTab[MAX_SQR_FILT_LENGTH], bitsCoeffScan[MAX_SCAN_VAL][MAX_EXP_GOLOMB],
+  minKStart, minBitsKStart, bitsKStart;
+  
+  pDepthInt = pDepthIntTab[fl-2];
+  
+  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(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 = 0; 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 = 0; 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;
+  ALFp->maxScanVal = maxScanVal;
+  for(scanPos = 0; scanPos < maxScanVal; scanPos++)
+  {
+    ALFp->kMinTab[scanPos] = kMinTab[scanPos];
+  }
+  len += writeFilterCodingParams(minKStart, maxScanVal, kMinTab);
+  
+  // Filter coefficients
+  len += writeFilterCoeffs(sqrFiltLength, filters_per_group, pDepthInt, ALFp->coeffmulti, kMinTab);
+  
+  return len;
+}
+
+Int TEncEntropy::writeFilterCodingParams(int minKStart, int maxScanVal, int kMinTab[])
+{
+  int scanPos;
+  int golombIndexBit;
+  int kMin;
+  
+  // Golomb parameters
+  m_pcEntropyCoderIf->codeAlfUvlc(minKStart - 1);
+  
+  kMin = minKStart; 
+  for(scanPos = 0; 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;
+      golombEncode(FilterCoeff[ind][i], kMinTab[scanPos]);
+    }
+  }
+  return 0;
+}
+
+Int TEncEntropy::golombEncode(int coeff, int k)
+{
+  int q, i, m;
+  int symbol = abs(coeff);
+  
+  m = (int)pow(2.0, k);
+  q = symbol / m;
+  
+  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)
+  {
+#if ENABLE_FORCECOEFF0
+    m_pcEntropyCoderIf->codeAlfFlag (pAlfParam->forceCoeff0);
+    if (pAlfParam->forceCoeff0)
+    {
+      for (int i=0; i<pAlfParam->filters_per_group; i++) m_pcEntropyCoderIf->codeAlfFlag (pAlfParam->codedVarBins[i]);
+    }
+#endif 
+    m_pcEntropyCoderIf->codeAlfFlag (pAlfParam->predMethod);
+  }
+  codeFilterCoeff (pAlfParam);
+}
+
+Void  print(ALFParam* pAlfParam)
+{
+  Int i=0;
+  Int ind=0;
+  Int FiltLengthTab[] = {22, 14, 8}; //0:9tap
+  Int FiltLength = FiltLengthTab[pAlfParam->realfiltNo];
+  
+  printf("set of params\n");
+  printf("realfiltNo:%d\n", pAlfParam->realfiltNo);
+  printf("filtNo:%d\n", pAlfParam->filtNo);
+  printf("filterPattern:");
+  for (i=0; i<NO_VAR_BINS; i++) printf("%d ", pAlfParam->filterPattern[i]);
+  printf("\n");
+  
+  printf("startSecondFilter:%d\n", pAlfParam->startSecondFilter);
+  printf("noFilters:%d\n", pAlfParam->noFilters);
+  printf("varIndTab:");
+  for (i=0; i<NO_VAR_BINS; i++) printf("%d ", pAlfParam->varIndTab[i]);
+  printf("\n");
+  printf("filters_per_group_diff:%d\n", pAlfParam->filters_per_group_diff);
+  printf("filters_per_group:%d\n", pAlfParam->filters_per_group);
+  printf("codedVarBins:");
+  for (i=0; i<NO_VAR_BINS; i++) printf("%d ", pAlfParam->codedVarBins[i]);
+  printf("\n");
+  printf("forceCoeff0:%d\n", pAlfParam->forceCoeff0);
+  printf("predMethod:%d\n", pAlfParam->predMethod);
+  
+  for (ind=0; ind<pAlfParam->filters_per_group_diff; ind++)
+  {
+    printf("coeffmulti(%d):", ind);
+    for (i=0; i<FiltLength; i++) printf("%d ", pAlfParam->coeffmulti[ind][i]);
+    printf("\n");
+  }
+  
+  printf("minKStart:%d\n", pAlfParam->minKStart);  
+  printf("maxScanVal:%d\n", pAlfParam->maxScanVal);  
+  printf("kMinTab:");
+  for(Int scanPos = 0; scanPos < pAlfParam->maxScanVal; scanPos++)
+  {
+    printf("%d ", pAlfParam->kMinTab[scanPos]);
+  }
+  printf("\n");
+  
+  printf("chroma_idc:%d\n", pAlfParam->chroma_idc);  
+  printf("tap_chroma:%d\n", pAlfParam->tap_chroma);  
+  printf("chroma_coeff:");
+  for(Int scanPos = 0; scanPos < pAlfParam->num_coeff_chroma; scanPos++)
+  {
+    printf("%d ", pAlfParam->coeff_chroma[scanPos]);
+  }
+  printf("\n");
+}
+
+/** encode merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiPUIdx
+ * \returns Void
+ */
+Void TEncEntropy::encodeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx )
+{ 
+  UInt uiNumCand = 0;
+  for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == uiIter + 1 )
+    {
+      uiNumCand++;
+      break;
+    }
+  }
+  if ( uiNumCand )
+  {
+    // at least one merge candidate exists
+    m_pcEntropyCoderIf->codeMergeFlag( pcCU, uiAbsPartIdx );
+  }
+  else
+  {
+    assert( !pcCU->getMergeFlag( uiAbsPartIdx ) );
+  }
+}
+
+#if HHI_MRG_SKIP
+/** encode merge index
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiPUIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx, Bool bRD )
+#else
+Void TEncEntropy::encodeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx )
+#endif
+{
+#if HHI_MRG_SKIP
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  }
+#endif
+
+  UInt uiNumCand = 0;
+  for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == uiIter + 1 )
+    {
+      uiNumCand++;
+    }
+  }
+#if HHI_MPI
+  if( pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+    uiNumCand++;
+#endif
+  if ( uiNumCand > 1 )
+  {
+    m_pcEntropyCoderIf->codeMergeIndex( pcCU, uiAbsPartIdx );
+  }
+}
+
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+Void 
+TEncEntropy::encodeResPredFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+
+  // check whether flag is coded
+  ROTVS( pcCU->getSlice()->getSPS()->isDepth                () );
+  ROFVS( pcCU->getSlice()->getSPS()->getViewId              () );
+  ROFVS( pcCU->getSlice()->getSPS()->getMultiviewResPredMode() );
+  ROTVS( pcCU->isIntra           ( uiAbsPartIdx )              );
+  ROFVS( pcCU->getResPredAvail   ( uiAbsPartIdx )              );
+
+  // encode flag
+  m_pcEntropyCoderIf->codeResPredFlag( pcCU, uiAbsPartIdx );
+}
+#endif
+
+
+Void TEncEntropy::encodeAlfParam(ALFParam* pAlfParam)
+{
+  m_pcEntropyCoderIf->codeAlfFlag(pAlfParam->alf_flag);
+  if (!pAlfParam->alf_flag)
+    return;
+  Int pos;
+  codeAux(pAlfParam);
+  codeFilt(pAlfParam);
+  
+  // filter parameters for chroma
+  m_pcEntropyCoderIf->codeAlfUvlc(pAlfParam->chroma_idc);
+  if(pAlfParam->chroma_idc)
+  {
+    m_pcEntropyCoderIf->codeAlfUvlc((pAlfParam->tap_chroma-5)/2);
+    
+    // filter coefficients for chroma
+    for(pos=0; pos<pAlfParam->num_coeff_chroma; pos++)
+    {
+      m_pcEntropyCoderIf->codeAlfSvlc(pAlfParam->coeff_chroma[pos]);
+    }
+  }
+  
+  // region control parameters for luma
+  m_pcEntropyCoderIf->codeAlfFlag(pAlfParam->cu_control_flag);
+  if (pAlfParam->cu_control_flag)
+  {
+    assert( (pAlfParam->cu_control_flag && m_pcEntropyCoderIf->getAlfCtrl()) || (!pAlfParam->cu_control_flag && !m_pcEntropyCoderIf->getAlfCtrl()));
+    m_pcEntropyCoderIf->codeAlfCtrlDepth();
+  }
+}
+
+Void TEncEntropy::encodeAlfCtrlFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  m_pcEntropyCoderIf->codeAlfCtrlFlag( pcCU, uiAbsPartIdx );
+}
+
+#if TSB_ALF_HEADER
+Void TEncEntropy::encodeAlfCtrlParam( ALFParam* pAlfParam )
+{
+  m_pcEntropyCoderIf->codeAlfFlagNum( pAlfParam->num_alf_cu_flag, pAlfParam->num_cus_in_frame );
+  
+  for(UInt i=0; i<pAlfParam->num_alf_cu_flag; i++)
+  {
+    m_pcEntropyCoderIf->codeAlfCtrlFlag( pAlfParam->alf_cu_flag[i] );
+  }
+}
+#endif
+
+/** 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 ( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+ 
+  m_pcEntropyCoderIf->codePredMode( pcCU, uiAbsPartIdx );
+}
+
+// Split mode
+Void TEncEntropy::encodeSplitFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
+{
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  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;
+  
+  m_pcEntropyCoderIf->codePartSize( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TEncEntropy::xEncodeTransformSubdiv( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiInnerQuadIdx, UInt& uiYCbfFront3, UInt& uiUCbfFront3, UInt& uiVCbfFront3 )
+{
+  const UInt uiSubdiv = pcCU->getTransformIdx( uiAbsPartIdx ) + pcCU->getDepth( uiAbsPartIdx ) > uiDepth;
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
+#if CAVLC_RQT_CBP
+  if(pcCU->getSlice()->getSymbolMode() == 0)
+  {
+    m_pcEntropyCoderIf->codeCbfTrdiv( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {//CABAC
+#endif
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    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 HHI_RQT_FORCE_SPLIT_ACC2_PU
+      UInt uiCtx = uiDepth;
+      const UInt uiTrMode = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+#if HHI_RQT_FORCE_SPLIT_NxN
+      const Bool bNxNOK         = pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN && uiTrMode > 0;
+#else
+      const Bool bNxNOK         = pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN;
+#endif
+#if HHI_RQT_FORCE_SPLIT_RECT
+      const Bool bSymmetricOK   = pcCU->getPartitionSize( uiAbsPartIdx ) >= SIZE_2NxN  && pcCU->getPartitionSize( uiAbsPartIdx ) < SIZE_NxN   && uiTrMode > 0;
+#else
+      const Bool bSymmetricOK   = pcCU->getPartitionSize( uiAbsPartIdx ) >= SIZE_2NxN  && pcCU->getPartitionSize( uiAbsPartIdx ) < SIZE_NxN;
+#endif
+      const Bool bNeedSubdivFlag = pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N || pcCU->getPredictionMode( uiAbsPartIdx ) == MODE_INTRA ||
+      bNxNOK || bSymmetricOK;
+      if( bNeedSubdivFlag )
+      {
+        m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSubdiv, uiCtx );
+      }
+#else
+      m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSubdiv, uiDepth );
+#endif
+    }
+#if CAVLC_RQT_CBP
+  }
+#endif
+  
+  if(pcCU->getSlice()->getSymbolMode() == 0)
+  {
+    if( uiSubdiv )
+    {
+      ++uiDepth;
+      const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+      UInt uiDummyCbfY = 0;
+      UInt uiDummyCbfU = 0;
+      UInt uiDummyCbfV = 0;
+      xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 0, uiDummyCbfY, uiDummyCbfU, uiDummyCbfV );
+      uiAbsPartIdx += uiQPartNum;
+      xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 1, uiDummyCbfY, uiDummyCbfU, uiDummyCbfV );
+      uiAbsPartIdx += uiQPartNum;
+      xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 2, uiDummyCbfY, uiDummyCbfU, uiDummyCbfV );
+      uiAbsPartIdx += uiQPartNum;
+      xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 3, uiDummyCbfY, uiDummyCbfU, uiDummyCbfV );
+    }
+  }
+  else
+  {
+    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && 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 > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        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 )
+    {
+      ++uiDepth;
+      const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+      
+      UInt uiCurrentCbfY = 0;
+      UInt uiCurrentCbfU = 0;
+      UInt uiCurrentCbfV = 0;
+      
+      xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 0, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV );
+      uiAbsPartIdx += uiQPartNum;
+      xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 1, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV );
+      uiAbsPartIdx += uiQPartNum;
+      xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 2, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV );
+      uiAbsPartIdx += uiQPartNum;
+      xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 3, uiCurrentCbfY, uiCurrentCbfU, uiCurrentCbfV );
+      
+      uiYCbfFront3 += uiCurrentCbfY;
+      uiUCbfFront3 += uiCurrentCbfU;
+      uiVCbfFront3 += uiCurrentCbfV;
+    }
+    else
+    {
+      {
+        DTRACE_CABAC_V( 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_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
+      {
+        if ( pcCU->getPredictionMode( uiAbsPartIdx ) != MODE_INTRA && uiInnerQuadIdx == 3 && uiYCbfFront3 == 0 && uiUCbfFront3 == 0 && uiVCbfFront3 == 0
+            && uiLog2TrafoSize < pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode ) )
+        {      
+          uiYCbfFront3++;
+        }    
+        else
+        {
+          m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode );
+          uiYCbfFront3 += pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiLumaTrMode );
+        }
+      }
+      
+      if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
+      {
+        Bool bCodeChroma = true;
+        if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+        {
+          UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+          bCodeChroma  = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+        }
+        if( bCodeChroma )
+        {
+          m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiChromaTrMode );
+          m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiChromaTrMode );
+        }
+      }
+    }
+  }
+}
+
+// transform index
+Void TEncEntropy::encodeTransformIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
+{
+  assert( !bRD ); // parameter bRD can be removed
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  DTRACE_CABAC_V( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
+  DTRACE_CABAC_V( uiDepth )
+  DTRACE_CABAC_T( "\n" )
+  UInt temp = 0;
+  UInt temp1 = 0;
+  UInt temp2 = 0;
+  xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 0, temp, temp1, temp2 );
+}
+
+// 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;
+  
+  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
+  {
+    if ( pcCU->getSlice()->getSPS()->getUseMRG() )
+    {
+      encodePUWise( pcCU, uiAbsPartIdx, bRD );
+    }
+    else
+    {
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+      if ( pcCU->getSlice()->getSymbolMode() == 0 )
+      {
+        if ( pcCU->isSuroundingRefIdxException( uiAbsPartIdx ) )
+        {
+          pcCU->getSlice()->setRefIdxCombineCoding( false );
+        }
+        else
+        {
+          pcCU->getSlice()->setRefIdxCombineCoding( true );
+        }
+      }
+#endif
+      encodeInterDir( pcCU, uiAbsPartIdx, bRD );
+      
+      {
+        if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )       // if ( ref. frame list0 has at least 1 entry )
+        {
+          encodeRefFrmIdx ( pcCU, uiAbsPartIdx, REF_PIC_LIST_0, bRD );
+          encodeMvd       ( pcCU, uiAbsPartIdx, REF_PIC_LIST_0, bRD );
+          encodeMVPIdx    ( pcCU, uiAbsPartIdx, REF_PIC_LIST_0      );
+        }
+        
+        if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )       // if ( ref. frame list1 has at least 1 entry )
+        {
+          encodeRefFrmIdx ( pcCU, uiAbsPartIdx, REF_PIC_LIST_1, bRD );
+          encodeMvd       ( pcCU, uiAbsPartIdx, REF_PIC_LIST_1, bRD );
+          encodeMVPIdx    ( pcCU, uiAbsPartIdx, REF_PIC_LIST_1      );
+        }
+      }
+    }
+  }
+}
+
+/** encode inter direction
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+  assert( pcCU->getSlice()->isInterB());
+
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  if ( !pcCU->getSlice()->isInterB() )
+  {
+    return;
+  }
+  
+  UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+  
+  switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+  {
+    case SIZE_2Nx2N:
+    {
+      m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+      break;
+    }
+      
+    case SIZE_2NxN:
+    {
+      m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+      uiAbsPartIdx += uiPartOffset << 1;
+      m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+      break;
+    }
+      
+    case SIZE_Nx2N:
+    {
+      m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+      uiAbsPartIdx += uiPartOffset;
+      m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+      break;
+    }
+      
+    case SIZE_NxN:
+    {
+      for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+      {
+        m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+        uiAbsPartIdx += uiPartOffset;
+      }
+      break;
+    }
+    default:
+      break;
+  }
+  
+  return;
+}
+
+/** encode motion information for every PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param bRD
+ * \returns Void
+ * This function is called only if merge is enabled.
+ */
+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 )
+  {
+#if PART_MRG
+    if (pcCU->getWidth( uiAbsPartIdx ) <= 8 || uiNumPU != 2 || uiPartIdx != 0)
+#endif
+    encodeMergeFlag( pcCU, uiSubPartIdx, uiPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      encodeMergeIndex( pcCU, uiSubPartIdx, uiPartIdx );
+    }
+    else
+    {
+#if MS_LCEC_LOOKUP_TABLE_EXCEPTION
+      if ( pcCU->getSlice()->getSymbolMode() == 0 )
+      {
+        if ( pcCU->isSuroundingRefIdxException( uiAbsPartIdx ) )
+        {
+          pcCU->getSlice()->setRefIdxCombineCoding( false );
+        }
+        else
+        {
+          pcCU->getSlice()->setRefIdxCombineCoding( true );
+        }
+      }
+#endif
+      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 DCM_COMB_LIST 
+  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
+  {
+#endif
+
+  if ( ( pcCU->getSlice()->getNumRefIdx( eRefList ) == 1 ) )
+  {
+    return;
+  }
+
+  if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+  {
+    m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+  }
+
+#if DCM_COMB_LIST 
+  }
+#endif
+
+  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->getMVPNum(eRefList, uiAbsPartIdx)> 1) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+  {
+    m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+  }
+
+  return;
+}
+
+Void TEncEntropy::encodeMVPIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Bool bRD )
+{
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+  
+  switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+  {
+    case SIZE_2Nx2N:
+    {
+      if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) && (pcCU->getMVPNum(eRefList, uiAbsPartIdx)> 1) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+      {
+        m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+      }
+      break;
+    }
+      
+    case SIZE_2NxN:
+    {
+      if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) && (pcCU->getMVPNum(eRefList, uiAbsPartIdx)> 1) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+      {
+        m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+      }
+      uiAbsPartIdx += uiPartOffset << 1;
+      if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) && (pcCU->getMVPNum(eRefList, uiAbsPartIdx)> 1) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+      {
+        m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+      }
+      break;
+    }
+      
+    case SIZE_Nx2N:
+    {
+      if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) && (pcCU->getMVPNum(eRefList, uiAbsPartIdx)> 1) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+      {
+        m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+      }
+      
+      uiAbsPartIdx += uiPartOffset;
+      if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) && (pcCU->getMVPNum(eRefList, uiAbsPartIdx)> 1) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+      {
+        m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+      }
+      
+      break;
+    }
+      
+    case SIZE_NxN:
+    {
+      for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+      {
+        if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) && (pcCU->getMVPNum(eRefList, uiAbsPartIdx)> 1) && (pcCU->getAMVPMode(uiAbsPartIdx) == AM_EXPL) )
+        {
+          m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+        }
+        uiAbsPartIdx += uiPartOffset;
+      }
+      break;
+    }
+    default:
+      break;
+  }
+  
+  return;
+  
+}
+
+Void TEncEntropy::encodeViewIdx(Int iViewIdx )
+{
+  m_pcEntropyCoderIf->codeViewIdx(iViewIdx);
+}
+
+/** encode reference frame index
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param eRefList
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Bool bRD )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+  
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+#if DCM_COMB_LIST
+  if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+  {
+    UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+
+    switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+    {
+      case SIZE_2Nx2N:
+      {
+        if ( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList== REF_PIC_LIST_0 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C ) > 1)
+        {
+          if ( pcCU->getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 1 )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, RefPicList(pcCU->getInterDir( uiAbsPartIdx )-1) );
+          }
+        }
+        else if (pcCU->getInterDir( uiAbsPartIdx ) == 3 &&  pcCU->getSlice()->getNumRefIdx( eRefList ) > 1)
+        {
+          if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+          }
+        }
+        break;
+      }
+      case SIZE_2NxN:
+      {
+        if ( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList== REF_PIC_LIST_0 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C ) > 1)
+        {
+          if ( pcCU->getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 1 )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, RefPicList(pcCU->getInterDir( uiAbsPartIdx )-1) );
+          }
+        }
+        else if (pcCU->getInterDir( uiAbsPartIdx ) == 3 &&  pcCU->getSlice()->getNumRefIdx( eRefList ) > 1)
+        {
+          if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+          }
+        }
+
+        uiAbsPartIdx += uiPartOffset << 1;
+
+        if ( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList== REF_PIC_LIST_0 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C ) > 1)
+        {
+          if ( pcCU->getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 1 )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, RefPicList(pcCU->getInterDir( uiAbsPartIdx )-1) );
+          }
+        }
+        else if (pcCU->getInterDir( uiAbsPartIdx ) == 3 &&  pcCU->getSlice()->getNumRefIdx( eRefList ) > 1)
+        {
+          if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+          }
+        }
+        break;
+      }
+      case SIZE_Nx2N:
+      {
+        if ( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList== REF_PIC_LIST_0 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C ) > 1)
+        {
+          if ( pcCU->getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 1 )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, RefPicList(pcCU->getInterDir( uiAbsPartIdx )-1) );
+          }
+        }
+        else if (pcCU->getInterDir( uiAbsPartIdx ) == 3 &&  pcCU->getSlice()->getNumRefIdx( eRefList ) > 1)
+        {
+          if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+          }
+        }
+
+        uiAbsPartIdx += uiPartOffset;
+
+        if ( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList== REF_PIC_LIST_0 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C ) > 1)
+        {
+          if ( pcCU->getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 1 )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, RefPicList(pcCU->getInterDir( uiAbsPartIdx )-1) );
+          }
+        }
+        else if (pcCU->getInterDir( uiAbsPartIdx ) == 3 &&  pcCU->getSlice()->getNumRefIdx( eRefList ) > 1)
+        {
+          if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+          }
+        }
+        break;
+      }
+      case SIZE_NxN:
+      {
+        for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+        {
+          if ( pcCU->getInterDir( uiAbsPartIdx ) != 3 && eRefList== REF_PIC_LIST_0 && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C ) > 1)
+          {
+            if ( pcCU->getSlice()->getNumRefIdx ( REF_PIC_LIST_C ) > 1 )
+            {
+              m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, RefPicList(pcCU->getInterDir( uiAbsPartIdx )-1) );
+            }
+          }
+          else if (pcCU->getInterDir( uiAbsPartIdx ) == 3 &&  pcCU->getSlice()->getNumRefIdx( eRefList ) > 1)
+          {
+            if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+            {
+              m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+            }
+          }
+
+          uiAbsPartIdx += uiPartOffset;
+        }
+        break;
+      }
+      default:
+        break;
+    }
+  }
+  else
+  {
+#endif
+    if ( pcCU->getSlice()->getNumRefIdx( eRefList ) == 1 )
+    {
+      return;
+    }
+
+    UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+
+    switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+    {
+      case SIZE_2Nx2N:
+      {
+        if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+        {
+          m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+        }
+        break;
+      }
+      case SIZE_2NxN:
+      {
+        if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+        {
+          m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+        }
+
+        uiAbsPartIdx += uiPartOffset << 1;
+        if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+        {
+          m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+        }
+        break;
+      }
+      case SIZE_Nx2N:
+      {
+        if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+        {
+          m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+        }
+
+        uiAbsPartIdx += uiPartOffset;
+        if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+        {
+          m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+        }
+        break;
+      }
+      case SIZE_NxN:
+      {
+        for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+        {
+          if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+          {
+            m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+          }
+          uiAbsPartIdx += uiPartOffset;
+        }
+        break;
+      }
+      default:
+        break;
+    }
+
+#if DCM_COMB_LIST 
+  }
+#endif
+
+  return;
+}
+
+/** encode motion vector difference
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param eRefList
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Bool bRD )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+  
+  if( bRD )
+    uiAbsPartIdx = 0;
+  
+  UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+  
+  switch ( pcCU->getPartitionSize( uiAbsPartIdx ) )
+  {
+    case SIZE_2Nx2N:
+    {
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+      }
+      break;
+    }
+      
+    case SIZE_2NxN:
+    {
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+      }
+      
+      uiAbsPartIdx += uiPartOffset << 1;
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+      }
+      break;
+    }
+      
+    case SIZE_Nx2N:
+    {
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+      }
+      
+      uiAbsPartIdx += uiPartOffset;
+      if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+      {
+        m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+      }
+      break;
+    }
+      
+    case SIZE_NxN:
+    {
+      for ( Int iPartIdx = 0; iPartIdx < 4; iPartIdx++ )
+      {
+        if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+        {
+          m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+        }
+        uiAbsPartIdx += uiPartOffset;
+      }
+      break;
+    }
+    default:
+      break;
+  }
+  
+  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()->getSPS()->getUseDQP() )
+  {
+    m_pcEntropyCoderIf->codeDeltaQP( pcCU, uiAbsPartIdx );
+  }
+}
+
+
+// texture
+Void TEncEntropy::xEncodeCoeff( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, UInt uiTrIdx, UInt uiCurrTrIdx, TextType eType, Bool bRD )
+{
+  if ( pcCU->getCbf( uiAbsPartIdx, eType, uiTrIdx ) )
+  {
+#if SNY_DQP
+    // dQP: only for LCU once
+    if ( pcCU->getSlice()->getSPS()->getUseDQP() )
+    {
+      if ( pcCU->getdQPFlag())// non-skip
+      {
+        encodeQP( pcCU, 0 );
+        pcCU->setdQPFlag(false);
+      }
+    }
+#endif//SNY_DQP
+    UInt uiLumaTrMode, uiChromaTrMode;
+    pcCU->convertTransIdx( uiAbsPartIdx, pcCU->getTransformIdx( uiAbsPartIdx ), uiLumaTrMode, uiChromaTrMode );
+    const UInt uiStopTrMode = eType == TEXT_LUMA ? uiLumaTrMode : uiChromaTrMode;
+    
+    assert(1); // as long as quadtrees are not used for residual transform
+    
+    if( uiTrIdx == uiStopTrMode )
+    {
+      assert( !bRD ); // parameter bRD can be removed
+      
+      UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+      if( eType != TEXT_LUMA && uiLog2TrSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+        if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+        {
+          return;
+        }
+        uiWidth  <<= 1;
+        uiHeight <<= 1;
+      }
+      m_pcEntropyCoderIf->codeCoeffNxN( pcCU, pcCoeff, uiAbsPartIdx, uiWidth, uiHeight, uiDepth, eType, bRD );
+    }
+    else
+    {
+      {
+        DTRACE_CABAC_V( g_nSymbolCounter++ );
+        DTRACE_CABAC_T( "\tgoing down\tdepth=" );
+        DTRACE_CABAC_V( uiDepth );
+        DTRACE_CABAC_T( "\ttridx=" );
+        DTRACE_CABAC_V( uiTrIdx );
+        DTRACE_CABAC_T( "\n" );
+      }
+      if( uiCurrTrIdx <= uiTrIdx )
+        assert(1);
+      
+      UInt uiSize;
+      uiWidth  >>= 1;
+      uiHeight >>= 1;
+      uiSize = uiWidth*uiHeight;
+      uiDepth++;
+      uiTrIdx++;
+      
+      UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+      UInt uiIdx      = uiAbsPartIdx;
+      
+#if !CAVLC_RQT_CBP
+      if(pcCU->getSlice()->getSymbolMode() == 0)
+      {
+        UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+        if( eType == TEXT_LUMA || uiLog2TrSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+          m_pcEntropyCoderIf->codeBlockCbf(pcCU, uiIdx, eType, uiTrIdx, uiQPartNum);
+        xEncodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType, bRD ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xEncodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType, bRD ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xEncodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType, bRD ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xEncodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType, bRD );
+      }
+      else
+      {
+#endif
+        xEncodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType, bRD ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xEncodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType, bRD ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xEncodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType, bRD ); pcCoeff += uiSize; uiIdx += uiQPartNum;
+        xEncodeCoeff( pcCU, pcCoeff, uiIdx, uiDepth, uiWidth, uiHeight, uiTrIdx, uiCurrTrIdx, eType, bRD );
+#if !CAVLC_RQT_CBP
+      }
+#endif
+      {
+        DTRACE_CABAC_V( g_nSymbolCounter++ );
+        DTRACE_CABAC_T( "\tgoing up\n" );
+      }
+    }
+  }
+}
+
+Void TEncEntropy::encodeCoeff( TComDataCU* pcCU, TCoeff* pCoeff, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, UInt uiMaxTrMode, UInt uiTrMode, TextType eType, Bool bRD )
+{
+  xEncodeCoeff( pcCU, pCoeff, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, uiTrMode, uiMaxTrMode, eType, bRD );
+}
+
+/** encode coefficients
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param uiWidth
+ * \param uiHeight
+ * \returns Void
+ */
+Void TEncEntropy::encodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight )
+{
+  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( pcCU->isIntra(uiAbsPartIdx) )
+  {
+    DTRACE_CABAC_V( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
+    DTRACE_CABAC_V( uiDepth )
+    DTRACE_CABAC_T( "\n" )
+    UInt temp = 0;
+    UInt temp1 = 0;
+    UInt temp2 = 0;
+    xEncodeTransformSubdiv( pcCU, uiAbsPartIdx, uiDepth, 0, temp, temp1, temp2 );
+    
+#if !CAVLC_RQT_CBP
+    if (pcCU->getSlice()->getSymbolMode() == 0)
+    {
+      m_pcEntropyCoderIf->codeCbf( pcCU, uiAbsPartIdx, TEXT_ALL, 0 );
+      if(pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, 0)==0 && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, 0)==0
+         && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, 0)==0)
+        return;
+    }
+#endif
+  }
+  else
+  {
+    if (pcCU->getSlice()->getSymbolMode()==0)
+    {
+#if !CAVLC_RQT_CBP
+      m_pcEntropyCoderIf->codeCbf( pcCU, uiAbsPartIdx, TEXT_ALL, 0 );
+      if(pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, 0)==0 && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U, 0)==0
+         && pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V, 0)==0)
+        return;
+#endif
+    }
+    else
+    {
+#if  HHI_MRG_SKIP
+#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 );
+      }
+#else
+      m_pcEntropyCoderIf->codeQtRootCbf( pcCU, uiAbsPartIdx );
+#endif
+      if ( !pcCU->getQtRootCbf( uiAbsPartIdx ) )
+      {
+        pcCU->setTrIdxSubParts( 0 , uiAbsPartIdx, uiDepth );
+        return;
+      }
+    }
+    
+    encodeTransformIdx( pcCU, uiAbsPartIdx, pcCU->getDepth(uiAbsPartIdx) );
+  }
+  
+  xEncodeCoeff( pcCU, pcCU->getCoeffY()  + uiLumaOffset,   uiAbsPartIdx, uiDepth, uiWidth,    uiHeight,    0, uiLumaTrMode,   TEXT_LUMA     );
+  xEncodeCoeff( pcCU, pcCU->getCoeffCb() + uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth>>1, uiHeight>>1, 0, uiChromaTrMode, TEXT_CHROMA_U );
+  xEncodeCoeff( pcCU, pcCU->getCoeffCr() + uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth>>1, uiHeight>>1, 0, uiChromaTrMode, TEXT_CHROMA_V );
+}
+
+Void TEncEntropy::encodeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiTrWidth, UInt uiTrHeight, UInt uiDepth, TextType eType, Bool bRD )
+{ // 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, bRD );
+}
+
+Void TEncEntropy::estimateBit (estBitsSbacStruct* pcEstBitsSbac, UInt uiWidth, TextType eTType)
+{
+  UInt uiCTXIdx;
+  
+  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;
+  }
+  
+  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : TEXT_CHROMA;
+  
+  m_pcEntropyCoderIf->estBit ( pcEstBitsSbac, uiCTXIdx, eTType );
+}
+
+#if MTK_SAO
+/** encode QAO One Part
+ * \param  pQaoParam, iPartIdx
+ */
+Void TEncEntropy::encodeQAOOnePart(SAOParam* pQaoParam, Int iPartIdx )
+{
+  SAOQTPart*  pAlfPart = &(pQaoParam->psSaoPart[iPartIdx]);
+  UInt uiSymbol;
+
+  if(!pAlfPart->bSplit)
+  {
+    if (pAlfPart->bEnableFlag)
+      uiSymbol = pAlfPart->iBestType + 1;
+    else
+      uiSymbol = 0;
+
+    m_pcEntropyCoderIf->codeAoUvlc(uiSymbol);
+    if (pAlfPart->bEnableFlag)
+    {
+      for(Int i=0; i< pAlfPart->iLength; i++)
+      {
+        m_pcEntropyCoderIf->codeAoSvlc(pAlfPart->iOffset[i]);
+      }   
+    }
+    return;
+  }
+
+  //split
+  if (pAlfPart->PartLevel < pQaoParam->iMaxSplitLevel)
+  {
+    for (Int i=0;i<NUM_DOWN_PART;i++)
+    {
+      encodeQAOOnePart(pQaoParam, pAlfPart->DownPartsIdx[i]);
+    }
+  }
+}
+/** encode QuadTree Split Flag
+ * \param  pQaoParam, iPartIdx
+ */
+Void TEncEntropy::encodeQuadTreeSplitFlag(SAOParam* pSaoParam, Int iPartIdx)
+{
+
+  SAOQTPart*  pSaoPart = &(pSaoParam->psSaoPart[iPartIdx]);
+
+  if(pSaoPart->PartLevel < pSaoParam->iMaxSplitLevel)
+  {
+
+    //send one flag
+    m_pcEntropyCoderIf->codeAoFlag( (pSaoPart->bSplit)?(1):(0)  );
+    if(pSaoPart->bSplit)
+    {
+      for (Int i=0;i<NUM_DOWN_PART;i++)
+      {
+        encodeQuadTreeSplitFlag(pSaoParam, pSaoPart->DownPartsIdx[i]);
+      }
+    } 
+  }
+
+}
+
+/** encode Sao Param
+ * \param  pQaoParam
+ */
+Void TEncEntropy::encodeSaoParam(SAOParam* pSaoParam)
+{
+
+  m_pcEntropyCoderIf->codeAoFlag(pSaoParam->bSaoFlag); 
+  if (pSaoParam->bSaoFlag)
+  {
+    encodeQuadTreeSplitFlag(pSaoParam, 0);
+    encodeQAOOnePart(pSaoParam, 0);
+  }
+
+}
+
+
+
+#endif
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncEntropy.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncEntropy.h	(revision 19)
@@ -0,0 +1,239 @@
+/* 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     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"
+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;
+  virtual Void  setBitstream          ( TComBitIf* p )  = 0;
+  virtual Void  setSlice              ( TComSlice* p )  = 0;
+  virtual Void  resetBits             ()                = 0;
+  virtual Void  resetCoeffCost        ()                = 0;
+  virtual UInt  getNumberOfWrittenBits()                = 0;
+  virtual UInt  getCoeffCost          ()                = 0;
+  
+  virtual Void  codeNALUnitHeader       ( NalUnitType eNalUnitType, NalRefIdc eNalRefIdc, UInt TemporalId = 0, Bool bOutputFlag = true ) = 0;
+
+  virtual Void  codeSPS                 ( TComSPS* pcSPS )                                      = 0;
+  virtual Void  codePPS                 ( TComPPS* pcPPS )                                      = 0;
+  virtual void codeSEI(const SEI&) = 0;
+  virtual Void  codeSliceHeader         ( TComSlice* pcSlice )                                  = 0;
+  virtual Void  codeTerminatingBit      ( UInt uilsLast )                                       = 0;
+  virtual Void  codeSliceFinish         ()                                                      = 0;
+  
+  virtual Void codeAlfCtrlDepth() = 0;
+  virtual Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) = 0;
+  
+  virtual Void codeViewIdx( Int iViewIdx ) = 0;
+
+public:
+  virtual Void codeAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  
+  virtual Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  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;
+  
+  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 codeCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth ) = 0;
+  virtual Void codeBlockCbf      ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiQPartNum, Bool bRD = false) = 0;
+#if CAVLC_RQT_CBP
+  virtual Void codeCbfTrdiv      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual UInt xGetFlagPattern   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#endif
+  virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType, Bool bRD = false ) = 0;
+  
+  virtual Void codeAlfFlag          ( UInt uiCode ) = 0;
+  virtual Void codeAlfUvlc          ( UInt uiCode ) = 0;
+  virtual Void codeAlfSvlc          ( Int   iCode ) = 0;
+#if TSB_ALF_HEADER
+  virtual Void codeAlfFlagNum       ( UInt uiCode, UInt minValue ) = 0;
+  virtual Void codeAlfCtrlFlag      ( UInt uiSymbol ) = 0;
+#endif
+#if MTK_SAO
+  virtual Void codeAoFlag          ( UInt uiCode ) = 0;
+  virtual Void codeAoUvlc          ( UInt uiCode ) = 0;
+  virtual Void codeAoSvlc          ( Int   iCode ) = 0;
+#endif
+  virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType) = 0;
+  
+  virtual ~TEncEntropyIf() {}
+};
+
+/// entropy encoder class
+class TEncEntropy
+{
+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();  }
+  
+  Void    encodeSliceHeader         ( TComSlice* pcSlice );
+  Void    encodeTerminatingBit      ( UInt uiIsLast );
+  Void    encodeSliceFinish         ();
+  
+  Void encodeAlfParam(ALFParam* pAlfParam);
+  Void encodeMVPIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Bool bRD = false );
+  
+  Void encodeViewIdx(Int iViewIdx );
+
+  TEncEntropyIf*      m_pcEntropyCoderIf;
+  
+public:
+  // SPS
+  Void encodeSPS               ( TComSPS* pcSPS );
+  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 );
+  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 );
+#if HHI_MRG_SKIP
+  Void encodeMergeIndex   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx, Bool bRD = false );
+#else
+  Void encodeMergeIndex   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Void encodeResPredFlag  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPUIdx, Bool bRD = false );
+#endif
+  Void encodeAlfCtrlFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+#if TSB_ALF_HEADER
+  Void encodeAlfCtrlParam      ( ALFParam *pAlfParam );
+#endif
+  Void encodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, 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 encodeInterDir          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeRefFrmIdx         ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Bool bRD = false );
+  Void encodeMvd               ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList, Bool bRD = false );
+  
+  Void encodeTransformIdx      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, 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 );
+  
+private:
+  Void xEncodeTransformSubdiv  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiInnerQuadIdx, UInt& uiYCbfFront3, UInt& uiUCbfFront3, UInt& uiVCbfFront3 );
+  Void xEncodeCoeff            ( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, UInt uiTrIdx, UInt uiCurrTrIdx, TextType eType, Bool bRD = false );
+public:
+  Void encodeCoeff             ( TComDataCU* pcCU                 , UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight );
+  Void encodeCoeff             ( TComDataCU* pcCU, TCoeff* pCoeff , UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, UInt uiMaxTrMode, UInt uiTrMode, TextType eType, Bool bRD = false );
+  
+  Void encodeCoeffNxN         ( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiTrWidth, UInt uiTrHeight, UInt uiDepth, TextType eType, Bool bRD = false );
+  
+  Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, UInt uiWidth, 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 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);
+#if MTK_SAO
+  Void    encodeQAOOnePart(SAOParam* pQaoParam, Int part_idx);
+  Void    encodeQuadTreeSplitFlag(SAOParam* pQaoParam, Int part_idx);
+  Void    encodeSaoParam(SAOParam* pQaoParam) ;
+#endif
+
+};// END CLASS DEFINITION TEncEntropy
+
+
+#endif // __TENCENTROPY__
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncFormattedStringParser.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncFormattedStringParser.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncFormattedStringParser.cpp	(revision 19)
@@ -0,0 +1,495 @@
+/* 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 "TEncFormattedStringParser.h"
+#include <sstream>
+#include <algorithm>
+
+const std::string TEncFormattedStringParser::sm_cSetOfTypes      ("AIPBNipbn");
+const std::string TEncFormattedStringParser::sm_cSetOfDigits     ("0123456789");
+const std::string TEncFormattedStringParser::sm_cSetOfPartStart  ("AIPBNipbn*");
+
+ErrVal TEncFormattedStringParser::extractFrameType( const std::string &rcString,
+                                                SliceType& reSliceType,
+                                                bool &rbStoreForRef,
+                                                bool &rbIsIDR,
+                                                std::string::size_type &ruiStartPos )
+{
+  ROT( rcString.length() <= ruiStartPos );
+
+  rbIsIDR = rcString[ruiStartPos] == 'A';
+  rbStoreForRef = isupper( rcString[ruiStartPos] ) != 0;
+
+  const char cType = rcString[ruiStartPos++];
+  switch( toupper( cType ) )
+  {
+  case 'A':
+  case 'I':
+    reSliceType = I_SLICE ;
+    break;
+  case 'P':
+    reSliceType = P_SLICE ;
+    break;
+  case 'B':
+    reSliceType = B_SLICE ;
+    break;
+  default:
+    ROT( 1 );
+  }
+
+  return Err::m_nOK;
+}
+
+
+
+
+ErrVal TEncFormattedStringParser::extractFrameIncrement( const std::string &rcString,
+                                                     UInt &ruiIncrement,
+                                                     std::string::size_type &ruiStartPos )
+{
+  RNOK( xExtractUInt( rcString, ruiIncrement, ruiStartPos ) );
+  return Err::m_nOK;
+}
+
+ErrVal TEncFormattedStringParser::extractFrameLayer( const std::string &rcString,
+                                                 UInt &ruiLayer,
+                                                 std::string::size_type &ruiStartPos )
+{
+  ruiLayer = 0;
+  ROTRS( std::string::npos == ruiStartPos, Err::m_nOK );
+  ROTRS( rcString.length() <= ruiStartPos, Err::m_nOK );
+  ROTRS( rcString[ruiStartPos] != 'L', Err::m_nOK );
+  ruiStartPos++;
+  RNOK( xExtractUInt( rcString, ruiLayer, ruiStartPos ) );
+  return Err::m_nOK;
+}
+
+ErrVal TEncFormattedStringParser::xExtractRelRefPocAndRefViewIdx( const std::string &rcString,
+                                                                  std::vector<int> &raiAllowedRelativeRefPocs,
+                                                                  std::vector<int> &raiAllowedReferenceViewIdx,
+                                                                  std::string::size_type &ruiStartPos )
+{
+  if( rcString[ruiStartPos] == 'v' || rcString[ruiStartPos] == 'V' )
+  {
+    ruiStartPos++;
+    int iRefViewIdx = 0;
+    RNOK( xExtractInt( rcString, iRefViewIdx, ruiStartPos ) );
+    assert( iRefViewIdx >= 0 );
+    ROF( raiAllowedReferenceViewIdx.end() == std::find( raiAllowedReferenceViewIdx.begin(), raiAllowedReferenceViewIdx.end(), iRefViewIdx ) );
+    raiAllowedReferenceViewIdx.push_back( iRefViewIdx );
+    raiAllowedRelativeRefPocs.push_back( 0 );
+  }
+  else
+  {
+    int iRelRefPoc = 0;
+    RNOK( xExtractInt( rcString, iRelRefPoc, ruiStartPos ) );
+    ROF( raiAllowedRelativeRefPocs.end() == std::find( raiAllowedRelativeRefPocs.begin(), raiAllowedRelativeRefPocs.end(), iRelRefPoc ) );
+    raiAllowedRelativeRefPocs.push_back( iRelRefPoc );
+    raiAllowedReferenceViewIdx.push_back( -1 );
+  }
+  return Err::m_nOK;
+}
+
+ErrVal TEncFormattedStringParser::extractAllowedRelativeRefPocs( const std::string &rcString,
+                                                             std::vector<int> &raiAllowedRelativeRefPocs,
+                                                             std::vector<int> &raiAllowedReferenceViewIdx,
+                                                             std::string::size_type &ruiStartPos )
+{
+  ROF( raiAllowedRelativeRefPocs.empty() );
+  ROTRS( std::string::npos == ruiStartPos, Err::m_nOK );
+  ROTRS( rcString.length() <= ruiStartPos, Err::m_nOK );
+  RNOK( xEatChar( rcString, '(', ruiStartPos ) );
+
+  do
+  {
+    RNOK( xExtractRelRefPocAndRefViewIdx( rcString, raiAllowedRelativeRefPocs, raiAllowedReferenceViewIdx, ruiStartPos ) );
+  }
+  while( xEatChar( rcString, ',', ruiStartPos ) == Err::m_nOK );
+  RNOK( xEatChar( rcString, ')', ruiStartPos ) );
+
+  return Err::m_nOK;
+}
+
+ErrVal TEncFormattedStringParser::extractAllowedRelativeRefPocs( const std::string &rcString,
+                                                             std::vector<int> &raiAllowedRelativeRefPocsL0,
+                                                             std::vector<int> &raiAllowedRelativeRefPocsL1,
+                                                             std::vector<int> &raiAllowedReferenceViewIdxL0,
+                                                             std::vector<int> &raiAllowedReferenceViewIdxL1,
+                                                             std::string::size_type &ruiStartPos )
+{
+  ROF( raiAllowedRelativeRefPocsL0.empty() );
+  ROF( raiAllowedRelativeRefPocsL1.empty() );
+
+  ROTRS( std::string::npos == ruiStartPos, Err::m_nOK );
+  ROTRS( rcString.length() <= ruiStartPos, Err::m_nOK );
+
+  RNOK( xEatChar( rcString, '(', ruiStartPos ) );
+  do
+  {
+    RNOK( xExtractRelRefPocAndRefViewIdx( rcString, raiAllowedRelativeRefPocsL0, raiAllowedReferenceViewIdxL0, ruiStartPos ) );
+  }
+  while( xEatChar( rcString, ',', ruiStartPos ) == Err::m_nOK );
+  RNOK( xEatChar( rcString, ';', ruiStartPos ) );
+  do
+  {
+    RNOK( xExtractRelRefPocAndRefViewIdx( rcString, raiAllowedRelativeRefPocsL1, raiAllowedReferenceViewIdxL1, ruiStartPos ) );
+  }
+  while( xEatChar( rcString, ',', ruiStartPos ) == Err::m_nOK );
+  RNOK( xEatChar( rcString, ')', ruiStartPos ) );
+  return Err::m_nOK;
+}
+
+
+
+
+
+
+ErrVal TEncFormattedStringParser::xEatChar( const std::string &rcString,
+                                        char cChar,
+                                        std::string::size_type &ruiStartPos )
+{
+  ROTS( std::string::npos == ruiStartPos );
+  ROTS( rcString.length() <= ruiStartPos );
+  ROFS( rcString[ruiStartPos] == cChar );
+  ruiStartPos++;
+  return Err::m_nOK;
+}
+
+ErrVal TEncFormattedStringParser::xExtractUInt( const std::string &rcString,
+                                            UInt &ruiVal,
+                                            std::string::size_type &ruiStartPos )
+{
+  ROT( std::string::npos == ruiStartPos );
+  ROT( rcString.length() <= ruiStartPos );
+  const std::string::size_type uiPos = rcString.find_first_not_of( sm_cSetOfDigits, ruiStartPos + ( rcString[ruiStartPos] == '+' ? 1 : 0 ) );
+  ROT( ruiStartPos == uiPos );
+  std::stringstream( rcString.substr( ruiStartPos, std::string::npos == uiPos ? std::string::npos : uiPos - ruiStartPos ) ) >> ruiVal;
+  ruiStartPos = uiPos;
+  return Err::m_nOK;
+}
+
+ErrVal TEncFormattedStringParser::xExtractInt( const std::string &rcString,
+                                           int &riVal,
+                                           std::string::size_type &ruiStartPos )
+{
+  ROT( std::string::npos == ruiStartPos );
+  ROT( rcString.length() <= ruiStartPos );
+  const std::string::size_type uiPos = rcString.find_first_not_of( sm_cSetOfDigits, ruiStartPos + ( rcString[ruiStartPos] == '+' || rcString[ruiStartPos] == '-' ? 1 : 0 ) );
+  ROT( ruiStartPos == uiPos );
+  std::stringstream( rcString.substr( ruiStartPos, std::string::npos == uiPos ? std::string::npos : uiPos - ruiStartPos ) ) >> riVal;
+  ruiStartPos = uiPos;
+  return Err::m_nOK;
+}
+
+
+ErrVal
+TEncFormattedStringParser::separatString   ( const std::string&  rcString,
+                                         std::string& rcFDString,
+                                         std::string& rcMmcoString,
+                                         std::string& rcRplrStringL0,
+                                         std::string& rcRplrStringL1)
+{
+  size_t uiMPos  = rcString.find_first_of( "M" );
+  size_t uiR1Pos = rcString.find_first_of( "R" );
+  size_t uiR2Pos = rcString.find_last_of ( "R" );
+
+  size_t uiSize = rcString.size();
+
+  if( std::string::npos == uiMPos )
+  {
+    rcMmcoString = "";
+    if( std::string::npos == uiR1Pos )
+    {
+      rcFDString    = rcString;
+      rcRplrStringL0 = "";
+      rcRplrStringL1 = "";
+    }
+    else
+    {
+      rcFDString      = rcString.substr( 0,     uiR1Pos );
+      if( uiR1Pos == uiR2Pos )
+      {
+        rcRplrStringL0 = rcString.substr( uiR1Pos, uiSize - uiR1Pos );
+        rcRplrStringL1 = "";
+      }
+      else
+      {
+        rcRplrStringL0 = rcString.substr( uiR1Pos, uiR2Pos - uiR1Pos );
+        rcRplrStringL1 = rcString.substr( uiR2Pos, uiSize  - uiR2Pos );
+      }
+    }
+  }
+  else
+  {
+    if( std::string::npos == uiR1Pos )
+    {
+      rcFDString      = rcString.substr( 0,     uiMPos );
+      rcMmcoString    = rcString.substr( uiMPos, uiSize - uiMPos );
+      rcRplrStringL0 = "";
+      rcRplrStringL1 = "";
+    }
+    else
+    {
+      if( uiMPos < uiR1Pos )
+      {
+        rcFDString      = rcString.substr( 0,      uiMPos );
+        rcMmcoString    = rcString.substr( uiMPos,  uiR1Pos - uiMPos );
+        if( uiR1Pos == uiR2Pos )
+        {
+          rcRplrStringL0 = rcString.substr( uiR1Pos, uiSize - uiR1Pos );
+          rcRplrStringL1 = "";
+        }
+        else
+        {
+          rcRplrStringL0 = rcString.substr( uiR1Pos, uiR2Pos - uiR1Pos );
+          rcRplrStringL1 = rcString.substr( uiR2Pos, uiSize  - uiR2Pos );
+        }
+      }
+      else
+      {
+        rcFDString      = rcString.substr( 0,      uiR1Pos );
+
+        if( uiR1Pos == uiR2Pos )
+        {
+          rcRplrStringL0 = rcString.substr( uiR1Pos, uiMPos - uiR1Pos );
+          rcRplrStringL1 = "";
+          rcMmcoString    = rcString.substr( uiMPos,  uiSize - uiMPos );
+        }
+        else
+        {
+          if( uiMPos < uiR2Pos )
+          {
+            rcRplrStringL0 = rcString.substr( uiR1Pos, uiMPos  - uiR1Pos );
+            rcMmcoString    = rcString.substr( uiMPos, uiR2Pos - uiMPos );
+            rcRplrStringL1 = rcString.substr( uiR2Pos, uiSize  - uiR2Pos );
+
+          }
+          else
+          {
+            rcRplrStringL0 = rcString.substr( uiR1Pos, uiR2Pos - uiR1Pos );
+            rcRplrStringL1 = rcString.substr( uiR2Pos, uiMPos  - uiR2Pos );
+            rcMmcoString    = rcString.substr( uiMPos,  uiSize  - uiMPos );
+          }
+        }
+      }
+    }
+  }
+
+  if( rcRplrStringL0.size() == 1 )
+  {
+    rcRplrStringL0 = "";
+  }
+
+  if( rcRplrStringL1.size() == 1 )
+  {
+    rcRplrStringL1 = "";
+  }
+
+  return Err::m_nOK;
+}
+
+bool
+TEncFormattedStringParser::isFrameSequencePart( const std::string& rcString )
+{
+  return ( rcString.find( '*', 1 ) == std::string::npos );
+}
+
+
+ErrVal
+TEncFormattedStringParser::extractRepetitions( const std::string&  rcString,
+                                           std::string&        rcNoRepString,
+                                           UInt&               ruiNumberOfRepetitions )
+{
+  ROT( rcString.empty() );
+  if( rcString[0] != '*' )
+  {
+    ruiNumberOfRepetitions = 1;
+    rcNoRepString          = rcString;
+  }
+  else
+  {
+    size_t  uiLastPos   = rcString.length () - 1;
+    size_t  uiOpenPos   = rcString.find   ( '{' );
+    size_t  uiClosePos  = rcString.rfind  ( '}' );
+
+    ROTS(  uiOpenPos   == std::string::npos  );
+    ROFS(  uiClosePos  == uiLastPos          );
+
+    rcNoRepString     = rcString.substr( uiOpenPos+1, uiClosePos-uiOpenPos-1 ); //GT: abc  if rcString = *n100{abc}
+    std::string cNStr = rcString.substr( 1,           uiOpenPos - 1          ); //GT  n100 if rcString = *n100{abc}
+    ROT( cNStr.empty() );
+
+    if( uiOpenPos==2 && cNStr[0]=='n' )
+    {
+//      ruiNumberOfRepetitions = TypeLimits<UInt>::m_iMax; // reserved value representing "infinity"
+      ruiNumberOfRepetitions = MAX_UINT; // reserved value representing "infinity"
+    }
+    else
+    {
+      ROFS( cNStr.find_first_not_of( sm_cSetOfDigits ) == std::string::npos );
+      ruiNumberOfRepetitions  = atoi( cNStr.c_str() );
+    }
+  }
+
+  return Err::m_nOK;
+}
+
+ErrVal
+TEncFormattedStringParser::getNumberOfFrames( const std::string&  rcString,
+                                          UInt&               ruiNumberOfFrames )
+{
+  size_t  uiPos           = rcString.find_first_of( sm_cSetOfTypes );
+  size_t  uiUnderScorePos = 0 ;
+  ruiNumberOfFrames = 0;
+
+
+  while( uiPos != std::string::npos )
+  {
+    ruiNumberOfFrames++;
+    uiUnderScorePos = rcString.find_first_of( std::string("_"), uiPos+1 ) ;
+    ROT( uiUnderScorePos == std::string::npos ) ;
+    uiPos = rcString.find_first_of( sm_cSetOfTypes, uiUnderScorePos+1 );
+  }
+
+  return Err::m_nOK;
+}
+
+ErrVal
+TEncFormattedStringParser::extractNextFrameDescription( const std::string&  rcString,
+                                                    std::string&        rcFDString,
+                                                    size_t&        ruiStartPos )
+{
+  ROTS( ruiStartPos >= rcString.length()-1 );
+  size_t uiUnderScorePos = rcString.find_first_of( std::string("_"), ruiStartPos+1 ) ;
+  ROT( uiUnderScorePos == std::string::npos ) ;
+  size_t uiEndPos = rcString.find_first_of( sm_cSetOfTypes, uiUnderScorePos+1 );
+
+  rcFDString  = rcString.substr( ruiStartPos, uiEndPos - ruiStartPos );
+  ruiStartPos = uiEndPos;
+
+  return Err::m_nOK;
+}
+
+ErrVal
+TEncFormattedStringParser::getNumberOfParts( const std::string& rcString,
+                                         UInt&              ruiNumberOfParts )
+{
+  size_t  uiPos       = rcString.find_first_of( sm_cSetOfPartStart );
+  ruiNumberOfParts  = 0;
+
+  while( uiPos != std::string::npos )
+  {
+    ruiNumberOfParts++;
+
+    if( rcString[uiPos] == '*' ) //GT: Exclude sub-parts
+    {
+      size_t  uiEndPos        = rcString.find( '{', uiPos+1 );
+      UInt  uiOpenBrackets  = 1;
+      ROTS( uiEndPos == std::string::npos );
+
+      while( uiOpenBrackets )
+      {
+        uiEndPos  = rcString.find_first_of( "{}", uiEndPos+1 );
+        ROTS( uiEndPos == std::string::npos );
+
+        if( rcString[uiEndPos] == '{' )   uiOpenBrackets++;
+        else                              uiOpenBrackets--;
+      }
+
+      uiPos = rcString.find_first_of( sm_cSetOfPartStart, uiEndPos + 1 );
+    }
+    else
+    {
+      uiPos = rcString.find( '*', uiPos+1 );
+    }
+  }
+
+  return Err::m_nOK;
+}
+
+ErrVal
+TEncFormattedStringParser::extractPart( const std::string&  rcString,
+                                    std::string&        rcPartString,
+                                    size_t&        ruiStartPos )
+{
+  ROTS( ruiStartPos >= rcString.length()-1 );
+
+  size_t uiNextStartPos;
+
+  if( rcString[ruiStartPos] == '*' )
+  {
+    size_t  uiEndPos        = rcString.find( '{', ruiStartPos+1 );
+    UInt  uiOpenBrackets  = 1;
+    ROTS( uiEndPos == std::string::npos );
+
+    while( uiOpenBrackets )
+    {
+      uiEndPos  = rcString.find_first_of( "{}", uiEndPos+1 );
+      ROTS( uiEndPos == std::string::npos );
+
+      if( rcString[uiEndPos] == '{' )   uiOpenBrackets++;
+      else                              uiOpenBrackets--;
+    }
+
+    uiNextStartPos = rcString.find_first_of( sm_cSetOfPartStart, uiEndPos + 1 );
+  }
+  else
+  {
+    uiNextStartPos = rcString.find( '*', ruiStartPos+1 );
+  }
+
+  rcPartString  = rcString.substr( ruiStartPos, uiNextStartPos - ruiStartPos );
+  ruiStartPos   = uiNextStartPos;
+
+  return Err::m_nOK;
+}
+
+ErrVal TEncFormattedStringParser::extractHighestLayerOfGOPString( const std::string &rcString, UInt &ruiLayer )
+{
+  std::string::size_type uiPos = 0;
+  ruiLayer = 0;
+
+  while( ( uiPos = rcString.find_first_of( 'L', uiPos ) ) != std::string::npos )
+  {
+    uiPos++;
+
+    UInt ui = 0;
+    RNOK( xExtractUInt( rcString, ui, uiPos ) );
+    if( ui > ruiLayer )
+      ruiLayer = ui;
+  }
+  return Err::m_nOK;
+}
+
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncFormattedStringParser.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncFormattedStringParser.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncFormattedStringParser.h	(revision 19)
@@ -0,0 +1,121 @@
+/* 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 !defined(AFX_TEncFormattedStringParser_H__268768B8_4D1D_484A_904E_586985833BAC__INCLUDED_)
+#define AFX_TEncFormattedStringParser_H__268768B8_4D1D_484A_904E_586985833BAC__INCLUDED_
+
+#include "../TLibCommon/CommonDef.h"
+#include <vector>
+
+class TEncFormattedStringParser
+{
+public:
+  static  ErrVal  separatString               ( const std::string&  rcString,
+                                                      std::string& rcFDString,
+                                                      std::string& rcMmcoString,
+                                                      std::string& rcRplrStringL0,
+                                                      std::string& rcRplrStringL1 );
+  static bool   isFrameSequencePart         ( const std::string&  rcString                  );
+
+  static ErrVal extractRepetitions          ( const std::string&  rcString,
+                                              std::string&        rcNoRepString,
+                                              UInt&               ruiNumberOfRepetitions    );
+
+  static ErrVal getNumberOfFrames           ( const std::string&  rcString,
+                                              UInt&               ruiNumberOfFrames         );
+
+  static ErrVal extractNextFrameDescription ( const std::string&  rcString,
+                                              std::string&        rcFDString,
+                                              size_t&        ruiStartPos );
+
+  static ErrVal getNumberOfParts            ( const std::string&  rcString,
+                                              UInt&               ruiNumberOfParts          );
+
+  static ErrVal extractPart                 ( const std::string&  rcString,
+                                              std::string&        rcPartString,
+                                              size_t&        ruiStartPos );
+
+  static ErrVal extractFrameType( const std::string &rcString,
+                                  SliceType& reSliceType,
+                                  bool &rbStoreForRef,
+                                  bool &rbIsIDR,
+                                  std::string::size_type &ruiStartPos );
+  static ErrVal extractFrameIncrement( const std::string &rcString,
+                                       UInt &ruiIncrement,
+                                       std::string::size_type &ruiStartPos );
+
+  static ErrVal extractFrameLayer( const std::string &rcString,
+                                   UInt &ruiLayer,
+                                   std::string::size_type &ruiStartPos );
+
+  static ErrVal extractAllowedRelativeRefPocs( const std::string &rcString,
+                                               std::vector<int> &raiAllowedRelativeRefPocs,
+                                               std::vector<int> &raiAllowedReferenceViewIdx,
+                                               std::string::size_type &ruiStartPos );
+  static ErrVal extractAllowedRelativeRefPocs( const std::string &rcString,
+                                                 std::vector<int> &raiAllowedRelativeRefPocsL0,
+                                                 std::vector<int> &raiAllowedRelativeRefPocsL1,
+                                                 std::vector<int> &raiAllowedReferenceViewIdxL0,
+                                                 std::vector<int> &raiAllowedReferenceViewIdxL1,
+                                                 std::string::size_type &ruiStartPos );
+
+
+  static ErrVal extractHighestLayerOfGOPString( const std::string &rcString, UInt &ruiLayer );
+
+private:
+  static ErrVal xExtractUInt( const std::string &rcString,
+                              UInt &ruiVal,
+                              std::string::size_type &ruiStartPos );
+
+  static ErrVal xExtractInt( const std::string &rcString,
+                             int &riVal,
+                             std::string::size_type &ruiStartPos );
+
+  static ErrVal xEatChar( const std::string &rcString,
+                          char cChar,
+                          std::string::size_type &ruiStartPos );
+
+  static ErrVal xExtractRelRefPocAndRefViewIdx( const std::string &rcString,
+                                                std::vector<int> &raiAllowedRelativeRefPocs,
+                                                std::vector<int> &raiAllowedReferenceViewIdx,
+                                                std::string::size_type &ruiStartPos );
+
+  static const std::string sm_cSetOfTypes;
+  static const std::string sm_cSetOfDigits;
+  static const std::string sm_cSetOfPartStart;
+};
+
+
+
+
+#endif // !defined(AFX_TEncFormattedStringParser_H__268768B8_4D1D_484A_904E_586985833BAC__INCLUDED_)
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 19)
@@ -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-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     TEncPic.cpp
+    \brief    GOP encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncGOP.h"
+#include "TEncAnalyze.h"
+#include "../libmd5/MD5.h"
+#include "../TLibCommon/SEI.h"
+
+#include <time.h>
+
+#include "../../App/TAppEncoder/TAppEncTop.h"
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TEncPic::TEncPic()
+{
+  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 HHI_INTER_VIEW_RESIDUAL_PRED
+  m_pcResidualGenerator = NULL;
+#endif
+
+#if DCM_DECODING_REFRESH
+  m_bRefreshPending     = 0;
+  m_uiPOCCDR            = 0;
+#endif
+
+  return;
+}
+
+TEncPic::~TEncPic()
+{
+}
+
+/** 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  TEncPic::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];
+  m_uiStoredStartCUAddrForEncodingEntropySlice = new UInt [uiNumCUsInFrame+1];
+}
+
+Void  TEncPic::destroy()
+{
+  delete [] m_uiStoredStartCUAddrForEncodingSlice; m_uiStoredStartCUAddrForEncodingSlice = NULL;
+  delete [] m_uiStoredStartCUAddrForEncodingEntropySlice; m_uiStoredStartCUAddrForEncodingEntropySlice = NULL;
+}
+
+Void TEncPic::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 HHI_INTER_VIEW_RESIDUAL_PRED
+  m_pcResidualGenerator  = pcTEncTop->getResidualGenerator();
+#endif
+
+  // Adaptive Loop filter
+  m_pcAdaptiveLoopFilter = pcTEncTop->getAdaptiveLoopFilter();
+  //--Adaptive Loop filter
+#if MTK_SAO
+  m_pcSAO                = pcTEncTop->getSAO();
+#endif
+  m_pcRdCost             = pcTEncTop->getRdCost();
+
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncPic::compressPic( TComBitstream* pcBitstreamOut, TComPicYuv cPicOrg, TComPic* pcPic, TComPicYuv* pcPicYuvRecOut,
+               TComPic* pcOrgRefList[2][MAX_REF_PIC_NUM], Bool&  rbSeqFirst, TComList<TComPic*>& rcListPic  )
+{
+  TComSlice*      pcSlice;
+
+      //-- For time output for each slice
+      long iBeforeTime = clock();
+
+      //  Bitstream reset
+      pcBitstreamOut->resetBits();
+      pcBitstreamOut->rewindStreamPacket();
+
+      //  Slice data initialization
+      pcPic->clearSliceBuffer();
+      assert(pcPic->getNumAllocatedSlice() == 1);
+      m_pcSliceEncoder->setSliceIdx(0);
+      pcPic->setCurrSliceIdx(0);
+      m_pcSliceEncoder->initEncSlice ( pcPic, pcSlice );
+      pcSlice->setSliceIdx(0);
+
+      //  Set SPS
+      pcSlice->setSPS( m_pcEncTop->getSPS() );
+      pcSlice->setPPS( m_pcEncTop->getPPS() );
+      pcSlice->setPPSId( pcSlice->getPPS()->getPPSId() );
+
+  // set mutliview parameters
+      pcSlice->initMultiviewSlice( pcPic->getCodedScale(), pcPic->getCodedOffset() );
+
+#if DCM_DECODING_REFRESH
+      // Set the nal unit type
+      if( pcSlice->getPOC() == 0 )
+        pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_IDR );
+      else
+        pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE );
+
+      //pcSlice->setNalUnitType(getNalUnitType(uiPOCCurr));
+      // Do decoding refresh marking if any
+      pcSlice->decodingRefreshMarking(m_uiPOCCDR, m_bRefreshPending, rcListPic);
+#endif
+
+// GT FIX
+  std::vector<TComPic*> apcSpatRefPics = m_pcEncTop->getEncTop()->getSpatialRefPics( pcPic->getViewIdx(), pcSlice->getPOC(), m_pcEncTop->isDepthCoder() );
+  TComPic * const pcTexturePic = m_pcEncTop->isDepthCoder() ? m_pcEncTop->getEncTop()->getPicFromView( pcPic->getViewIdx(), pcSlice->getPOC(), false ) : NULL;
+  assert( ! m_pcEncTop->isDepthCoder() || pcTexturePic != NULL );
+  pcSlice->setTexturePic( pcTexturePic );
+
+  pcSlice->setRefPicListFromGOPSTring( rcListPic, apcSpatRefPics );
+
+#if HHI_VSO
+  m_pcEncTop->getEncTop()->setMVDPic(pcPic->getViewIdx(), pcSlice->getPOC(), pcPic->getMVDReferenceInfo() );
+
+
+  Bool bUseVSO = m_pcEncTop->getUseVSO();
+  m_pcRdCost->setUseVSO( bUseVSO );
+
+  if ( bUseVSO )
+  {
+    Int iVSOMode = m_pcEncTop->getVSOMode();
+    m_pcRdCost->setVSOMode( iVSOMode  );
+#if HHI_VSO_DIST_INT
+    m_pcRdCost->setAllowNegDist( m_pcEncTop->getAllowNegDist() );
+#endif
+
+    if ( iVSOMode == 4 )
+    {
+      m_pcEncTop->getEncTop()->setupRenModel( pcSlice->getPOC(), pcPic->getViewIdx(), m_pcEncTop->isDepthCoder() ? 1 : 0 );
+    }
+    else
+  {
+    m_pcRdCost->setRefDataFromMVDInfo( pcPic->getMVDReferenceInfo() );
+  }
+  }
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  if ( m_pcEncTop->getInterViewSkip() )
+  {
+    m_pcEncTop->getEncTop()->getUsedPelsMap( pcPic->getViewIdx(), pcPic->getPOC(), pcPic->getUsedPelsMap() );
+  }
+#endif
+
+      pcSlice->setNoBackPredFlag( false );
+#if DCM_COMB_LIST
+      if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
+#else
+      if ( pcSlice->getSliceType() == B_SLICE )
+#endif
+      {
+        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 DCM_COMB_LIST
+      if(pcSlice->getNoBackPredFlag())
+      {
+        pcSlice->setNumRefIdx(REF_PIC_LIST_C, -1);
+      }
+      pcSlice->generateCombinedList();
+#endif
+
+      /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
+      //  Slice compression
+      if (m_pcCfg->getUseASR())
+      {
+        m_pcSliceEncoder->setSearchRange(pcSlice);
+      }
+#ifdef ROUNDING_CONTROL_BIPRED
+      Bool b = true;
+      if (m_pcCfg->getUseRoundingControlBipred())
+      {
+        if (m_pcCfg->getCodedPictureBufferSize()==1)
+          b = ((pcSlice->getPOC()&1)==0);
+        else
+          b = (pcSlice->isReferenced() == 0);
+      }
+
+#if HIGH_ACCURACY_BI
+      pcSlice->setRounding(false);
+#else
+      pcSlice->setRounding(b);
+#endif
+#endif
+
+      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()+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()+1));
+
+      UInt uiNextCUAddr = 0;
+      m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx++]                = uiNextCUAddr;
+      m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = uiNextCUAddr;
+
+#if DEPTH_MAP_GENERATION
+      // init view component and predict virtual depth map
+      m_pcDepthMapGenerator->initViewComponent( pcPic );
+      m_pcDepthMapGenerator->predictDepthMap  ( pcPic );
+#if HHI_INTER_VIEW_MOTION_PRED
+      m_pcDepthMapGenerator->covertOrgDepthMap( pcPic );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      m_pcResidualGenerator->initViewComponent( pcPic );
+#endif
+#endif
+
+      while(uiNextCUAddr<pcPic->getPicSym()->getNumberOfCUsInFrame()) // 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 < pcPic->getPicSym()->getNumberOfCUsInFrame())
+          {
+            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);
+          }
+        }
+        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 MTK_SAO  // PRE_DF
+      SAOParam cSaoParam;
+#endif
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      // set residual picture
+      m_pcResidualGenerator->setRecResidualPic( pcPic );
+#endif
+#if DEPTH_MAP_GENERATION
+      // update virtual depth map
+      m_pcDepthMapGenerator->updateDepthMap( pcPic );
+#endif
+
+      //-- Loop filter
+      m_pcLoopFilter->setCfg(pcSlice->getLoopFilterDisable(), m_pcCfg->getLoopFilterAlphaC0Offget(), m_pcCfg->getLoopFilterBetaOffget());
+      m_pcLoopFilter->loopFilterPic( pcPic );
+
+#if MTK_NONCROSS_INLOOP_FILTER
+      pcSlice = pcPic->getSlice(0);
+
+      if(pcSlice->getSPS()->getUseALF())
+      {
+        if(pcSlice->getSPS()->getLFCrossSliceBoundaryFlag())
+        {
+          m_pcAdaptiveLoopFilter->setUseNonCrossAlf(false);
+        }
+        else
+        {
+          UInt uiNumSlices = uiStartCUAddrSliceIdx-1;
+          m_pcAdaptiveLoopFilter->setUseNonCrossAlf( (uiNumSlices > 1)  );
+          if(m_pcAdaptiveLoopFilter->getUseNonCrossAlf())
+          {
+            m_pcAdaptiveLoopFilter->setNumSlicesInPic( uiNumSlices );
+            m_pcAdaptiveLoopFilter->createSlice();
+
+            //set the startLCU and endLCU addr. to ALF slices
+            for(UInt i=0; i< uiNumSlices ; i++)
+            {
+              (*m_pcAdaptiveLoopFilter)[i].create(pcPic, i,
+                                                  m_uiStoredStartCUAddrForEncodingSlice[i],
+                                                  m_uiStoredStartCUAddrForEncodingSlice[i+1]-1
+                                                  );
+
+            }
+          }
+        }
+      }
+#endif
+      /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
+      // Set entropy coder
+      m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+
+      /* write various header sets.
+       * The header sets are written into a separate bitstream buffer to
+       * allow SEI messages that are calculated after the picture has been
+       * encoded to be sent before the picture.
+       */
+      TComBitstream bs_SPS_PPS_SEI;
+      bs_SPS_PPS_SEI.create(512); /* TODO: this should dynamically resize */
+      if ( rbSeqFirst )
+      {
+        m_pcEntropyCoder->setBitstream(&bs_SPS_PPS_SEI);
+
+        m_pcEntropyCoder->encodeSPS( pcSlice->getSPS() );
+        bs_SPS_PPS_SEI.write( 1, 1 );
+        bs_SPS_PPS_SEI.writeAlignZero();
+        // generate start code
+        bs_SPS_PPS_SEI.write( 1, 32);
+
+        m_pcEntropyCoder->encodePPS( pcSlice->getPPS() );
+        bs_SPS_PPS_SEI.write( 1, 1 );
+        bs_SPS_PPS_SEI.writeAlignZero();
+        // generate start code
+        bs_SPS_PPS_SEI.write( 1, 32);
+        rbSeqFirst = false;
+      }
+
+      /* use the main bitstream buffer for storing the marshalled picture */
+      m_pcEntropyCoder->setBitstream(pcBitstreamOut);
+
+      uiStartCUAddrSliceIdx = 0;
+      uiStartCUAddrSlice    = 0;
+      pcBitstreamOut->allocateMemoryForSliceLocations( pcPic->getPicSym()->getNumberOfCUsInFrame() ); // Assuming number of slices <= number of LCU. Needs to be changed for sub-LCU slice coding.
+      pcBitstreamOut->setSliceCount( 0 );                                      // intialize number of slices to zero, used while converting RBSP to NALU
+
+      uiStartCUAddrEntropySliceIdx = 0;
+      uiStartCUAddrEntropySlice    = 0;
+      uiNextCUAddr                 = 0;
+      pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
+      while (uiNextCUAddr < pcPic->getPicSym()->getNumberOfCUsInFrame()) // Iterate over all slices
+      {
+        pcSlice->setNextSlice       ( false );
+        pcSlice->setNextEntropySlice( false );
+        if (uiNextCUAddr == m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx])
+        {
+          pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
+          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++;
+        }
+
+        // Get ready for writing slice header (other than the first one in the picture)
+        if (uiNextCUAddr!=0)
+        {
+          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+          m_pcEntropyCoder->setBitstream      ( pcBitstreamOut          );
+          m_pcEntropyCoder->resetEntropy      ();
+        }
+
+      // write SliceHeader
+      m_pcEntropyCoder->encodeSliceHeader ( pcSlice                 );
+
+      // is it needed?
+      if ( pcSlice->getSymbolMode() )
+      {
+        m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+        m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+        m_pcEntropyCoder->resetEntropy    ();
+      }
+
+        if (uiNextCUAddr==0)  // Compute ALF params and write only for first slice header
+        {
+          // adaptive loop filter
+#if MTK_SAO
+          if ( pcSlice->getSPS()->getUseALF() || (pcSlice->getSPS()->getUseSAO()) )
+#else
+          if ( pcSlice->getSPS()->getUseALF())
+#endif
+          {
+            ALFParam cAlfParam;
+#if TSB_ALF_HEADER
+            m_pcAdaptiveLoopFilter->setNumCUsInFrame(pcPic);
+#endif
+            m_pcAdaptiveLoopFilter->allocALFParam(&cAlfParam);
+
+            // set entropy coder for RD
+            if ( pcSlice->getSymbolMode() )
+            {
+              m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
+            }
+            else
+            {
+              m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+            }
+            m_pcEntropyCoder->resetEntropy    ();
+            m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+
+            m_pcAdaptiveLoopFilter->startALFEnc(pcPic, m_pcEntropyCoder );
+#if MTK_SAO  // PostDF
+            {
+              if (pcSlice->getSPS()->getUseSAO())
+              {
+                m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcCfg->getUseSBACRD() ?  m_pcEncTop->getRDGoOnSbacCoder() : NULL);
+                m_pcSAO->SAOProcess(pcPic->getSlice(0)->getLambda());
+                m_pcSAO->copyQaoData(&cSaoParam);
+                m_pcSAO->endSaoEnc();
+              }
+            }
+#endif
+            UInt uiMaxAlfCtrlDepth;
+
+            UInt64 uiDist, uiBits;
+#if MTK_SAO
+            if ( pcSlice->getSPS()->getUseALF())
+#endif
+              m_pcAdaptiveLoopFilter->ALFProcess( &cAlfParam, pcPic->getSlice(0)->getLambda(), uiDist, uiBits, uiMaxAlfCtrlDepth );
+#if MTK_SAO
+            else
+              cAlfParam.cu_control_flag = 0;
+#endif
+            m_pcAdaptiveLoopFilter->endALFEnc();
+
+            // set entropy coder for writing
+            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+            if ( pcSlice->getSymbolMode() )
+            {
+              m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+            }
+            else
+            {
+              m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+            }
+            m_pcEntropyCoder->resetEntropy    ();
+            m_pcEntropyCoder->setBitstream    ( pcBitstreamOut );
+            if (cAlfParam.cu_control_flag)
+            {
+              m_pcEntropyCoder->setAlfCtrl( true );
+              m_pcEntropyCoder->setMaxAlfCtrlDepth(uiMaxAlfCtrlDepth);
+              if (pcSlice->getSymbolMode() == 0)
+              {
+                m_pcCavlcCoder->setAlfCtrl(true);
+                m_pcCavlcCoder->setMaxAlfCtrlDepth(uiMaxAlfCtrlDepth); //D0201
+              }
+            }
+            else
+            {
+              m_pcEntropyCoder->setAlfCtrl(false);
+            }
+#if MTK_SAO
+            if (pcSlice->getSPS()->getUseSAO())
+            {
+              m_pcEntropyCoder->encodeSaoParam(&cSaoParam);
+            }
+            if (pcSlice->getSPS()->getUseALF())
+#endif
+            m_pcEntropyCoder->encodeAlfParam(&cAlfParam);
+
+#if TSB_ALF_HEADER
+            if(cAlfParam.cu_control_flag)
+            {
+              m_pcEntropyCoder->encodeAlfCtrlParam(&cAlfParam);
+            }
+#endif
+            m_pcAdaptiveLoopFilter->freeALFParam(&cAlfParam);
+          }
+        }
+
+        // File writing
+        m_pcSliceEncoder->encodeSlice( pcPic, pcBitstreamOut );
+
+        //  End of bitstream & byte align
+        pcBitstreamOut->write( 1, 1 );
+        pcBitstreamOut->writeAlignZero();
+
+        UInt uiBoundingAddrSlice, uiBoundingAddrEntropySlice;
+        uiBoundingAddrSlice        = m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];
+        uiBoundingAddrEntropySlice = m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx];
+        uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrEntropySlice);
+        if (uiNextCUAddr < pcPic->getPicSym()->getNumberOfCUsInFrame())   // if more slices to be encoded insert start code
+        {
+          UInt uiSliceCount = pcBitstreamOut->getSliceCount();
+          pcBitstreamOut->setSliceByteLocation( uiSliceCount, (pcBitstreamOut->getNumberOfWrittenBits()>>3) );
+          pcBitstreamOut->setSliceCount( uiSliceCount+1 );
+          pcBitstreamOut->write( 1, 32);
+        }
+      } // end iteration over slices
+
+
+#if MTK_NONCROSS_INLOOP_FILTER
+      if(pcSlice->getSPS()->getUseALF())
+      {
+        if(m_pcAdaptiveLoopFilter->getUseNonCrossAlf())
+          m_pcAdaptiveLoopFilter->destroySlice();
+      }
+#endif
+
+
+      pcBitstreamOut->flushBuffer();
+      pcBitstreamOut->convertRBSPToPayload(0);
+
+/*#if AMVP_BUFFERCOMPRESS
+      pcPic->compressMotion(); // moved to end of access unit
+#endif */
+      pcBitstreamOut->freeMemoryAllocatedForSliceLocations();
+
+      //-- For time output for each slice
+      Double dEncTime = (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+
+      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), pcBitstreamOut->getNumberOfWrittenBits(), dEncTime );
+
+#if FIXED_ROUNDING_FRAME_MEMORY
+      pcPic->getPicYuvRec()->xFixedRoundingPic();
+#endif
+
+      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);
+        printf("[MD5:%s] ", digestToString(sei_recon_picture_digest.digest));
+
+        TComBitstream seiBs;
+        seiBs.create(1024);
+        /* write the SEI messages */
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_pcEntropyCoder->setBitstream(&seiBs);
+        m_pcEntropyCoder->encodeSEI(sei_recon_picture_digest);
+        /* and trailing bits */
+        seiBs.write(1, 1);
+        seiBs.writeAlignZero();
+        seiBs.flushBuffer();
+        seiBs.convertRBSPToPayload(0);
+
+        /* append the SEI message after any SPS/PPS */
+        /* the following loop is a work around current limitations in
+         * TComBitstream that won't be fixed before HM-3.0 */
+        UChar *seiData = reinterpret_cast<UChar *>(seiBs.getStartStream());
+        for (Int i = 0; i < seiBs.getNumberOfWrittenBits()/8; i++)
+        {
+          bs_SPS_PPS_SEI.write(seiData[i], 8);
+        }
+        bs_SPS_PPS_SEI.write(1, 32);
+        seiBs.destroy();
+      }
+
+      /* insert the bs_SPS_PPS_SEI before the pcBitstreamOut */
+      bs_SPS_PPS_SEI.flushBuffer();
+      pcBitstreamOut->insertAt(bs_SPS_PPS_SEI, 0);
+
+      bs_SPS_PPS_SEI.destroy();
+      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
+
+      pcPic->setReconMark   ( true );
+
+}
+
+Void TEncPic::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
+{
+  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  Bool bCalcDist = false;
+
+  m_pcLoopFilter->setCfg(pcSlice->getLoopFilterDisable(), m_pcCfg->getLoopFilterAlphaC0Offget(), m_pcCfg->getLoopFilterBetaOffget());
+  m_pcLoopFilter->loopFilterPic( pcPic );
+
+  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
+  m_pcEntropyCoder->resetEntropy    ();
+  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+
+  // Adaptive Loop filter
+  if( pcSlice->getSPS()->getUseALF() )
+  {
+    ALFParam cAlfParam;
+#if TSB_ALF_HEADER
+    m_pcAdaptiveLoopFilter->setNumCUsInFrame(pcPic);
+#endif
+    m_pcAdaptiveLoopFilter->allocALFParam(&cAlfParam);
+
+    m_pcAdaptiveLoopFilter->startALFEnc(pcPic, m_pcEntropyCoder);
+
+    UInt uiMaxAlfCtrlDepth;
+    m_pcAdaptiveLoopFilter->ALFProcess(&cAlfParam, pcSlice->getLambda(), ruiDist, ruiBits, uiMaxAlfCtrlDepth );
+    m_pcAdaptiveLoopFilter->endALFEnc();
+    m_pcAdaptiveLoopFilter->freeALFParam(&cAlfParam);
+  }
+
+  m_pcEntropyCoder->resetEntropy    ();
+  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+
+  if (!bCalcDist)
+    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+UInt64 TEncPic::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;
+}
+
+Void TEncPic::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, UInt uibits, 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;
+
+  UInt   maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
+  Double fRefValueY = (double) maxval * maxval * iSize;
+  Double fRefValueC = fRefValueY / 4.0;
+
+  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 ( m_pcRdCost->getUseRenModel() )
+  {
+    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
+  {
+  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;
+  }
+  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 );
+  }
+  // fix: total bits should consider slice size bits (32bit)
+  uibits += 32;
+
+#if RVM_VCEGAM10
+  m_vRVM_RP.push_back( uibits );
+#endif
+
+  //===== add PSNR =====
+  m_pcEncTop->m_cAnalyzeAll.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  TComSlice*  pcSlice = pcPic->getSlice(0);
+  if (pcSlice->isIntra())
+  {
+    m_pcEncTop->m_cAnalyzeI.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if (pcSlice->isInterP())
+  {
+    m_pcEncTop->m_cAnalyzeP.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if (pcSlice->isInterB())
+  {
+    m_pcEncTop->m_cAnalyzeB.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+  }
+  if(pcPic->getViewIdx()!=-1)
+  {
+    if(! m_pcEncTop->isDepthCoder())
+    {
+      printf("\nView \t\t%2d\t POC %4d ( %c-SLICE, QP %d ) %10d bits ",
+      pcSlice->getViewIdx(),
+      pcSlice->getPOC(),
+      pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B',
+      pcSlice->getSliceQp(),
+      uibits );
+    }
+    else
+    {
+      printf("\nDepth View \t%2d\t POC %4d ( %c-SLICE, QP %d ) %10d bits ",
+            pcSlice->getViewIdx(),
+            pcSlice->getPOC(),
+            pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B',
+            pcSlice->getSliceQp(),
+            uibits );
+    }
+  }
+  else
+  {
+    printf("\nPOC %4d ( %c-SLICE, QP %d ) %10d bits ",
+           pcSlice->getPOC(),
+           pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B',
+           pcSlice->getSliceQp(),
+           uibits );
+  }
+
+  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->getViewIdx() != pcSlice->getRefViewIdx( RefPicList(iRefList), iRefIndex ) )
+      {
+        printf( "V%d", pcSlice->getRefViewIdx( RefPicList(iRefList), iRefIndex ) );
+        if( pcSlice->getPOC() != pcSlice->getRefPOC( RefPicList(iRefList), iRefIndex ) )
+          printf( "(%d)", pcSlice->getRefPOC( RefPicList(iRefList), iRefIndex ) );
+        printf( " " );
+      }
+      else
+        printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
+    }
+    printf ("] ");
+  }
+#if DCM_COMB_LIST
+  if(pcSlice->getNumRefIdx(REF_PIC_LIST_C)>0 && !pcSlice->getNoBackPredFlag())
+  {
+    printf ("[LC ");
+    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(REF_PIC_LIST_C); iRefIndex++)
+    {
+      printf ("%d ", pcSlice->getRefPOC((RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex)));
+    }
+    printf ("] ");
+  }
+#endif
+
+  fflush(stdout);
+}
+
+#if DCM_DECODING_REFRESH
+/** 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 TEncPic::getNalUnitType(UInt uiPOCCurr)
+{
+  if (uiPOCCurr == 0)
+  {
+    return NAL_UNIT_CODED_SLICE_IDR;
+  }
+#if 0
+  if (uiPOCCurr % m_pcCfg->getIntraPeriod() == 0)
+  {
+    if (m_pcCfg->getDecodingRefreshType() == 1)
+    {
+      return NAL_UNIT_CODED_SLICE_CDR;
+    }
+    else if (m_pcCfg->getDecodingRefreshType() == 2)
+    {
+      return NAL_UNIT_CODED_SLICE_IDR;
+    }
+  }
+#endif
+  return NAL_UNIT_CODED_SLICE;
+}
+#endif
+
+#if RVM_VCEGAM10
+Double TEncPic::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 );
+}
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncGOP.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncGOP.h	(revision 19)
@@ -0,0 +1,158 @@
+/* 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     TEncPic.h
+    \brief    GOP encoder class (header)
+*/
+
+#ifndef __TEncPic__
+#define __TEncPic__
+
+#include <stdlib.h>
+
+#include "../TLibCommon/TComList.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComBitStream.h"
+#include "../TLibCommon/TComBitCounter.h"
+#include "../TLibCommon/TComLoopFilter.h"
+#include "../TLibCommon/TComDepthMapGenerator.h"
+#include "../TLibCommon/TComResidualGenerator.h"
+#include "TEncAdaptiveLoopFilter.h"
+#include "TEncSlice.h"
+#include "TEncEntropy.h"
+#include "TEncCavlc.h"
+#include "TEncSbac.h"
+
+#include "TEncAnalyze.h"
+
+#ifdef WEIGHT_PRED
+#include "WeightPredAnalysis.h"
+#endif
+
+#if RVM_VCEGAM10
+#include <vector>
+#endif
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP encoder class
+class TEncPic
+{
+private:
+  //  Data
+  Int                     m_iHrchDepth;
+  
+  //  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 HHI_INTER_VIEW_RESIDUAL_PRED
+  TComResidualGenerator*  m_pcResidualGenerator;
+#endif
+  
+  // Adaptive Loop filter
+  TEncAdaptiveLoopFilter* m_pcAdaptiveLoopFilter;
+  //--Adaptive Loop filter
+#if MTK_SAO
+  TEncSampleAdaptiveOffset*  m_pcSAO;
+#endif
+  TComBitCounter*         m_pcBitCounter;
+  
+  TComRdCost*             m_pcRdCost;                           ///< RD cost computation
+  
+#if DCM_DECODING_REFRESH
+  // clean decoding refresh
+  Bool                    m_bRefreshPending;
+  UInt                    m_uiPOCCDR;
+#endif
+  UInt*                   m_uiStoredStartCUAddrForEncodingSlice;
+  UInt*                   m_uiStoredStartCUAddrForEncodingEntropySlice;
+
+// #if MTK_NONCROSS_INLOOP_FILTER
+//   UInt                    m_uiILSliceCount;
+//   UInt*                   m_puiILSliceStartLCU;
+//   UInt*                   m_puiILSliceEndLCU;
+// #endif
+
+#if RVM_VCEGAM10
+  std::vector<Int> m_vRVM_RP;
+#endif
+
+public:
+  TEncPic();
+  virtual ~TEncPic();
+  
+  Void  create      ( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight );
+  Void  destroy     ();
+  
+  Void  init        ( TEncTop* pcTEncTop );
+  Void compressPic( TComBitstream* pcBitstreamOut, TComPicYuv cPicOrg, TComPic* pcPic, TComPicYuv* pcPicYuvRecOut,
+                 TComPic* pcOrgRefList[2][MAX_REF_PIC_NUM], Bool&  rbSeqFirst, TComList<TComPic*>& rcListPic  );
+  TComList<TComPic*>*   getListPic()      { return m_pcListPic; }
+  
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits );
+
+  
+protected:
+#if DCM_DECODING_REFRESH
+  NalUnitType getNalUnitType( UInt uiPOCCurr );
+#endif
+
+  Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, UInt uiBits, Double dEncTime );
+  
+  UInt64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
+
+#if RVM_VCEGAM10
+  Double xCalculateRVM();
+#endif
+};// END CLASS DEFINITION TEncPic
+
+
+#endif // __TEncPic__
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 19)
@@ -0,0 +1,2428 @@
+/* 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     TEncSbac.cpp
+    \brief    SBAC encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSbac.h"
+
+#include <map>
+
+extern UChar  stateMappingTable[113];
+extern Int entropyBits[128];
+
+// ====================================================================================================================
+// 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_cCUSplitFlagSCModel       ( 1,             1,               NUM_SPLIT_FLAG_CTX            )
+, m_cCUSkipFlagSCModel        ( 1,             1,               NUM_SKIP_FLAG_CTX             )
+, m_cCUMergeFlagExtSCModel    ( 1,             1,               NUM_MERGE_FLAG_EXT_CTX        )
+, m_cCUMergeIdxExtSCModel     ( 1,             1,               NUM_MERGE_IDX_EXT_CTX         )
+, m_cCUMVMergeIdxExtSCModel   ( 1,             1,               NUM_MV_MERGE_IDX_EXT_CTX      )
+, m_cResPredFlagSCModel       ( 1,             1,               NUM_RES_PRED_FLAG_CTX         )
+, m_cCUPartSizeSCModel        ( 1,             1,               NUM_PART_SIZE_CTX             )
+, m_cCUPredModeSCModel        ( 1,             1,               NUM_PRED_MODE_CTX             )
+, m_cCUAlfCtrlFlagSCModel     ( 1,             1,               NUM_ALF_CTRL_FLAG_CTX         )
+, m_cCUIntraPredSCModel       ( 1,             1,               NUM_ADI_CTX                   )
+#if ADD_PLANAR_MODE
+, m_cPlanarFlagSCModel        ( 1,             1,               NUM_PLANARFLAG_CTX            )
+#endif
+, m_cCUChromaPredSCModel      ( 1,             1,               NUM_CHROMA_PRED_CTX           )
+, m_cCUDeltaQpSCModel         ( 1,             1,               NUM_DELTA_QP_CTX              )
+, m_cCUInterDirSCModel        ( 1,             1,               NUM_INTER_DIR_CTX             )
+, m_cCURefPicSCModel          ( 1,             1,               NUM_REF_NO_CTX                )
+, m_cCUMvdSCModel             ( 1,             2,               NUM_MV_RES_CTX                )
+, m_cCUQtCbfSCModel           ( 1,             3,               NUM_QT_CBF_CTX                )
+, m_cCUTransSubdivFlagSCModel ( 1,             1,               NUM_TRANS_SUBDIV_FLAG_CTX     )
+, m_cCUQtRootCbfSCModel       ( 1,             1,               NUM_QT_ROOT_CBF_CTX           )
+#if SIMPLE_CONTEXT_SIG
+, m_cCUSigSCModel             ( 4,             2,               NUM_SIG_FLAG_CTX              )
+#else
+, m_cCUSigSCModel             ( MAX_CU_DEPTH,  2,               NUM_SIG_FLAG_CTX              )
+#endif
+#if PCP_SIGMAP_SIMPLE_LAST
+, m_cCuCtxLastX               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          )
+, m_cCuCtxLastY               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          )
+#else
+, m_cCULastSCModel            ( MAX_CU_DEPTH,  2,               NUM_LAST_FLAG_CTX             )
+#endif
+, m_cCUOneSCModel             ( 1,             2,               NUM_ONE_FLAG_CTX              )
+, m_cCUAbsSCModel             ( 1,             2,               NUM_ABS_FLAG_CTX              )
+, m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               )
+, m_cALFFlagSCModel           ( 1,             1,               NUM_ALF_FLAG_CTX              )
+, m_cALFUvlcSCModel           ( 1,             1,               NUM_ALF_UVLC_CTX              )
+, m_cALFSvlcSCModel           ( 1,             1,               NUM_ALF_SVLC_CTX              )
+#if MTK_SAO
+, m_cAOFlagSCModel            ( 1,             1,               NUM_AO_FLAG_CTX              )
+, m_cAOUvlcSCModel            ( 1,             1,               NUM_AO_UVLC_CTX              )
+, m_cAOSvlcSCModel            ( 1,             1,               NUM_AO_SVLC_CTX              )
+#endif
+, m_cViewIdxSCModel           ( 1,             1,               NUM_VIEW_IDX_CTX              )
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+, m_cIntraDMMSCModel          ( 1,             1,               NUM_DMM_CTX                   )
+, m_cIntraWedgeSCModel        ( 1,             1,               NUM_WEDGE_CTX                 )
+#endif
+{
+
+}
+
+TEncSbac::~TEncSbac()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncSbac::resetEntropy           ()
+{
+  Int  iQp              = m_pcSlice->getSliceQp();
+  SliceType eSliceType  = m_pcSlice->getSliceType();
+  
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (Short*)INIT_SPLIT_FLAG );
+  
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_SKIP_FLAG );
+  m_cCUAlfCtrlFlagSCModel.initBuffer     ( eSliceType, iQp, (Short*)INIT_ALF_CTRL_FLAG );
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (Short*)INIT_MERGE_FLAG_EXT);
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (Short*)INIT_MERGE_IDX_EXT);
+  m_cCUMVMergeIdxExtSCModel.initBuffer   ( eSliceType, iQp, (Short*)INIT_MV_MERGE_IDX_EXT );
+  m_cResPredFlagSCModel.initBuffer       ( eSliceType, iQp, (Short*)INIT_RES_PRED_FLAG );
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (Short*)INIT_INTRA_PRED_MODE );
+#if ADD_PLANAR_MODE
+  m_cPlanarFlagSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_PLANARFLAG );
+#endif
+  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (Short*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (Short*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (Short*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (Short*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (Short*)INIT_QT_ROOT_CBF );
+  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (Short*)INIT_SIG_FLAG );
+#if PCP_SIGMAP_SIMPLE_LAST
+  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (Short*)INIT_LAST_X );
+  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (Short*)INIT_LAST_Y );
+#else
+  m_cCULastSCModel.initBuffer            ( eSliceType, iQp, (Short*)INIT_LAST_FLAG );
+#endif
+  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (Short*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (Short*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (Short*)INIT_MVP_IDX );
+  m_cALFFlagSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_ALF_FLAG );
+  m_cALFUvlcSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_ALF_UVLC );
+  m_cALFSvlcSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_ALF_SVLC );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (Short*)INIT_TRANS_SUBDIV_FLAG );
+#if MTK_SAO
+  m_cAOFlagSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_AO_FLAG );
+  m_cAOUvlcSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_AO_UVLC );
+  m_cAOSvlcSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_AO_SVLC );
+#endif
+  m_cViewIdxSCModel.initBuffer           ( eSliceType, iQp, (Short*)INIT_VIEW_IDX );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  m_cIntraDMMSCModel.initBuffer          ( eSliceType, iQp, (Short*)INIT_INTRA_DMM );
+  m_cIntraWedgeSCModel.initBuffer        ( eSliceType, iQp, (Short*)INIT_INTRA_WEDGELET );
+#endif
+
+  // new structure
+  m_uiLastQp = iQp;
+  
+  m_pcBinIf->start();
+  
+  return;
+}
+
+Void TEncSbac::codeNALUnitHeader( NalUnitType eNalUnitType, NalRefIdc eNalRefIdc, UInt TemporalId, Bool bOutputFlag )
+{
+  assert (0);
+  return;
+}
+
+void TEncSbac::codeSEI(const SEI&)
+{
+  assert(0);
+}
+
+Void TEncSbac::codeSPS( TComSPS* pcSPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codePPS( TComPPS* pcPPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeSliceHeader( TComSlice* pcSlice )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeTerminatingBit( UInt uilsLast )
+{
+  m_pcBinIf->encodeBinTrm( uilsLast );
+}
+
+Void TEncSbac::codeSliceFinish()
+{
+  m_pcBinIf->finish();
+}
+
+
+
+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 )
+{
+  while( uiSymbol >= (UInt)(1<<uiCount) )
+  {
+    m_pcBinIf->encodeBinEP( 1 );
+    uiSymbol -= 1<<uiCount;
+    uiCount  ++;
+  }
+  m_pcBinIf->encodeBinEP( 0 );
+  while( uiCount-- )
+  {
+    m_pcBinIf->encodeBinEP( (uiSymbol>>uiCount) & 1 );
+  }
+  
+  return;
+}
+
+#if E253
+/** 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 uiCount      = 0;
+  UInt uiMaxVlc     = g_auiGoRiceRange[ ruiGoRiceParam ];
+  Bool bExGolomb    = ( uiSymbol > uiMaxVlc );
+  UInt uiCodeWord   = min<UInt>( uiSymbol, ( uiMaxVlc + 1 ) );
+  UInt uiQuotient   = uiCodeWord >> ruiGoRiceParam;
+  UInt uiUnaryPart  = uiQuotient;
+  UInt uiRemainder  = 1;
+  UInt uiMaxPreLen  = g_auiGoRicePrefixLen[ ruiGoRiceParam ];
+
+  if( uiUnaryPart )
+  {
+    m_pcBinIf->encodeBinEP( 1 );
+    uiCount++;
+
+    while( --uiUnaryPart && uiCount < uiMaxPreLen )
+    {
+      m_pcBinIf->encodeBinEP( 1 );
+      uiCount++;
+    }
+
+    if( uiCount < uiMaxPreLen )
+    {
+      m_pcBinIf->encodeBinEP( uiUnaryPart ? 1 : 0 );
+    }
+  }
+  else
+  {
+    m_pcBinIf->encodeBinEP( 0 );
+  }
+
+  for( UInt ui = 0; ui < ruiGoRiceParam; ui++ )
+  {
+    m_pcBinIf->encodeBinEP( ( uiRemainder & uiCodeWord ) ? 1 : 0 );
+    uiRemainder = uiRemainder << 1;
+  }
+
+  ruiGoRiceParam = g_aauiGoRiceUpdate[ ruiGoRiceParam ][ min<UInt>( uiSymbol, 15 ) ];
+
+  if( bExGolomb )
+  {
+    uiSymbol -= uiMaxVlc + 1;
+    xWriteEpExGolomb( uiSymbol, 0 );
+  }
+
+  return;
+}
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+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
+#else
+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
+
+// SBAC RD
+Void  TEncSbac::load ( TEncSbac* pScr)
+{
+  this->xCopyFrom(pScr);
+}
+
+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;
+  
+  this->m_cCUSplitFlagSCModel      .copyFrom( &pSrc->m_cCUSplitFlagSCModel       );
+  this->m_cCUSkipFlagSCModel       .copyFrom( &pSrc->m_cCUSkipFlagSCModel        );
+  this->m_cCUMergeFlagExtSCModel  .copyFrom( &pSrc->m_cCUMergeFlagExtSCModel);
+  this->m_cCUMergeIdxExtSCModel   .copyFrom( &pSrc->m_cCUMergeIdxExtSCModel);
+  this->m_cCUMVMergeIdxExtSCModel .copyFrom( &pSrc->m_cCUMVMergeIdxExtSCModel );
+  this->m_cResPredFlagSCModel     .copyFrom( &pSrc->m_cResPredFlagSCModel        );
+  this->m_cCUPartSizeSCModel       .copyFrom( &pSrc->m_cCUPartSizeSCModel        );
+  this->m_cCUPredModeSCModel       .copyFrom( &pSrc->m_cCUPredModeSCModel        );
+  this->m_cCUIntraPredSCModel      .copyFrom( &pSrc->m_cCUIntraPredSCModel       );
+#if ADD_PLANAR_MODE
+  this->m_cPlanarFlagSCModel       .copyFrom( &pSrc->m_cPlanarFlagSCModel        );
+#endif
+  this->m_cCUChromaPredSCModel     .copyFrom( &pSrc->m_cCUChromaPredSCModel      );
+  this->m_cCUDeltaQpSCModel        .copyFrom( &pSrc->m_cCUDeltaQpSCModel         );
+  this->m_cCUInterDirSCModel       .copyFrom( &pSrc->m_cCUInterDirSCModel        );
+  this->m_cCURefPicSCModel         .copyFrom( &pSrc->m_cCURefPicSCModel          );
+  this->m_cCUMvdSCModel            .copyFrom( &pSrc->m_cCUMvdSCModel             );
+  this->m_cCUQtCbfSCModel          .copyFrom( &pSrc->m_cCUQtCbfSCModel           );
+  this->m_cCUTransSubdivFlagSCModel.copyFrom( &pSrc->m_cCUTransSubdivFlagSCModel );
+  this->m_cCUQtRootCbfSCModel      .copyFrom( &pSrc->m_cCUQtRootCbfSCModel       );
+  this->m_cCUSigSCModel            .copyFrom( &pSrc->m_cCUSigSCModel             );
+#if PCP_SIGMAP_SIMPLE_LAST
+  this->m_cCuCtxLastX              .copyFrom( &pSrc->m_cCuCtxLastX               );
+  this->m_cCuCtxLastY              .copyFrom( &pSrc->m_cCuCtxLastY               );
+#else
+  this->m_cCULastSCModel           .copyFrom( &pSrc->m_cCULastSCModel            );
+#endif
+  this->m_cCUOneSCModel            .copyFrom( &pSrc->m_cCUOneSCModel             );
+  this->m_cCUAbsSCModel            .copyFrom( &pSrc->m_cCUAbsSCModel             );
+  this->m_cMVPIdxSCModel           .copyFrom( &pSrc->m_cMVPIdxSCModel            );
+  this->m_cViewIdxSCModel          .copyFrom( &pSrc->m_cViewIdxSCModel           );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  this->m_cIntraDMMSCModel         .copyFrom( &pSrc->m_cIntraDMMSCModel          );
+  this->m_cIntraWedgeSCModel       .copyFrom( &pSrc->m_cIntraWedgeSCModel        );
+#endif
+}
+
+Void TEncSbac::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  Int iSymbol = pcCU->getMVPIdx(eRefList, uiAbsPartIdx);
+  Int iNum    = pcCU->getMVPNum(eRefList, uiAbsPartIdx);
+
+  xWriteUnaryMaxSymbol(iSymbol, m_cMVPIdxSCModel.get(0), 1, iNum-1);
+}
+
+Void TEncSbac::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
+  
+  if ( pcCU->getSlice()->isInterB() && pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+#if HHI_RMP_SWITCH
+    if( pcCU->getSlice()->getSPS()->getUseRMP() )
+#endif
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+    }
+#if HHI_DISABLE_INTER_NxN_SPLIT
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 3) );
+    }
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+    {
+      m_pcBinIf->encodeBin( (eSize == SIZE_2Nx2N? 0 : 1), m_cCUPartSizeSCModel.get( 0, 0, 4) );
+    }
+    return;
+  }
+  
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+#if MTK_DISABLE_INTRA_NxN_SPLIT
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+    {
+      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:
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+      
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+      
+      break;
+    }
+    case SIZE_NxN:
+    {
+#if HHI_DISABLE_INTER_NxN_SPLIT
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+      {
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+#if HHI_RMP_SWITCH
+        if( pcCU->getSlice()->getSPS()->getUseRMP() )
+#endif
+        {
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+        }
+        
+        if (pcCU->getSlice()->isInterB())
+        {
+          m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 3) );
+        }
+      }
+      break;
+    }
+    default:
+    {
+      assert(0);
+    }
+  }
+}
+
+/** code prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx  
+ * \returns Void
+ */
+Void TEncSbac::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  Int iPredMode = pcCU->getPredictionMode( uiAbsPartIdx );
+  if (pcCU->getSlice()->isInterB() )
+  {
+    return;
+  }
+
+  m_pcBinIf->encodeBin( iPredMode == MODE_INTER ? 0 : 1, m_cCUPredModeSCModel.get( 0, 0, 1 ) );
+}
+
+Void TEncSbac::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;
+  
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUAlfCtrlFlagSCModel.get( 0, 0, pcCU->getCtxAlfCtrlFlag( uiAbsPartIdx) ) );
+}
+
+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_V( 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");
+}
+
+/** code merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiCtx = 0;
+#if CHANGE_MERGE_CONTEXT
+  uiCtx = pcCU->getCtxMergeFlag( uiAbsPartIdx );
+#else
+  for(UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; uiIter++ )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == uiIter + 1 )
+    {
+      if( uiIter == 0 )
+      {
+        uiCtx++;
+      }
+      else if( uiIter == 1 )
+      {
+        uiCtx++;
+      }
+    }
+  }
+#endif
+  UInt uiSymbol = pcCU->getMergeFlag( uiAbsPartIdx ) ? 1 : 0;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUMergeFlagExtSCModel.get( 0, 0, uiCtx ) );
+
+  DTRACE_CABAC_V( 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 );
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+  {
+    DTRACE_CABAC_T( "\tNumMrgCand: " );
+    DTRACE_CABAC_V( ui );
+    DTRACE_CABAC_T( "\t==\t" );
+    DTRACE_CABAC_V( UInt( pcCU->getNeighbourCandIdx( ui, uiAbsPartIdx ) ) );
+  }
+  DTRACE_CABAC_T( "\n" );
+}
+
+
+
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+Void TEncSbac::codeMergeIndexMV( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  //--- set number of candidates and availability ---
+  Bool  abAvailable[ MRG_MAX_NUM_CANDS ];
+  UInt  uiNumCand = 0;
+#if HHI_MPI
+  const Bool bMVIAvailable = pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE;
+  const UInt uiMviMergePos = bMVIAvailable ? HHI_MPI_MERGE_POS : MRG_MAX_NUM_CANDS;
+#endif
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS; uiIdx++ )
+  {
+#if HHI_MPI
+    if( uiIdx == uiMviMergePos )
+    {
+      abAvailable[ uiIdx ] = true;
+      uiNumCand++;
+    }
+    else if( uiIdx > uiMviMergePos )
+    {
+      if( ( abAvailable[ uiIdx ] = ( pcCU->getNeighbourCandIdx( uiIdx - 1, uiAbsPartIdx ) == uiIdx ) ) )
+      {
+        uiNumCand++;
+      }
+    }
+    else
+#endif
+    if( ( abAvailable[ uiIdx ] = ( pcCU->getNeighbourCandIdx( uiIdx, uiAbsPartIdx ) == uiIdx + 1 ) ) )
+    {
+      uiNumCand++;
+    }
+  }
+  AOF( uiNumCand > 1 );
+
+  //--- determine contexts ---
+  AOF( NUM_MV_MERGE_IDX_EXT_CTX >= MRG_MAX_NUM_CANDS - 1 );
+  UInt  auiCtx[ MRG_MAX_NUM_CANDS - 1 ];
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS - 1; uiIdx++ )
+  {
+    auiCtx[ uiIdx ] = MRG_MAX_NUM_CANDS;
+    if( uiNumCand > uiIdx + 1 )
+    {
+      Bool bAvComb    = false;
+      for( UInt uiCId = uiIdx; uiCId < MRG_MAX_NUM_CANDS - 1; uiCId++ )
+      {
+        bAvComb = ( bAvComb || abAvailable[ uiCId ] );
+        if( abAvailable[ uiCId + 1 ] && bAvComb )
+        {
+          auiCtx[ uiIdx ] = uiCId;
+          break;
+        }
+      }
+      AOT( auiCtx[ uiIdx ] == MRG_MAX_NUM_CANDS );
+    }
+  }
+
+  //--- determine unary index ---
+  UInt  uiMergeIdx  = pcCU->getMergeIndex( uiAbsPartIdx );
+#if HHI_MPI
+  if( bMVIAvailable )
+  {
+    const Bool bUseMVI = pcCU->getTextureModeDepth( uiAbsPartIdx ) != -1;
+    if( bUseMVI )
+    {
+      uiMergeIdx = HHI_MPI_MERGE_POS;
+    }
+    else if( uiMergeIdx >= HHI_MPI_MERGE_POS )
+    {
+      uiMergeIdx++;
+    }
+  }
+#endif
+  UInt  uiUnaryIdx  = uiMergeIdx;
+  for( UInt uiIdx = 0; uiIdx < uiMergeIdx; uiIdx++ )
+  {
+    if( ! abAvailable[ uiIdx ] )
+    {
+      uiUnaryIdx--;
+    }
+  }
+
+  //--- code unary index ---
+  for( UInt ui = 0; ui < uiNumCand - 1; ui++ )
+  {
+    const UInt uiSymbol = ( ui == uiUnaryIdx ? 0 : 1 );
+    m_pcBinIf->encodeBin( uiSymbol, m_cCUMVMergeIdxExtSCModel.get( 0, 0, auiCtx[ui] ) );
+    if( uiSymbol == 0 )
+    {
+      break;
+    }
+  }
+
+  //--- trace ---
+  DTRACE_CABAC_V( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tparseMergeIndex():" );
+  DTRACE_CABAC_T( "   MRGIdx = " );
+  DTRACE_CABAC_V( uiMergeIdx );
+  DTRACE_CABAC_T( "   UnaryIdx = " );
+  DTRACE_CABAC_V( uiUnaryIdx );
+  DTRACE_CABAC_T( "   NumCand = " );
+  DTRACE_CABAC_V( uiNumCand );
+  DTRACE_CABAC_T( "   Availibility = " );
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS; uiIdx++ )
+  {
+    DTRACE_CABAC_V( abAvailable[ uiIdx ] ? 1 : 0 );
+  }
+  DTRACE_CABAC_T( "   Contexts = " );
+  for( UInt uiIdx = 0; uiIdx < MRG_MAX_NUM_CANDS - 1; uiIdx++ )
+  {
+    DTRACE_CABAC_V( auiCtx[ uiIdx ] );
+  }
+  DTRACE_CABAC_T( "\n" );
+}
+#endif
+
+
+/** code merge index
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+#if HHI_INTER_VIEW_MOTION_PRED && HHI_MPI
+  if( ( pcCU->getSlice()->getSPS()->getViewId() > 0 && ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) == PDM_USE_FOR_MERGE ) ||
+      ( pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N ) )
+#elif HHI_MPI
+  if( pcCU->getSlice()->getSPS()->getUseMVI() && pcCU->getSlice()->getSliceType() != I_SLICE && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+#else
+  if( pcCU->getSlice()->getSPS()->getViewId() > 0 && ( pcCU->getSlice()->getSPS()->getMultiviewMvPredMode() & PDM_USE_FOR_MERGE ) == PDM_USE_FOR_MERGE )
+#endif
+  {
+    codeMergeIndexMV( pcCU, uiAbsPartIdx );
+    return;
+  }
+#endif
+
+  Bool bLeftInvolved = false;
+  Bool bAboveInvolved = false;
+  Bool bCollocatedInvolved = false;
+  Bool bCornerInvolved = false;
+  Bool bCornerBLInvolved = false;
+  UInt uiNumCand = 0;
+  for( UInt uiIter = 0; uiIter < MRG_MAX_NUM_CANDS; ++uiIter )
+  {
+    if( pcCU->getNeighbourCandIdx( uiIter, uiAbsPartIdx ) == uiIter + 1 )
+    {
+      uiNumCand++;
+      if( uiIter == 0 )
+      {
+        bLeftInvolved = true;
+      }
+      else if( uiIter == 1 )
+      {
+        bAboveInvolved = true;
+      }
+      else if( uiIter == 2 )
+      {
+        bCollocatedInvolved = true;
+      }
+      else if( uiIter == 3 )
+      {
+        bCornerInvolved = true;
+      }
+      else if( uiIter == 4 )
+      {
+        bCornerBLInvolved = true;
+      }
+    }
+  }
+  assert( uiNumCand > 1 );
+
+  UInt auiCtx[4] = { 0, 0, 0, 3 };
+  if( bLeftInvolved && bAboveInvolved )
+  {
+    auiCtx[0] = 0;
+  }
+  else if( bLeftInvolved || bAboveInvolved )
+  {
+    auiCtx[0] = bCollocatedInvolved ? 1 : 2;
+  }
+  else
+  {
+    auiCtx[0] = bCollocatedInvolved ? 2 : 3;
+  }
+
+  if( uiNumCand >= 3 )
+  {
+    if( bAboveInvolved )
+    {
+      auiCtx[1] = bCollocatedInvolved ? 1 : 2;
+    }
+    else
+    {
+      auiCtx[1] = bCollocatedInvolved ? 2 : 3;
+    }
+  }
+
+  if( uiNumCand >= 4 )
+  {
+    auiCtx[2] =  bCollocatedInvolved ? 2 : 3;
+  }
+
+  UInt uiUnaryIdx = pcCU->getMergeIndex( uiAbsPartIdx );
+
+  if( !bCornerInvolved && uiUnaryIdx > 3 )
+  {
+    --uiUnaryIdx;
+  }
+  if( !bCollocatedInvolved && uiUnaryIdx > 2 )
+  {
+    --uiUnaryIdx;
+  }
+  if( !bAboveInvolved && uiUnaryIdx > 1 )
+  {
+    --uiUnaryIdx;
+  }
+  if( !bLeftInvolved && uiUnaryIdx > 0 )
+  {
+    --uiUnaryIdx;
+  }
+
+  for( UInt ui = 0; ui < uiNumCand - 1; ++ui )
+  {
+    const UInt uiSymbol = ui == uiUnaryIdx ? 0 : 1;
+    m_pcBinIf->encodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, auiCtx[ui] ) );
+    if( uiSymbol == 0 )
+    {
+      break;
+    }
+  }
+
+  DTRACE_CABAC_V( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tparseMergeIndex()" );
+  DTRACE_CABAC_T( "\tuiMRGIdx= " );
+  DTRACE_CABAC_V( pcCU->getMergeIndex( uiAbsPartIdx ) );
+  DTRACE_CABAC_T( "\tuiNumCand= " );
+  DTRACE_CABAC_V( uiNumCand );
+  DTRACE_CABAC_T( "\tbLeftInvolved= " );
+  DTRACE_CABAC_V( bLeftInvolved );
+  DTRACE_CABAC_T( "\tbAboveInvolved= " );
+  DTRACE_CABAC_V( bAboveInvolved );
+  DTRACE_CABAC_T( "\tbCollocatedInvolved= " );
+  DTRACE_CABAC_V( bCollocatedInvolved );
+  DTRACE_CABAC_T( "\tbCornerRTInvolved= " );
+  DTRACE_CABAC_V( bCornerInvolved );
+  DTRACE_CABAC_T( "\tbCornerBLInvolved= " );
+  DTRACE_CABAC_V( bCornerBLInvolved );
+  DTRACE_CABAC_T( "\n" );
+}
+
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+Void 
+TEncSbac::codeResPredFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt  uiCtx     = 0;
+  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 );
+  m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_V( 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_V( 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 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_cIntraWedgeSCModel.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_cIntraWedgeSCModel.get(0, 0, 0) );
+  }
+
+  Int iDeltaDC1 = pcCU->getWedgeFullDeltaDC1( uiAbsPartIdx );
+  Int iDeltaDC2 = pcCU->getWedgeFullDeltaDC2( uiAbsPartIdx );
+
+   xWriteExGolombLevel( UInt( abs( iDeltaDC1 ) ), m_cIntraWedgeSCModel.get(0, 0, 1) );
+   if ( iDeltaDC1 != 0 )
+   {
+     UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+     m_pcBinIf->encodeBinEP( uiSign );
+   }
+   xWriteExGolombLevel( UInt( abs( iDeltaDC2 ) ), m_cIntraWedgeSCModel.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_cIntraWedgeSCModel.get(0, 0, 3) );
+
+    if( iDeltaEnd != 0 )
+    {
+      UInt uiAbsValMinus1 = abs(iDeltaEnd)-1;
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x01),      m_cIntraWedgeSCModel.get(0, 0, 3) );
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x02) >> 1, m_cIntraWedgeSCModel.get(0, 0, 3) );
+
+      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_cIntraWedgeSCModel.get(0, 0, 3) );
+
+    if( iDeltaEnd != 0 )
+  {
+      UInt uiAbsValMinus1 = abs(iDeltaEnd)-1;
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x01),      m_cIntraWedgeSCModel.get(0, 0, 3) );
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x02) >> 1, m_cIntraWedgeSCModel.get(0, 0, 3) );
+
+      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_cIntraWedgeSCModel.get(0, 0, 1) );
+  if ( iDeltaDC1 != 0 )
+  {
+    UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+  xWriteExGolombLevel( UInt( abs( iDeltaDC2 ) ), m_cIntraWedgeSCModel.get(0, 0, 1) );
+  if ( iDeltaDC2 != 0 )
+  {
+    UInt uiSign = iDeltaDC2 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+}
+#endif
+#if HHI_DMM_PRED_TEX
+Void TEncSbac::xCodeWedgePredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDeltaDC1 = pcCU->getWedgePredTexDeltaDC1( uiAbsPartIdx );
+  Int iDeltaDC2 = pcCU->getWedgePredTexDeltaDC2( uiAbsPartIdx );
+
+  xWriteExGolombLevel( UInt( abs( iDeltaDC1 ) ), m_cIntraWedgeSCModel.get(0, 0, 1) );
+  if ( iDeltaDC1 != 0 )
+  {
+    UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+  xWriteExGolombLevel( UInt( abs( iDeltaDC2 ) ), m_cIntraWedgeSCModel.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_cIntraWedgeSCModel.get(0, 0, 1) );
+  if ( iDeltaDC1 != 0 )
+  {
+    UInt uiSign = iDeltaDC1 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+  xWriteExGolombLevel( UInt( abs( iDeltaDC2 ) ), m_cIntraWedgeSCModel.get(0, 0, 1) );
+  if ( iDeltaDC2 != 0 )
+  {
+    UInt uiSign = iDeltaDC2 > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+}
+#endif
+
+#if MTK_DCM_MPM
+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()->isDepth() && pcCU->getSlice()->getSPS()->getUseDMM() && pcCU->getWidth( uiAbsPartIdx ) < 64 )
+  {
+    m_pcBinIf->encodeBin( uiDir > MAX_MODE_ID_INTRA_DIR, m_cIntraDMMSCModel.get(0, 0, 0) );
+  }
+  if( uiDir > MAX_MODE_ID_INTRA_DIR )
+  {
+    assert( pcCU->getWidth( uiAbsPartIdx ) < 64 );
+    UInt uiDMMode = uiDir - (MAX_MODE_ID_INTRA_DIR+1);
+
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+    m_pcBinIf->encodeBin( (uiDMMode & 0x01),      m_cIntraDMMSCModel.get(0, 0, 1) );
+    m_pcBinIf->encodeBin( (uiDMMode & 0x02) >> 1, m_cIntraDMMSCModel.get(0, 0, 1) );
+
+      if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && pcCU->getWidth( uiAbsPartIdx ) > 4 )
+      {
+      m_pcBinIf->encodeBin( (uiDMMode & 0x04) >> 2, m_cIntraDMMSCModel.get(0, 0, 1) );
+        }
+#else
+                                  m_pcBinIf->encodeBin( (uiDMMode & 0x01),      m_cIntraDMMSCModel.get(0, 0, 1) );
+
+    if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && pcCU->getWidth( uiAbsPartIdx ) > 4 )
+    {
+      m_pcBinIf->encodeBin( (uiDMMode & 0x02) >> 1, m_cIntraDMMSCModel.get(0, 0, 1) );
+    }
+#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( uiDir == DMM_WEDGE_PREDTEX_D_IDX )     { xCodeWedgePredTexDeltaInfo  ( pcCU, uiAbsPartIdx ); }
+    if( uiDir == DMM_CONTOUR_PREDTEX_D_IDX )   { xCodeContourPredTexDeltaInfo( pcCU, uiAbsPartIdx ); }
+#endif
+  }
+  else
+#endif
+  {
+  Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+#if ADD_PLANAR_MODE
+  UInt planarFlag    = 0;
+  if (uiDir == PLANAR_IDX)
+  {
+    uiDir = 2;
+    planarFlag = 1;
+  }
+#endif
+  
+  Int uiPreds[2] = {-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 ) );
+    if(uiPredNum == 2)
+    {
+      m_pcBinIf->encodeBin( uiPredIdx, m_cCUIntraPredSCModel.get( 0, 0, 2 ) );
+    }
+
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+  
+    for(Int i = (uiPredNum - 1); i >= 0; i--)
+    {
+      uiDir = uiDir > uiPreds[i] ? uiDir - 1 : uiDir;
+    }
+
+    if ( g_aucIntraModeBitsAng[iIntraIdx] < 6 )
+    {
+      m_pcBinIf->encodeBin((uiDir & 0x01), m_cCUIntraPredSCModel.get(0, 0, 1));
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) { m_pcBinIf->encodeBin((uiDir & 0x02) >> 1, m_cCUIntraPredSCModel.get(0, 0, 1));}
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) { m_pcBinIf->encodeBin((uiDir & 0x04) >> 2, m_cCUIntraPredSCModel.get(0, 0, 1));}
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 4 ) { m_pcBinIf->encodeBin((uiDir & 0x08) >> 3, m_cCUIntraPredSCModel.get(0, 0, 1));}
+    }
+    else
+    {
+      if (uiDir < 31){ // uiDir is here 0...32, 5 bits for uiDir 0...30, 31 is an escape code for coding one more bit for 31 and 32
+        m_pcBinIf->encodeBin((uiDir & 0x01),      m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir & 0x02) >> 1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir & 0x04) >> 2, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir & 0x08) >> 3, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir & 0x10) >> 4, m_cCUIntraPredSCModel.get(0, 0, 1));
+      }
+      else{
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir == 32) ? 1 : 0, m_cCUIntraPredSCModel.get(0, 0, 1));
+       }
+     }
+   }
+#if ADD_PLANAR_MODE
+  uiDir = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  if ( (uiDir == PLANAR_IDX) || (uiDir == 2) )
+  {
+    m_pcBinIf->encodeBin( planarFlag, m_cPlanarFlagSCModel.get(0,0,0) );
+  }
+#endif
+  }
+  return;
+}
+#else
+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()->isDepth() && pcCU->getSlice()->getSPS()->getUseDMM() && pcCU->getWidth( uiAbsPartIdx ) < 64 )
+  {
+    m_pcBinIf->encodeBin( uiDir > MAX_MODE_ID_INTRA_DIR, m_cIntraDMMSCModel.get(0, 0, 0) );
+  }
+  if( uiDir > MAX_MODE_ID_INTRA_DIR )
+  {
+    assert( pcCU->getWidth( uiAbsPartIdx ) < 64 );
+    UInt uiDMMode = uiDir - (MAX_MODE_ID_INTRA_DIR+1);
+
+#if HHI_DMM_WEDGE_INTRA && HHI_DMM_PRED_TEX
+    m_pcBinIf->encodeBin( (uiDMMode & 0x01),      m_cIntraDMMSCModel.get(0, 0, 1) );
+    m_pcBinIf->encodeBin( (uiDMMode & 0x02) >> 1, m_cIntraDMMSCModel.get(0, 0, 1) );
+
+      if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && pcCU->getWidth( uiAbsPartIdx ) > 4 )
+      {
+      m_pcBinIf->encodeBin( (uiDMMode & 0x04) >> 2, m_cIntraDMMSCModel.get(0, 0, 1) );
+        }
+#else
+        m_pcBinIf->encodeBin( (uiDMMode & 0x01),      m_cIntraDMMSCModel.get(0, 0, 1) );
+
+      if ( pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN && pcCU->getWidth( uiAbsPartIdx ) > 4 )
+      {
+      m_pcBinIf->encodeBin( (uiDMMode & 0x02) >> 1, m_cIntraDMMSCModel.get(0, 0, 1) );
+      }
+#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( uiDir == DMM_WEDGE_PREDTEX_D_IDX )     { xCodeWedgePredTexDeltaInfo  ( pcCU, uiAbsPartIdx ); }
+    if( uiDir == DMM_CONTOUR_PREDTEX_D_IDX )   { xCodeContourPredTexDeltaInfo( pcCU, uiAbsPartIdx ); }
+#endif
+  }
+  else
+#endif
+  {
+  Int  iMostProbable = pcCU->getMostProbableIntraDirLuma( uiAbsPartIdx );
+#if ADD_PLANAR_MODE
+  UInt planarFlag    = 0;
+  if (uiDir == PLANAR_IDX)
+  {
+    uiDir = 2;
+    planarFlag = 1;
+  }
+#endif
+  
+  if (uiDir == iMostProbable)
+    m_pcBinIf->encodeBin( 1, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+  else
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+    uiDir = uiDir > iMostProbable ? uiDir - 1 : uiDir;
+    Int iIntraIdx = pcCU->getIntraSizeIdx(uiAbsPartIdx);
+    if ( g_aucIntraModeBitsAng[iIntraIdx] < 6 )
+    {
+      m_pcBinIf->encodeBin((uiDir & 0x01), m_cCUIntraPredSCModel.get(0, 0, 1));
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 2 ) m_pcBinIf->encodeBin((uiDir & 0x02) >> 1, m_cCUIntraPredSCModel.get(0, 0, 1));
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 3 ) m_pcBinIf->encodeBin((uiDir & 0x04) >> 2, m_cCUIntraPredSCModel.get(0, 0, 1));
+      if ( g_aucIntraModeBitsAng[iIntraIdx] > 4 ) m_pcBinIf->encodeBin((uiDir & 0x08) >> 3, m_cCUIntraPredSCModel.get(0, 0, 1));
+    }
+    else
+    {
+      if (uiDir < 31)
+      { // uiDir is here 0...32, 5 bits for uiDir 0...30, 31 is an escape code for coding one more bit for 31 and 32
+        m_pcBinIf->encodeBin((uiDir & 0x01),      m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir & 0x02) >> 1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir & 0x04) >> 2, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir & 0x08) >> 3, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir & 0x10) >> 4, m_cCUIntraPredSCModel.get(0, 0, 1));
+      }
+      else
+      {
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin(1, m_cCUIntraPredSCModel.get(0, 0, 1));
+        m_pcBinIf->encodeBin((uiDir == 32) ? 1 : 0, m_cCUIntraPredSCModel.get(0, 0, 1));
+      }
+    }
+  }
+  
+#if ADD_PLANAR_MODE
+  uiDir = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  if ( (uiDir == PLANAR_IDX) || (uiDir == 2) )
+  {
+    m_pcBinIf->encodeBin( planarFlag, m_cPlanarFlagSCModel.get(0,0,0) );
+  }
+#endif
+  }
+  return;
+}
+#endif
+Void TEncSbac::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiCtx            = pcCU->getCtxIntraDirChroma( uiAbsPartIdx );
+  UInt uiIntraDirChroma = pcCU->getChromaIntraDir   ( uiAbsPartIdx );
+#if ADD_PLANAR_MODE
+  UInt planarFlag       = 0;
+  if (uiIntraDirChroma == PLANAR_IDX)
+  {
+    uiIntraDirChroma = 2;
+    planarFlag = 1;
+  }
+#endif
+ 
+#if CHROMA_CODEWORD
+  UInt uiMode = pcCU->getLumaIntraDir(uiAbsPartIdx);
+#if ADD_PLANAR_MODE
+  if ( (uiMode == 2 ) || (uiMode == PLANAR_IDX) )
+  {
+    uiMode = 4;
+  }
+#endif
+
+#if LM_CHROMA
+
+  Bool bUseLMFlag = pcCU->getSlice()->getSPS()->getUseLMChroma();
+
+  Int  iMaxMode = bUseLMFlag ? 3 : 4;
+
+  Int  iMax = uiMode < iMaxMode ? 2 : 3; 
+  
+  //switch codeword
+  if (uiIntraDirChroma == 4) 
+  {
+    uiIntraDirChroma = 0;
+  } 
+  else if (uiIntraDirChroma == 3 && bUseLMFlag )
+  {
+    uiIntraDirChroma = 1;
+  }
+  else
+  {
+    if (uiIntraDirChroma < uiMode)
+      uiIntraDirChroma++;
+
+    if (bUseLMFlag)
+      uiIntraDirChroma++;
+
+#if CHROMA_CODEWORD_SWITCH 
+    uiIntraDirChroma = ChromaMapping[iMax-2][uiIntraDirChroma];
+#endif
+
+  }
+
+
+#else // <-- LM_CHROMA
+  Int  iMax = uiMode < 4 ? 2 : 3; 
+  
+  //switch codeword
+  if (uiIntraDirChroma == 4) {
+    uiIntraDirChroma = 0;
+  } 
+#if CHROMA_CODEWORD_SWITCH 
+  else {
+    if (uiIntraDirChroma < uiMode) {
+      uiIntraDirChroma++;
+    }
+    uiIntraDirChroma = ChromaMapping[iMax-2][uiIntraDirChroma];
+  }
+#else
+  else if (uiIntraDirChroma < uiMode) {
+    uiIntraDirChroma++;
+  }
+#endif
+#endif // <-- LM_CHROMA
+  
+  if ( 0 == uiIntraDirChroma )
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, uiCtx ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, uiCtx ) );
+    xWriteUnaryMaxSymbol( uiIntraDirChroma - 1, m_cCUChromaPredSCModel.get( 0, 0 ) + 3, 0, iMax );
+  }
+#else // CHROMA_CODEWORD
+  if ( 0 == uiIntraDirChroma )
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, uiCtx ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, uiCtx ) );
+    xWriteUnaryMaxSymbol( uiIntraDirChroma - 1, m_cCUChromaPredSCModel.get( 0, 0 ) + 3, 0, 3 );
+  }
+#endif
+
+#if ADD_PLANAR_MODE
+  uiIntraDirChroma = pcCU->getChromaIntraDir( uiAbsPartIdx );
+#if CHROMA_CODEWORD
+  uiMode = pcCU->getLumaIntraDir(uiAbsPartIdx);
+  mapPlanartoDC( uiIntraDirChroma );
+  mapPlanartoDC( uiMode );
+  if ( (uiIntraDirChroma == 2) && (uiMode != 2) )
+#else
+  if ( (uiIntraDirChroma == PLANAR_IDX) || (uiIntraDirChroma == 2) )
+#endif
+  {
+    m_pcBinIf->encodeBin( planarFlag, m_cPlanarFlagSCModel.get(0,0,1) );
+  }
+#endif
+  return;
+}
+
+Void TEncSbac::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiInterDir = pcCU->getInterDir   ( uiAbsPartIdx );
+  UInt uiCtx      = pcCU->getCtxInterDir( uiAbsPartIdx );
+  uiInterDir--;
+  m_pcBinIf->encodeBin( ( uiInterDir == 2 ? 1 : 0 ), m_cCUInterDirSCModel.get( 0, 0, uiCtx ) );
+  
+  if ( pcCU->getSlice()->getNoBackPredFlag() )
+  {
+    assert( uiInterDir != 1 );
+    return;
+  }
+  
+#if DCM_COMB_LIST
+  if ( uiInterDir < 2 && pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0)
+#else
+  if ( uiInterDir < 2 )
+#endif
+  {
+    m_pcBinIf->encodeBin( uiInterDir, m_cCUInterDirSCModel.get( 0, 0, 3 ) );
+  }
+  
+  return;
+}
+
+Void TEncSbac::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+#if DCM_COMB_LIST
+  if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getInterDir( uiAbsPartIdx ) != 3)
+  {
+    Int iRefFrame = pcCU->getSlice()->getRefIdxOfLC(eRefList, pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx ));
+    UInt uiCtx;
+
+    uiCtx = pcCU->getCtxRefIdx( uiAbsPartIdx, RefPicList(pcCU->getSlice()->getListIdFromIdxOfLC(0)) );
+
+    m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), m_cCURefPicSCModel.get( 0, 0, uiCtx ) );
+
+    if ( iRefFrame > 0 )
+    {
+      xWriteUnaryMaxSymbol( iRefFrame - 1, &m_cCURefPicSCModel.get( 0, 0, 4 ), 1, pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_C )-2 );
+    }
+  }
+  else
+  {
+#endif
+  Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
+  
+  UInt uiCtx = pcCU->getCtxRefIdx( uiAbsPartIdx, eRefList );
+  
+  m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), m_cCURefPicSCModel.get( 0, 0, uiCtx ) );
+  
+  if ( iRefFrame > 0 )
+  {
+    xWriteUnaryMaxSymbol( iRefFrame - 1, &m_cCURefPicSCModel.get( 0, 0, 4 ), 1, pcCU->getSlice()->getNumRefIdx( eRefList )-2 );
+  }
+#if DCM_COMB_LIST
+  }
+#endif
+  return;
+}
+
+Void TEncSbac::codeViewIdx(Int iViewIdx)
+{
+  assert(0) ; // not implemented yet
+  xWriteUnaryMaxSymbol(iViewIdx, &m_cViewIdxSCModel.get( 0, 0, 4),1, MAX_NUMBER_VIEWS   );
+}
+
+Void TEncSbac::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  TComCUMvField* pcCUMvField = pcCU->getCUMvField( eRefList );
+  Int iHor = pcCUMvField->getMvd( uiAbsPartIdx ).getHor();
+  Int iVer = pcCUMvField->getMvd( uiAbsPartIdx ).getVer();
+  
+  UInt uiAbsPartIdxL, uiAbsPartIdxA;
+#if MVD_CTX
+  Int iHorPredL, iVerPredL;
+  Int iHorPredA, iVerPredA;
+#else
+  Int iHorPred, iVerPred;
+#endif
+
+  TComDataCU* pcCUL   = pcCU->getPULeft ( uiAbsPartIdxL, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  TComDataCU* pcCUA   = pcCU->getPUAbove( uiAbsPartIdxA, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  
+  TComCUMvField* pcCUMvFieldL = ( pcCUL == NULL || pcCUL->isIntra( uiAbsPartIdxL ) ) ? NULL : pcCUL->getCUMvField( eRefList );
+  TComCUMvField* pcCUMvFieldA = ( pcCUA == NULL || pcCUA->isIntra( uiAbsPartIdxA ) ) ? NULL : pcCUA->getCUMvField( eRefList );
+  
+#if MVD_CTX
+  iHorPredA = ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsHor() );
+  iVerPredA = ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsVer() );
+  iHorPredL = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsHor() );
+  iVerPredL = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsVer() );
+
+  xWriteMvd( iHor, iHorPredL, iHorPredA, 0 );
+  xWriteMvd( iVer, iVerPredL, iVerPredA, 1 );
+#else  
+  iHorPred = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsHor() ) +
+  ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsHor() );
+  iVerPred = ( (pcCUMvFieldL == NULL) ? 0 : pcCUMvFieldL->getMvd( uiAbsPartIdxL ).getAbsVer() ) +
+  ( (pcCUMvFieldA == NULL) ? 0 : pcCUMvFieldA->getMvd( uiAbsPartIdxA ).getAbsVer() );
+
+  xWriteMvd( iHor, iHorPred, 0 );
+  xWriteMvd( iVer, iVerPred, 1 );
+#endif
+
+  
+  return;
+}
+
+Void TEncSbac::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getSlice()->getSliceQp();
+  
+  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 uiDQp = (UInt)( iDQp > 0 ? ( 2 * iDQp - 2 ) : ( -2 * iDQp - 1 ) );
+    xWriteUnarySymbol( uiDQp, &m_cCUDeltaQpSCModel.get( 0, 0, 2 ), 1 );
+  }
+  
+  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 ? eType - 1 : eType, uiCtx ) );
+  DTRACE_CABAC_V( 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" )
+}
+
+UInt xCheckCoeffPlainCNoRecur( const TCoeff* pcCoef, UInt uiSize, UInt uiDepth )
+{
+  UInt uiNumofCoeff = 0;
+  UInt ui = uiSize>>uiDepth;
+  {
+    UInt x, y;
+    const TCoeff* pCeoff = pcCoef;
+    for( y=0 ; y<ui ; y++ )
+    {
+      for( x=0 ; x<ui ; x++ )
+      {
+        if( pCeoff[x] != 0 )
+        {
+          uiNumofCoeff++;
+        }
+      }
+      pCeoff += uiSize;
+    }
+  }
+  return uiNumofCoeff;
+}
+
+Void TEncSbac::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiCbf = pcCU->getQtRootCbf( uiAbsPartIdx );
+  UInt uiCtx = pcCU->getCtxQtRootCbf( uiAbsPartIdx );
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_V( 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" )
+}
+
+Void TEncSbac::xCheckCoeff( TCoeff* pcCoef, UInt uiSize, UInt uiDepth, UInt& uiNumofCoeff, UInt& uiPart )
+{
+  UInt ui = uiSize>>uiDepth;
+  if( uiPart == 0 )
+  {
+    if( ui <= 4 )
+    {
+      UInt x, y;
+      TCoeff* pCeoff = pcCoef;
+      for( y=0 ; y<ui ; y++ )
+      {
+        for( x=0 ; x<ui ; x++ )
+        {
+          if( pCeoff[x] != 0 )
+          {
+            uiNumofCoeff++;
+          }
+        }
+        pCeoff += uiSize;
+      }
+    }
+    else
+    {
+      xCheckCoeff( pcCoef,                            uiSize, uiDepth+1, uiNumofCoeff, uiPart ); uiPart++; //1st Part
+      xCheckCoeff( pcCoef             + (ui>>1),      uiSize, uiDepth+1, uiNumofCoeff, uiPart ); uiPart++; //2nd Part
+      xCheckCoeff( pcCoef + (ui>>1)*uiSize,           uiSize, uiDepth+1, uiNumofCoeff, uiPart ); uiPart++; //3rd Part
+      xCheckCoeff( pcCoef + (ui>>1)*uiSize + (ui>>1), uiSize, uiDepth+1, uiNumofCoeff, uiPart );           //4th Part
+    }
+  }
+  else
+  {
+    UInt x, y;
+    TCoeff* pCeoff = pcCoef;
+    for( y=0 ; y<ui ; y++ )
+    {
+      for( x=0 ; x<ui ; x++ )
+      {
+        if( pCeoff[x] != 0 )
+        {
+          uiNumofCoeff++;
+        }
+      }
+      pCeoff += uiSize;
+    }
+  }
+}
+
+UInt xCheckCoeffPlainCNoRecur( const TCoeff* pcCoef, UInt uiSize, UInt uiDepth );
+
+#if PCP_SIGMAP_SIMPLE_LAST
+/** Encode (X,Y) position of the last significant coefficient
+ * \param uiPosX X component of last coefficient
+ * \param uiPosY Y component of last coefficient
+ * \param uiWidth block width
+ * \param eTType plane type / luminance or chrominance
+ * \param uiCTXIdx block size context
+ * \param uiScanIdx scan type (zig-zag, hor, ver)
+ * \returns Void
+ * This method encodes the X and Y component within a block of the last significant coefficient.
+ */
+__inline Void TEncSbac::codeLastSignificantXY( UInt uiPosX, UInt uiPosY, const UInt uiWidth, const TextType eTType, const UInt uiCTXIdx, const UInt uiScanIdx )
+{  
+  UInt  uiCtxLast;
+  const UInt uiCtxOffset = g_uiCtxXYOffset[uiCTXIdx];
+
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosX, uiPosY );
+  }
+
+  for(uiCtxLast=0; uiCtxLast<uiPosX; uiCtxLast++)
+  {
+    m_pcBinIf->encodeBin( 0, m_cCuCtxLastX.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiCtxLast] ) );
+  }
+  if(uiPosX < uiWidth - 1)
+  {
+    m_pcBinIf->encodeBin( 1, m_cCuCtxLastX.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiCtxLast] ) );
+  }
+
+  for(uiCtxLast=0; uiCtxLast<uiPosY; uiCtxLast++)
+  {
+    m_pcBinIf->encodeBin( 0, m_cCuCtxLastY.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiCtxLast] ) );
+  }
+  if(uiPosY < uiWidth - 1)
+  {
+    m_pcBinIf->encodeBin( 1, m_cCuCtxLastY.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiCtxLast] ) );
+  }
+}
+#endif
+
+Void TEncSbac::codeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType, Bool bRD )
+{
+  DTRACE_CABAC_V( 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;
+  UInt uiCTXIdx = 0;
+  
+  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;
+  }
+  
+  // compute number of significant coefficients
+  UInt  uiPart = 0;
+  xCheckCoeff(pcCoef, uiWidth, 0, uiNumSig, uiPart );
+  
+  if ( bRD )
+  {
+    UInt uiTempDepth = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+    pcCU->setCbfSubParts( ( uiNumSig ? 1 : 0 ) << uiTempDepth, eTType, uiAbsPartIdx, uiDepth );
+  }
+  
+  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;
+  const UInt   uiMaxNumCoeff     = 1 << ( uiLog2BlockSize << 1 );
+#if !PCP_SIGMAP_SIMPLE_LAST
+  const UInt   uiMaxNumCoeffM1   = uiMaxNumCoeff - 1;
+#endif
+  const UInt   uiNum4x4Blk       = max<UInt>( 1, uiMaxNumCoeff >> 4 );
+#if QC_MDCS
+  const UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+#endif //QC_MDCS
+  
+#if PCP_SIGMAP_SIMPLE_LAST
+    //===== code last coeff =====
+    UInt uiScanPosLast = 0, uiPosLastX, uiPosLastY;
+    for( UInt uiScanPos = 0; uiScanPos < uiMaxNumCoeff; uiScanPos++ )
+    {
+#if QC_MDCS
+      UInt uiBlkPos    = g_auiSigLastScan[uiScanIdx][uiLog2BlockSize-1][uiScanPos]; 
+#else
+      UInt  uiBlkPos   = g_auiFrameScanXY[ uiLog2BlockSize-1 ][ uiScanPos ];
+#endif //QC_MDCS
+      uiPosLastY = uiBlkPos >> uiLog2BlockSize;
+      uiPosLastX = uiBlkPos - ( uiPosLastY << uiLog2BlockSize );
+
+      if( pcCoef[ uiBlkPos ] != 0 )
+      {
+        uiNumSig--;
+        if( uiNumSig == 0 )
+        {
+          codeLastSignificantXY(uiPosLastX, uiPosLastY, uiWidth, eTType, uiCTXIdx, uiScanIdx);
+          uiScanPosLast = uiScanPos;
+          break;
+        }
+      }
+    }
+
+    //===== code significance flag =====
+    {
+      for( UInt uiScanPos = 0; uiScanPos < uiScanPosLast; uiScanPos++ )
+      {
+#if QC_MDCS
+        UInt uiBlkPos   = g_auiSigLastScan[uiScanIdx][uiLog2BlockSize-1][uiScanPos]; 
+#else
+        UInt  uiBlkPos  = g_auiFrameScanXY[ uiLog2BlockSize-1 ][ uiScanPos ];
+#endif //QC_MDCS
+        UInt  uiPosY    = uiBlkPos >> uiLog2BlockSize;
+        UInt  uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+        UInt  uiSig     = pcCoef[ uiBlkPos ] != 0 ? 1 : 0;
+        UInt  uiCtxSig  = TComTrQuant::getSigCtxInc( pcCoef, uiPosX, uiPosY, uiLog2BlockSize, uiWidth );
+#if SIMPLE_CONTEXT_SIG
+        if( uiCtxSig < 4 || eTType)
+        {
+          m_pcBinIf->encodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx-2, eTType, uiCtxSig ) );
+        }
+        else
+        {
+          m_pcBinIf->encodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx-2 ? uiCTXIdx-2 : 1, eTType, uiCtxSig ) );
+        }
+#else
+        m_pcBinIf->encodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx, eTType, uiCtxSig ) );
+#endif
+      }
+    }
+
+#else
+  for( UInt uiScanPos = 0; uiScanPos < uiMaxNumCoeffM1; uiScanPos++ )
+  {
+#if QC_MDCS
+    UInt uiBlkPos   = g_auiSigLastScan[uiScanIdx][uiLog2BlockSize-1][uiScanPos]; 
+#else
+    UInt  uiBlkPos  = g_auiFrameScanXY[ uiLog2BlockSize-1 ][ uiScanPos ];
+#endif //QC_MDCS
+    UInt  uiPosY    = uiBlkPos >> uiLog2BlockSize;
+    UInt  uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+    
+    //===== code significance flag =====
+    UInt  uiSig    = pcCoef[ uiBlkPos ] != 0 ? 1 : 0;
+    UInt  uiCtxSig = TComTrQuant::getSigCtxInc( pcCoef, uiPosX, uiPosY, uiLog2BlockSize, uiWidth );
+#if SIMPLE_CONTEXT_SIG
+      if( uiCtxSig < 4 || eTType)
+      {
+        m_pcBinIf->encodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx-2, eTType, uiCtxSig ) );
+      }
+      else
+      {
+        m_pcBinIf->encodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx-2 ? uiCTXIdx-2 : 1, eTType, uiCtxSig ) );
+      }
+#else
+    m_pcBinIf->encodeBin( uiSig, m_cCUSigSCModel.get( uiCTXIdx, eTType, uiCtxSig ) );
+#endif
+    if( uiSig )
+    {
+      uiNumSig--;
+      
+      //===== code last flag =====
+      UInt  uiLast    = ( uiNumSig == 0 ) ? 1 : 0;
+      UInt  uiCtxLast = TComTrQuant::getLastCtxInc( uiPosX, uiPosY, uiLog2BlockSize );
+      m_pcBinIf->encodeBin( uiLast, m_cCULastSCModel.get( uiCTXIdx, eTType, uiCtxLast ) );
+      
+      if( uiLast )
+      {
+        break;
+      }
+    }
+  }
+#endif 
+  /*
+   * Sign and bin0 PCP (Section 3.2 and 3.3 of JCTVC-B088)
+   */
+  Int  c1, c2;
+  UInt uiSign;
+  UInt uiAbs;
+#if E253
+  UInt uiGoRiceParam = 0;
+#endif
+
+  if( uiNum4x4Blk > 1 )
+  {
+    Bool b1stBlk  = true;
+    UInt uiNumOne = 0;
+    
+    for( UInt uiSubBlk = 0; uiSubBlk < uiNum4x4Blk; uiSubBlk++ )
+    {
+      UInt uiCtxSet    = 0;
+      UInt uiSubNumSig = 0;
+      UInt uiSubPosX   = 0;
+      UInt uiSubPosY   = 0;
+#if E253
+      uiGoRiceParam    = 0;
+#endif
+
+      uiSubPosX = g_auiFrameScanX[ g_aucConvertToBit[ uiWidth ] - 1 ][ uiSubBlk ] << 2;
+      uiSubPosY = g_auiFrameScanY[ g_aucConvertToBit[ uiWidth ] - 1 ][ uiSubBlk ] << 2;
+      
+      TCoeff* piCurr = &pcCoef[ uiSubPosX + uiSubPosY * uiWidth ];
+      
+      for( UInt uiY = 0; uiY < 4; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < 4; uiX++ )
+        {
+          if( piCurr[ uiX ] )
+          {
+            uiSubNumSig++;
+          }
+        }
+        piCurr += uiWidth;
+      }
+      
+      if( uiSubNumSig > 0 )
+      {
+        c1 = 1;
+        c2 = 0;
+        
+        if( b1stBlk )
+        {
+          b1stBlk  = false;
+          uiCtxSet = 5;
+        }
+        else
+        {
+          uiCtxSet = ( uiNumOne >> 2 ) + 1;
+          uiNumOne = 0;
+        }
+        
+        for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+        {
+          UInt  uiBlkPos  = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+          UInt  uiPosY    = uiBlkPos >> 2;
+          UInt  uiPosX    = uiBlkPos - ( uiPosY << 2 );
+          UInt  uiIndex   = ( ( uiSubPosY + uiPosY ) << uiLog2BlockSize ) + uiSubPosX + uiPosX;
+          
+          if( pcCoef[ uiIndex ]  )
+          {
+            if( pcCoef[ uiIndex ] > 0) { uiAbs = static_cast<UInt>( pcCoef[ uiIndex ]);  uiSign = 0; }
+            else                       { uiAbs = static_cast<UInt>(-pcCoef[ uiIndex ]);  uiSign = 1; }
+            
+            UInt uiCtx    = min<UInt>(c1, 4);
+            UInt uiSymbol = uiAbs > 1 ? 1 : 0;
+            m_pcBinIf->encodeBin( uiSymbol, m_cCUOneSCModel.get( 0, eTType, ( uiCtxSet << 2 ) + uiCtxSet + uiCtx ) );
+            
+            if( uiSymbol )
+            {
+              c1     = 0;
+            }
+            else if( c1 )
+            {
+              c1++;
+            }
+          }
+        }
+        
+        for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+        {
+          UInt  uiBlkPos  = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+          UInt  uiPosY    = uiBlkPos >> 2;
+          UInt  uiPosX    = uiBlkPos - ( uiPosY << 2 );
+          UInt  uiIndex   = ( ( uiSubPosY + uiPosY ) << uiLog2BlockSize ) + uiSubPosX + uiPosX;
+          
+          if( pcCoef[ uiIndex ]  )
+          {
+            if( pcCoef[ uiIndex ] > 0) { uiAbs = static_cast<UInt>( pcCoef[ uiIndex ]);  uiSign = 0; }
+            else                       { uiAbs = static_cast<UInt>(-pcCoef[ uiIndex ]);  uiSign = 1; }
+            
+            UInt uiSymbol = uiAbs > 1 ? 1 : 0;
+            
+            if( uiSymbol )
+            {
+              UInt uiCtx  = min<UInt>(c2, 4);
+              uiAbs -= 2;
+              c2++;
+              uiNumOne++;
+#if E253
+              uiSymbol = uiAbs > 0 ? 1 : 0;
+
+              m_pcBinIf->encodeBin( uiSymbol, m_cCUAbsSCModel.get( 0, eTType, ( uiCtxSet << 2 ) + uiCtxSet + uiCtx ) );
+
+              if( uiSymbol )
+              {
+                uiAbs -= 1;
+                xWriteGoRiceExGolomb( uiAbs, uiGoRiceParam );
+              }
+#else
+              xWriteExGolombLevel( uiAbs, m_cCUAbsSCModel.get( 0, eTType, ( uiCtxSet << 2 ) + uiCtxSet + uiCtx ) );
+#endif
+            }
+          }
+        }
+        
+        for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+        {
+          UInt  uiBlkPos  = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+          UInt  uiPosY    = uiBlkPos >> 2;
+          UInt  uiPosX    = uiBlkPos - ( uiPosY << 2 );
+          UInt  uiIndex   = ( ( uiSubPosY + uiPosY ) << uiLog2BlockSize ) + uiSubPosX + uiPosX;
+          
+          if( pcCoef[ uiIndex ]  )
+          {
+            if( pcCoef[ uiIndex ] > 0) { uiAbs = static_cast<UInt>( pcCoef[ uiIndex ]);  uiSign = 0; }
+            else                       { uiAbs = static_cast<UInt>(-pcCoef[ uiIndex ]);  uiSign = 1; }
+            m_pcBinIf->encodeBinEP( uiSign );
+          }
+        }
+        
+      }
+    }
+  }
+  else
+  {
+    c1 = 1;
+    c2 = 0;
+    
+    for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+    {
+      UInt uiIndex = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+      
+      if( pcCoef[ uiIndex ]  )
+      {
+        if( pcCoef[ uiIndex ] > 0) { uiAbs = static_cast<UInt>( pcCoef[ uiIndex ]);  uiSign = 0; }
+        else                       { uiAbs = static_cast<UInt>(-pcCoef[ uiIndex ]);  uiSign = 1; }
+        
+        UInt uiCtx    = min<UInt>(c1, 4);
+        UInt uiSymbol = uiAbs > 1 ? 1 : 0;
+        m_pcBinIf->encodeBin( uiSymbol, m_cCUOneSCModel.get( 0, eTType, uiCtx ) );
+        
+        if( uiSymbol )
+        {
+          c1 = 0;
+        }
+        else if( c1 )
+        {
+          c1++;
+        }
+      }
+    }
+    
+    for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+    {
+      UInt uiIndex = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+      
+      if( pcCoef[ uiIndex ]  )
+      {
+        if( pcCoef[ uiIndex ] > 0) { uiAbs = static_cast<UInt>( pcCoef[ uiIndex ]);  uiSign = 0; }
+        else                       { uiAbs = static_cast<UInt>(-pcCoef[ uiIndex ]);  uiSign = 1; }
+        
+        UInt uiSymbol = uiAbs > 1 ? 1 : 0;
+        
+        if( uiSymbol )
+        {
+          UInt uiCtx  = min<UInt>(c2, 4);
+          uiAbs -= 2;
+          c2++;
+#if E253
+          uiSymbol = uiAbs > 0 ? 1 : 0;
+
+          m_pcBinIf->encodeBin( uiSymbol, m_cCUAbsSCModel.get( 0, eTType, uiCtx ) );
+
+          if( uiSymbol )
+          {
+            uiAbs -= 1;
+            xWriteGoRiceExGolomb( uiAbs, uiGoRiceParam );
+          }
+#else
+          xWriteExGolombLevel( uiAbs, m_cCUAbsSCModel.get( 0, eTType, uiCtx ) );
+#endif
+        }
+      }
+    }
+    
+    for( UInt uiScanPos = 0; uiScanPos < 16; uiScanPos++ )
+    {
+      UInt uiIndex = g_auiFrameScanXY[ 1 ][ 15 - uiScanPos ];
+      
+      if( pcCoef[ uiIndex ]  )
+      {
+        if( pcCoef[ uiIndex ] > 0) { uiAbs = static_cast<UInt>( pcCoef[ uiIndex ]);  uiSign = 0; }
+        else                       { uiAbs = static_cast<UInt>(-pcCoef[ uiIndex ]);  uiSign = 1; }
+        
+        m_pcBinIf->encodeBinEP( uiSign );
+      }
+    }
+  }
+  return;
+}
+
+#if MVD_CTX
+/** Encode a motion vector difference
+ * \param iMvd motion vector difference
+ * \param uiAbsSumL motion vector difference of left PU
+ * \param uiAbsSumA motion vector difference of above PU
+ * \param uiCtx index for context set based on vertical or horizontal component
+ */
+Void TEncSbac::xWriteMvd( Int iMvd, UInt uiAbsSumL, UInt uiAbsSumA, UInt uiCtx )
+#else
+Void TEncSbac::xWriteMvd( Int iMvd, UInt uiAbsSum, UInt uiCtx )
+#endif
+{
+  UInt uiLocalCtx = 0;
+#if MVD_CTX
+  uiLocalCtx += (uiAbsSumA>16) ? 1 : 0;
+  uiLocalCtx += (uiAbsSumL>16) ? 1 : 0;
+#else
+  if ( uiAbsSum >= 3 )
+  {
+    uiLocalCtx += ( uiAbsSum > 32 ) ? 2 : 1;
+  }
+#endif
+
+  UInt uiSymbol = ( 0 == iMvd ) ? 0 : 1;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUMvdSCModel.get( 0, uiCtx, uiLocalCtx ) );
+  if ( 0 == uiSymbol )
+  {
+    return;
+  }
+  
+  UInt uiSign = 0;
+  if ( 0 > iMvd )
+  {
+    uiSign = 1;
+    iMvd   = -iMvd;
+  }
+  xWriteExGolombMvd( iMvd-1, &m_cCUMvdSCModel.get( 0, uiCtx, 3 ), 3 );
+  m_pcBinIf->encodeBinEP( uiSign );
+  
+  return;
+}
+
+Void  TEncSbac::xWriteExGolombMvd( UInt uiSymbol, ContextModel* pcSCModel, UInt uiMaxBin )
+{
+  if ( ! uiSymbol )
+  {
+    m_pcBinIf->encodeBin( 0, *pcSCModel );
+    return;
+  }
+  
+  m_pcBinIf->encodeBin( 1, *pcSCModel );
+  
+  Bool bNoExGo = ( uiSymbol < 8 );
+  UInt uiCount = 1;
+  pcSCModel++;
+  
+  while ( --uiSymbol && ++uiCount <= 8 )
+  {
+    m_pcBinIf->encodeBin( 1, *pcSCModel );
+    if ( uiCount == 2 )
+    {
+      pcSCModel++;
+    }
+    if ( uiCount == uiMaxBin )
+    {
+      pcSCModel++;
+    }
+  }
+  
+  if ( bNoExGo )
+  {
+    m_pcBinIf->encodeBin( 0, *pcSCModel );
+  }
+  else
+  {
+    xWriteEpExGolomb( uiSymbol, 3 );
+  }
+  
+  return;
+}
+
+Void TEncSbac::codeAlfFlag       ( UInt uiCode )
+{
+  UInt uiSymbol = ( ( uiCode == 0 ) ? 0 : 1 );
+  m_pcBinIf->encodeBin( uiSymbol, m_cALFFlagSCModel.get( 0, 0, 0 ) );
+}
+
+#if TSB_ALF_HEADER
+Void TEncSbac::codeAlfFlagNum( UInt uiCode, UInt minValue )
+{
+  UInt uiLength = 0;
+  UInt maxValue = (minValue << (this->getMaxAlfCtrlDepth()*2));
+  assert((uiCode>=minValue)&&(uiCode<=maxValue));
+  UInt temp = maxValue - minValue;
+  for(UInt i=0; i<32; i++)
+  {
+    if(temp&0x1)
+    {
+      uiLength = i+1;
+    }
+    temp = (temp >> 1);
+  }
+  UInt uiSymbol = uiCode - minValue;
+  if(uiLength)
+  {
+    while( uiLength-- )
+    {
+      m_pcBinIf->encodeBinEP( (uiSymbol>>uiLength) & 0x1 );
+    }
+  }
+}
+
+Void TEncSbac::codeAlfCtrlFlag( UInt uiSymbol )
+{
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUAlfCtrlFlagSCModel.get( 0, 0, 0) );
+}
+#endif
+
+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 ) );
+  }
+}
+
+#if MTK_SAO
+Void TEncSbac::codeAoFlag       ( UInt uiCode )
+{
+  UInt uiSymbol = ( ( uiCode == 0 ) ? 0 : 1 );
+  m_pcBinIf->encodeBin( uiSymbol, m_cAOFlagSCModel.get( 0, 0, 0 ) );
+}
+Void TEncSbac::codeAoUvlc       ( UInt uiCode )
+{
+  Int i;
+
+  if ( uiCode == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cAOUvlcSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cAOUvlcSCModel.get( 0, 0, 0 ) );
+    for ( i=0; i<uiCode-1; i++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cAOUvlcSCModel.get( 0, 0, 1 ) );
+    }
+    m_pcBinIf->encodeBin( 0, m_cAOUvlcSCModel.get( 0, 0, 1 ) );
+  }
+}
+Void TEncSbac::codeAoSvlc       ( Int iCode )
+{
+  Int i;
+
+  if ( iCode == 0 )
+  {
+    m_pcBinIf->encodeBin( 0, m_cAOSvlcSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cAOSvlcSCModel.get( 0, 0, 0 ) );
+
+    // write sign
+    if ( iCode > 0 )
+    {
+      m_pcBinIf->encodeBin( 0, m_cAOSvlcSCModel.get( 0, 0, 1 ) );
+    }
+    else
+    {
+      m_pcBinIf->encodeBin( 1, m_cAOSvlcSCModel.get( 0, 0, 1 ) );
+      iCode = -iCode;
+    }
+
+    // write magnitude
+    for ( i=0; i<iCode-1; i++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cAOSvlcSCModel.get( 0, 0, 2 ) );
+    }
+    m_pcBinIf->encodeBin( 0, m_cAOSvlcSCModel.get( 0, 0, 2 ) );
+  }
+}
+#endif
+
+/*!
+ ****************************************************************************
+ * \brief
+ *   estimate bit cost for CBP, significant map and significant coefficients
+ ****************************************************************************
+ */
+Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType )
+{
+  estCBFBit( pcEstBitsSbac, 0, eTType );
+  
+  // encode significance map
+  estSignificantMapBit( pcEstBitsSbac, uiCTXIdx, eTType );
+  
+  // encode significant coefficients
+  estSignificantCoefficientsBit( pcEstBitsSbac, uiCTXIdx, 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 < 45; uiCtxInc++ )
+  {
+    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 0 ] = biari_no_bits( 0, pCtx[ uiCtxInc ] );
+    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 1 ] = biari_no_bits( 1, pCtx[ uiCtxInc ] );
+  }
+
+  for( UInt uiCtxInc = 0; uiCtxInc < 4; uiCtxInc++ )
+  {
+    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 0 ] = biari_no_bits( 0, m_cCUQtRootCbfSCModel.get( 0, 0, uiCtxInc ) );
+    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 1 ] = biari_no_bits( 1, m_cCUQtRootCbfSCModel.get( 0, 0, uiCtxInc ) );
+  }
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate SAMBAC bit cost for significant coefficient map
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType )
+{
+  for ( UInt uiCtx = 0; uiCtx < 16; uiCtx++ )
+  {
+    for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+    {
+#if SIMPLE_CONTEXT_SIG
+      if( uiCtx < 4 || eTType )
+      {
+        pcEstBitsSbac->significantBits[ uiCtx ][ uiBin ] = biari_no_bits ( uiBin, m_cCUSigSCModel.get( uiCTXIdx-2, eTType, uiCtx ) );
+      }
+      else
+      {
+        pcEstBitsSbac->significantBits[ uiCtx ][ uiBin ] = biari_no_bits ( uiBin, m_cCUSigSCModel.get( uiCTXIdx-2 ? uiCTXIdx-2 : 1, eTType, uiCtx ) );
+      }
+#else
+      pcEstBitsSbac->significantBits[ uiCtx ][ uiBin ] = biari_no_bits ( uiBin, m_cCUSigSCModel.get(  uiCTXIdx, eTType, uiCtx ) );
+#endif
+
+#if !PCP_SIGMAP_SIMPLE_LAST    
+      pcEstBitsSbac->lastBits[ uiCtx ][ uiBin ]        = biari_no_bits ( uiBin, m_cCULastSCModel.get( uiCTXIdx, eTType, uiCtx ) );
+#endif
+    }
+  }
+
+#if PCP_SIGMAP_SIMPLE_LAST
+  Int iBitsX = 0, iBitsY = 0;
+  const UInt uiCtxOffset = g_uiCtxXYOffset[uiCTXIdx];
+  const UInt uiWidthM1   = (1 << (7-uiCTXIdx)) - 1;
+  for ( UInt uiCtx = 0; uiCtx < uiWidthM1; uiCtx++ )
+  {
+    pcEstBitsSbac->lastXBits[uiCtx] = iBitsX + biari_no_bits (1, m_cCuCtxLastX.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiCtx] ));
+    pcEstBitsSbac->lastYBits[uiCtx] = iBitsY + biari_no_bits (1, m_cCuCtxLastY.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiCtx] ));
+    iBitsX += biari_no_bits (0, m_cCuCtxLastX.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiCtx] ));
+    iBitsY += biari_no_bits (0, m_cCuCtxLastY.get( 0, eTType, uiCtxOffset + g_uiCtxXY[uiCtx] ));
+  }
+  pcEstBitsSbac->lastXBits[uiWidthM1] = iBitsX;
+  pcEstBitsSbac->lastYBits[uiWidthM1] = iBitsY;
+#endif
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost of significant coefficient
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType )
+{
+  for( UInt uiSet = 0; uiSet < 6; uiSet++ )
+  {
+    for( UInt uiCtx = 0; uiCtx < 5; uiCtx++ )
+    {
+      pcEstBitsSbac->greaterOneBits[ uiSet ][ 0 ][ uiCtx ][ 0 ] = biari_no_bits( 0, m_cCUOneSCModel.get( 0, eTType, ( uiSet << 2 ) + uiSet + uiCtx ) );
+      pcEstBitsSbac->greaterOneBits[ uiSet ][ 0 ][ uiCtx ][ 1 ] = biari_no_bits( 1, m_cCUOneSCModel.get( 0, eTType, ( uiSet << 2 ) + uiSet + uiCtx ) );
+      pcEstBitsSbac->greaterOneBits[ uiSet ][ 1 ][ uiCtx ][ 0 ] = biari_no_bits( 0, m_cCUAbsSCModel.get( 0, eTType, ( uiSet << 2 ) + uiSet + uiCtx ) );
+      pcEstBitsSbac->greaterOneBits[ uiSet ][ 1 ][ uiCtx ][ 1 ] = biari_no_bits( 1, m_cCUAbsSCModel.get( 0, eTType, ( uiSet << 2 ) + uiSet + uiCtx ) );
+    }
+  }
+}
+
+Int TEncSbac::biari_no_bits( Short symbol, ContextModel& rcSCModel )
+{
+  UInt  uiEstBits;
+  Short ui16State;
+  
+  symbol    = (Short)( symbol != 0 );
+  ui16State = symbol == rcSCModel.getMps() ? 64 + rcSCModel.getState() : 63 - rcSCModel.getState();
+  uiEstBits = entropyBits[ 127 - ui16State ];
+  return uiEstBits;
+}
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncSbac.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncSbac.h	(revision 19)
@@ -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-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     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"
+
+class TEncTop;
+
+// ====================================================================================================================
+// 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           ();
+  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  store                  ( TEncSbac* pDest );
+  Void  resetBits              ()                { m_pcBinIf->resetBits(); m_pcBitIf->resetBits(); }
+  UInt  getNumberOfWrittenBits ()                { return m_pcBinIf->getNumWrittenBits(); }
+  //--SBAC RD
+  
+  Void  codeNALUnitHeader       ( NalUnitType eNalUnitType, NalRefIdc eNalRefIdc, UInt TemporalId = 0, Bool bOutputFlag = true );
+
+  Void  codeSPS                 ( TComSPS* pcSPS     );
+  Void  codePPS                 ( TComPPS* pcPPS     );
+  void codeSEI(const SEI&);
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast      );
+  Void  codeSliceFinish         ();
+  
+  Void  codeAlfFlag       ( UInt uiCode );
+  Void  codeAlfUvlc       ( UInt uiCode );
+  Void  codeAlfSvlc       ( Int  uiCode );
+  Void  codeAlfCtrlDepth  ();
+#if TSB_ALF_HEADER
+  Void codeAlfFlagNum        ( UInt uiCode, UInt minValue );
+  Void codeAlfCtrlFlag       ( UInt uiSymbol );
+#endif
+#if MTK_SAO
+  Void  codeAoFlag       ( UInt uiCode );
+  Void  codeAoUvlc       ( UInt uiCode );
+  Void  codeAoSvlc       ( Int  uiCode );
+#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 );
+#if E253
+  Void  xWriteGoRiceExGolomb ( UInt uiSymbol, UInt &ruiGoRiceParam );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void  xWriteExGolombLevel  ( UInt uiSymbol, ContextModel& rcSCModel  );
+#endif
+#else
+  Void  xWriteExGolombLevel  ( UInt uiSymbol, ContextModel& rcSCModel  );
+#endif
+  Void  xWriteTerminatingBit ( UInt uiBit );
+  
+  Void  xCheckCoeff( TCoeff* pcCoef, UInt uiSize, UInt uiDepth, UInt& uiNumofCoeff, UInt& uiPart );
+
+#if MVD_CTX
+  Void  xWriteMvd            ( Int iMvd, UInt uiAbsSumL, UInt uiAbsSumA, UInt uiCtx );
+#else
+  Void  xWriteMvd            ( Int iMvd, UInt uiAbsSum, UInt uiCtx );
+#endif
+  Void  xWriteExGolombMvd    ( UInt uiSymbol, ContextModel* pcSCModel, UInt uiMaxBin );
+  Void  xCopyFrom            ( TEncSbac* pSrc );
+  
+#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
+  Void  xCodeWedgePredTexDeltaInfo  ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void  xCodeContourPredTexDeltaInfo( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#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;
+  //--Adaptive loop filter
+
+public:
+  Void codeAlfCtrlFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if HHI_INTER_VIEW_MOTION_PRED || HHI_MPI
+  Void codeMergeIndexMV  ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  Void codeResPredFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codeMVPIdx        ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+  Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void 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 codeViewIdx 			 (Int iViewIdx);
+
+  Void codeDeltaQP             ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeCbf                 ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth ) {}
+  Void codeBlockCbf            ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiQPartNum, Bool bRD = false ) {}
+  
+#if CAVLC_RQT_CBP
+  Void codeCbfTrdiv      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) {}
+  UInt xGetFlagPattern   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) { return 0; }
+#endif
+#if PCP_SIGMAP_SIMPLE_LAST
+  __inline Void codeLastSignificantXY ( UInt uiPosX, UInt uiPosY, const UInt uiWidth, const TextType eTType, const UInt uiCTXIdx, const UInt uiScanIdx );
+#endif
+  Void codeCoeffNxN            ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType, Bool bRD = false );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // for RD-optimizatioon
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void estBit                        ( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  Void estCBFBit                     ( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  Void estSignificantMapBit          ( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  Void estSignificantCoefficientsBit ( estBitsSbacStruct* pcEstBitsSbac, UInt uiCTXIdx, TextType eTType );
+  
+  __inline Int  biari_no_bits        ( Short symbol, ContextModel& rcSCModel );
+  
+  TEncBinIf* getEncBinIf()  { return m_pcBinIf; }
+private:
+  UInt                 m_uiLastQp;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+  ContextModel3DBuffer m_cCUMVMergeIdxExtSCModel;
+  ContextModel3DBuffer m_cResPredFlagSCModel;
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUAlfCtrlFlagSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+#if ADD_PLANAR_MODE
+  ContextModel3DBuffer m_cPlanarFlagSCModel;
+#endif
+  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_cCUSigSCModel;
+#if PCP_SIGMAP_SIMPLE_LAST
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+#else
+  ContextModel3DBuffer m_cCULastSCModel;
+#endif
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+  
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+  
+  ContextModel3DBuffer m_cALFFlagSCModel;
+  ContextModel3DBuffer m_cALFUvlcSCModel;
+  ContextModel3DBuffer m_cALFSvlcSCModel;
+#if MTK_SAO
+  ContextModel3DBuffer m_cAOFlagSCModel;
+  ContextModel3DBuffer m_cAOUvlcSCModel;
+  ContextModel3DBuffer m_cAOSvlcSCModel;
+#endif
+  ContextModel3DBuffer m_cViewIdxSCModel;
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  ContextModel3DBuffer m_cIntraDMMSCModel;
+  ContextModel3DBuffer m_cIntraWedgeSCModel;
+#endif
+};
+
+#endif // !defined(AFX_TENCSBAC_H__DDA7CDC4_EDE3_4015_9D32_2156249C82AA__INCLUDED_)
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 19)
@@ -0,0 +1,6000 @@
+/* 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     TEncSearch.cpp
+ \brief    encoder search class
+ */
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComMotionInfo.h"
+#include "TEncSearch.h"
+
+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;
+  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;
+#ifdef WEIGHT_PRED
+  setWpScalingDistParam( NULL, -1, -1, REF_PIC_LIST_X );
+#endif
+}
+
+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];
+      m_pcQTTempTComYuv[ui].destroy();
+    }
+  }
+  delete[] m_ppcQTTempCoeffY;
+  delete[] m_ppcQTTempCoeffCb;
+  delete[] m_ppcQTTempCoeffCr;
+  delete[] m_pcQTTempCoeffY;
+  delete[] m_pcQTTempCoeffCb;
+  delete[] m_pcQTTempCoeffCr;
+  delete[] m_puhQTTempTrIdx;
+  delete[] m_puhQTTempCbf[0];
+  delete[] m_puhQTTempCbf[1];
+  delete[] m_puhQTTempCbf[2];
+  delete[] m_pcQTTempTComYuv;
+}
+
+void TEncSearch::init(TEncCfg*      pcEncCfg,
+                      TComTrQuant*  pcTrQuant,
+                      Int           iSearchRange,
+                      Int           bipredSearchRange,
+                      Int           iFastSearch,
+                      Int           iMaxDeltaQP,
+                      TEncEntropy*  pcEntropyCoder,
+                      TComRdCost*   pcRdCost,
+                      TEncSbac*** pppcRDSbacCoder,
+                      TEncSbac*   pcRDGoOnSbacCoder
+                      )
+{
+  m_pcEncCfg             = pcEncCfg;
+  m_pcTrQuant            = pcTrQuant;
+  m_iSearchRange         = iSearchRange;
+  m_bipredSearchRange    = bipredSearchRange;
+  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
+  m_pcRdCost->initRateDistortionModel( m_iSearchRange << 2 );
+
+  for( Int iNum = 0; iNum < AMVP_MAX_NUM_CANDS+1; iNum++)
+  {
+    for( Int iIdx = 0; iIdx < AMVP_MAX_NUM_CANDS; iIdx++)
+    {
+      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];
+
+  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];
+    m_pcQTTempTComYuv[ui].create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+  }
+}
+
+#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;
+    }
+  }
+#ifdef WEIGHT_PRED
+  setDistParamComp(0);  // Y component
+#endif
+
+  // distortion
+  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
+}
+
+#ifdef ROUNDING_CONTROL_BIPRED
+UInt TEncSearch::xPatternRefinement_Bi    ( TComPattern* pcPatternKey, Pel* piRef, Int iRefStride, Int iIntStep, Int iFrac, TComMv& rcMvFrac, Pel* pcRef2, Bool bRound, Bool bInterview )
+{
+  UInt  uiDist;
+  UInt  uiDistBest  = MAX_UINT;
+  UInt  uiDirecBest = 0;
+
+  Pel*  piRefPos;
+
+  m_pcRdCost->setDistParam_Bi( pcPatternKey, piRef, iRefStride, iIntStep, m_cDistParam, m_pcEncCfg->getUseHADME() );
+
+  TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
+
+  for (UInt i = 0; i < 9; i++)
+  {
+    TComMv cMvTest = pcMvRefine[i];
+    cMvTest += rcMvFrac;
+    piRefPos = piRef + (pcMvRefine[i].getHor() + iRefStride * pcMvRefine[i].getVer()) * iFrac;
+    m_cDistParam.pCur = piRefPos;
+    uiDist = m_cDistParam.DistFuncRnd( &m_cDistParam, pcRef2, bRound );
+    uiDist += m_pcRdCost->getCost( cMvTest.getHor(), cMvTest.getVer() );
+
+    if ( uiDist < uiDistBest )
+    {
+      uiDistBest  = uiDist;
+      uiDirecBest = i;
+    }
+  }
+
+  rcMvFrac = pcMvRefine[uiDirecBest];
+
+  return uiDistBest;
+}
+#endif
+
+//<--
+
+UInt TEncSearch::xPatternRefinement( TComPattern* pcPatternKey, Pel* piRef, Int iRefStride, Int iIntStep, Int iFrac, TComMv& rcMvFrac )
+{
+  UInt  uiDist;
+  UInt  uiDistBest  = MAX_UINT;
+  UInt  uiDirecBest = 0;
+
+  Pel*  piRefPos;
+  m_pcRdCost->setDistParam( pcPatternKey, piRef, iRefStride, iIntStep, m_cDistParam, m_pcEncCfg->getUseHADME() );
+
+  TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
+
+  for (UInt i = 0; i < 9; i++)
+  {
+    TComMv cMvTest = pcMvRefine[i];
+    cMvTest += rcMvFrac;
+    piRefPos = piRef + (pcMvRefine[i].getHor() + iRefStride * pcMvRefine[i].getVer()) * iFrac;
+    m_cDistParam.pCur = piRefPos;
+#ifdef WEIGHT_PRED
+    setDistParamComp(0);  // Y component
+#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 CAVLC_RQT_CBP
+  if(pcCU->getSlice()->getSymbolMode() == 0)
+  {
+    if(bLuma && bChroma)
+    {
+      m_pcEntropyCoder->m_pcEntropyCoderIf->codeCbfTrdiv( pcCU, uiAbsPartIdx, uiFullDepth);
+    }
+    else
+    {
+      UInt uiFlagPattern = m_pcEntropyCoder->m_pcEntropyCoderIf->xGetFlagPattern(pcCU, uiAbsPartIdx, uiFullDepth);
+      if(bLuma)
+      {
+        if(uiTrDepth==0 || pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA, uiTrDepth-1))
+          m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrDepth);
+        if(uiFlagPattern & 0x01)
+          m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, uiFullDepth );
+      }
+      else if(bChroma)
+      {
+        if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+        {
+          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(uiFlagPattern & 0x01)
+          m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, uiFullDepth );
+      }
+    }
+  }
+#endif
+
+#if CAVLC_RQT_CBP
+  if(pcCU->getSlice()->getSymbolMode())
+  {
+#endif
+  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 CAVLC_RQT_CBP
+  }
+#endif
+
+  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;
+  }
+
+  if(pcCU->getSlice()->getSymbolMode())
+  {
+    //===== Cbfs =====
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+    }
+    if( bChroma )
+    {
+      Bool bCodeChroma = true;
+      if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        assert( uiTrDepth > 0 );
+        UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+        bCodeChroma  = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+      }
+      if( bCodeChroma )
+      {
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+      }
+    }
+  }
+}
+
+
+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 );
+#if !CAVLC_RQT_CBP
+    if ( pcCU->getSlice()->getSymbolMode() || pcCU->getCbf( uiAbsPartIdx, eTextType, uiTrDepth ))
+    {
+      if(pcCU->getSlice()->getSymbolMode() == 0)
+      {
+        if( eTextType == TEXT_LUMA || uiLog2TrafoSize-1 > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeBlockCbf(pcCU, uiAbsPartIdx, eTextType, uiTrDepth + 1, uiQPartNum, true);
+      }
+#endif
+      for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+      {
+        xEncCoeffQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiQPartNum, eTextType, bRealCoeff );
+      }
+#if !CAVLC_RQT_CBP
+    }
+#endif
+    return;
+  }
+
+  if( eTextType != TEXT_LUMA && uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    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, false );
+}
+
+
+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 );
+    }
+    // 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
+                                )
+{
+  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;
+  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 HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( uiLumaPredMode > MAX_MODE_ID_INTRA_DIR )
+  {
+    predIntraLumaDMM( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail, true );
+  }
+  else
+#endif
+  {
+    //===== get prediction signal =====
+    predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, 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, 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 );
+  m_pcTrQuant->transformNxN     ( pcCU, piResi, uiStride, pcCoeff, uiWidth, uiHeight, uiAbsSum, TEXT_LUMA, uiAbsPartIdx );
+
+  //--- set coded block flag ---
+  pcCU->setCbfSubParts          ( ( uiAbsSum ? 1 : 0 ) << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+  //--- inverse transform ---
+  if( uiAbsSum )
+  {
+#if INTRA_DST_TYPE_7
+    m_pcTrQuant->invtransformNxN( TEXT_LUMA,pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight );
+#else
+    m_pcTrQuant->invtransformNxN( piResi, uiStride, pcCoeff, uiWidth, uiHeight );
+#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() )
+  {
+    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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    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;
+  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 !LM_CHROMA
+  if( uiChromaPredMode == 4 )
+  {
+    uiChromaPredMode          = pcCU->getLumaIntraDir( 0 );
+  }
+#endif
+
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
+  pcCU->getPattern()->initAdiPatternChroma( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+  Int*  pPatChroma  = ( uiChromaId > 0 ? pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_piYuvExt ) : pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_piYuvExt ) );
+
+  //===== get prediction signal =====
+#if LM_CHROMA
+  if(pcCU->getSlice()->getSPS()->getUseLMChroma() && uiChromaPredMode == 3)
+  {
+    predLMIntraChroma( pcCU->getPattern(), pPatChroma, piPred, uiStride, uiWidth, uiHeight, uiChromaId );
+  }
+  else
+  {
+    if( uiChromaPredMode == 4 )
+    {
+      uiChromaPredMode          = pcCU->getLumaIntraDir( 0 );
+    }
+  predIntraChromaAng( pcCU->getPattern(), pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+  }
+#else // LM_CHROMA
+  predIntraChromaAng( pcCU->getPattern(), pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+#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;
+    }
+  }
+
+  //===== transform and quantization =====
+  {
+    //--- init rate estimation arrays for RDOQ ---
+    if( m_pcEncCfg->getUseRDOQ() )
+    {
+      m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, eText );
+    }
+    //--- transform and quantization ---
+    UInt uiAbsSum = 0;
+    m_pcTrQuant->setQPforQuant     ( pcCU->getQP( 0 ), !pcCU->getSlice()->getDepth(), pcCU->getSlice()->getSliceType(), TEXT_CHROMA );
+    m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 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 )
+    {
+#if INTRA_DST_TYPE_7
+    m_pcTrQuant->invtransformNxN( TEXT_CHROMA, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight );
+#else
+    m_pcTrQuant->invtransformNxN( piResi, uiStride, pcCoeff, uiWidth, uiHeight );
+#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 =====
+  ruiDist += m_pcRdCost->getDistPart( piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+}
+
+
+
+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 )
+{
+  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 ) > MAX_MODE_ID_INTRA_DIR )
+  {
+    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;
+    xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistY );
+    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
+    {
+      dSingleCost = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDistY + uiSingleDistC );
+    }
+#else
+    dSingleCost = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDistY + uiSingleDistC );
+#endif
+  }
+
+  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
+    {
+      dSplitCost       = m_pcRdCost->calcRdCost( uiSplitBits, uiSplitDistY + uiSplitDistC );
+    }
+#else
+    dSplitCost       = m_pcRdCost->calcRdCost( uiSplitBits, uiSplitDistY + uiSplitDistC );
+#endif
+
+    //===== 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 ] );
+    }
+  }
+
+  if( bCheckSplit )
+  {
+    //--- 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;
+}
+
+
+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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      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( !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 );
+    }
+
+    //===== 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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      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 );
+
+    //===== 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 );  //GT: change metric here?
+    uiSAD       += m_pcRdCost->calcHAD( piOrgV, uiStride, piPredV, uiStride, uiWidth, uiHeight );  //GT: change metric here?
+    //--- 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;
+  UInt    CandModeList[ FAST_UDI_MAX_RDMODE_NUM ];
+  Double  CandCostList[ FAST_UDI_MAX_RDMODE_NUM ];
+  UInt    uiFastCandNum=g_aucIntraModeNumFast[ uiWidthBit ];
+
+  //===== set QP and clear Cbf =====
+  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) =====
+    UInt uiMaxMode     = g_aucIntraModeNumAng[uiWidthBit];
+#if ADD_PLANAR_MODE
+    uiMaxMode += 1;
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    Bool bTestDmm = false;
+    if ( m_pcEncCfg->isDepthCoder() && m_pcEncCfg->getUseDMM() )
+      bTestDmm = true;
+#endif
+    UInt uiMaxModeFast = g_aucIntraModeNumFast[ uiWidthBit ];
+    Pel* piOrg         = pcOrgYuv ->getLumaAddr( uiPU, uiWidth );
+    Pel* piPred        = pcPredYuv->getLumaAddr( uiPU, uiWidth );
+    UInt uiStride      = pcPredYuv->getStride();
+
+    if ( uiFastCandNum != uiMaxMode ) uiMaxModeFast = 0;
+    for( Int i=0; i < uiFastCandNum; i++ )
+    {
+      CandCostList[ i ] = MAX_DOUBLE;
+    }
+    CandNum = 0;
+
+#if ADD_PLANAR_MODE
+    UInt uiHdModeList[NUM_INTRA_MODE];
+    uiHdModeList[0] = PLANAR_IDX;
+    for( Int i=1; i < uiMaxMode; i++) uiHdModeList[i] = i-1;
+
+    for( Int iMode = Int(uiMaxModeFast); iMode < Int(uiMaxMode); iMode++ )
+    {
+      UInt uiMode = uiHdModeList[iMode];
+#if (!REFERENCE_SAMPLE_PADDING)
+      if ( !predIntraLumaDirAvailable( uiMode, uiWidthBit, bAboveAvail, bLeftAvail ) )
+        continue;
+#endif
+      predIntraLumaAng( pcCU->getPattern(), uiMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+#else
+    for( UInt uiMode = uiMaxModeFast; uiMode < uiMaxMode; uiMode++ )
+    {
+#if (!REFERENCE_SAMPLE_PADDING)
+      if ( !predIntraLumaDirAvailable( uiMode, uiWidthBit, bAboveAvail, bLeftAvail ) )
+        continue;
+#endif
+
+      predIntraLumaAng( pcCU->getPattern(), uiMode, piPred, uiStride, uiWidth, uiHeight, pcCU, bAboveAvail, bLeftAvail );
+#endif
+      // use hadamard transform here
+      Dist uiSad;
+#if HHI_VSO
+      if ( m_pcRdCost->getUseVSO() )
+      {
+        Bool bSad = !m_pcRdCost->getUseRenModel();
+        uiSad = m_pcRdCost->getDistVS(pcCU, uiPartOffset, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, bSad, 0 );
+      }
+      else
+      {
+        uiSad = (Dist) m_pcRdCost->calcHAD( piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+      }
+#else
+        uiSad = (Dist) m_pcRdCost->calcHAD( piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+#endif
+
+      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, uiFastCandNum, CandModeList, CandCostList );
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      if ( bTestDmm ) bTestDmm = uiSad ? true : false;
+#endif
+    }
+    UInt uiRdModeList[FAST_UDI_MAX_RDMODE_NUM];
+    UInt uiNewMaxMode;
+    UInt uiMinMode = 0;
+
+    if(uiFastCandNum!=uiMaxMode)
+    {
+      uiNewMaxMode = Min( uiFastCandNum, CandNum );
+      for( Int i = 0; i < uiNewMaxMode; i++)
+      {
+        uiRdModeList[i] = CandModeList[i];
+      }
+#if FAST_UDI_USE_MPM
+#if MTK_DCM_MPM
+      Int uiPreds[2] = {-1, -1};
+      Int numCand = pcCU->getIntraDirLumaPredictor(uiPartOffset, uiPreds);
+
+      for( Int j=0; j < numCand; j++)
+      {
+        Bool mostProbableModeIncluded = false;
+        Int mostProbableMode = uiPreds[j];
+#if ADD_PLANAR_MODE
+      if (mostProbableMode == 2)
+      {
+        mostProbableMode = PLANAR_IDX;
+      }
+#endif
+        for( Int i=0; i < uiNewMaxMode; i++)
+        {
+          mostProbableModeIncluded |= (mostProbableMode == uiRdModeList[i]);
+        }
+        if (!mostProbableModeIncluded)
+        {
+          uiRdModeList[uiNewMaxMode++] = mostProbableMode;
+        }
+      }
+#else
+      Int mostProbableMode = pcCU->getMostProbableIntraDirLuma( uiPartOffset );
+#if ADD_PLANAR_MODE
+      if (mostProbableMode == 2)
+      {
+        mostProbableMode = PLANAR_IDX;
+      }
+#endif
+      Bool mostProbableModeIncluded = false;
+      for( Int i=0; i < uiNewMaxMode; i++)
+      {
+        mostProbableModeIncluded |= (mostProbableMode == uiRdModeList[i]);
+      }
+      if (!mostProbableModeIncluded)
+      {
+        uiRdModeList[uiNewMaxMode++] = mostProbableMode;
+      }
+#endif
+#endif
+    }
+    else
+    {
+      uiNewMaxMode = uiMaxMode;
+#if ADD_PLANAR_MODE
+      uiRdModeList[0] = PLANAR_IDX;
+      for( Int i=1; i < uiNewMaxMode; i++) uiRdModeList[i] = i-1;
+#else
+      for( Int i=0; i < uiNewMaxMode; i++) uiRdModeList[i] = i;
+#endif
+    }
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+    if( m_pcEncCfg->isDepthCoder() && uiWidth >= 4 && uiWidth < 64 && m_pcEncCfg->getUseDMM() && bTestDmm && 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, WedgeDist_SAD );
+      pcCU->setWedgeFullTabIdxSubParts  ( uiTabIdx,  uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setWedgeFullDeltaDC1SubParts( iDeltaDC1, uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setWedgeFullDeltaDC2SubParts( iDeltaDC2, uiPartOffset, uiDepth + uiInitTrDepth );
+
+      uiRdModeList[ uiNewMaxMode++ ] = DMM_WEDGE_FULL_IDX;
+      uiRdModeList[ uiNewMaxMode++ ] = 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, WedgeDist_SAD );
+        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[ uiNewMaxMode++ ] = DMM_WEDGE_PREDDIR_IDX;
+        uiRdModeList[ uiNewMaxMode++ ] = DMM_WEDGE_PREDDIR_D_IDX;
+      }
+#endif
+#if HHI_DMM_PRED_TEX
+      TComYuv cTempYuv; cTempYuv.create( uiWidth, uiHeight ); cTempYuv.clear();
+      Pel* piTempY      = cTempYuv.getLumaAddr();
+
+      fillTexturePicTempBlock( pcCU, uiPartOffset, piTempY, uiWidth, uiHeight );
+
+      piTempY = cTempYuv.getLumaAddr();
+
+      UInt uiTexTabIdx  = 0;
+      Int  iTexDeltaDC1 = 0;
+      Int  iTexDeltaDC2 = 0;
+      findWedgeTexMinDist( pcCU, uiPartOffset, piOrg, piPred, uiStride, uiWidth, uiHeight, uiTexTabIdx, iTexDeltaDC1, iTexDeltaDC2, bAboveAvail, bLeftAvail, WedgeDist_SAD, piTempY ); 
+      pcCU->setWedgePredTexTabIdxSubParts  ( uiTexTabIdx,  uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setWedgePredTexDeltaDC1SubParts( iTexDeltaDC1, uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setWedgePredTexDeltaDC2SubParts( iTexDeltaDC2, uiPartOffset, uiDepth + uiInitTrDepth );
+
+      uiRdModeList[ uiNewMaxMode++ ] = DMM_WEDGE_PREDTEX_IDX;
+      uiRdModeList[ uiNewMaxMode++ ] = DMM_WEDGE_PREDTEX_D_IDX;
+
+      if ( uiWidth > 4 )
+      {
+        piTempY = cTempYuv.getLumaAddr();
+
+        iTexDeltaDC1 = 0;
+        iTexDeltaDC2 = 0;
+
+        findContourPredTex( pcCU, uiPartOffset, piOrg, piPred, uiStride, uiWidth, uiHeight, iTexDeltaDC1, iTexDeltaDC2, bAboveAvail, bLeftAvail, piTempY );
+        pcCU->setContourPredTexDeltaDC1SubParts( iTexDeltaDC1, uiPartOffset, uiDepth + uiInitTrDepth );
+        pcCU->setContourPredTexDeltaDC2SubParts( iTexDeltaDC2, uiPartOffset, uiDepth + uiInitTrDepth );
+
+        uiRdModeList[ uiNewMaxMode++ ] = DMM_CONTOUR_PREDTEX_IDX;
+        uiRdModeList[ uiNewMaxMode++ ] = DMM_CONTOUR_PREDTEX_D_IDX;
+      }
+
+      cTempYuv.destroy();
+#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;
+    for( UInt uiMode = uiMinMode; uiMode < uiNewMaxMode; uiMode++ )
+    {
+      // set luma prediction mode
+      UInt uiOrgMode = uiRdModeList[uiMode];
+
+#if (!REFERENCE_SAMPLE_PADDING)
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      if ( !predIntraLumaDirAvailable( uiOrgMode, uiWidthBit, bAboveAvail, bLeftAvail, uiWidth, uiHeight, pcCU, uiPartOffset ) )
+        continue;
+#else
+      if ( !predIntraLumaDirAvailable( uiOrgMode, uiWidthBit, bAboveAvail, bLeftAvail ) )
+        continue;
+#endif
+#else
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      if( m_pcEncCfg->isDepthCoder() && !predIntraLumaDMMAvailable( uiOrgMode, uiWidth, uiHeight ) )
+        continue;
+#endif
+#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 HHI_RQT_INTRA_SPEEDUP
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, true, dPUCost );
+#else
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, dPUCost );
+#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;
+
+        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 HHI_RQT_INTRA_SPEEDUP_MOD
+      else if( dPUCost < dSecondBestPUCost )
+      {
+        uiSecondBestMode  = uiOrgMode;
+        dSecondBestPUCost = dPUCost;
+      }
+#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
+
+#if (!REFERENCE_SAMPLE_PADDING)
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      if ( !predIntraLumaDirAvailable( uiOrgMode, uiWidthBit, bAboveAvail, bLeftAvail, uiWidth, uiHeight, pcCU, uiPartOffset ) )
+        continue;
+#else
+      if ( !predIntraLumaDirAvailable( uiOrgMode, uiWidthBit, bAboveAvail, bLeftAvail ) )
+        continue;
+#endif
+#else
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+      if( m_pcEncCfg->isDepthCoder() && !predIntraLumaDMMAvailable( uiOrgMode, uiWidth, uiHeight ) )
+        continue;
+#endif
+#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;
+
+        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;
+
+    //--- 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 ) );
+
+    //--- 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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        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 );
+    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 -----
+#if ADD_PLANAR_MODE
+  UInt  uiModeList[6];
+  uiModeList[0] = PLANAR_IDX;
+  for( Int i = 0; i < 5; i++ )
+  {
+    uiModeList[i+1] = i;
+  }
+  UInt uiLumaMode = pcCU->getLumaIntraDir(0);
+#else
+  UInt  uiModeList[5];
+  for( Int i = 0; i < 4; i++ )
+  {
+    uiModeList[i] = i;
+  }
+
+  uiModeList[4]   = pcCU->getLumaIntraDir(0);
+#endif
+
+  UInt  uiMinMode = 0;
+#if CHROMA_CODEWORD
+#if ADD_PLANAR_MODE
+  UInt  uiMaxMode = 6;
+
+#if LM_CHROMA
+  UInt  uiIgnore;
+  if(pcCU->getSlice()->getSPS()->getUseLMChroma())
+  {
+    uiIgnore = ( ( (uiLumaMode != PLANAR_IDX) && (uiLumaMode >= 3) ) ? uiMaxMode : uiLumaMode );
+  }
+  else
+  {
+    uiIgnore = ( ( (uiLumaMode != PLANAR_IDX) && (uiLumaMode >= 4) ) ? uiMaxMode : uiLumaMode );
+  }
+#else
+  UInt  uiIgnore = ( ( (uiLumaMode != PLANAR_IDX) && (uiLumaMode >= 4) ) ? uiMaxMode : uiLumaMode );
+#endif
+
+#else
+  UInt  uiMaxMode = 5;
+
+#if LM_CHROMA
+  UInt  uiIgnore;
+  if(pcCU->getSlice()->getSPS()->getUseLMChroma())
+  {
+    uiIgnore = (uiModeList[4] >= 0 && uiModeList[4] < 3) ? uiModeList[4] : 6;
+  }
+  else
+  {
+    uiIgnore = (uiModeList[4] >= 0 && uiModeList[4] < 4) ? uiModeList[4] : 6;
+  }
+#else
+  UInt  uiIgnore = (uiModeList[4] < 4) ? uiModeList[4] : 6;
+#endif
+
+#endif
+#else
+#if ADD_PLANAR_MODE
+  UInt  uiMaxMode = ( ( (uiLumaMode != PLANAR_IDX) && (uiLumaMode >= 4) ) ? 6 : 5 );
+#else
+  UInt  uiMaxMode = ( uiModeList[4] >= 4 ? 5 : 4 );
+#endif
+#endif
+
+  //----- check chroma modes -----
+  for( UInt uiMode = uiMinMode; uiMode < uiMaxMode; uiMode++ )
+  {
+#if CHROMA_CODEWORD
+#if ADD_PLANAR_MODE
+    if ( uiModeList[uiMode] == uiIgnore )
+#else
+    if (uiMode == uiIgnore)
+#endif
+    {
+      continue;
+    }
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+#if ADD_PLANAR_MODE
+    if ( uiModeList[uiMode] == 4 && pcCU->getLumaIntraDir(0) > MAX_MODE_ID_INTRA_DIR )
+    {
+      continue;
+    }
+#else
+    if ( uiMode == 4 && pcCU->getLumaIntraDir(0) > MAX_MODE_ID_INTRA_DIR )
+    {
+      continue;
+    }
+#endif
+#endif
+    //----- restore context models -----
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+    }
+
+    //----- chroma coding -----
+    Dist    uiDist = 0;
+#if ADD_PLANAR_MODE
+    pcCU->setChromIntraDirSubParts  ( uiModeList[uiMode], 0, uiDepth );
+#else
+    pcCU->setChromIntraDirSubParts  ( uiMode, 0, uiDepth );
+#endif
+    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;
+#if ADD_PLANAR_MODE
+      uiBestMode  = uiModeList[uiMode];
+#else
+      uiBestMode  = uiMode;
+#endif
+      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] );
+  }
+}
+
+#if (!REFERENCE_SAMPLE_PADDING)
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+Bool TEncSearch::predIntraLumaDirAvailable( UInt uiMode, UInt uiWidthBit, Bool bAboveAvail, Bool bLeftAvail, UInt uiWidth, UInt uiHeight, TComDataCU* pcCU, UInt uiAbsPartIdx   )
+#else
+Bool TEncSearch::predIntraLumaDirAvailable( UInt uiMode, UInt uiWidthBit, Bool bAboveAvail, Bool bLeftAvail )
+#endif
+{
+  Bool bDirAvailable;
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( uiMode > MAX_MODE_ID_INTRA_DIR )
+  {
+    return predIntraLumaDMMAvailable( uiMode, bAboveAvail, bLeftAvail, uiWidth, uiHeight );
+  }
+  else
+#endif
+  {
+    bDirAvailable = true;
+    UInt uiNewMode = g_aucAngIntraModeOrder[uiMode];
+    if ( uiNewMode > 0 && ( ( (!bAboveAvail) && uiNewMode < 18 ) || ( (!bLeftAvail) && uiNewMode > 17 ) ) )
+    {
+      bDirAvailable = false;
+    }
+  }
+
+  return bDirAvailable;
+}
+#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         bAbove,
+                                      Bool         bLeft,
+                                      WedgeDist    eWedgeDist
+                                      )
+{
+  assert( uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+  xSearchWedgeFullMinDist( pcCU, uiAbsPtIdx, pacWedgeList, piOrig, uiStride, uiWidth, uiHeight, ruiTabIdx );
+
+  TComWedgelet* pcBestWedgelet = &(pacWedgeList->at(ruiTabIdx));
+  xGetWedgeDeltaDCsMinDist( pcBestWedgelet, pcCU, uiAbsPtIdx, piOrig, piPredic, uiStride, uiWidth, uiHeight, riDeltaDC1, riDeltaDC2, bAbove, bLeft );
+}
+
+Void TEncSearch::xSearchWedgeFullMinDist( TComDataCU* pcCU, UInt uiAbsPtIdx, WedgeList* pacWedgeList, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx )
+{
+  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() )
+    {
+      uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, 0 );
+    }
+    else
+    {
+      uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, DF_SAD );
+    }
+#else
+    uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, DF_SAD );
+#endif
+
+    if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+    {
+      uiBestDist   = uiActDist;
+      uiBestTabIdx = uiIdx;
+    }
+  }
+  ruiTabIdx = uiBestTabIdx;
+
+  cPredYuv.destroy();
+  return;
+}
+
+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         bAbove,
+                                         Bool         bLeft,
+                                         WedgeDist    eWedgeDist )
+{
+  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, bAbove, bLeft );
+}
+
+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() )
+    {
+      uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false, 0 );
+    }
+    else
+    {
+      uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, DF_SAD );
+    }
+#else
+    uiActDist = m_pcRdCost->getDistPart( piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, 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
+
+#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         bAbove, 
+                                      Bool         bLeft, 
+                                      WedgeDist    eWedgeDist,
+                                      Pel*         piTextureRef
+                                    )
+  {
+  assert( uiWidth >= DMM_WEDGEMODEL_MIN_SIZE && uiWidth <= DMM_WEDGEMODEL_MAX_SIZE );
+  WedgeList* pacWedgeList = &g_aacWedgeLists[(g_aucConvertToBit[uiWidth])];
+
+  ruiTabIdx = getBestWedgeFromText( pcCU, uiAbsPtIdx, uiWidth, uiHeight, eWedgeDist, piTextureRef );
+
+  TComWedgelet* pcBestWedgelet = &(pacWedgeList->at(ruiTabIdx));
+  xGetWedgeDeltaDCsMinDist( pcBestWedgelet, pcCU, uiAbsPtIdx, piOrig, piPredic, uiStride, uiWidth, uiHeight, riDeltaDC1, riDeltaDC2, bAbove, bLeft );
+}
+
+Void TEncSearch::findContourPredTex( TComDataCU*  pcCU,
+                                     UInt         uiAbsPtIdx,
+                                     Pel*         piOrig,
+                                     Pel*         piPredic,
+                                     UInt         uiStride,
+                                     UInt         uiWidth,
+                                     UInt         uiHeight,
+                                     Int&         riDeltaDC1,
+                                     Int&         riDeltaDC2,
+                                     Bool         bAbove,
+                                     Bool         bLeft,
+                                     Pel*         piTextureRef )
+{
+  // get contour pattern
+  TComWedgelet* pcContourWedge = new TComWedgelet( uiWidth, uiHeight );
+  getBestContourFromText( pcCU, uiAbsPtIdx, uiWidth, uiHeight, pcContourWedge, piTextureRef );
+
+  xGetWedgeDeltaDCsMinDist( pcContourWedge, pcCU, uiAbsPtIdx, piOrig, piPredic, uiStride, uiWidth, uiHeight, riDeltaDC1, riDeltaDC2, bAbove, bLeft );
+
+  pcContourWedge->destroy();
+  delete pcContourWedge;
+}
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+Void TEncSearch::xGetWedgeDeltaDCsMinDist( TComWedgelet* pcWedgelet,
+                                           TComDataCU*   pcCU,
+                                           UInt          uiAbsPtIdx,
+                                           Pel*          piOrig,
+                                           Pel*          piPredic,
+                                           UInt          uiStride,
+                                           UInt          uiWidth,
+                                           UInt          uiHeight,
+                                           Int&          riDeltaDC1,
+                                           Int&          riDeltaDC2,
+                                           Bool          bAbove,
+                                           Bool          bLeft )
+{
+  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, bAbove, bLeft );
+
+  riDeltaDC1 = iDC1 - iPredDC1;
+  riDeltaDC2 = iDC2 - iPredDC2;
+
+#if HHI_VSO
+  if( m_pcRdCost->getUseVSO() )
+  {
+    Int iFullDeltaDC1 = riDeltaDC1;
+    Int iFullDeltaDC2 = riDeltaDC2;
+
+    xDeltaDCQuantScaleDown( pcCU, iFullDeltaDC1 );
+    xDeltaDCQuantScaleDown( pcCU, iFullDeltaDC2 );
+
+    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);
+
+    for( UInt uiQStepDC1 = 1; uiQStepDC1 <= uiDeltaDC1Max; uiQStepDC1++  )
+    {
+      Int iLevelDeltaDC1 = (Int)(uiQStepDC1) * (Int)(( iFullDeltaDC1 < 0 ) ? -1 : 1);
+      xDeltaDCQuantScaleUp( pcCU, iLevelDeltaDC1 );
+
+      Int iTestDC1 = Clip( iPredDC1 + iLevelDeltaDC1 );
+      for( UInt uiQStepDC2 = 1; uiQStepDC2 <= uiDeltaDC2Max; uiQStepDC2++  )
+      {
+        Int iLevelDeltaDC2 = (Int)(uiQStepDC2) * (Int)(( iFullDeltaDC2 < 0 ) ? -1 : 1);
+        xDeltaDCQuantScaleUp( pcCU, iLevelDeltaDC2 );
+
+        Int iTestDC2 = Clip( iPredDC2 + iLevelDeltaDC2 );
+
+        assignWedgeDCs2Pred( pcWedgelet, piPredic, uiStride, iTestDC1, iTestDC2 );
+
+        Dist uiActDist = m_pcRdCost->getDistVS( pcCU, 0, piPredic, uiStride,  piOrig, uiStride, uiWidth, uiHeight, false, 0 );
+        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);
+    xDeltaDCQuantScaleUp( pcCU, iFullDeltaDC1 );
+    xDeltaDCQuantScaleUp( pcCU, iFullDeltaDC2 );
+    riDeltaDC1 = iFullDeltaDC1;
+    riDeltaDC2 = iFullDeltaDC2;
+  }
+#endif
+
+  xDeltaDCQuantScaleDown( pcCU, riDeltaDC1 );
+  xDeltaDCQuantScaleDown( pcCU, riDeltaDC2 );
+}
+
+Bool TEncSearch::predIntraLumaDMMAvailable( UInt uiMode, UInt uiWidth, UInt uiHeight )
+{
+  if( uiMode <= MAX_MODE_ID_INTRA_DIR ) 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;
+    }
+  }
+
+#endif
+
+  return bDMMAvailable;
+}
+
+Void TEncSearch::xDeltaDCQuantScaleDown( TComDataCU*  pcCU, Int& riDeltaDC )
+{
+  Int  iSign  = riDeltaDC < 0 ? -1 : 1;
+  UInt uiAbs  = abs( riDeltaDC );
+
+  Int riB = 0;
+  Int iQp = pcCU->getQP(0);
+  Int iMax = ( 1<<( g_uiBitDepth + g_uiBitIncrement - 1) );
+  Double dStepSize = Clip3( 1, iMax, pow( 2.0, iQp/10.0 + g_dDeltaDCsQuantOffset ) );
+
+  riB = roftoi( uiAbs / dStepSize );
+
+  riDeltaDC = riB * iSign;
+  return;
+}
+#endif
+
+
+Void TEncSearch::xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, UInt& ruiErr, Bool bHadamard )
+{
+  TComYuv cYuvPred;
+  cYuvPred.create( pcYuvOrg->getWidth(), pcYuvOrg->getHeight() );
+
+#ifdef WEIGHT_PRED
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0;
+  Int iRefIdx[2];
+  pcCU->getPartIndexAndSize( iPartIdx, uiAbsPartIdx, iWidth, iHeight );
+
+  iRefIdx[0] = pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiAbsPartIdx );
+  iRefIdx[1] = pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiAbsPartIdx );
+  if ( iRefIdx[0]>=0 && iRefIdx[1]<1 )
+    setWpScalingDistParam( pcCU, iRefIdx[0], iRefIdx[1], REF_PIC_LIST_0);
+  else
+    setWpScalingDistParam( pcCU, iRefIdx[0], iRefIdx[1], REF_PIC_LIST_1);
+
+  motionCompensation( pcCU, &cYuvPred, REF_PIC_LIST_X, iPartIdx );
+#else
+  motionCompensation( pcCU, &cYuvPred, REF_PIC_LIST_X, iPartIdx );
+
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0;
+  pcCU->getPartIndexAndSize( iPartIdx, uiAbsPartIdx, iWidth, iHeight );
+#endif
+
+  DistParam cDistParam;
+#ifdef WEIGHT_PRED
+  cDistParam.applyWeight = false;
+#endif
+  m_pcRdCost->setDistParam( cDistParam,
+                            pcYuvOrg->getLumaAddr( uiAbsPartIdx ), pcYuvOrg->getStride(),
+                            cYuvPred .getLumaAddr( uiAbsPartIdx ), cYuvPred .getStride(),
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME() );
+  ruiErr = cDistParam.DistFunc( &cDistParam );
+
+  cYuvPred.destroy();
+}
+
+/** 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, UInt& ruiBits, UChar* puhNeighCands,Bool& bValid )
+{
+  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  UInt uiNeighbourCandIdx[MRG_MAX_NUM_CANDS]; //MVs with same idx => same cand
+
+  for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ++ui )
+  {
+    uhInterDirNeighbours[ui] = 0;
+    uiNeighbourCandIdx[ui] = 0;
+  }
+
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0;
+
+  pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
+  UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
+  pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, uiDepth, cMvFieldNeighbours,uhInterDirNeighbours, uiNeighbourCandIdx );
+
+  UInt uiNumCand = 0;
+  for( UInt uiMergeCand = 0; uiMergeCand < MRG_MAX_NUM_CANDS; ++uiMergeCand )
+  {
+    if( uiNeighbourCandIdx[uiMergeCand] == ( uiMergeCand + 1 ) )
+    {
+      uiNumCand++;
+    }
+  }
+
+  UInt uiBestSAD = MAX_UINT;
+  UInt uiBestBitCost = MAX_UINT;
+  UInt uiBestBits = MAX_UINT;
+
+  ruiCost = MAX_UINT;
+  ruiBits = MAX_UINT;
+
+  bValid = false;
+
+  for( UInt uiMergeCand = 0; uiMergeCand < MRG_MAX_NUM_CANDS; ++uiMergeCand )
+  {
+    if( uiNeighbourCandIdx[uiMergeCand] == ( uiMergeCand + 1 ) )
+    {
+      bValid = true;
+      UInt uiCostCand = MAX_UINT;
+      UInt uiBitsCand = 0;
+
+      PartSize ePartSize = pcCU->getPartitionSize( 0 );
+
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand].getMv(), cMvFieldNeighbours[0 + 2*uiMergeCand].getRefIdx(), ePartSize, uiAbsPartIdx, iPUIdx, 0 );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand].getMv(), cMvFieldNeighbours[1 + 2*uiMergeCand].getRefIdx(), ePartSize, uiAbsPartIdx, iPUIdx, 0 );
+
+      xGetInterPredictionError( pcCU, pcYuvOrg, iPUIdx, uiCostCand, m_pcEncCfg->getUseHADME() );
+
+      if( uiNumCand == 1 )
+      {
+        uiBitsCand = 1;
+      }
+      else
+      {
+        if( uiMergeCand == 0 || uiNumCand == 2 )
+        {
+          uiBitsCand = 2;
+        }
+        else if( uiMergeCand == 1 || uiNumCand == 3 )
+        {
+          uiBitsCand = 3;
+        }
+        else if( uiMergeCand == 2 || uiNumCand == 4 )
+        {
+          uiBitsCand = 4;
+        }
+        else
+        {
+          uiBitsCand = 5;
+        }
+      }
+
+      if ( uiCostCand < ruiCost )
+      {
+        ruiCost = uiCostCand;
+        ruiBits = uiBitsCand;
+        pacMvField[0] = cMvFieldNeighbours[0 + 2*uiMergeCand];
+        pacMvField[1] = cMvFieldNeighbours[1 + 2*uiMergeCand];
+        uiInterDir = uhInterDirNeighbours[uiMergeCand];
+        uiMergeIndex = uiMergeCand;
+        for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+        {
+          UChar uhNeighCand = uiNeighbourCandIdx[ui];
+          puhNeighCands[ui] = uhNeighCand;
+        }
+
+        uiBestSAD = uiCostCand;
+        uiBestBitCost = m_pcRdCost->getCost( uiBitsCand );
+        uiBestBits = uiBitsCand;
+      }
+    }
+  }
+}
+
+/** search of the best candidate for inter prediction
+ * \param pcCU
+ * \param pcOrgYuv
+ * \param rpcPredYuv
+ * \param rpcResiYuv
+ * \param rpcRecoYuv
+ * \param bUseRes
+ * \returns Void
+ */
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes )
+{
+  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];
+
+#ifdef WEIGHT_PRED
+  Int           iRefIdx[2]={0,0}; //If un-initialized, may cause SEGV in bi-directional prediction iterative stage.
+#else
+  Int           iRefIdx[2];
+#endif
+  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 );
+
+#if ZERO_MVD_EST
+  Int           aiZeroMvdMvpIdx[2] = {-1, -1};
+  Int           aiZeroMvdRefIdx[2] = {0, 0};
+  Int           iZeroMvdDir = -1;
+#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
+
+#if DCM_COMB_LIST
+    UInt          uiCostTempL0[MAX_NUM_REF];
+    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++) uiCostTempL0[iNumRef] = MAX_UINT;
+#endif
+
+    xGetBlkBits( ePartSize, pcCU->getSlice()->isInterP(), iPartIdx, uiLastMode, uiMbBits);
+
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+
+#if PART_MRG
+    Bool bTestNormalMC = true;
+    if (pcCU->getWidth( 0 ) > 8 && iNumPart == 2 && iPartIdx == 0)
+      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++ )
+      {
+#ifdef WEIGHT_PRED
+        if ( eRefPicList == REF_PIC_LIST_0 ) setWpScalingDistParam( pcCU, iRefIdxTemp, -1 , eRefPicList);
+        if ( eRefPicList == REF_PIC_LIST_1 ) setWpScalingDistParam( pcCU, -1, iRefIdxTemp , eRefPicList);
+#endif
+        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, &uiZeroMvdDistTemp);
+#else
+        xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp]);
+#endif
+        aaiMvpIdx[iRefList][iRefIdxTemp] = pcCU->getMVPIdx(eRefPicList, uiPartAddr);
+        aaiMvpNum[iRefList][iRefIdxTemp] = pcCU->getMVPNum(eRefPicList, uiPartAddr);
+
+        uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][aaiMvpNum[iRefList][iRefIdxTemp]];
+#if ZERO_MVD_EST
+#if DCM_COMB_LIST
+        if ((iRefList != 1 || !pcCU->getSlice()->getNoBackPredFlag()) &&
+            (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0 || pcCU->getSlice()->getRefIdxOfLC(eRefPicList, iRefIdxTemp)>=0))
+#endif
+        {
+          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 DCM_COMB_LIST
+        if ( pcCU->getSlice()->getSPS()->getUseLDC() || pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
+#else
+        if ( pcCU->getSlice()->getSPS()->getUseLDC() )
+#endif
+        {
+#if DCM_COMB_LIST
+          if ( iRefList && ( (pcCU->getSlice()->getSPS()->getUseLDC() && (iRefIdxTemp != iRefIdx[0])) || pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag() && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)>=0 ) ) )
+#else
+          if ( iRefList && ( iRefIdxTemp != iRefIdx[0] || pcCU->getSlice()->getNoBackPredFlag() ) )
+#endif
+            {
+#if DCM_COMB_LIST
+              if (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag())
+              {
+                uiCostTemp = uiCostTempL0[pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)];
+              }
+              else
+              {
+                uiCostTemp = MAX_UINT;
+              }
+#else
+              uiCostTemp = MAX_UINT;
+#endif
+#if DCM_COMB_LIST
+              if ( pcCU->getSlice()->getNoBackPredFlag() || pcCU->getSlice()->getSPS()->getUseLDC() )
+#else
+              if ( pcCU->getSlice()->getNoBackPredFlag() )
+#endif
+              {
+                cMvTemp[1][iRefIdxTemp] = cMvTemp[0][iRefIdxTemp];
+              }
+#if DCM_COMB_LIST
+              else
+              {
+                cMvTemp[1][iRefIdxTemp] = cMvTemp[0][pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)];
+              }
+#endif
+            }
+            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 DCM_COMB_LIST
+        if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag())
+        {
+          if(iRefList==REF_PIC_LIST_0)
+          {
+            uiCostTempL0[iRefIdxTemp] = uiCostTemp;
+            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;
+            }
+          }
+        }
+#endif
+
+        if ( ( iRefList == 0 && uiCostTemp < uiCost[iRefList] ) ||
+            ( iRefList == 1 &&  pcCU->getSlice()->getNoBackPredFlag() && iRefIdxTemp == iRefIdx[0] ) ||
+#if DCM_COMB_LIST
+            ( iRefList == 1 && (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0) && (iRefIdxTemp==0 || iRefIdxTemp == iRefIdx[0]) && !pcCU->getSlice()->getNoBackPredFlag() && (iRefIdxTemp == pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(iRefIdxTemp)) ) ||
+#endif
+            ( 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)->setAllMvField( cMv[iRefList], iRefIdx[iRefList], ePartSize, uiPartAddr, iPartIdx, 0 );
+
+            // storing list 1 prediction signal for iterative bi-directional prediction
+            if ( eRefPicList == REF_PIC_LIST_1 )
+            {
+              TComYuv*  pcYuvPred = &m_acYuvPred[iRefList];
+              motionCompensation ( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+            }
+#if DCM_COMB_LIST
+            if ( (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) && eRefPicList == REF_PIC_LIST_0 )
+#else
+            if ( pcCU->getSlice()->getNoBackPredFlag() && eRefPicList == REF_PIC_LIST_0 )
+#endif
+            {
+              TComYuv*  pcYuvPred = &m_acYuvPred[iRefList];
+              motionCompensation ( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+            }
+          }
+      }
+    }
+    //  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] = { uiBits[0] - uiMbBits[0], 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() )
+      {
+        iNumIter = 1;
+      }
+
+      for ( Int iIter = 0; iIter < iNumIter; iIter++ )
+      {
+
+        Int         iRefList    = iIter % 2;
+#if DCM_COMB_LIST
+        if ( m_pcEncCfg->getUseFastEnc() && (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) )
+#else
+        if ( m_pcEncCfg->getUseFastEnc() && pcCU->getSlice()->getNoBackPredFlag() )
+#endif
+        {
+          iRefList = 1;
+        }
+        RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+        Bool bChanged = false;
+
+#if GPB_SIMPLE
+        if ( pcCU->getSlice()->getSPS()->getUseLDC() && iRefList )
+        {
+          iRefStart = iRefIdxBi[1-iRefList];
+          iRefEnd   = iRefIdxBi[1-iRefList];
+        }
+        else
+        {
+          iRefStart = 0;
+          iRefEnd   = pcCU->getSlice()->getNumRefIdx(eRefPicList)-1;
+        }
+#else
+        iRefStart = 0;
+        iRefEnd   = pcCU->getSlice()->getNumRefIdx(eRefPicList)-1;
+#endif
+
+#if DCM_COMB_LIST
+        if ( m_pcEncCfg->getUseFastEnc() && (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) )
+#else
+        if ( m_pcEncCfg->getUseFastEnc() && pcCU->getSlice()->getNoBackPredFlag() )
+#endif
+        {
+          iRefStart = 0;
+          iRefEnd   = pcCU->getSlice()->getNumRefIdx(eRefPicList)-1;
+        }
+
+        for ( Int iRefIdxTemp = iRefStart; iRefIdxTemp <= iRefEnd; iRefIdxTemp++ )
+        {
+#ifdef WEIGHT_PRED
+          if ( eRefPicList == REF_PIC_LIST_0 ) setWpScalingDistParam( pcCU, iRefIdxTemp, -1 , eRefPicList);
+          if ( eRefPicList == REF_PIC_LIST_1 ) setWpScalingDistParam( pcCU, -1, iRefIdxTemp , eRefPicList);
+#endif
+          uiBitsTemp = uiMbBits[2] + uiMotBits[1-iRefList];
+          if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 )
+          {
+            uiBitsTemp += iRefIdxTemp+1;
+            if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
+          }
+
+          uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdxBi[iRefList][iRefIdxTemp]][aaiMvpNum[iRefList][iRefIdxTemp]];
+          // 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;
+
+            //  Set motion
+            pcCU->getCUMvField( eRefPicList )->setAllMvField( cMvBi[iRefList], iRefIdxBi[iRefList], ePartSize, uiPartAddr, iPartIdx, 0 );
+
+            TComYuv* pcYuvPred = &m_acYuvPred[iRefList];
+            motionCompensation( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+          }
+        } // 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);
+            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 PART_MRG
+    } //end if bTestNormalMC
+#endif
+    //  Clear Motion Field
+    {
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( cMvZero, NOT_VALID, ePartSize, uiPartAddr, iPartIdx, 0 );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvZero, NOT_VALID, ePartSize, uiPartAddr, iPartIdx, 0 );
+    }
+    pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, iPartIdx, 0 );
+    pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, iPartIdx, 0 );
+
+    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 DCM_COMB_LIST
+    if ( pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 ) )
+#else
+    if ( pcCU->getSlice()->getNoBackPredFlag() )
+#endif
+    {
+      uiCost[1] = MAX_UINT;
+    }
+#if PART_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)->setAllMvField( cMvBi[0], iRefIdxBi[0], ePartSize, uiPartAddr, iPartIdx, 0 );
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvBi[1], iRefIdxBi[1], ePartSize, uiPartAddr, iPartIdx, 0 );
+      }
+      {
+        TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, iPartIdx, 0 );
+#if DCM_SIMPLIFIED_MVP==0
+        if (pcCU->clearMVPCand(TempMv, &aacAMVPInfo[0][iRefIdxBi[0]]))
+        {
+          aaiMvpIdxBi[0][iRefIdxBi[0]] = pcCU->searchMVPIdx(cMvPredBi[0][iRefIdxBi[0]], &aacAMVPInfo[0][iRefIdxBi[0]]);
+          aaiMvpNum[0][iRefIdxBi[0]] = aacAMVPInfo[0][iRefIdxBi[0]].iN;
+        }
+#endif
+      }
+      {
+        TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, iPartIdx, 0 );
+#if DCM_SIMPLIFIED_MVP==0
+        if (pcCU->clearMVPCand(TempMv, &aacAMVPInfo[1][iRefIdxBi[1]]))
+        {
+          aaiMvpIdxBi[1][iRefIdxBi[1]] = pcCU->searchMVPIdx(cMvPredBi[1][iRefIdxBi[1]], &aacAMVPInfo[1][iRefIdxBi[1]]);
+          aaiMvpNum[1][iRefIdxBi[1]] = aacAMVPInfo[1][iRefIdxBi[1]].iN;
+        }
+#endif
+      }
+
+      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)->setAllMvField( cMv[0],   iRefIdx[0],   ePartSize, uiPartAddr, iPartIdx, 0 );
+
+      {
+        TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, iPartIdx, 0 );
+#if DCM_SIMPLIFIED_MVP==0
+        if (pcCU->clearMVPCand(TempMv, &aacAMVPInfo[0][iRefIdx[0]]))
+        {
+          aaiMvpIdx[0][iRefIdx[0]] = pcCU->searchMVPIdx(cMvPred[0][iRefIdx[0]], &aacAMVPInfo[0][iRefIdx[0]]);
+          aaiMvpNum[0][iRefIdx[0]] = aacAMVPInfo[0][iRefIdx[0]].iN;
+        }
+#endif
+      }
+      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)->setAllMvField( cMv[1],   iRefIdx[1],   ePartSize, uiPartAddr, iPartIdx, 0 );
+
+      {
+        TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, iPartIdx, 0 );
+#if DCM_SIMPLIFIED_MVP==0
+        if (pcCU->clearMVPCand(TempMv, &aacAMVPInfo[1][iRefIdx[1]]))
+        {
+          aaiMvpIdx[1][iRefIdx[1]] = pcCU->searchMVPIdx(cMvPred[1][iRefIdx[1]], &aacAMVPInfo[1][iRefIdx[1]]);
+          aaiMvpNum[1][iRefIdx[1]] = aacAMVPInfo[1][iRefIdx[1]].iN;
+        }
+#endif
+      }
+      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 PART_MRG
+    } // end if bTestNormalMC
+#endif
+
+    if ( pcCU->getSlice()->getSPS()->getUseMRG() && pcCU->getPartitionSize( uiPartAddr ) == SIZE_2Nx2N )
+    {
+      UChar       uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+      UInt        uiNeighbourCandIdx  [MRG_MAX_NUM_CANDS];
+      TComMvField cMvFieldNeighbours  [MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+      for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+      {
+        uhInterDirNeighbours[ui] = 0;
+        uiNeighbourCandIdx  [ui] = 0;
+      }
+      pcCU->getInterMergeCandidates( uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ), cMvFieldNeighbours, uhInterDirNeighbours, uiNeighbourCandIdx );
+      for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+      {
+        pcCU->setNeighbourCandIdxSubParts( ui, uiNeighbourCandIdx[ui], uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+      }
+    }
+
+    if ( pcCU->getSlice()->getSPS()->getUseMRG() && pcCU->getPartitionSize( uiPartAddr ) != SIZE_2Nx2N )
+    {
+      UInt uiMRGInterDir = 0;
+      TComMvField cMRGMvField[2];
+      UInt uiMRGIndex = 0;
+
+      UInt uiMEInterDir = 0;
+      TComMvField cMEMvField[2];
+
+      m_pcRdCost->getMotionCost( 1, 0 );
+#if PART_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 uiMRGError = MAX_UINT;
+      UInt uiMRGBits = MAX_UINT;
+      Bool bMergeValid = false;
+      UChar ucNeighCand[MRG_MAX_NUM_CANDS];
+      for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+      {
+        ucNeighCand[ui] = 0;
+      }
+      xMergeEstimation( pcCU, pcOrgYuv, iPartIdx, uiMRGInterDir, cMRGMvField, uiMRGIndex, uiMRGError, uiMRGBits, ucNeighCand, bMergeValid );
+      UInt uiMRGCost = uiMRGError + m_pcRdCost->getCost( uiMRGBits );
+
+      for( UInt ui = 0; ui < MRG_MAX_NUM_CANDS; ui++ )
+      {
+        pcCU->setNeighbourCandIdxSubParts( ui, ucNeighCand[ui], uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+      }
+      if ( bMergeValid && uiMRGCost < uiMECost )
+      {
+        // set Merge result
+        pcCU->setMergeFlagSubParts ( true,          uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setMergeIndexSubParts( uiMRGIndex,    uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        {
+          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0].getMv(), cMRGMvField[0].getRefIdx(), ePartSize, uiPartAddr, iPartIdx, 0 );
+          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1].getMv(), cMRGMvField[1].getRefIdx(), ePartSize, uiPartAddr, iPartIdx, 0 );
+        }
+
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, iPartIdx, 0 );
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, iPartIdx, 0 );
+        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 ) );
+        {
+          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0].getMv(), cMEMvField[0].getRefIdx(), ePartSize, uiPartAddr, iPartIdx, 0 );
+          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1].getMv(), cMEMvField[1].getRefIdx(), ePartSize, uiPartAddr, iPartIdx, 0 );
+        }
+      }
+#if PART_MRG
+      if (!bTestNormalMC && !bMergeValid)
+      {
+        assert(pcCU->getWidth( 0 ) > 8 && iNumPart == 2 && iPartIdx == 0);
+        return;
+      }
+#endif
+    }
+
+    //  MC
+    motionCompensation ( pcCU, rpcPredYuv, REF_PIC_LIST_X, iPartIdx );
+
+  } //  end of for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
+
+#ifdef WEIGHT_PRED
+  setWpScalingDistParam( pcCU, -1, -1, REF_PIC_LIST_X );
+#endif
+  return;
+}
+
+// AMVP
+#if ZERO_MVD_EST
+Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, UInt* puiDist )
+#else
+Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled )
+#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));
+    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 ZERO_MVD_EST
+      uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, pcAMVPInfo->iN, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
+#else
+      uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, pcAMVPInfo->iN, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+#endif
+      if ( uiBestCost > uiTmpCost )
+      {
+        uiBestCost = uiTmpCost;
+        cBestMv   = pcAMVPInfo->m_acMvCand[i];
+        iBestIdx  = i;
+        #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 )
+  {
+    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 )
+  {
+    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;
+
+  m_pcRdCost->setPredictor( rcMvPred );
+  Int iOrgMvBits  = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+  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 (iMvBits < iBestMvBits)
+    {
+      iBestMvBits = iMvBits;
+      iBestMVPIdx = iMVPIdx;
+    }
+  }
+
+  if (iBestMVPIdx != riMVPIdx)  //if changed
+  {
+    rcMvPred = pcAMVPInfo->m_acMvCand[iBestMVPIdx];
+
+    iOrgMvBits  += m_auiMVPIdxCost[riMVPIdx][pcAMVPInfo->iN];
+    iBestMvBits += m_auiMVPIdxCost[iBestMVPIdx][pcAMVPInfo->iN];
+
+    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();
+
+  // prediction pattern
+  xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand );
+
+#ifdef WEIGHT_PRED
+  if ( pcCU->getSlice()->getPPS()->getUseWP() )
+  {
+    PartSize  ePartSize = pcCU->getPartitionSize( 0 );
+    pcCU->getCUMvField(eRefPicList)->setAllMvField( cMvCand, iRefIdx, ePartSize, uiPartAddr, uiPartIdx, 0 );
+#if 0
+    TComMvField mvField;
+    mvField.setMvField( cMvCand, iRefIdx);
+    pcCU->getCUMvField(eRefPicList)->setAllMvField( mvField, ePartSize, uiPartAddr, 0 );
+#endif
+    xWeightedPredictionUni( pcCU, pcTemplateCand, uiPartAddr, iSizeX, iSizeY, eRefPicList, pcTemplateCand, uiPartIdx );
+  }
+#endif
+
+  // 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(),
+                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
+  // MW: check VSO here
+  ruiDist = cDistParam.DistFunc( &cDistParam );
+  uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
+#else
+#if HHI_VSO
+  if ( false /*m_pcRdCost->getUseVSO()*/ ) // GT: currently disabled
+  {
+    uiCost = m_pcRdCost->getDistVS  ( pcCU, uiPartAddr,  pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, true, 0);
+    uiCost = (UInt) m_pcRdCost->calcRdCostVSO( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
+  }
+  else
+#endif
+  {
+    uiCost = m_pcRdCost->getDistPart( pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, DF_SAD );
+    uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
+  }
+#endif
+  return uiCost;
+}
+
+Void TEncSearch::xMotionEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, RefPicList eRefPicList, TComMv* pcMvPred, Int iRefIdxPred, TComMv& rcMv, UInt& ruiBits, UInt& ruiCost, Bool bBi  )
+{
+  UInt          uiPartAddr;
+  Int           iRoiWidth;
+  Int           iRoiHeight;
+
+  TComMv        cMvHalf, cMvQter;
+  TComMv        cMvSrchRngLT;
+  TComMv        cMvSrchRngRB;
+
+  TComYuv*      pcYuv = pcYuvOrg;
+#ifdef ROUNDING_CONTROL_BIPRED
+  Pel           pRefBufY[16384];  // 128x128
+#endif
+  m_iSearchRange = m_aaiAdaptSR[eRefPicList][iRefIdxPred];
+
+  Int           iSrchRng      = ( bBi ? m_bipredSearchRange : m_iSearchRange );
+  TComPattern*  pcPatternKey  = pcCU->getPattern        ();
+
+  Double        fWeight       = 1.0;
+
+  pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+
+  if ( bBi )
+  {
+    TComYuv*  pcYuvOther = &m_acYuvPred[1-(Int)eRefPicList];
+    pcYuv                = &m_cYuvPredTemp;
+
+    pcYuvOrg->copyPartToPartYuv( pcYuv, uiPartAddr, iRoiWidth, iRoiHeight );
+
+#ifdef ROUNDING_CONTROL_BIPRED
+    Int y;
+    //Int x;
+    Pel *pRefY = pcYuvOther->getLumaAddr(uiPartAddr);
+    Int iRefStride = pcYuvOther->getStride();
+
+    // copy the MC block into pRefBufY
+    for( y = 0; y < iRoiHeight; y++)
+    {
+      memcpy(pRefBufY+y*iRoiWidth,pRefY,sizeof(Pel)*iRoiWidth);
+      pRefY += iRefStride;
+    }
+#else
+    pcYuv->removeHighFreq( pcYuvOther, uiPartAddr, iRoiWidth, iRoiHeight );
+#endif
+
+    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 ( bBi )  xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  else        xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+
+  m_pcRdCost->getMotionCost ( 1, 0 );
+
+  m_pcRdCost->setPredictor  ( *pcMvPred );
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getSPS()->isDepth() )
+    m_pcRdCost->setCostScale  ( 0 );
+  else
+#endif
+  m_pcRdCost->setCostScale  ( 2 );
+
+#if HHI_INTER_VIEW_MOTION_PRED
+  { // 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 )
+    {
+      xSetSearchRange( pcCU, cOrgDepthMapMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+    }
+  }
+#endif
+
+  //  Do integer search
+#ifdef ROUNDING_CONTROL_BIPRED
+  if( bBi )
+  {
+    xPatternSearch_Bi      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost, pRefBufY, pcCU->getSlice()->isRounding() );
+  }
+  else
+  {
+    if ( !m_iFastSearch)
+    {
+      xPatternSearch      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+    }
+    else
+    {
+      rcMv = *pcMvPred;
+      xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+    }
+  }
+#else
+  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 );
+  }
+#endif
+
+
+  m_pcRdCost->getMotionCost( 1, 0 );
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( ! pcCU->getSlice()->getSPS()->isDepth() )
+  {
+#endif
+  m_pcRdCost->setCostScale ( 1 );
+
+#ifdef ROUNDING_CONTROL_BIPRED
+  if( bBi )
+  {
+    Bool bRound =  pcCU->getSlice()->isRounding() ;
+    xPatternSearchFracDIF_Bi( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, pRefBufY, bRound );
+  }
+  else
+#endif
+  {
+    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost );
+  }
+
+
+
+  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()->getSPS()->isDepth() )
+    ruiCost += m_pcRdCost->getCost( uiMvBits );
+#endif
+
+  ruiBits   += uiMvBits;
+  ruiCost       = (UInt)( floor( fWeight * ( (Double)ruiCost - (Double)m_pcRdCost->getCost( uiMvBits ) ) ) + (Double)m_pcRdCost->getCost( ruiBits ) );
+}
+
+
+Void TEncSearch::xSetSearchRange ( TComDataCU* pcCU, TComMv& cMvPred, Int iSrchRng, TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB )
+{
+  Int  iMvShift = 2;
+#if HHI_FULL_PEL_DEPTH_MAP_MV_ACC
+  if( pcCU->getSlice()->getSPS()->isDepth() )
+    iMvShift = 0;
+#endif
+  pcCU->clipMv( cMvPred );
+
+  rcMvSrchRngLT.setHor( cMvPred.getHor() - (iSrchRng << iMvShift) );
+  rcMvSrchRngLT.setVer( cMvPred.getVer() - (iSrchRng << iMvShift) );
+
+  rcMvSrchRngRB.setHor( cMvPred.getHor() + (iSrchRng << iMvShift) );
+  rcMvSrchRngRB.setVer( cMvPred.getVer() + (iSrchRng << iMvShift) );
+
+  pcCU->clipMv        ( rcMvSrchRngLT );
+  pcCU->clipMv        ( rcMvSrchRngRB );
+
+  rcMvSrchRngLT >>= iMvShift;
+  rcMvSrchRngRB >>= iMvShift;
+}
+
+#ifdef ROUNDING_CONTROL_BIPRED
+Void TEncSearch::xPatternSearch_Bi( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD, Pel* pcRefY2, Bool bRound )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+
+  UInt  uiSad;
+  Dist  uiSadBest         = RDO_DIST_MAX;
+  Int   iBestX = 0;
+  Int   iBestY = 0;
+
+  Pel*  piRefSrch;
+
+  //-- jclee for using the SAD function pointer
+  m_pcRdCost->setDistParam_Bi( 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;
+      uiSad = m_cDistParam.DistFuncRnd( &m_cDistParam, pcRefY2, bRound );
+
+      // 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;
+}
+#endif
+
+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;
+#ifdef WEIGHT_PRED
+      setDistParamComp(0);
+#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()->getSPS()->isDepth() )
+#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()->getSPS()->isDepth() )
+#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 );
+}
+
+
+#ifdef ROUNDING_CONTROL_BIPRED
+Void TEncSearch::xPatternSearchFracDIF_Bi( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvInt, TComMv& rcMvHalf, TComMv& rcMvQter, UInt& ruiCost, Pel* piRefY2, Bool bRound )
+{
+  //  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 );
+  Pel*  piRef;
+  iRefStride  = m_cYuvExt.getStride();
+
+  //  Half-pel refinement
+  xExtDIFUpSamplingH ( &cPatternRoi, &m_cYuvExt );
+  piRef = m_cYuvExt.getLumaAddr() + ((iRefStride + 4) << 2);
+
+  rcMvHalf = *pcMvInt;   rcMvHalf <<= 1;    // for mv-cost
+  ruiCost = xPatternRefinement_Bi( pcPatternKey, piRef, iRefStride, 4, 2, rcMvHalf, piRefY2, bRound );
+
+  m_pcRdCost->setCostScale( 0 );
+
+  //  Quater-pel refinement
+  Pel*  piSrcPel = cPatternRoi.getROIY() + (rcMvHalf.getHor() >> 1) + cPatternRoi.getPatternLStride() * (rcMvHalf.getVer() >> 1);
+  Int*  piSrc    = m_piYuvExt  + ((m_iYuvExtStride + 4) << 2) + (rcMvHalf.getHor() << 1) + m_iYuvExtStride * (rcMvHalf.getVer() << 1);
+  piRef += (rcMvHalf.getHor() << 1) + iRefStride * (rcMvHalf.getVer() << 1);
+  xExtDIFUpSamplingQ ( pcPatternKey, piRef, iRefStride, piSrcPel, cPatternRoi.getPatternLStride(), piSrc, m_iYuvExtStride, m_puiDFilter[rcMvHalf.getHor()+rcMvHalf.getVer()*3] );
+
+  rcMvQter = *pcMvInt;   rcMvQter <<= 1;    // for mv-cost
+  rcMvQter += rcMvHalf;  rcMvQter <<= 1;
+  ruiCost = xPatternRefinement_Bi( pcPatternKey, piRef, iRefStride, 4, 1, rcMvQter, piRefY2, bRound );
+}
+
+#endif
+
+Void TEncSearch::xPatternSearchFracDIF( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvInt, TComMv& rcMvHalf, TComMv& rcMvQter, UInt& ruiCost )
+{
+  //  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 );
+  Pel*  piRef;
+  iRefStride  = m_cYuvExt.getStride();
+
+  //  Half-pel refinement
+  xExtDIFUpSamplingH ( &cPatternRoi, &m_cYuvExt );
+  piRef = m_cYuvExt.getLumaAddr() + ((iRefStride + 4) << 2);
+
+  rcMvHalf = *pcMvInt;   rcMvHalf <<= 1;    // for mv-cost
+  ruiCost = xPatternRefinement( pcPatternKey, piRef, iRefStride, 4, 2, rcMvHalf   );
+
+  m_pcRdCost->setCostScale( 0 );
+
+  //  Quater-pel refinement
+  Pel*  piSrcPel = cPatternRoi.getROIY() + (rcMvHalf.getHor() >> 1) + cPatternRoi.getPatternLStride() * (rcMvHalf.getVer() >> 1);
+  Int*  piSrc    = m_piYuvExt  + ((m_iYuvExtStride + 4) << 2) + (rcMvHalf.getHor() << 1) + m_iYuvExtStride * (rcMvHalf.getVer() << 1);
+  piRef += (rcMvHalf.getHor() << 1) + iRefStride * (rcMvHalf.getVer() << 1);
+  xExtDIFUpSamplingQ ( pcPatternKey, piRef, iRefStride, piSrcPel, cPatternRoi.getPatternLStride(), piSrc, m_iYuvExtStride, m_puiDFilter[rcMvHalf.getHor()+rcMvHalf.getVer()*3] );
+
+  rcMvQter = *pcMvInt;   rcMvQter <<= 1;    // for mv-cost
+  rcMvQter += rcMvHalf;  rcMvQter <<= 1;
+  ruiCost = xPatternRefinement( pcPatternKey, piRef, iRefStride, 4, 1, rcMvQter );
+}
+
+Void TEncSearch::predInterSkipSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv )
+{
+  SliceType eSliceType = pcCU->getSlice()->getSliceType();
+  if ( eSliceType == I_SLICE )
+    return;
+
+  if ( eSliceType == P_SLICE && pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+  {
+    pcCU->setInterDirSubParts( 1, 0, 0, pcCU->getDepth( 0 ) );
+
+    TComMv cMv;
+    TComMv cZeroMv;
+    xEstimateMvPredAMVP( pcCU, pcOrgYuv, 0, REF_PIC_LIST_0, 0, cMv, (pcCU->getCUMvField( REF_PIC_LIST_0 )->getAMVPInfo()->iN > 0?  true:false) );
+    pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMv, 0, SIZE_2Nx2N, 0, 0, 0 );
+    pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, 0, 0, 0 );  //unnecessary
+    pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cZeroMv, NOT_VALID, SIZE_2Nx2N, 0, 0, 0 );  //unnecessary
+    pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, 0, 0, 0 );  //unnecessary
+
+    pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_1, 0, 0, pcCU->getDepth(0));
+    pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_1, 0, 0, pcCU->getDepth(0));
+
+    //  Motion compensation
+    motionCompensation ( pcCU, rpcPredYuv, REF_PIC_LIST_0 );
+
+  }
+  else if ( eSliceType == B_SLICE &&
+           pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 &&
+           pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0  )
+  {
+    TComMv cMv;
+    TComMv cZeroMv;
+
+    if (pcCU->getInterDir(0)!=2)
+    {
+      xEstimateMvPredAMVP( pcCU, pcOrgYuv, 0, REF_PIC_LIST_0, 0, cMv, (pcCU->getCUMvField( REF_PIC_LIST_0 )->getAMVPInfo()->iN > 0?  true:false) );
+      pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMv, 0, SIZE_2Nx2N, 0, 0, 0 );
+      pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, 0, 0, 0 ); //unnecessary
+    }
+
+    if (pcCU->getInterDir(0)!=1)
+    {
+      xEstimateMvPredAMVP( pcCU, pcOrgYuv, 0, REF_PIC_LIST_1, 0, cMv, (pcCU->getCUMvField( REF_PIC_LIST_1 )->getAMVPInfo()->iN > 0?  true:false) );
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMv, 0, SIZE_2Nx2N, 0, 0, 0 );
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvd    ( cZeroMv, SIZE_2Nx2N, 0, 0, 0 );  //unnecessary
+    }
+
+    motionCompensation ( pcCU, rpcPredYuv );
+
+  }
+  else
+  {
+    assert( 0 );
+  }
+
+  return;
+}
+
+/** encode residual and calculate rate-distortion for a CU block
+ * \param pcCU
+ * \param pcYuvOrg
+ * \param pcYuvPred
+ * \param rpcYuvResi
+ * \param rpcYuvResiBest
+ * \param rpcYuvRec
+ * \param bSkipRes
+ * \returns Void
+ */
+Void TEncSearch::encodeResAndCalcRdInterCU( TComDataCU* pcCU, TComYuv* pcYuvOrg, TComYuv* pcYuvPred, TComYuv*& rpcYuvResi, TComYuv*& rpcYuvResiBest, TComYuv*& rpcYuvRec, TComYuv*& rpcYuvResPrd, Bool bSkipRes )
+{
+  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 HHI_INTER_VIEW_RESIDUAL_PRED
+    // add residual prediction
+    if( pcCU->getResPredFlag( 0 ) )
+    {
+      rpcYuvRec->add( rpcYuvResPrd, uiWidth, uiHeight );
+      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 );
+    }
+    else
+#endif
+    {
+      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 );
+    }
+    
+
+    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);
+#if HHI_MRG_SKIP
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, 0, 0, true );
+#else
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 ) //if ( ref. frame list0 has at least 1 entry )
+    {
+      m_pcEntropyCoder->encodeMVPIdx( pcCU, 0, REF_PIC_LIST_0);
+    }
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 ) //if ( ref. frame list1 has at least 1 entry )
+    {
+      m_pcEntropyCoder->encodeMVPIdx( pcCU, 0, REF_PIC_LIST_1);
+    }
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    m_pcEntropyCoder->encodeResPredFlag( pcCU, 0, 0, true );
+#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
+    // set Model
+    if( m_pcRdCost->getUseRenModel() )
+    {
+      Pel*  piSrc       = rpcYuvRec->getLumaAddr();
+      UInt  uiSrcStride = rpcYuvRec->getStride();
+      m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+    }
+#endif
+
+    return;
+  }
+
+  //  Residual coding.
+  UInt    uiQp, uiQpBest = 0, uiQpMin, uiQpMax;
+  Double  dCost, dCostBest = MAX_DOUBLE;
+
+  UInt uiBestTrMode = 0;
+
+  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--;
+
+  uiQpMin      = bHighPass ? Min( MAX_QP, Max( MIN_QP, pcCU->getQP(0) - m_iMaxDeltaQP ) ) : pcCU->getQP( 0 );
+  uiQpMax      = bHighPass ? Min( MAX_QP, Max( MIN_QP, pcCU->getQP(0) + m_iMaxDeltaQP ) ) : pcCU->getQP( 0 );
+
+  pcYuvPred->copyToPartYuv( rpcYuvRec, 0 );
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  // add residual prediction
+  if( pcCU->getResPredFlag( 0 ) )
+  {
+    rpcYuvRec->add( rpcYuvResPrd, uiWidth, uiHeight );
+  }
+#endif
+#if HHI_INTERVIEW_SKIP
+  if( bSkipRes)
+  {
+    rpcYuvResi->clear() ;
+  }
+  else
+  {
+    rpcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, uiWidth );
+  }
+#else
+  rpcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, uiWidth );
+#endif
+
+  for ( uiQp = uiQpMin; uiQp <= uiQpMax; uiQp++ )
+  {
+    pcCU->setQPSubParts( uiQp, 0, pcCU->getDepth(0) );
+    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
+
+    xEstimateResidualQT( pcCU, 0, 0, pcYuvOrg, rpcYuvRec, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
+
+#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 ( 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, 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, rpcYuvResiBest, pcCU->getDepth(0), true );
+      }
+
+      if( uiQpMin != uiQpMax && uiQp != uiQpMax )
+      {
+        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 );
+      }
+      uiBitsBest       = uiBits;
+      uiDistortionBest = uiDistortion;
+      dCostBest        = dCost;
+      uiQpBest         = uiQp;
+
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+      }
+    }
+
+#if HHI_VSO
+    // reset Model
+    if( m_pcRdCost->getUseRenModel() )
+    {
+      Pel*  piSrc       = pcYuvOrg->getLumaAddr();
+      UInt  uiSrcStride = pcYuvOrg->getStride();
+      m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+    }
+#endif
+  }
+
+  assert ( dCostBest != MAX_DOUBLE );
+
+  if( uiQpMin != uiQpMax && uiQpBest != uiQpMax )
+  {
+    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 );
+  }
+  rpcYuvRec->addClip ( rpcYuvRec, rpcYuvResiBest, 0, uiWidth );
+
+  // update with clipped distortion and cost (qp estimation loop uses unclipped values)
+
+#if HHI_VSO
+  if ( m_pcRdCost->getUseVSO() )
+  {
+    uiDistortionBest = m_pcRdCost->getDistVS  ( pcCU, 0, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight, false, 0    );
+  }
+  else
+#endif
+  {
+    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 );
+  }
+
+#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) )
+  {
+    uiBestTrMode = 0;
+    pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
+  }
+
+  pcCU->setQPSubParts( uiQpBest, 0, pcCU->getDepth(0) );
+
+  // set Model
+#if HHI_VSO
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    Pel*  piSrc       = rpcYuvRec->getLumaAddr();
+    UInt  uiSrcStride = rpcYuvRec->getStride();
+    m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+}
+
+Void TEncSearch::xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, Dist &ruiDist, Dist *puiZeroDist )
+{
+  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;
+
+#if HHI_RQT_FORCE_SPLIT_ACC2_PU
+#if HHI_RQT_FORCE_SPLIT_NxN
+  const Bool bNxNOK = pcCU->getPartitionSize( 0 ) == SIZE_NxN && uiTrMode > 0;
+#else
+  const Bool bNxNOK = pcCU->getPartitionSize( 0 ) == SIZE_NxN;
+#endif
+#if HHI_RQT_FORCE_SPLIT_RECT
+  const Bool bSymmetricOK  = pcCU->getPartitionSize( 0 ) >= SIZE_2NxN  && pcCU->getPartitionSize( 0 ) < SIZE_NxN   && uiTrMode > 0;
+#else
+  const Bool bSymmetricOK  = pcCU->getPartitionSize( 0 ) >= SIZE_2NxN  && pcCU->getPartitionSize( 0 ) < SIZE_NxN;
+#endif
+  const Bool bNoForceSplit = pcCU->getPartitionSize( 0 ) == SIZE_2Nx2N || bNxNOK || bSymmetricOK;
+  const Bool bCheckFull    = bNoForceSplit && ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+#else
+  const Bool bCheckFull    = ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+#endif
+
+  const Bool bCheckSplit  = ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+
+  assert( bCheckFull || bCheckSplit );
+
+  Bool  bCodeChroma   = true;
+  UInt  uiTrModeC     = uiTrMode;
+  UInt  uiLog2TrSizeC = uiLog2TrSize-1;
+  if( uiLog2TrSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    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);
+
+    pcCU->setTrIdxSubParts( uiDepth - pcCU->getDepth( 0 ), uiAbsPartIdx, uiDepth );
+    if (m_pcEncCfg->getUseRDOQ())
+    {
+      m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, 1<< uiLog2TrSize, TEXT_LUMA );
+    }
+    m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_LUMA );
+    m_pcTrQuant->transformNxN( pcCU, pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride (), pcCoeffCurrY, 1<< uiLog2TrSize,    1<< uiLog2TrSize,    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, 1<<uiLog2TrSizeC, TEXT_CHROMA );
+      }
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_CHROMA );
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCbAddr( uiAbsPartIdx ), pcResi->getCStride(), pcCoeffCurrU, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC, uiAbsSumU, TEXT_CHROMA_U, uiAbsPartIdx );
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr( uiAbsPartIdx ), pcResi->getCStride(), pcCoeffCurrV, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC, 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();
+
+    if (pcCU->getSlice()->getSymbolMode())
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+
+    m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, 1<< uiLog2TrSize,    1<< uiLog2TrSize,    uiDepth, TEXT_LUMA,     false );
+    const UInt uiSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+    UInt uiSingleBitsU = 0;
+    UInt uiSingleBitsV = 0;
+    if( bCodeChroma )
+    {
+      if (pcCU->getSlice()->getSymbolMode())
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC, uiDepth, TEXT_CHROMA_U, false );
+      uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsY;
+
+      if (pcCU->getSlice()->getSymbolMode())
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC, uiDepth, TEXT_CHROMA_V, false );
+      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() )
+    {
+      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
+    }
+    else
+#endif
+    {
+#if IBDI_DISTORTION
+      uiDistY = m_pcRdCost->getDistPart( pcPred->getLumaAddr( uiAbsPartIdx ), pcPred->getStride(), pcOrg->getLumaAddr( uiAbsPartIdx ), pcOrg->getStride(), 1<< uiLog2TrSize, 1<< uiLog2TrSize);
+#else
+      uiDistY = m_pcRdCost->getDistPart( m_pTempPel, 1<< uiLog2TrSize, pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(), 1<< uiLog2TrSize, 1<< uiLog2TrSize ); // initialized with zero residual distortion
+#endif
+    }
+
+
+    if ( puiZeroDist )
+    {
+      *puiZeroDist += uiDistY;
+    }
+    if( uiAbsSumY )
+    {
+      Pel *pcResiCurrY = m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( uiAbsPartIdx );
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_LUMA );
+#if INTRA_DST_TYPE_7 // Inside Inter Encoder Search. So use conventional DCT.
+    m_pcTrQuant->invtransformNxN( TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, 1<< uiLog2TrSize,    1<< uiLog2TrSize );//this is for inter mode only
+#else
+    m_pcTrQuant->invtransformNxN( pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, 1<< uiLog2TrSize,    1<< uiLog2TrSize );
+#endif
+
+      Dist uiNonzeroDistY;
+
+#if HHI_VSO      
+      if ( m_pcRdCost->getUseVSO() )
+      {
+        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 );
+      }
+      else
+#endif
+      {
+        uiNonzeroDistY = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( uiAbsPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
+                                                  pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(), 1<< uiLog2TrSize,    1<< uiLog2TrSize );
+      }
+
+      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;
+      }
+    }
+
+    if( !uiAbsSumY )
+    {
+      Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( uiAbsPartIdx );
+      const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride();
+      for( UInt uiY = 0; uiY < 1<< uiLog2TrSize; ++uiY )
+      {
+        ::memset( pcPtr, 0, sizeof(Pel) << uiLog2TrSize );
+        pcPtr += uiStride;
+      }
+    }
+
+    Dist uiDistU = 0;
+    Dist uiDistV = 0;
+    if( bCodeChroma )
+    {
+#if IBDI_DISTORTION
+      uiDistU = m_pcRdCost->getDistPart( pcPred->getCbAddr( uiAbsPartIdx ), pcPred->getCStride(), pcOrg->getCbAddr( uiAbsPartIdx ), pcOrg->getCStride(), 1<< uiLog2TrSizeC, 1<< uiLog2TrSizeC);
+#else
+      uiDistU = m_pcRdCost->getDistPart( m_pTempPel, 1<<uiLog2TrSizeC, pcResi->getCbAddr( uiAbsPartIdx ), pcResi->getCStride(), 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC ); // initialized with zero residual destortion
+#endif
+      if ( puiZeroDist )
+      {
+        *puiZeroDist += uiDistU;
+      }
+      if( uiAbsSumU )
+      {
+        Pel *pcResiCurrU = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( uiAbsPartIdx );
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_CHROMA );
+#if INTRA_DST_TYPE_7  // Inside Inter Encoder Search. So use conventional DCT.
+        m_pcTrQuant->invtransformNxN( TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC);
+#else
+        m_pcTrQuant->invtransformNxN( pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC );
+#endif
+        const UInt uiNonzeroDistU = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( uiAbsPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+                                                            pcResi->getCbAddr( uiAbsPartIdx ), pcResi->getCStride(), 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC );
+        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;
+        }
+      }
+      if( !uiAbsSumU )
+      {
+        Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( uiAbsPartIdx );
+        const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
+        for( UInt uiY = 0; uiY < 1<<uiLog2TrSizeC; ++uiY )
+        {
+          ::memset( pcPtr, 0, sizeof(Pel) << uiLog2TrSizeC );
+          pcPtr += uiStride;
+        }
+      }
+
+#if IBDI_DISTORTION
+      uiDistV = m_pcRdCost->getDistPart( pcPred->getCrAddr( uiAbsPartIdx ), pcPred->getCStride(), pcOrg->getCrAddr( uiAbsPartIdx ), pcOrg->getCStride(), 1<< uiLog2TrSizeC, 1<< uiLog2TrSizeC);
+#else
+      uiDistV = m_pcRdCost->getDistPart( m_pTempPel, 1<<uiLog2TrSizeC, pcResi->getCrAddr( uiAbsPartIdx ), pcResi->getCStride(), 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC ); // initialized with zero residual destortion
+#endif
+      if ( puiZeroDist )
+      {
+        *puiZeroDist += uiDistV;
+      }
+      if( uiAbsSumV )
+      {
+        Pel *pcResiCurrV = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr  ( uiAbsPartIdx );
+        if( !uiAbsSumU )
+        {
+          m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), false, pcCU->getSlice()->getSliceType(), TEXT_CHROMA );
+        }
+#if INTRA_DST_TYPE_7   // Inside Inter Encoder Search. So use conventional DCT.
+        m_pcTrQuant->invtransformNxN( TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC );
+#else
+        m_pcTrQuant->invtransformNxN( pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC );
+#endif
+        const UInt uiNonzeroDistV = m_pcRdCost->getDistPart( m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( uiAbsPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+                                                            pcResi->getCrAddr( uiAbsPartIdx ), pcResi->getCStride(), 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC );
+        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;
+        }
+      }
+      if( !uiAbsSumV )
+      {
+        Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( uiAbsPartIdx );
+        const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
+        for( UInt uiY = 0; uiY < 1<<uiLog2TrSizeC; ++uiY )
+        {
+          ::memset( pcPtr, 0, sizeof(Pel) << uiLog2TrSizeC );
+          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 CAVLC_RQT_CBP
+    if (pcCU->getSlice()->getSymbolMode())
+    {
+#endif
+    if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( 0, uiDepth );
+    }
+#if CAVLC_RQT_CBP
+    }
+#endif
+
+    if (pcCU->getSlice()->getSymbolMode())
+    {
+      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, 1<< uiLog2TrSize,    1<< uiLog2TrSize,    uiDepth, TEXT_LUMA,     false );
+
+    if( bCodeChroma )
+    {
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC, uiDepth, TEXT_CHROMA_U, false );
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC, uiDepth, TEXT_CHROMA_V, false );
+    }
+
+    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 );
+    }
+  }
+
+  // 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 )
+    {
+      xEstimateResidualQT( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, pcOrg, pcPred, pcResi, uiDepth + 1, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist );
+    }
+
+    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 ( m_pcRdCost->getUseRenModel() )
+  {
+    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 CAVLC_RQT_CBP
+  if(pcCU->getSlice()->getSymbolMode() == 0 )
+  {
+    if( bSubdivAndCbf && uiCurrTrMode != 0)
+      m_pcEntropyCoder->m_pcEntropyCoderIf->codeCbfTrdiv( pcCU, uiAbsPartIdx, uiDepth );
+  }
+#endif
+
+#if CAVLC_RQT_CBP
+  if(pcCU->getSlice()->getSymbolMode())
+  {
+#endif
+  if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, uiDepth );
+  }
+#if CAVLC_RQT_CBP
+  }
+#endif
+
+  if (pcCU->getSlice()->getSymbolMode())
+  {
+    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 > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+      {
+        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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      uiLog2TrSizeC++;
+      uiTrModeC    --;
+      UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
+      bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    }
+
+    if( bSubdivAndCbf )
+    {
+      if (pcCU->getSlice()->getSymbolMode())
+      {
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+      }
+    }
+    else
+    {
+      if( eType == TEXT_LUMA     && pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA,     uiTrMode ) )
+      {
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, 1<< uiLog2TrSize,    1<< uiLog2TrSize,    uiDepth, TEXT_LUMA,     false );
+      }
+      if( bCodeChroma )
+      {
+        if( eType == TEXT_CHROMA_U && pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode ) )
+        {
+          m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC, uiDepth, TEXT_CHROMA_U, false );
+        }
+        if( eType == TEXT_CHROMA_V && pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode ) )
+        {
+          m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC, uiDepth, TEXT_CHROMA_V, false );
+        }
+      }
+    }
+  }
+  else
+  {
+    if( bSubdivAndCbf || pcCU->getCbf( uiAbsPartIdx, eType, uiCurrTrMode ) )
+    {
+      const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
+#if !CAVLC_RQT_CBP
+      if(pcCU->getSlice()->getSymbolMode() == 0)
+      {
+        if( !bSubdivAndCbf && (eType == TEXT_LUMA || uiLog2TrSize-1 > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize()) )
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeBlockCbf(pcCU, uiAbsPartIdx, eType, uiCurrTrMode + 1, uiQPartNumSubdiv, true);
+      }
+#endif
+      for( UInt ui = 0; ui < 4; ++ui )
+      {
+        xEncodeResidualQT( pcCU, uiAbsPartIdx + ui * uiQPartNumSubdiv, uiDepth + 1, bSubdivAndCbf, eType );
+      }
+    }
+  }
+}
+
+Void TEncSearch::xSetResidualQTData( TComDataCU* pcCU, UInt uiAbsPartIdx, 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 == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      uiLog2TrSizeC++;
+      uiTrModeC    --;
+      UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
+      bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    }
+
+    if( bSpatial )
+    {
+      m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartLuma    ( pcResi, uiAbsPartIdx, 1<<uiLog2TrSize , 1<<uiLog2TrSize  );
+      if( bCodeChroma )
+      {
+        m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1<<uiLog2TrSizeC, 1<<uiLog2TrSizeC );
+      }
+    }
+    else
+    {
+      UInt    uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+      UInt    uiNumCoeffY = ( 1 << ( uiLog2TrSize << 1 ) );
+      TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      TCoeff* pcCoeffDstY = pcCU->getCoeffY() + uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+      if( 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 );
+      }
+    }
+  }
+  else
+  {
+    const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
+    for( UInt ui = 0; ui < 4; ++ui )
+    {
+      xSetResidualQTData( pcCU, uiAbsPartIdx + ui * uiQPartNumSubdiv, pcResi, uiDepth + 1, bSpatial );
+    }
+  }
+}
+
+UInt TEncSearch::xModeBitsIntra( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth )
+{
+  if( m_bUseSBACRD )
+  {
+    m_pcRDGoOnSbacCoder->load( 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);
+    ruiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+    m_pcEntropyCoder->resetBits();
+#if HHI_MRG_SKIP
+    m_pcEntropyCoder->encodeMergeIndex(pcCU, 0, 0, true);
+#else
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 ) //if ( ref. frame list0 has at least 1 entry )
+    {
+      m_pcEntropyCoder->encodeMVPIdx( pcCU, 0, REF_PIC_LIST_0);
+    }
+    if ( pcCU->getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 ) //if ( ref. frame list1 has at least 1 entry )
+    {
+      m_pcEntropyCoder->encodeMVPIdx( pcCU, 0, REF_PIC_LIST_1);
+    }
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    m_pcEntropyCoder->encodeResPredFlag( pcCU, 0, 0, true );
+#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 HHI_MRG_SKIP
+      if (pcCU->getPredictionMode(0) == MODE_SKIP)
+      {
+        pcCU->setPredModeSubParts( MODE_INTER, 0, pcCU->getDepth(0) );
+      }
+#endif
+      m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+      m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+      m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      m_pcEntropyCoder->encodeResPredFlag( pcCU, 0, 0, true );
+#endif
+#if HHI_MPI
+    }
+#endif
+    m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0) );
+
+    ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+}
+
+
+Void TEncSearch::xExtDIFUpSamplingH ( TComPattern* pcPattern, TComYuv* pcYuvExt  )
+{
+  Int   x, y;
+
+  Int   iWidth      = pcPattern->getROIYWidth();
+  Int   iHeight     = pcPattern->getROIYHeight();
+
+  Int   iPatStride  = pcPattern->getPatternLStride();
+  Int   iExtStride  = pcYuvExt ->getStride();
+
+  Int*  piSrcY;
+  Int*  piDstY;
+  Pel*  piDstYPel;
+  Pel*  piSrcYPel;
+
+  //  Copy integer-pel
+  piSrcYPel = pcPattern->getROIY() - 4 - iPatStride;
+  piDstY    = m_piYuvExt;//pcYuvExt->getLumaAddr();
+  piDstYPel = pcYuvExt->getLumaAddr();
+  for ( y = 0; y < iHeight + 2; y++ )
+  {
+    for ( x = 0; x < iWidth + 8; x++ )
+    {
+      piDstYPel[x << 2] = piSrcYPel[x];
+    }
+    piSrcYPel +=  iPatStride;
+    piDstY    += (m_iYuvExtStride << 2);
+    piDstYPel += (iExtStride      << 2);
+  }
+
+  //  Half-pel NORM. : vertical
+  piSrcYPel = pcPattern->getROIY()    - iPatStride - 4;
+  piDstY    = m_piYuvExt              + (m_iYuvExtStride<<1);
+  piDstYPel = pcYuvExt->getLumaAddr() + (iExtStride<<1);
+  xCTI_FilterHalfVer     (piSrcYPel, iPatStride,     1, iWidth + 8, iHeight + 1, m_iYuvExtStride<<2, 4, piDstY, iExtStride<<2, piDstYPel);
+
+  //  Half-pel interpolation : horizontal
+  piSrcYPel = pcPattern->getROIY()   -  iPatStride - 1;
+  piDstYPel = pcYuvExt->getLumaAddr() + 14;
+  xCTI_FilterHalfHor (piSrcYPel, iPatStride,     1,  iWidth + 1, iHeight + 1,  iExtStride<<2, 4, piDstYPel);
+
+  //  Half-pel interpolation : center
+  piSrcY    = m_piYuvExt              + (m_iYuvExtStride<<1) + (3 << 2);
+  piDstYPel = pcYuvExt->getLumaAddr() + (iExtStride<<1)      + 14;
+  xCTI_FilterHalfHor       (piSrcY, m_iYuvExtStride<<2, 4, iWidth + 1, iHeight + 1,iExtStride<<2, 4, piDstYPel);
+
+}
+
+Void TEncSearch::xExtDIFUpSamplingQ   ( TComPattern* pcPatternKey, Pel* piDst, Int iDstStride, Pel* piSrcPel, Int iSrcPelStride, Int* piSrc, Int iSrcStride, UInt uiFilter )
+{
+  Int   x, y;
+
+  Int   iWidth      = pcPatternKey->getROIYWidth();
+  Int   iHeight     = pcPatternKey->getROIYHeight();
+
+  Int*  piSrcY;
+  Int*  piDstY;
+  Pel*  piDstYPel;
+  Pel*  piSrcYPel;
+
+  Int iSrcStride4 = (iSrcStride<<2);
+  Int iDstStride4 = (iDstStride<<2);
+
+  switch (uiFilter)
+  {
+    case 0:
+    {
+      //  Quater-pel interpolation : vertical
+      piSrcYPel = piSrcPel - 3;
+      piDstY    = piSrc - 14 - iSrcStride;
+      xCTI_FilterQuarter0Ver(piSrcYPel, iSrcPelStride, 1, iWidth + 7, iHeight, iSrcStride4, 4, piDstY);
+
+      piSrcYPel = piSrcPel - 3;
+      piDstY    = piSrc - 14 + iSrcStride;
+      xCTI_FilterQuarter1Ver(piSrcYPel, iSrcPelStride, 1, iWidth + 7, iHeight, iSrcStride4, 4, piDstY);
+      // Above three pixels
+      piSrcY    = piSrc-2 - iSrcStride;
+      piDstYPel = piDst-1 - iDstStride;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2 - iSrcStride;
+      piDstYPel = piDst   - iDstStride;;
+      xCTI_FilterHalfHor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2 - iSrcStride;
+      piDstYPel = piDst+1 - iDstStride;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      // Middle two pixels
+      piSrcY    = piSrc-2;
+      piDstYPel = piDst-1;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2;
+      piDstYPel = piDst+1;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      // Below three pixels
+      piSrcY    = piSrc-2 + iSrcStride;
+      piDstYPel = piDst-1 + iDstStride;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2 + iSrcStride;
+      piDstYPel = piDst   + iDstStride;;
+      xCTI_FilterHalfHor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2 + iSrcStride;
+      piDstYPel = piDst+1 + iDstStride;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+      break;
+    }
+    case 1:
+    {
+      //  Quater-pel interpolation : vertical
+      piSrcYPel = piSrcPel - 4;
+      piDstY    = piSrc-16 - iSrcStride;
+      xCTI_FilterQuarter0Ver(piSrcYPel, iSrcPelStride, 1, iWidth + 8, iHeight, iSrcStride4, 4, piDstY);
+
+      piSrcYPel = piSrcPel - 4;
+      piDstY    = piSrc-16 + iSrcStride;
+      xCTI_FilterQuarter1Ver(piSrcYPel, iSrcPelStride, 1, iWidth + 8, iHeight, iSrcStride4, 4, piDstY);
+      // Left three pixels
+      piSrcY    = piSrc-4 - iSrcStride;
+      piDstYPel = piDst-1 - iDstStride;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-4;
+      piDstYPel = piDst-1;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-4 + iSrcStride;
+      piDstYPel = piDst-1 + iDstStride;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      // Middle two pixels
+      piSrcY    = piSrc - iSrcStride;
+      piDstYPel = piDst - iDstStride;
+      Int iSrcStride2 = (iSrcStride<<1);
+      Int iDstStride2 = (iDstStride<<1);
+
+      for (y=0; y < iHeight*2; y++)
+      {
+        for (x=0; x < iWidth; x++)
+        {
+          piDstYPel[x*4] = Clip( (piSrcY[x*4] +  32) >>  6 );
+        }
+        piSrcY+=iSrcStride2;
+        piDstYPel+=iDstStride2;
+      }
+
+      // Right three pixels
+      piSrcY    = piSrc   - iSrcStride;
+      piDstYPel = piDst+1 - iDstStride;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc;
+      piDstYPel = piDst+1;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc   + iSrcStride;
+      piDstYPel = piDst+1 + iDstStride;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      break;
+    }
+    case 2:
+    {
+      //  Quater-pel interpolation : vertical
+      piSrcYPel = piSrcPel - 3 - iSrcPelStride;;
+      piDstY    = piSrc - 14 - iSrcStride;
+      xCTI_FilterQuarter1Ver(piSrcYPel, iSrcPelStride, 1, iWidth + 7, iHeight, iSrcStride4, 4, piDstY);
+
+      piSrcYPel = piSrcPel - 3;
+      piDstY    = piSrc - 14 + iSrcStride;
+      xCTI_FilterQuarter0Ver(piSrcYPel, iSrcPelStride, 1, iWidth + 7, iHeight, iSrcStride4, 4, piDstY);
+      // Above three pixels
+      piSrcY    = piSrc-2 - iSrcStride;
+      piDstYPel = piDst-1 - iDstStride;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2 - iSrcStride;
+      piDstYPel = piDst   - iDstStride;;
+      xCTI_FilterHalfHor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2 - iSrcStride;
+      piDstYPel = piDst+1 - iDstStride;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      // Middle two pixels
+      piDstYPel = piDst - 1;
+      xCTI_FilterQuarter0Hor(piSrcPel, iSrcPelStride, 1, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piDstYPel = piDst + 1;
+      xCTI_FilterQuarter1Hor(piSrcPel, iSrcPelStride, 1, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      // Below three pixels
+      piSrcY    = piSrc-2 + iSrcStride;
+      piDstYPel = piDst-1 + iDstStride;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2 + iSrcStride;
+      piDstYPel = piDst   + iDstStride;;
+      xCTI_FilterHalfHor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-2 + iSrcStride;
+      piDstYPel = piDst+1 + iDstStride;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+      break;
+    }
+    case 3:
+    {
+      //  Quater-pel interpolation : vertical
+      piSrcYPel = piSrcPel-4 - iSrcPelStride;
+      piDstY    = piSrc-16 - iSrcStride;
+      xCTI_FilterQuarter1Ver(piSrcYPel, iSrcPelStride, 1, iWidth + 8, iHeight, iSrcStride4, 4, piDstY);
+
+      piSrcYPel = piSrcPel-4;
+      piDstY    = piSrc-16 + iSrcStride;
+      xCTI_FilterQuarter0Ver(piSrcYPel, iSrcPelStride, 1, iWidth + 8, iHeight, iSrcStride4, 4, piDstY);
+      // Left three pixels
+      piSrcY    = piSrc-4 - iSrcStride;
+      piDstYPel = piDst-1 - iDstStride;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcYPel = piSrcPel-1;
+      piDstYPel = piDst-1;
+      xCTI_FilterQuarter1Hor(piSrcYPel, iSrcPelStride, 1, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc-4 + iSrcStride;
+      piDstYPel = piDst-1 + iDstStride;
+      xCTI_FilterQuarter1Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      // Middle two pixels
+      piSrcY    = piSrc - iSrcStride;
+      piDstYPel = piDst - iDstStride;
+      Int iSrcStride2 = (iSrcStride<<1);
+      Int iDstStride2 = (iDstStride<<1);
+
+      for (y=0; y < iHeight*2; y++)
+      {
+        for (x=0; x < iWidth; x++)
+        {
+          piDstYPel[x*4] = Clip( (piSrcY[x*4] + 32) >>  6 );
+        }
+        piSrcY+=iSrcStride2;
+        piDstYPel+=iDstStride2;
+      }
+
+      // Right three pixels
+      piSrcY    = piSrc   - iSrcStride;
+      piDstYPel = piDst+1 - iDstStride;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piDstYPel = piDst+1;
+      xCTI_FilterQuarter0Hor(piSrcPel, iSrcPelStride, 1, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      piSrcY    = piSrc   + iSrcStride;
+      piDstYPel = piDst+1 + iDstStride;
+      xCTI_FilterQuarter0Hor(piSrcY, iSrcStride4, 4, iWidth, iHeight, iDstStride4, 4, piDstYPel);
+
+      break;
+    }
+    default:
+    {
+      assert(0);
+    }
+  }
+}
+#ifdef WEIGHT_PRED
+Void  TEncSearch::setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1 , RefPicList eRefPicListCur )
+{
+  if ( iRefIdx0<0 && iRefIdx1<0 )
+  {
+    m_cDistParam.applyWeight = false;
+    return;
+  }
+
+  TComSlice       *pcSlice  = pcCU->getSlice();
+  TComPPS         *pps      = pcCU->getSlice()->getPPS();
+  wpScalingParam  *wp0 , *wp1;
+
+  m_cDistParam.applyWeight = ( pcSlice->getSliceType()==P_SLICE && pps->getUseWP() ) || ( pcSlice->getSliceType()==B_SLICE && pps->getWPBiPredIdc() ) ;
+
+  if ( !m_cDistParam.applyWeight ) return;
+
+  getWpScaling( pcCU, iRefIdx0, iRefIdx1, wp0 , wp1 );
+
+  if ( iRefIdx0 < 0 ) wp0 = NULL;
+  if ( iRefIdx1 < 0 ) wp1 = NULL;
+
+  m_cDistParam.wpCur  = NULL;
+  m_cDistParam.wpRef  = NULL;
+
+  if ( eRefPicListCur == REF_PIC_LIST_0 )
+  {
+    m_cDistParam.wpCur = wp0;
+    m_cDistParam.wpRef = wp1;
+  }
+  else
+  {
+    m_cDistParam.wpCur = wp1;
+    m_cDistParam.wpRef = wp0;
+  }
+}
+#endif
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncSearch.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncSearch.h	(revision 19)
@@ -0,0 +1,555 @@
+/* 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     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/TComPredFilter.h"
+#include "../TLibCommon/TComPrediction.h"
+#include "../TLibCommon/TComTrQuant.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComWedgelet.h"
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TEncCfg.h"
+
+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;
+  UChar*          m_puhQTTempTrIdx;
+  UChar*          m_puhQTTempCbf[3];
+  
+  TComYuv*        m_pcQTTempTComYuv;
+protected:
+  // interface to option
+  TEncCfg*        m_pcEncCfg;
+  
+  // interface to classes
+  TComTrQuant*    m_pcTrQuant;
+  TComRdCost*     m_pcRdCost;
+  TEncEntropy*    m_pcEntropyCoder;
+  
+  // ME parameters
+  Int             m_iSearchRange;
+  Int             m_bipredSearchRange; // Search range for bi-prediction
+  Int             m_iFastSearch;
+  Int             m_aaiAdaptSR[2][33];
+  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
+  // 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
+  
+public:
+  TEncSearch();
+  virtual ~TEncSearch();
+  
+  Void init(  TEncCfg*      pcEncCfg,
+            TComTrQuant*  pcTrQuant,
+            Int           iSearchRange,
+            Int           bipredSearchRange,
+            Int           iFastSearch,
+            Int           iMaxDeltaQP,
+            TEncEntropy*  pcEntropyCoder,
+            TComRdCost*   pcRdCost,
+            TEncSbac***   pppcRDSbacCoder,
+            TEncSbac*     pcRDGoOnSbacCoder );
+  
+protected:
+  
+  /// sub-function for motion vector refinement used in fractional-pel accuracy
+#ifdef ROUNDING_CONTROL_BIPRED
+  UInt  xPatternRefinement_Bi( TComPattern* pcPatternKey, Pel* piRef, Int iRefStride, Int iIntStep, Int iFrac, TComMv& rcMvFrac, Pel* pRefY2, Bool bRound );
+#endif
+  
+  UInt  xPatternRefinement( TComPattern* pcPatternKey, Pel* piRef, Int iRefStride, Int iIntStep, Int iFrac, TComMv& rcMvFrac );
+  
+#if (!REFERENCE_SAMPLE_PADDING)
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool predIntraLumaDirAvailable( UInt uiMode, UInt uiWidthBit, Bool bAboveAvail, Bool bLeftAvail, UInt uiWidth, UInt uiHeight, TComDataCU* pcCU, UInt uiAbsPartIdx );
+#else
+  Bool predIntraLumaDirAvailable( UInt uiMode, UInt uiWidthBit, Bool bAboveAvail, Bool bLeftAvail);
+#endif
+#endif
+
+#if HHI_DMM_WEDGE_INTRA
+  Void xSearchWedgeFullMinDist   ( TComDataCU* pcCU, UInt uiAbsPtIdx, WedgeList* pacWedgeList, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx );
+  Void xSearchWedgePredDirMinDist( TComDataCU* pcCU, UInt uiAbsPtIdx, WedgeList* pacWedgeList, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, Int& riWedgeDeltaEnd );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Void xGetWedgeDeltaDCsMinDist  ( TComWedgelet* pcWedgelet, 
+                                   TComDataCU*   pcCU, 
+                                   UInt          uiAbsPtIdx, 
+                                   Pel*          piOrig, 
+                                   Pel*          piPredic, 
+                                   UInt          uiStride, 
+                                   UInt          uiWidth, 
+                                   UInt          uiHeight, 
+                                   Int&          riDeltaDC1, 
+                                   Int&          riDeltaDC2, 
+                                   Bool          bAbove, 
+                                   Bool          bLeft );
+
+  Void xDeltaDCQuantScaleDown( TComDataCU*  pcCU, Int& riDeltaDC );
+#endif
+
+  
+  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 );
+  
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  Bool predIntraLumaDMMAvailable( UInt         uiMode, 
+                                  UInt         uiWidth, 
+                                  UInt         uiHeight );
+#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         bAbove,
+                                  Bool         bLeft,
+                                  WedgeDist    eWedgeDist );
+  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         bAbove,
+                                  Bool         bLeft,
+                                  WedgeDist    eWedgeDist );
+#endif
+#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         bAbove,
+                                  Bool         bLeft,
+                                  WedgeDist    eWedgeDist,
+                                  Pel*         piTextureRef = NULL );
+
+  Void findContourPredTex       ( TComDataCU*  pcCU, 
+                                  UInt         uiAbsPtIdx,
+                                  Pel*         piOrig,
+                                  Pel*         piPredic,
+                                  UInt         uiStride,
+                                  UInt         uiWidth,
+                                  UInt         uiHeight,
+                                  Int&         riDeltaDC1,
+                                  Int&         riDeltaDC2,
+                                  Bool         bAbove,
+                                  Bool         bLeft,
+                                  Pel*         piTextureRef = NULL );
+#endif
+  
+  /// encoder estimation - inter prediction (non-skip)
+  Void predInterSearch          ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*&   rpcPredYuv,
+                                  TComYuv*&   rpcResiYuv,
+                                  TComYuv*&   rpcRecoYuv,
+                                  Bool        bUseRes = false );
+  
+  /// encoder estimation - intra prediction (skip)
+  Void predInterSkipSearch      ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*&   rpcPredYuv,
+                                  TComYuv*&   rpcResiYuv,
+                                  TComYuv*&   rpcRecoYuv );
+  
+  /// 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 );
+  
+  /// set ME search range
+  Void setAdaptiveSearchRange   ( Int iDir, Int iRefIdx, Int iSearchRange) { m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange; }
+  
+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
+                                   );
+
+  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 );
+  
+  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 );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // Inter search (AMP)
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xEstimateMvPredAMVP        ( TComDataCU* pcCU,
+                                    TComYuv*    pcOrgYuv,
+                                    UInt        uiPartIdx,
+                                    RefPicList  eRefPicList,
+                                    Int         iRefIdx,
+                                    TComMv&     rcMvPred,
+                                    Bool        bFilled = false
+                                  #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,
+                                    UInt&           ruiBits,
+                                    UChar*          puhNeighCands,
+                                    Bool&           bValid );
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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 );
+  
+  Void xSetSearchRange            ( TComDataCU*   pcCU,
+                                    TComMv&       cMvPred,
+                                    Int           iSrchRng,
+                                    TComMv&       rcMvSrchRngLT,
+                                    TComMv&       rcMvSrchRngRB );
+  
+  Void xPatternSearchFast         ( TComDataCU*   pcCU,
+                                    TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvSrchRngLT,
+                                    TComMv*       pcMvSrchRngRB,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiSAD );
+  
+#ifdef ROUNDING_CONTROL_BIPRED
+  Void xPatternSearch_Bi             ( TComPattern*  pcPatternKey,
+                                       Pel*          piRefY,
+                                       Int           iRefStride,
+                                       TComMv*       pcMvSrchRngLT,
+                                       TComMv*       pcMvSrchRngRB,
+                                       TComMv&       rcMv,
+                                       UInt&         ruiSAD,
+                                       Pel*          pcRefY2,
+                                       Bool          bRound);
+  
+  Void xPatternSearchFracDIF_Bi      ( TComDataCU*   pcCU,
+                                       TComPattern*  pcPatternKey,
+                                       Pel*          piRefY,
+                                       Int           iRefStride,
+                                       TComMv*       pcMvInt,
+                                       TComMv&       rcMvHalf,
+                                       TComMv&       rcMvQter,
+                                       UInt&         ruiCost,
+                                       Pel*          pcRefY2,
+                                       Bool          bRound);
+#endif
+  
+  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 
+                                   );
+  
+  Void xExtDIFUpSamplingH         ( TComPattern*  pcPattern, TComYuv* pcYuvExt  );
+  
+  Void xExtDIFUpSamplingQ         ( TComPattern* pcPatternKey,
+                                    Pel*          piDst,
+                                    Int           iDstStride,
+                                    Pel*          piSrcPel,
+                                    Int           iSrcPelStride,
+                                    Int*          piSrc,
+                                    Int           iSrcStride,
+                                    UInt          uiFilter  );
+  
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // T & Q & Q-1 & T-1
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType );
+  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, Dist &ruiDist, Dist *puiZeroDist );
+  Void xSetResidualQTData( TComDataCU* pcCU, UInt uiAbsPartIdx, 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 );
+  
+#ifdef WEIGHT_PRED
+  Void  setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1 , RefPicList eRefPicList );
+  inline  Void  setDistParamComp( UInt uiComp )  { m_cDistParam.uiComp = uiComp; }
+#endif
+};// END CLASS DEFINITION TEncSearch
+
+
+#endif // __TENCSEARCH__
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncSeqStructure.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncSeqStructure.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncSeqStructure.cpp	(revision 19)
@@ -0,0 +1,386 @@
+/* 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 "TEncSeqStructure.h"
+#include "TEncFormattedStringParser.h"
+#include <algorithm>
+
+ErrVal FrameDescriptor::initFrameDescriptor( const std::string&  rcString, UInt &ruiIncrement, std::map<UInt, UInt>& rcColDirTracker)
+{
+  std::string::size_type uiPos = 0;
+
+  while( 1 )
+  {
+    SliceType eSliceType;
+    Bool bStoreForRef;
+    Bool bIsIDR;
+    UInt uiLayer;
+
+    RNOK( TEncFormattedStringParser::extractFrameType( rcString, eSliceType, bStoreForRef, bIsIDR, uiPos ) );
+    RNOK( TEncFormattedStringParser::extractFrameLayer( rcString, uiLayer, uiPos ) );
+
+    m_aeSliceType.push_back( eSliceType );
+    m_abStoreForRef.push_back( bStoreForRef );
+    m_abIsIDR.push_back( bIsIDR );
+    m_auiLayer.push_back( uiLayer );
+    m_aaiAllowedRelativeRefPocsL0.push_back( std::vector<int>() );
+    m_aaiAllowedRelativeRefPocsL1.push_back( std::vector<int>() );
+    m_aaiAllowedReferenceViewIdxL0.push_back( std::vector<int>() );
+    m_aaiAllowedReferenceViewIdxL1.push_back( std::vector<int>() );
+
+    if( eSliceType == P_SLICE )
+    {
+      RNOK( TEncFormattedStringParser::extractAllowedRelativeRefPocs( rcString, m_aaiAllowedRelativeRefPocsL0.back(), m_aaiAllowedReferenceViewIdxL0.back(), uiPos ) );
+    }
+    else if( eSliceType == B_SLICE )
+    {
+      RNOK( TEncFormattedStringParser::extractAllowedRelativeRefPocs( rcString, m_aaiAllowedRelativeRefPocsL0.back(), m_aaiAllowedRelativeRefPocsL1.back(),
+                                                                      m_aaiAllowedReferenceViewIdxL0.back(), m_aaiAllowedReferenceViewIdxL1.back(), uiPos ) );
+    }
+
+    // check that only available views are referenced
+    {
+      const Int iCurrViewIdx = Int( m_aeSliceType.size() - 1 );
+      for( UInt ui = 0; ui < m_aaiAllowedReferenceViewIdxL0.back().size(); ui++ )
+      {
+        const Int iRefViewIdx = m_aaiAllowedReferenceViewIdxL0.back()[ui];
+        ROF( iRefViewIdx == -1 || ( 0 <= iRefViewIdx && iRefViewIdx < iCurrViewIdx ) );
+      }
+      for( UInt ui = 0; ui < m_aaiAllowedReferenceViewIdxL1.back().size(); ui++ )
+      {
+        const Int iRefViewIdx = m_aaiAllowedReferenceViewIdxL1.back()[ui];
+        ROF( iRefViewIdx == -1 || ( 0 <= iRefViewIdx && iRefViewIdx < iCurrViewIdx ) );
+      }
+    }
+
+    ROT( eSliceType == I_SLICE && ! m_aaiAllowedRelativeRefPocsL0.back().empty() && ! m_aaiAllowedRelativeRefPocsL1.back().empty() );
+    ROT( eSliceType == P_SLICE && ! m_aaiAllowedRelativeRefPocsL1.back().empty() );
+    if( rcString[uiPos] == '_' )
+    {
+      uiPos++;
+      break;
+    }
+  }
+
+  RNOK( TEncFormattedStringParser::extractFrameIncrement( rcString, ruiIncrement, uiPos ) );
+
+  if(rcColDirTracker.find( m_auiLayer[0] )==rcColDirTracker.end())
+    rcColDirTracker.insert( std::make_pair(m_auiLayer[0],1) );
+
+  m_uiColDir = rcColDirTracker[ m_auiLayer[0] ];
+  rcColDirTracker[ m_auiLayer[0]  ] = 1 - rcColDirTracker[ m_auiLayer[0] ];
+
+  ROF( std::string::npos == uiPos || rcString.length() == uiPos );
+
+  return Err::m_nOK;
+}
+
+
+UInt64 TEncSeqStructure::FrameSequencePart::findIncrement( UInt64 uiIncrement, bool &rbSuccess ) const
+{
+  TOF( isInfinitelyLong() || uiIncrement < getSize() );
+  rbSuccess = false;
+  const UInt64 uiOffset = uiIncrement % xGetSize();
+  for( UInt ui = 0; ui < UInt( m_auiIncrements.size() ); ui++ )
+  {
+    if( uiOffset == m_auiIncrements[ui] )
+    {
+      rbSuccess = true;
+      return uiIncrement - uiOffset + ui;
+    }
+  }
+  return 0;
+}
+
+
+TEncSeqStructure::FrameSequencePart::FrameSequencePart( const std::string& rcString )
+{
+  std::string cNoRepString;
+
+  //----- get number of repetitions and number of frames -----
+  UInt uiNumRep = 0;
+  TNOK( TEncFormattedStringParser::extractRepetitions( rcString, cNoRepString, uiNumRep ) );
+  xSetNumRep( uiNumRep );
+  UInt uiNumberOfFrames = 0;
+  TNOK( TEncFormattedStringParser::getNumberOfFrames( cNoRepString, uiNumberOfFrames ) );
+  TOF( uiNumberOfFrames );
+  //----- create array -----
+  m_acFrameDescriptors.resize( uiNumberOfFrames );
+  TOF( m_acFrameDescriptors.size() == uiNumberOfFrames );
+  m_auiIncrements.resize( uiNumberOfFrames );
+
+  //----- initialize array -----
+  UInt uiIndex;
+  size_t uiPos;
+  for( uiPos = 0, uiIndex = 0; uiIndex < uiNumberOfFrames; uiIndex++ )
+  {
+    std::string cFDString;
+    TNOK( TEncFormattedStringParser::extractNextFrameDescription( cNoRepString, cFDString, uiPos ) );
+    UInt uiIncrement = 0;
+    TNOK( m_acFrameDescriptors[uiIndex].initFrameDescriptor( cFDString, uiIncrement, m_cColDirTracker ) );
+    m_auiIncrements[uiIndex] = uiIncrement;
+  }
+  TNOK( xCheck() );
+}
+
+
+ErrVal TEncSeqStructure::FrameSequencePart::xCheck()
+{
+  ROTS( m_acFrameDescriptors.empty() );
+
+  std::vector<bool> abCovered( m_acFrameDescriptors.size(), false );
+  for( UInt uiIndex = 0; uiIndex < m_acFrameDescriptors.size(); uiIndex++ )
+  {
+    const UInt uiInc = m_auiIncrements[uiIndex];
+    ROT( uiInc >= m_acFrameDescriptors.size() ); // error in config file parameter GOPFormatString
+    ROT( abCovered[ uiInc ] );
+    abCovered[uiInc] = true;
+  }
+
+  return Err::m_nOK;
+}
+
+
+TEncSeqStructure::GeneralSequencePart::GeneralSequencePart( const std::string& rcString )
+{
+  std::string cNoRepString;
+
+  UInt uiNumRep = 0;
+  TNOK( TEncFormattedStringParser::extractRepetitions( rcString, cNoRepString, uiNumRep ) );
+  xSetNumRep( uiNumRep );
+  UInt uiNumberOfParts = 0;
+  TNOK( TEncFormattedStringParser::getNumberOfParts( cNoRepString, uiNumberOfParts ) );
+  TOF( uiNumberOfParts );
+
+  //----- create array -----
+  m_apcSequenceParts.resize( uiNumberOfParts );
+
+  //----- initialize array -----
+  UInt uiIndex;
+  size_t uiPos;
+  for( uiPos = 0, uiIndex = 0; uiIndex < uiNumberOfParts; uiIndex++ )
+  {
+    std::string cPartString;
+
+    TNOK( TEncFormattedStringParser::extractPart( cNoRepString, cPartString, uiPos ) );
+
+    if( TEncFormattedStringParser::isFrameSequencePart( cPartString ) )
+    {
+      m_apcSequenceParts[uiIndex] = new FrameSequencePart( cPartString );
+    }
+    else
+    {
+      m_apcSequenceParts[uiIndex] = new GeneralSequencePart( cPartString );
+    }
+  }
+}
+
+
+TEncSeqStructure::TEncSeqStructure()
+: m_pcSequencePart( NULL )
+{
+}
+
+TEncSeqStructure::~TEncSeqStructure()
+{
+  delete m_pcSequencePart; m_pcSequencePart = NULL ;
+}
+
+ErrVal TEncSeqStructure::init( const std::string& rcString )
+{
+  std::string cStringWithoutWhitespace;
+  for( UInt ui = 0; ui < rcString.length(); ui++ )
+  {
+    if( rcString[ui] != ' ' && rcString[ui] != '\t' )
+    {
+      cStringWithoutWhitespace += rcString[ui];
+    }
+  }
+
+  if( cStringWithoutWhitespace.find( "*n{" ) == std::string::npos )
+  {
+    cStringWithoutWhitespace = "*n{" + cStringWithoutWhitespace + "}";
+  }
+  m_pcSequencePart = new GeneralSequencePart( cStringWithoutWhitespace );
+
+  return Err::m_nOK;
+}
+
+
+UInt TEncSeqStructure::getMaxAbsPocDiff( const UInt uiNumberOfFrames )
+{
+  TEncSeqStructure::Iterator cSeqIter = TEncSeqStructure::Iterator( *this, PicOrderCnt( 0 ), 0 );
+
+  UInt uiMaxAbsPocDiff = 0;
+  Int64 iLastPoc = cSeqIter.getPoc();
+  int iNumFramesLeft = uiNumberOfFrames;
+
+  for( int iIndex = 0; 0 != iNumFramesLeft; ++cSeqIter, iIndex++ )
+  {
+    Int64 iPoc = cSeqIter.getPoc();
+    if( iPoc >= uiNumberOfFrames )
+    {
+      // skiped due to frame behind end of sequence
+      continue;
+    }
+    iNumFramesLeft--;
+    //----- check POC differences -----
+    UInt uiAbsFrameDiffRef = (UInt) gAbs( iPoc - iLastPoc );
+    if( uiMaxAbsPocDiff < uiAbsFrameDiffRef  )
+    {
+      uiMaxAbsPocDiff = uiAbsFrameDiffRef;
+    }
+    iLastPoc = iPoc;
+  }
+
+  return uiMaxAbsPocDiff;
+}
+
+TEncSeqStructure::Iterator::Iterator( const TEncSeqStructure &r, PicOrderCnt cLayerChangeStartPoc, int iLayerOffset )
+: m_cBasePoc( 0 )
+, m_cLayerChangeStartPoc( cLayerChangeStartPoc )
+, m_iLayerOffset( iLayerOffset )
+{
+  m_acSeqPartPath.resize( 1 );
+  xGetCurr().m_pcSeqPart = r.m_pcSequencePart;
+  xGetCurr().m_uiCurrPos = 0;
+  xGoToLeaf( false );
+}
+
+void TEncSeqStructure::Iterator::xGoToLeaf( bool bGoToRightmostLeaf )
+{
+  while( !xGetCurr().m_pcSeqPart->isLeafNode() )
+  {
+    SequencePartWithPos cPartWithPos;
+    cPartWithPos.m_pcSeqPart = xGetCurr().m_pcSeqPart->getChildNode( xGetCurr().m_uiCurrPos );
+    cPartWithPos.m_uiCurrPos = 0;
+    if( bGoToRightmostLeaf )
+    {
+      TOT( cPartWithPos.m_pcSeqPart->isInfinitelyLong() );
+      cPartWithPos.m_uiCurrPos = cPartWithPos.m_pcSeqPart->getSize() - 1;
+    }
+    m_acSeqPartPath.push_back( cPartWithPos );
+  }
+}
+
+
+TEncSeqStructure::Iterator& TEncSeqStructure::Iterator::operator++()
+{
+  ++xGetCurr().m_uiCurrPos;
+  if( !xGetCurr().m_pcSeqPart->isInfinitelyLong() && xGetCurr().m_uiCurrPos == xGetCurr().m_pcSeqPart->getSize() )
+  {
+    xGoToNextFrameSequencePart();
+    xGetCurr().m_uiCurrPos = 0;
+  }
+  return *this;
+}
+
+
+TEncSeqStructure::Iterator& TEncSeqStructure::Iterator::traverseByPocDiff( Int64 iPocDiff )
+{
+  const PicOrderCnt cTargetPoc = getPoc() + iPocDiff;
+  const Int64 iIncrement = Int64( xGetCurr().m_pcSeqPart->getIncrement( xGetCurr().m_uiCurrPos ) );
+  if( iIncrement + iPocDiff < 0 )
+  {
+    xGoToPreviousFrameSequencePart();
+    const Int64 iNewIncrement = Int64( xGetCurr().m_pcSeqPart->getIncrement( xGetCurr().m_uiCurrPos ) );
+    const Int64 iNewSize = Int64( xGetCurr().m_pcSeqPart->getSize() );
+    traverseByPocDiff( iPocDiff + iIncrement + iNewSize - iNewIncrement );
+    TOF( cTargetPoc == getPoc() );
+    return *this;
+  }
+
+  if( !xGetCurr().m_pcSeqPart->isInfinitelyLong() )
+  {
+    const Int64 iSize = Int64( xGetCurr().m_pcSeqPart->getSize() );
+    if( iIncrement + iPocDiff >= iSize )
+    {
+      xGoToNextFrameSequencePart();
+      traverseByPocDiff( iPocDiff - ( iSize - iIncrement ) );
+      TOF( cTargetPoc == getPoc() );
+      return *this;
+    }
+  }
+
+  UInt64 uiPocDiffToFind = UInt64( iIncrement + iPocDiff );
+  bool bFound = false;
+  xGetCurr().m_uiCurrPos = xGetCurr().m_pcSeqPart->findIncrement( uiPocDiffToFind, bFound );
+  TOF( bFound );
+  TOF( cTargetPoc == getPoc() );
+  return *this;
+}
+
+
+TEncSeqStructure::Iterator TEncSeqStructure::Iterator::getIterByPocDiff( Int64 iPocDiff ) const
+{
+  Iterator cCopy = *this;
+  cCopy.traverseByPocDiff( iPocDiff );
+  return cCopy;
+}
+
+
+void TEncSeqStructure::Iterator::xGoToPreviousFrameSequencePart()
+{
+  TOF( xGetCurr().m_pcSeqPart->isLeafNode() );
+  TOF( m_acSeqPartPath.size() > 1 );
+  m_acSeqPartPath.pop_back();
+  while( xGetCurr().m_uiCurrPos == 0 )
+  {
+    TOF( m_acSeqPartPath.size() > 1 );
+    m_acSeqPartPath.pop_back();
+  }
+  xGetCurr().m_uiCurrPos--;
+  xGoToLeaf( true );
+  m_cBasePoc -= xGetCurr().m_pcSeqPart->getSize();
+}
+
+
+void TEncSeqStructure::Iterator::xGoToNextFrameSequencePart()
+{
+  TOF( xGetCurr().m_pcSeqPart->isLeafNode() );
+  TOT( xGetCurr().m_pcSeqPart->isInfinitelyLong() );
+  m_cBasePoc += xGetCurr().m_pcSeqPart->getSize();
+  m_acSeqPartPath.pop_back();
+  while( !xGetCurr().m_pcSeqPart->isInfinitelyLong() && xGetCurr().m_uiCurrPos == xGetCurr().m_pcSeqPart->getSize() - 1 )
+  {
+    TOF( m_acSeqPartPath.size() > 1 );
+    m_acSeqPartPath.pop_back();
+  }
+  xGetCurr().m_uiCurrPos++;
+  xGoToLeaf( false );
+}
+
+
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncSeqStructure.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncSeqStructure.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncSeqStructure.h	(revision 19)
@@ -0,0 +1,260 @@
+/* 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 !defined(AFX_TEncSeqStructure_H__268768B8_4D1D_484A_904E_586985833BAC__INCLUDED_)
+#define AFX_TEncSeqStructure_H__268768B8_4D1D_484A_904E_586985833BAC__INCLUDED_
+
+#include <cctype>
+#include "../TLibCommon/CommonDef.h"
+#include <vector>
+
+#include <map>
+
+
+class FrameDescriptor
+{
+public:
+  ErrVal initFrameDescriptor( const std::string&  rcString, UInt &ruiIncrement, std::map<UInt, UInt>& cColDirTracker);
+
+  const std::vector<int>& getAllowedRelativeRefPocs( RefPicList eRefPicList, UInt uiViewIdx ) const {
+    assert( eRefPicList == REF_PIC_LIST_0 || eRefPicList == REF_PIC_LIST_1 );
+    assert( m_aaiAllowedRelativeRefPocsL0.size() == m_aaiAllowedRelativeRefPocsL1.size() );
+    if( m_aaiAllowedRelativeRefPocsL0.size() <= uiViewIdx )
+    {
+      return eRefPicList == REF_PIC_LIST_0 ? m_aaiAllowedRelativeRefPocsL0.back() : m_aaiAllowedRelativeRefPocsL1.back();
+    }
+    return eRefPicList == REF_PIC_LIST_0 ? m_aaiAllowedRelativeRefPocsL0[uiViewIdx]: m_aaiAllowedRelativeRefPocsL1[uiViewIdx];
+  }
+
+  const std::vector<int>& getAllowedReferenceViewIdx( RefPicList eRefPicList, UInt uiViewIdx  ) const {
+    assert( eRefPicList == REF_PIC_LIST_0 || eRefPicList == REF_PIC_LIST_1 );
+    assert( m_aaiAllowedReferenceViewIdxL0.size() == m_aaiAllowedReferenceViewIdxL1.size() );
+    if( m_aaiAllowedReferenceViewIdxL0.size() <= uiViewIdx )
+    {
+      return eRefPicList == REF_PIC_LIST_0 ? m_aaiAllowedReferenceViewIdxL0.back() : m_aaiAllowedReferenceViewIdxL1.back();
+    }
+    return eRefPicList == REF_PIC_LIST_0 ? m_aaiAllowedReferenceViewIdxL0[uiViewIdx]: m_aaiAllowedReferenceViewIdxL1[uiViewIdx];
+  }
+
+  UInt getTEncSeqStructureLayer(UInt uiViewIdx)  const {
+    if (m_auiLayer.size() <= uiViewIdx)
+    {
+      return m_auiLayer.back();
+    }
+    return m_auiLayer[uiViewIdx];
+  }
+
+  bool getStoreForRef(UInt uiViewIdx)            const {
+    if (m_abStoreForRef.size() <= uiViewIdx)
+    {
+      return m_abStoreForRef.back();
+    }
+    return m_abStoreForRef[uiViewIdx];
+  }
+  bool isIdr(UInt uiViewIdx)                     const {
+    if (m_abIsIDR.size() <= uiViewIdx)
+    {
+      return m_abIsIDR.back();
+    }
+    return m_abIsIDR[uiViewIdx];
+  }
+  SliceType getSliceType(UInt uiViewIdx)        const {
+    if (m_aeSliceType.size() <= uiViewIdx)
+    {
+      return m_aeSliceType.back();
+    }
+    return m_aeSliceType[uiViewIdx];
+  }
+
+  UInt getColDir()  const { return m_uiColDir ; }
+
+  void addLayerOffset( Int iLayerOffset ) {
+     for(Int i = 0; i<m_auiLayer.size(); i++)
+     {
+       m_auiLayer[i] += iLayerOffset ;
+     }
+  }
+
+private:
+  std::vector<bool> m_abStoreForRef;
+  std::vector<bool> m_abIsIDR;
+  std::vector<UInt> m_auiLayer;
+  std::vector<SliceType>  m_aeSliceType;
+  std::vector< std::vector<int> > m_aaiAllowedRelativeRefPocsL0;
+  std::vector< std::vector<int> > m_aaiAllowedRelativeRefPocsL1;
+  std::vector< std::vector<int> > m_aaiAllowedReferenceViewIdxL0;
+  std::vector< std::vector<int> > m_aaiAllowedReferenceViewIdxL1;
+  UInt m_uiColDir ;
+
+};
+class TEncSeqStructure
+{
+private:
+  class SequencePart
+  {
+    DISABLE_DEFAULT_CPYCTOR_AND_ASOP( SequencePart );
+  protected:
+    SequencePart() : m_uiNumberOfRepetitions( 0 ) {}
+
+  public:
+    virtual ~SequencePart() {}
+
+    virtual bool isLeafNode() const = 0;
+    virtual SequencePart* getChildNode( UInt64 ui ) const { TOT( 1 ); return NULL; }
+    virtual const FrameDescriptor* getFrameDescriptor( UInt64 ui ) const { TOT( 1 ); return NULL; }
+
+    UInt64 getSize() const { TOT( isInfinitelyLong() ); return UInt64( m_uiNumberOfRepetitions ) * xGetSize(); }
+    UInt64 getIncrement( UInt64 ui ) const { return ui - UInt64( xGetIdx( ui ) ) + UInt64( xGetIncrement( ui ) ); }
+//    bool isInfinitelyLong() const { return m_uiNumberOfRepetitions == TypeLimits<UInt>::m_iMax; }
+    bool isInfinitelyLong() const { return m_uiNumberOfRepetitions == MAX_UINT; }
+
+    virtual UInt64 findIncrement( UInt64 uiIncrement, bool &rbSuccess ) const { TOT( 1 ); return 0; }
+
+  protected:
+    UInt xGetIdx( UInt64 ui ) const { return UInt( ui % xGetSize() ); }
+    void xSetNumRep( UInt ui )
+    {
+      TOT( m_uiNumberOfRepetitions );
+      TOF( ui );
+      m_uiNumberOfRepetitions = ui;
+    }
+
+  private:
+    virtual UInt   xGetIncrement( UInt64 ui ) const { TOT( 1 ); return 0; }
+    virtual UInt64 xGetSize() const = 0;
+
+    UInt m_uiNumberOfRepetitions; //GT: *n5{...}
+  };
+
+
+  class FrameSequencePart : public SequencePart //GT: Sequence of Frames without repetitions
+  {
+  public:
+    FrameSequencePart( const std::string& rcString );
+    virtual ~FrameSequencePart() {}
+
+    UInt64 xGetSize() const { return UInt64( m_acFrameDescriptors.size() ); }
+    bool isLeafNode() const { return true; }
+    const FrameDescriptor* getFrameDescriptor( UInt64 ui ) const { return &m_acFrameDescriptors[xGetIdx( ui )]; }
+    UInt xGetIncrement( UInt64 ui ) const { return m_auiIncrements[xGetIdx( ui )]; }
+    virtual UInt64 findIncrement( UInt64 uiIncrement, bool &rbSuccess ) const;
+
+  private:
+    ErrVal xCheck();
+
+    std::vector<FrameDescriptor> m_acFrameDescriptors; //GT: one descriptor for each frame B3L2(-4,+3)
+    std::vector<UInt> m_auiIncrements;                 //GT: same size as frame descriptor, stores increments  P7L1(-8)B3L2(-4,+3)b0L4(-2,+2,+6) -> 1 3 0
+
+    std::map<UInt,UInt> m_cColDirTracker ;
+  };
+
+
+  class GeneralSequencePart : public SequencePart  //GT: Sequence of FrameSequences
+  {
+  public:
+    GeneralSequencePart( const std::string& rcString );
+    virtual ~GeneralSequencePart() {}
+
+    UInt64 xGetSize() const { return UInt64( m_apcSequenceParts.size() ); }
+    bool isLeafNode() const { return false; }
+    SequencePart* getChildNode( UInt64 ui ) const { return m_apcSequenceParts[xGetIdx( ui )]; }
+
+  private:
+    AutoDeletePtrVector<SequencePart> m_apcSequenceParts;
+  };
+
+public:
+  TEncSeqStructure();
+  virtual ~TEncSeqStructure();
+
+  ErrVal init( const std::string& rcString );
+  UInt getMaxAbsPocDiff( const UInt uiNumberOfFrames );
+  UInt getDecodedPictureBufferSize( const UInt uiNumberOfFrames );
+  class Iterator
+  {
+  private:
+    class SequencePartWithPos
+    {
+    public:
+      const SequencePart *m_pcSeqPart;
+      UInt64 m_uiCurrPos;
+    };
+
+  public:
+    Iterator() : m_cBasePoc( 0 ) {}
+    virtual ~Iterator() {}
+
+    Iterator( const TEncSeqStructure &r, PicOrderCnt cLayerChangeStartPoc, int iLayerOffset );
+
+    FrameDescriptor getFrameDescriptor() const
+    {
+      if( m_iLayerOffset != 0 && getPoc() >= m_cLayerChangeStartPoc )
+      {
+        FrameDescriptor cModified = *xGetCurr().m_pcSeqPart->getFrameDescriptor( xGetCurr().m_uiCurrPos );
+        cModified.addLayerOffset ( m_iLayerOffset );
+        return cModified;
+      }
+      return *xGetCurr().m_pcSeqPart->getFrameDescriptor( xGetCurr().m_uiCurrPos );
+    }
+
+    PicOrderCnt getPoc() const { return m_cBasePoc + xGetCurr().m_pcSeqPart->getIncrement( xGetCurr().m_uiCurrPos ); }
+
+    Iterator& operator++();
+    Iterator& traverseByPocDiff( Int64 iPocDiff );
+    Iterator getIterByPocDiff( Int64 iPocDiff ) const;
+
+  private:
+    SequencePartWithPos&       xGetCurr()       { return m_acSeqPartPath.back(); }
+    const SequencePartWithPos& xGetCurr() const { return m_acSeqPartPath.back(); }
+
+    void xGoToPreviousFrameSequencePart();
+    void xGoToNextFrameSequencePart();
+
+    void xGoToLeaf( bool bGoToRightmostLeaf );
+
+    std::vector<SequencePartWithPos> m_acSeqPartPath;
+    PicOrderCnt m_cBasePoc;
+    PicOrderCnt m_cLayerChangeStartPoc;
+    int m_iLayerOffset;
+  };
+
+private:
+  SequencePart *m_pcSequencePart;
+};
+
+
+
+
+#endif // !defined(AFX_TEncSeqStructure_H__268768B8_4D1D_484A_904E_586985833BAC__INCLUDED_)
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 19)
@@ -0,0 +1,758 @@
+/* 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     TEncSlice.cpp
+    \brief    slice encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSlice.h"
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSlice::TEncSlice()
+{
+  m_apcPicYuvPred = NULL;
+  m_apcPicYuvResi = NULL;
+
+  m_pdRdPicLambda = NULL;
+  m_pdRdPicQp     = NULL;
+  m_piRdPicQp     = NULL;
+}
+
+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; }
+}
+
+Void TEncSlice::init( TEncTop* pcEncTop )
+{
+  m_pcCfg             = pcEncTop;
+  m_pcListPic         = pcEncTop->getListPic();
+
+  m_pcPicEncoder      = pcEncTop->getPicEncoder();
+  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
+ .
+ \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
+ */
+Void TEncSlice::initEncSlice( TComPic* pcPic, TComSlice*& rpcSlice )
+{
+  Double dQP;
+  Double dLambda;
+
+  rpcSlice = pcPic->getSlice(0);
+  rpcSlice->setSliceBits(0);
+  rpcSlice->setPic( pcPic );
+  rpcSlice->initSlice();
+  rpcSlice->setPOC( pcPic->getPOC() );
+
+  // slice type
+  SliceType eSliceType  = pcPic->getSliceType()  ;
+  rpcSlice->setSliceType    ( eSliceType );
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // Non-referenced frame marking
+  // ------------------------------------------------------------------------------------------------------------------
+
+  rpcSlice->setReferenced(pcPic->getReferenced()) ;
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // QP setting
+  // ------------------------------------------------------------------------------------------------------------------
+
+  Double dOrigQP = double(pcPic->getQP());
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // Lambda computation
+  // ------------------------------------------------------------------------------------------------------------------
+
+  Int iQP;
+
+  // pre-compute lambda and QP values for all possible QP candidates
+#if QC_MOD_LCEC_RDOQ
+  m_pcTrQuant->setRDOQOffset(1);
+#endif
+
+  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->getRateGOPSize() - 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)
+    if(eSliceType == I_SLICE || eSliceType == P_SLICE )
+    {
+      if ( m_pcCfg->getUseRDOQ() && rpcSlice->isIntra() && dQP == dOrigQP )
+      {
+        dLambda = 0.57 * pow( 2.0, qp_temp/3.0 );
+      }
+      else
+      {
+        if ( NumberBFrames > 0 ) // HB structure or HP structure
+        {
+          dLambda = 0.68 * pow( 2.0, qp_temp/3.0 );
+        }
+        else                     // IPP structure
+        {
+          dLambda = 0.85 * pow( 2.0, qp_temp/3.0 );
+        }
+      }
+      dLambda *= dLambda_scale;
+    }
+    else // P or B slices for HB or HP structure
+    {
+      dLambda = 0.68 * pow( 2.0, qp_temp/3.0 );
+      if ( pcPic->getSlice(0)->isInterB () )
+      {
+#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 ( rpcSlice->isReferenced() ) // HB structure and referenced
+        {
+          dLambda *= 0.80;
+          dLambda *= dLambda_scale;
+        }
+      }
+      else
+      {
+        dLambda *= dLambda_scale;
+      }
+    }
+    // if hadamard is used in ME process
+    if ( !m_pcCfg->getUseHADME() ) dLambda *= 0.95;
+
+    iQP = Max( MIN_QP, 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];
+
+  // store lambda
+#if HHI_VSO
+  m_pcRdCost->setUseLambdaScaleVSO  ( (m_pcCfg->getUseVSO() ||  m_pcCfg->getForceLambdaScaleVSO()) && m_pcCfg->isDepthCoder()  );
+  m_pcRdCost->setLambdaVSO( dLambda * m_pcCfg->getLambdaScaleVSO() );
+#endif
+
+  m_pcRdCost ->setLambda      ( dLambda );
+  m_pcTrQuant->setLambda      ( dLambda );
+  rpcSlice   ->setLambda      ( dLambda );
+#if HHI_INTER_VIEW_MOTION_PRED
+  m_pcRdCost ->setLambdaMVReg ( dLambda * m_pcCfg->getMultiviewMvRegLambdaScale() );
+#endif
+
+//#if HB_LAMBDA_FOR_LDC
+//  // restore original slice type
+//  if ( m_pcCfg->getUseLDC() )
+//  {
+//    eSliceType = P_SLICE;
+//  }
+//  eSliceType = (iPOCLast == 0 || uiPOCCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+//
+//  rpcSlice->setSliceType        ( eSliceType );
+//#endif
+
+  rpcSlice->setSliceQp          ( iQP );
+  rpcSlice->setSliceQpDelta     ( 0 );
+  rpcSlice->setNumRefIdx        ( REF_PIC_LIST_0, eSliceType == I_SLICE ? 0 : pcPic->getNumRefs(REF_PIC_LIST_0) ) ;
+  rpcSlice->setNumRefIdx        ( REF_PIC_LIST_1, eSliceType == I_SLICE ? 0 : pcPic->getNumRefs(REF_PIC_LIST_1) ) ;
+
+  rpcSlice->setSymbolMode       ( m_pcCfg->getSymbolMode());
+  rpcSlice->setLoopFilterDisable( m_pcCfg->getLoopFilterDisable() );
+
+  rpcSlice->setDepth            ( 0 );
+  rpcSlice->setViewIdx          ( pcPic->getViewIdx() );
+
+  rpcSlice->setColDir( pcPic->getColDir());
+
+  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() );
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncSlice::setSearchRange( TComSlice* pcSlice )
+{
+  Int iCurrPOC = pcSlice->getPOC();
+  Int iRefPOC;
+  Int iRateGOPSize = m_pcCfg->getRateGOPSize();
+  Int iOffset = (iRateGOPSize >> 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)/iRateGOPSize);
+      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;
+  Double dSumCURdCostBest;
+  UInt64     uiPicDistBest;
+  UInt64     uiPicBitsBest;
+  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);
+#if HHI_VSO
+  m_pcRdCost      ->setFrameLambdaVSO( dFrameLambda * m_pcCfg->getLambdaScaleVSO() );
+#endif
+
+  // for each QP candidate
+  for ( UInt uiQpIdx = 0; uiQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; uiQpIdx++ )
+  {
+    pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdx] );
+    m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+    m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#if HHI_INTER_VIEW_MOTION_PRED
+    m_pcRdCost    ->setLambdaMVReg         ( m_pdRdPicLambda[uiQpIdx] * m_pcCfg->getMultiviewMvRegLambdaScale() );
+#endif
+
+    // try compress
+    compressSlice   ( rpcPic );
+
+    Double dPicRdCost;
+    UInt64 uiPicDist        = m_uiPicDist;
+    UInt64 uiALFBits        = 0;
+
+    m_pcPicEncoder->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;
+      dSumCURdCostBest = m_dPicRdCost;
+
+      uiPicBitsBest = m_uiPicTotalBits + uiALFBits;
+      uiPicDistBest = uiPicDist;
+    }
+  }
+
+  // set best values
+  pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdxBest] );
+  m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+  m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#if HHI_INTER_VIEW_MOTION_PRED
+  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;
+  UInt64 uiBitsCoded            = 0;
+  TEncBinCABAC* pppcRDSbacCoder = NULL;
+  TComSlice* pcSlice            = rpcPic->getSlice(getSliceIdx());
+  xDetermineStartAndBoundingCUAddr ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, false );
+
+#ifdef WEIGHT_PRED
+  //------------------------------------------------------------------------------
+  //  Weighted Prediction parameters estimation.
+  //------------------------------------------------------------------------------
+  // calculate AC/DC values for current picture
+  if( pcSlice->getPPS()->getUseWP() || pcSlice->getPPS()->getWPBiPredIdc() )
+    xCalcACDCParamSlice(pcSlice);
+
+  Bool	wp_Explicit =  (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPredIdc()==1);
+  Bool	wp_Implicit = (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPredIdc()==2);
+
+  if ( wp_Explicit || wp_Implicit )
+  {
+	//------------------------------------------------------------------------------
+	//  Weighted Prediction implemented at Slice level, sliceMode=2 only.
+	//------------------------------------------------------------------------------
+    if ( pcSlice->getSliceMode()==2 || pcSlice->getEntropySliceMode()==2 )
+    {
+      printf("Weighted Prediction not implemented with slice mode determined by max number of bins.\n"); exit(0);
+    }
+
+    if( wp_Explicit )
+      xEstimateWPParamSlice(pcSlice);
+
+    pcSlice->initWpScaling();
+    pcSlice->displayWpScaling();
+  }
+#endif
+
+  // initialize cost values
+  m_uiPicTotalBits  = 0;
+  m_dPicRdCost      = 0;
+  m_uiPicDist       = 0;
+
+  // 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_pcCavlcCoder  ->setAdaptFlag    ( false );
+    m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+    m_pcEntropyCoder->resetEntropy      ();
+    m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+  }
+
+  // initialize ALF parameters
+  m_pcEntropyCoder->setAlfCtrl(false);
+  m_pcEntropyCoder->setMaxAlfCtrlDepth(0); //unnecessary
+
+  // for every CU in slice
+  for(  uiCUAddr = uiStartCUAddr; uiCUAddr < uiBoundingCUAddr; uiCUAddr++  )
+  {
+    // set QP
+    m_pcCuEncoder->setQpLast( pcSlice->getSliceQp() );
+    // initialize CU encoder
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+    pcCU->initCU( rpcPic, uiCUAddr );
+
+    // 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    ( m_pcBitCounter );
+
+      // 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    ( m_pcBitCounter );
+      pppcRDSbacCoder->setBinCountingEnableFlag( true );
+
+      m_pcCuEncoder->encodeCU( pcCU );
+
+      pppcRDSbacCoder->setBinCountingEnableFlag( false );
+      uiBitsCoded += m_pcBitCounter->getNumberOfWrittenBits();
+      if (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE && ( ( pcSlice->getSliceBits() + uiBitsCoded ) >> 3 ) > m_pcCfg->getSliceArgument())
+      {
+        if (uiCUAddr==uiStartCUAddr && pcSlice->getSliceBits()==0)
+        {
+          // Could not fit even a single LCU within the slice under the defined byte-constraint. Display a warning message and code 1 LCU in the slice.
+          fprintf(stdout,"\nSlice overflow warning! codedBits=%6d, limitBytes=%6d", m_pcBitCounter->getNumberOfWrittenBits(), m_pcCfg->getSliceArgument() );
+          uiCUAddr = uiCUAddr + 1;
+        }
+        pcSlice->setNextSlice( true );
+        break;
+      }
+
+      UInt uiBinsCoded = pppcRDSbacCoder->getBinsCoded();
+      if (m_pcCfg->getEntropySliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE && uiBinsCoded > m_pcCfg->getEntropySliceArgument())
+      {
+        if (uiCUAddr == uiStartCUAddr)
+        {
+          // Could not fit even a single LCU within the entropy slice under the defined byte-constraint. Display a warning message and code 1 LCU in the entropy slice.
+          fprintf(stdout,"\nEntropy Slice overflow warning! codedBins=%6d, limitBins=%6d", uiBinsCoded, m_pcCfg->getEntropySliceArgument() );
+          uiCUAddr = uiCUAddr + 1;
+        }
+        pcSlice->setNextEntropySlice( true );
+        break;
+      }
+    }
+    // other case: encodeCU is not called
+    else
+    {
+      m_pcCuEncoder->compressCU( pcCU );
+      m_pcCavlcCoder ->setAdaptFlag(true);
+      m_pcCuEncoder->encodeCU( pcCU );
+
+      uiBitsCoded += m_pcBitCounter->getNumberOfWrittenBits();
+      if (m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE && ( ( pcSlice->getSliceBits() + uiBitsCoded ) >> 3 ) > m_pcCfg->getSliceArgument())
+      {
+        if (uiCUAddr==uiStartCUAddr && pcSlice->getSliceBits()==0)
+        {
+          // Could not fit even a single LCU within the slice under the defined byte-constraint. Display a warning message and code 1 LCU in the slice.
+          fprintf(stdout,"\nSlice overflow warning! codedBits=%6d, limitBytes=%6d", m_pcBitCounter->getNumberOfWrittenBits(), m_pcCfg->getSliceArgument() );
+          uiCUAddr = uiCUAddr + 1;
+        }
+        pcSlice->setNextSlice( true );
+        break;
+      }
+
+      if (m_pcCfg->getEntropySliceMode()==SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE && uiBitsCoded > m_pcCfg->getEntropySliceArgument())
+      {
+        if (uiCUAddr == uiStartCUAddr)
+        {
+          // Could not fit even a single LCU within the entropy slice under the defined bit/bin-constraint. Display a warning message and code 1 LCU in the entropy slice.
+          fprintf(stdout,"\nEntropy Slice overflow warning! codedBits=%6d, limitBits=%6d", m_pcBitCounter->getNumberOfWrittenBits(), m_pcCfg->getEntropySliceArgument() );
+          uiCUAddr = uiCUAddr + 1;
+        }
+        pcSlice->setNextEntropySlice( true );
+        break;
+      }
+      m_pcCavlcCoder ->setAdaptFlag(false);
+    }
+
+    m_uiPicTotalBits += pcCU->getTotalBits();
+    m_dPicRdCost     += pcCU->getTotalCost();
+    m_uiPicDist      += pcCU->getTotalDistortion();
+  }
+  pcSlice->setSliceCurEndCUAddr( uiCUAddr );
+  pcSlice->setEntropySliceCurEndCUAddr( uiCUAddr );
+  pcSlice->setSliceBits( (UInt)(pcSlice->getSliceBits() + uiBitsCoded) );
+}
+
+/**
+ \param  rpcPic        picture class
+ \retval rpcBitstream  bitstream class
+ */
+Void TEncSlice::encodeSlice   ( TComPic*& rpcPic, TComBitstream*& rpcBitstream )
+{
+  UInt       uiCUAddr;
+  UInt       uiStartCUAddr;
+  UInt       uiBoundingCUAddr;
+  xDetermineStartAndBoundingCUAddr  ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, true );
+  TComSlice* pcSlice = rpcPic->getSlice(getSliceIdx());
+
+  // choose entropy coder
+  Int iSymbolMode = pcSlice->getSymbolMode();
+  if (iSymbolMode)
+  {
+    m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+    m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+  }
+  else
+  {
+    m_pcCavlcCoder  ->setAdaptFlag( true );
+    m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+    m_pcEntropyCoder->resetEntropy();
+  }
+
+  // set bitstream
+  m_pcEntropyCoder->setBitstream( rpcBitstream );
+  // for every CU
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_V( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( rpcPic->getPOC() );
+  DTRACE_CABAC_T( "\n" );
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+  for(  uiCUAddr = uiStartCUAddr; uiCUAddr<uiBoundingCUAddr; uiCUAddr++  )
+  {
+    m_pcCuEncoder->setQpLast( pcSlice->getSliceQp() );
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+    if ( (m_pcCfg->getSliceMode()!=0 || m_pcCfg->getEntropySliceMode()!=0) && uiCUAddr==uiBoundingCUAddr-1 )
+    {
+      m_pcCuEncoder->encodeCU( pcCU, true );
+    }
+    else
+    {
+      m_pcCuEncoder->encodeCU( pcCU );
+    }
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#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;
+  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 ) ? (uiStartCUAddrSlice + uiCUAddrIncrement     ) : uiNumberOfCUsInFrame;
+      break;
+    case AD_HOC_SLICES_FIXED_NUMBER_OF_BYTES_IN_SLICE:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = pcSlice->getSliceCurEndCUAddr();
+      break;
+    default:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame;
+      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 ) ? (uiStartCUAddrSlice + uiCUAddrIncrement     ) : uiNumberOfCUsInFrame;
+      break;
+    default:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame;
+      break;
+    }
+    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+  }
+
+  // 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 ) ? (uiStartCUAddrEntropySlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame;
+      break;
+    case SHARP_MULTIPLE_CONSTRAINT_BASED_ENTROPY_SLICE:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrEntropySlice    = pcSlice->getEntropySliceCurEndCUAddr();
+      break;
+    default:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrEntropySlice    = uiNumberOfCUsInFrame;
+      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 ) ? (uiStartCUAddrEntropySlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame;
+      break;
+    default:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrEntropySlice    = uiNumberOfCUsInFrame;
+      break;
+    }
+    pcSlice->setEntropySliceCurEndCUAddr( uiBoundingCUAddrEntropySlice );
+  }
+
+  // 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) )
+    {
+      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: /tags/0.2r1/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncSlice.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncSlice.h	(revision 19)
@@ -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     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"
+#ifdef WEIGHT_PRED
+#include "WeightPredAnalysis.h"
+#endif
+
+class TEncTop;
+class TEncPic;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice encoder class
+class TEncSlice
+#ifdef WEIGHT_PRED
+  : public WeightPredAnalysis
+#endif
+{
+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
+  TEncPic*                m_pcPicEncoder;                       ///< Pic 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)
+  
+  UInt                    m_uiSliceIdx;
+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)
+  Void    initEncSlice        ( TComPic* pcPic, TComSlice*& rpcSlice );
+  
+  // 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, TComBitstream*& rpcBitstream  );      ///< entropy coding of slice
+  
+  // 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;                       }
+};
+
+
+#endif // __TENCSLICE__
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncTop.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncTop.cpp	(revision 19)
@@ -0,0 +1,820 @@
+/* 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     TEncTop.cpp
+    \brief    encoder class
+*/
+
+#include "../TLibCommon/CommonDef.h"
+#include "TEncTop.h"
+
+#include "TEncGOP.h"
+#include "../../App/TAppEncoder/TAppEncTop.h"
+
+// ====================================================================================================================
+// 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_bSeqFirst = true;
+  m_iFrameNumInCodingOrder = 0;
+}
+
+TEncTop::~TEncTop()
+{
+#if ENC_DEC_TRACE
+  fclose( g_hTrace );
+#endif
+}
+
+Void TEncTop::create ()
+{
+  // initialize global variables
+  if(m_uiViewId<1 && !m_bIsDepth)
+    initROM();
+
+  // create processing unit classes
+  m_cPicEncoder.        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 MTK_SAO
+  if (m_bUseSAO)
+  {
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+    m_cEncSAO.createEncBuffer();
+  }
+#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 );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_cResidualGenerator. create( false, getSourceWidth(), getSourceHeight(), g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiBitDepth + g_uiBitIncrement );
+#endif
+
+#if MQT_BA_RA && MQT_ALF_NPASS
+  if(m_bUseALF)
+  {
+    m_cAdaptiveLoopFilter.createAlfGlobalBuffers(m_iALFEncodePassReduction);
+  }
+#endif
+
+  // if SBAC-based RD optimization is used
+  if( m_bUseSBACRD )
+  {
+    UInt uiNumCEnc = 1 + Max( g_uiMaxCUDepth, AO_MAX_DEPTH ); // HS: prevents crash in SAO for small maximum CU sizes
+    m_pppcRDSbacCoder = new TEncSbac** [uiNumCEnc];
+    m_pppcBinCoderCABAC = new TEncBinCABAC** [uiNumCEnc];
+
+    for ( Int iDepth = 0; iDepth < uiNumCEnc; iDepth++ )
+    {
+      m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
+      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
+
+      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+      {
+        m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
+        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+        m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
+      }
+    }
+  }
+
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  if( g_aacWedgeLists.empty() && m_bUseDMM && m_bIsDepth )
+  {
+    initWedgeLists();
+  }
+#endif
+}
+
+Void TEncTop::destroy ()
+{
+#if MQT_BA_RA && MQT_ALF_NPASS
+  if(m_bUseALF)
+  {
+    m_cAdaptiveLoopFilter.destroyAlfGlobalBuffers();
+  }
+#endif
+
+  // destroy processing unit classes
+  m_cPicEncoder.        destroy();
+  m_cSliceEncoder.      destroy();
+  m_cCuEncoder.         destroy();
+#if MTK_SAO
+  if (m_cSPS.getUseSAO())
+  {
+    m_cEncSAO.destroy();
+    m_cEncSAO.destoryEncBuffer();
+  }
+#endif
+  m_cAdaptiveLoopFilter.destroy();
+  m_cLoopFilter.        destroy();
+#if DEPTH_MAP_GENERATION
+  m_cDepthMapGenerator. destroy();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_cResidualGenerator. destroy();
+#endif
+
+  // 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;
+  }
+
+  // destroy ROM
+  if(m_uiViewId<1 && !m_bIsDepth)
+    destroyROM();
+
+  return;
+}
+
+Void TEncTop::init( TAppEncTop* pcTAppEncTop )
+{
+  UInt *aTable4=NULL, *aTable8=NULL;
+#if QC_MOD_LCEC
+  UInt* aTableLastPosVlcIndex=NULL;
+#endif
+  // initialize SPS
+  xInitSPS();
+
+#if CONSTRAINED_INTRA_PRED
+  // initialize PPS
+  xInitPPS();
+#endif
+
+  // initialize processing unit classes
+  m_cPicEncoder.  init( this );
+  m_cSliceEncoder.init( this );
+  m_cCuEncoder.   init( this );
+
+  m_pcTAppEncTop = pcTAppEncTop;
+#if DEPTH_MAP_GENERATION
+  m_cDepthMapGenerator.init( (TComPrediction*)this->getPredSearch(), m_pcTAppEncTop->getSPSAccess(), m_pcTAppEncTop->getAUPicAccess() );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  m_cResidualGenerator.init( &m_cTrQuant, &m_cDepthMapGenerator );
+#endif
+
+  // initialize transform & quantization class
+  m_pcCavlcCoder = getCavlcCoder();
+#if !CAVLC_COEF_LRG_BLK
+  aTable8 = m_pcCavlcCoder->GetLP8Table();
+#endif
+  aTable4 = m_pcCavlcCoder->GetLP4Table();
+#if QC_MOD_LCEC
+  aTableLastPosVlcIndex=m_pcCavlcCoder->GetLastPosVlcIndexTable();
+
+  m_cTrQuant.init( g_uiMaxCUWidth, g_uiMaxCUHeight, 1 << m_uiQuadtreeTULog2MaxSize, m_iSymbolMode, aTable4, aTable8,
+    aTableLastPosVlcIndex, m_bUseRDOQ, true );
+#else
+  m_cTrQuant.init( g_uiMaxCUWidth, g_uiMaxCUHeight, 1 << m_uiQuadtreeTULog2MaxSize, m_iSymbolMode, aTable4, aTable8, m_bUseRDOQ, true );
+#endif
+
+  // initialize encoder search class
+  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_iFastSearch, 0, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
+  m_cSeqIter  = TEncSeqStructure::Iterator( m_cSequenceStructure, 0, 0 );
+  m_bPicWaitingForCoding = false ;
+
+#if MQT_ALF_NPASS
+  if(m_bUseALF)
+  {
+    m_cAdaptiveLoopFilter.setALFEncodePassReduction( m_iALFEncodePassReduction );
+  }
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+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, std::map<PicOrderCnt, TComPicYuv*>& rcMapPicYuvRecOut, TComBitstream* pcBitstreamOut, Bool& bNewPicNeeded )
+{
+
+  //  TComBitstream*  pcBitstreamOut ;
+  TComPicYuv*     pcPicYuvRecOut;
+  TComPic*        pcOrgRefList[2][MAX_REF_PIC_NUM];  //GT: not used?
+  TComPic*        pcPic ;
+
+  bool bSomethingCoded = false ;
+
+  if (m_bPicWaitingForCoding )
+  {
+    std::map<Int, TComPic*>::iterator cIter = m_acInputPicMap.find( (Int)m_cSeqIter.getPoc() );
+    const bool bPictureAvailable = cIter != m_acInputPicMap.end();
+    if (bPictureAvailable) //GT: it is possible that poc to code is not in input-picmap, but m_bPicWaitingForCoding is true, since current poc is beyond sequence-end
+    {
+      assert( m_acOutputPicMap.find( m_cSeqIter.getPoc() ) != m_acOutputPicMap.end() );
+      pcPicYuvRecOut = m_acOutputPicMap[m_cSeqIter.getPoc()];
+      m_acOutputPicMap.erase( m_cSeqIter.getPoc() );
+      pcPic          = cIter->second ;
+
+#if DEPTH_MAP_GENERATION
+      // add extra pic buffers
+      Bool  bNeedPrdDepthMapBuf = ( m_uiPredDepthMapGeneration > 0 );
+      if( bNeedPrdDepthMapBuf && !pcPic->getPredDepthMap() )
+      {
+        pcPic->addPrdDepthMapBuffer();
+      }
+#endif
+
+      // needed? dont think so
+      TComPicYuv      cPicOrg;
+      cPicOrg.create( pcPic->getPicYuvOrg()->getWidth(), pcPic->getPicYuvOrg()->getHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+      pcPic->getPicYuvOrg()->copyToPic( &cPicOrg );
+      xSetPicProperties( pcPic) ;
+      m_cPicEncoder.compressPic( pcBitstreamOut, cPicOrg, pcPic, pcPicYuvRecOut, pcOrgRefList,  m_bSeqFirst,  m_cListPic);
+      bSomethingCoded = true;
+      m_acInputPicMap.erase( cIter );
+      cPicOrg.destroy() ;
+      assert( rcMapPicYuvRecOut.find( pcPic->getPOC() ) == rcMapPicYuvRecOut.end() );
+      rcMapPicYuvRecOut[pcPic->getPOC()] = pcPicYuvRecOut;
+    }
+    else if(m_uiViewId==-1)
+      printf("\nPOC %4d skipped due to sequence end", Int(m_cSeqIter.getPoc()) );
+    else
+    {
+      if( m_bIsDepth )
+      {
+        printf("\nDepth View \t%4d\t POC %4d skipped due to sequence end", m_uiViewId, Int(m_cSeqIter.getPoc() ));
+      }
+      else
+      {
+        printf("\nView \t\t%4d\t POC %4d skipped due to sequence end", m_uiViewId, Int(m_cSeqIter.getPoc() ));
+      }
+    }
+    ++m_cSeqIter; //GT: increment, even bPictureAvailable might be false, (POC beyond sequence end);
+
+    Bool hitSeqEndButHasToCode = bEos && !m_acInputPicMap.empty();
+    if( (m_acInputPicMap.find( (Int)m_cSeqIter.getPoc() ) != m_acInputPicMap.end()) || hitSeqEndButHasToCode ) //GT: new poc also in InputList
+    {
+      m_bPicWaitingForCoding = true;
+      bNewPicNeeded = false ;
+    }
+    else
+    {
+      m_bPicWaitingForCoding = false;
+      bNewPicNeeded = true ;
+    }
+  }
+
+
+  if(bSomethingCoded && !m_bPicWaitingForCoding ) //GT: no gaps any more
+  {
+    m_uiNumAllPicCoded += m_iNumPicRcvd;
+    m_iNumPicRcvd       = 0;
+  }
+
+
+  if (bEos&&m_uiViewId==-1)
+  {
+    printOutSummary (m_uiNumAllPicCoded);
+  }
+}
+
+
+Void TEncTop::receivePic( bool bEos, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvRec, TComPicYuv* pcOrgPdmDepth )
+{
+  if( !m_bPicWaitingForCoding ) //GT: insert pcPicYuvOrg in m_acInputPicMap and m_cListPic
+  {
+    TComPic* pcPicCurr = NULL;
+    xGetNewPicBuffer( pcPicCurr ); //GT: assigns next POC to input pic and stores it in m_cListPic
+    pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+#if HHI_INTER_VIEW_MOTION_PRED
+    if( m_uiMultiviewMvRegMode )
+    {
+      AOF( pcOrgPdmDepth );
+      AOF( pcPicCurr->getOrgDepthMap() );
+      pcOrgPdmDepth->copyToPic( pcPicCurr->getOrgDepthMap() );
+    }
+    else
+    {
+      AOT( pcOrgPdmDepth );
+      AOT( pcPicCurr->getOrgDepthMap() );
+    }
+#endif
+    m_acInputPicMap.insert( std::make_pair(pcPicCurr->getPOC(), pcPicCurr)); //GT: input pic to m_acInputPicMap
+    assert( m_acOutputPicMap.find( pcPicCurr->getPOC() ) == m_acOutputPicMap.end() );
+    m_acOutputPicMap[pcPicCurr->getPOC()] = pcPicYuvRec;
+  }
+
+  bool hitSeqEndButHasToCode = bEos && !m_acInputPicMap.empty();  //GT: End of sequence has been reached, but still pictures to code left
+  m_bPicWaitingForCoding = m_bPicWaitingForCoding || hitSeqEndButHasToCode ;
+
+  if( m_acInputPicMap.find( (Int)m_cSeqIter.getPoc() ) != m_acInputPicMap.end() ) //GT: If poc to code is in input-picmap; not necessary
+  {
+    m_bPicWaitingForCoding = true;
+  }
+}
+
+
+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 )
+  {
+    pcPic->removeOriginalBuffer   ();
+#if HHI_INTER_VIEW_MOTION_PRED
+    pcPic->removeOrgDepthMapBuffer();
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    pcPic->removeResidualBuffer   ();
+#endif
+#if HHI_INTERVIEW_SKIP
+    pcPic->removeUsedPelsMapBuffer();
+#endif
+  }
+}
+
+
+#if AMVP_BUFFERCOMPRESS
+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();
+  }
+}
+#endif
+
+
+
+// ====================================================================================================================
+// 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);
+
+  // bug-fix - erase frame memory (previous GOP) which is not used for reference any more
+  if (m_cListPic.size() >=  m_uiCodedPictureStoreSize )  // 2)   //  K. Lee bug fix - for multiple reference > 2
+  {
+    rpcPic = m_cListPic.popFront();
+
+    // is it necessary without long-term reference?
+  }
+  else
+  {
+    rpcPic = new TComPic;
+    rpcPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  }
+
+  m_cListPic.pushBack( rpcPic );
+  rpcPic->setReconMark (false);
+
+  m_iPOCLast++;
+  m_iNumPicRcvd++;
+
+  rpcPic->addOriginalBuffer();
+#if HHI_INTER_VIEW_MOTION_PRED
+  if( m_uiMultiviewMvRegMode )
+  {
+    rpcPic->addOrgDepthMapBuffer();
+  }
+#endif
+
+#if HHI_INTERVIEW_SKIP
+  if( getInterViewSkip() )
+  {
+    rpcPic->addUsedPelsMapBuffer();
+  }
+#endif
+
+  rpcPic->setCurrSliceIdx( 0 ); // MW
+  rpcPic->getSlice(0)->setPOC( m_iPOCLast );
+
+  // mark it should be extended
+  rpcPic->getPicYuvRec()->setBorderExtension(false);
+}
+
+
+Void TEncTop::xInitSPS()
+{
+  m_cSPS.setWidth         ( m_iSourceWidth      );
+  m_cSPS.setHeight        ( m_iSourceHeight     );
+  m_cSPS.setPad           ( m_aiPad             );
+  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.setUseALF        ( m_bUseALF           );
+
+  m_cSPS.setQuadtreeTULog2MaxSize( m_uiQuadtreeTULog2MaxSize );
+  m_cSPS.setQuadtreeTULog2MinSize( m_uiQuadtreeTULog2MinSize );
+  m_cSPS.setQuadtreeTUMaxDepthInter( m_uiQuadtreeTUMaxDepthInter    );
+  m_cSPS.setQuadtreeTUMaxDepthIntra( m_uiQuadtreeTUMaxDepthIntra    );
+
+  m_cSPS.setUseDQP        ( m_iMaxDeltaQP != 0  );
+#if !HHI_NO_LowDelayCoding
+  m_cSPS.setUseLDC        ( m_bUseLDC           );
+#endif
+  m_cSPS.setUsePAD        ( m_bUsePAD           );
+
+  m_cSPS.setUseMRG        ( m_bUseMRG           ); // SOPH:
+
+#if LM_CHROMA
+  m_cSPS.setUseLMChroma   ( m_bUseLMChroma           );
+#endif
+
+  m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
+
+  if( m_bIsDepth )
+  {
+    m_cSPS.initMultiviewSPSDepth    ( m_uiViewId, m_iViewOrderIdx );
+#if DEPTH_MAP_GENERATION
+    m_cSPS.setPredDepthMapGeneration( m_uiViewId, true );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+    m_cSPS.setMultiviewResPredMode  ( 0 );
+#endif
+  }
+  else
+  {
+    m_cSPS.initMultiviewSPS           ( m_uiViewId, m_iViewOrderIdx, m_uiCamParPrecision, m_bCamParInSliceHeader, m_aaiCodedScale, m_aaiCodedOffset );
+    if( m_uiViewId )
+    {
+#if DEPTH_MAP_GENERATION
+#if HHI_INTER_VIEW_MOTION_PRED
+      m_cSPS.setPredDepthMapGeneration( m_uiViewId, false, m_uiPredDepthMapGeneration, m_uiMultiviewMvPredMode, m_uiPdmPrecision, m_aaiPdmScaleNomDelta, m_aaiPdmOffset );
+#else
+      m_cSPS.setPredDepthMapGeneration( m_uiViewId, false, m_uiPredDepthMapGeneration, 0, m_uiPdmPrecision, m_aaiPdmScaleNomDelta, m_aaiPdmOffset );
+#endif
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      m_cSPS.setMultiviewResPredMode  ( m_uiMultiviewResPredMode );
+#endif
+    }
+    else
+    {
+#if DEPTH_MAP_GENERATION
+      m_cSPS.setPredDepthMapGeneration( m_uiViewId, false );
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+      m_cSPS.setMultiviewResPredMode  ( 0 );
+#endif
+    }
+  }
+  m_cSPS.setSPSId( ( m_uiViewId << 1 ) + ( m_bIsDepth ? 1 : 0 ) );
+
+#if DCM_COMB_LIST
+  m_cSPS.setUseLComb    ( m_bUseLComb           );
+  m_cSPS.setLCMod       ( m_bLCMod   );
+#endif
+
+  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
+
+
+#if HHI_RMP_SWITCH
+  m_cSPS.setUseRMP( m_bUseRMP );
+#endif
+
+  m_cSPS.setBitDepth    ( g_uiBitDepth        );
+  m_cSPS.setBitIncrement( g_uiBitIncrement    );
+
+#if MTK_NONCROSS_INLOOP_FILTER
+  m_cSPS.setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+#endif
+#if MTK_SAO
+  m_cSPS.setUseSAO             ( m_bUseSAO         );
+#endif
+#if HHI_DMM_WEDGE_INTRA || HHI_DMM_PRED_TEX
+  m_cSPS.setUseDMM( m_bUseDMM );
+#endif
+#if HHI_MPI
+  m_cSPS.setUseMVI( m_bUseMVI );
+#endif
+
+  m_cSPS.setCodedPictureBufferSize( m_uiCodedPictureStoreSize );
+}
+
+#if CONSTRAINED_INTRA_PRED
+Void TEncTop::xInitPPS()
+{
+  m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
+  m_cPPS.setPPSId( ( m_uiViewId << 1 ) + ( m_bIsDepth ? 1 : 0 ) );
+  m_cPPS.setSPSId( ( m_uiViewId << 1 ) + ( m_bIsDepth ? 1 : 0 ) );
+
+#ifdef WEIGHT_PRED
+  m_cPPS.setUseWP( m_bUseWeightPred );
+  m_cPPS.setWPBiPredIdc( m_uiBiPredIdc );
+#endif
+}
+#endif
+
+
+Void TEncTop::setTEncTopList(std::vector<TEncTop*>* pacTEncTopList )
+{
+  assert(m_uiViewId!=-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_uiViewId==-1)
+    printf( "\n\nSUMMARY --------------------------------------------------------\n" );
+  else {
+    if ( m_bIsDepth )
+    {
+      printf( "\n\nSUMMARY ---------------------------------------------- DEPTH %2d\n", m_uiViewId );
+    }
+    else
+    {
+      printf( "\n\nSUMMARY ---------------------------------------------- VIDEO %2d\n", m_uiViewId );
+    }
+  };
+  m_cAnalyzeAll.printOut('a');
+
+  printf( "\n\nI Slices--------------------------------------------------------\n" );
+  m_cAnalyzeI.printOut('i');
+
+  printf( "\n\nP Slices--------------------------------------------------------\n" );
+  m_cAnalyzeP.printOut('p');
+
+  printf( "\n\nB Slices--------------------------------------------------------\n" );
+  m_cAnalyzeB.printOut('b');
+
+#if _SUMMARY_OUT_
+  m_cAnalyzeAll.printSummaryOut();
+#endif
+#if _SUMMARY_PIC_
+  m_cAnalyzeI.printSummary('I');
+  m_cAnalyzeP.printSummary('P');
+  m_cAnalyzeB.printSummary('B');
+#endif
+}
+
+Void TEncTop::xSetRefPics( TComPic* pcPic, RefPicList eRefPicList )
+{
+  assert(m_cSeqIter.getFrameDescriptor().getAllowedRelativeRefPocs( eRefPicList, pcPic->getViewIdx() ).size() == m_cSeqIter.getFrameDescriptor().getAllowedReferenceViewIdx( eRefPicList, pcPic->getViewIdx()).size());
+#if 1
+  // check if refPic is available
+  Int iNumberOfRefs = 0;
+  std::vector<Int> aiRefPocs ;
+  std::vector<Int> aiRefViews ;
+
+  for( Int i=0; i<(Int)m_cSeqIter.getFrameDescriptor().getAllowedRelativeRefPocs( eRefPicList, pcPic->getViewIdx() ).size(); i++ )
+  {
+    Int iRefPoc  = m_cSeqIter.getFrameDescriptor().getAllowedRelativeRefPocs( eRefPicList, pcPic->getViewIdx() )[i]+pcPic->getPOC() ;
+    Int iRefViewIdx = m_cSeqIter.getFrameDescriptor().getAllowedReferenceViewIdx( eRefPicList, pcPic->getViewIdx() )[i];
+    Bool bFoundRefPic = false;
+
+    if( iRefPoc == pcPic->getPOC() ) // interview
+    {
+      assert( iRefViewIdx < (Int)m_uiViewId );
+      aiRefPocs.push_back(iRefPoc);
+      aiRefViews.push_back(iRefViewIdx);
+      iNumberOfRefs++ ;
+      bFoundRefPic = true ;
+      continue;
+    }
+    else if ( iRefViewIdx < 0 ) // temporal
+    {
+      for( TComList<TComPic*>::iterator it = m_cListPic.begin(); it!=m_cListPic.end(); it++)
+      {
+        if( (*it)->getViewIdx() == pcPic->getViewIdx() && (*it)->getPOC() == iRefPoc && (*it)->getReconMark() )
+        {
+          aiRefPocs.push_back(iRefPoc);
+          aiRefViews.push_back(m_uiViewId);
+          bFoundRefPic = true ;
+          iNumberOfRefs++ ;
+          break;
+        }
+      }
+      if( (iRefPoc < pcPic->getPOC()) && !bFoundRefPic )
+      {
+        printf("\nInconsistence in GOP-String!");
+        assert(0);
+      }
+    }
+  }
+  for ( Int i=0; i< iNumberOfRefs; i++)
+  {
+    pcPic->setRefViewIdx( aiRefViews[i], eRefPicList, i );
+    pcPic->setRefPOC(aiRefPocs[i], eRefPicList, i );
+  }
+  pcPic->setNumRefs( iNumberOfRefs, eRefPicList );
+#else
+  for( Int i=0; i<(Int)m_cSeqIter.getFrameDescriptor().getAllowedRelativeRefPocs( eRefPicList, pcPic->getViewIdx() ).size(); i++ )
+  {
+    const int iRefViewIdx = m_cSeqIter.getFrameDescriptor().getAllowedReferenceViewIdx( eRefPicList, pcPic->getViewIdx() )[i];
+    if( iRefViewIdx < 0 )
+    {
+      // temporal reference from current view
+      pcPic->setRefViewIdx( m_iViewIdx, eRefPicList, i );
+    }
+    else
+    {
+      pcPic->setRefViewIdx( iRefViewIdx, eRefPicList, i );
+    }
+    pcPic->setRefPOC(m_cSeqIter.getFrameDescriptor().getAllowedRelativeRefPocs( eRefPicList, pcPic->getViewIdx() )[i]+pcPic->getPOC(), eRefPicList, i );
+  }
+  pcPic->setNumRefs( m_cSeqIter.getFrameDescriptor().getAllowedRelativeRefPocs( eRefPicList, pcPic->getViewIdx() ).size(), eRefPicList );
+#endif
+}
+
+Void TEncTop::xCheckSliceType(TComPic* pcPic)
+{
+  if( pcPic->getNumRefs(REF_PIC_LIST_0) == 0 && pcPic->getNumRefs(REF_PIC_LIST_1) == 0 && pcPic->getSliceType() == I_SLICE )
+  {
+    return ;
+  }
+  if( pcPic->getNumRefs(REF_PIC_LIST_0) != 0 && pcPic->getNumRefs(REF_PIC_LIST_1) == 0 && pcPic->getSliceType() == P_SLICE )
+  {
+    return ;
+  }
+  if( pcPic->getNumRefs(REF_PIC_LIST_0) != 0 && pcPic->getNumRefs(REF_PIC_LIST_1) != 0 && pcPic->getSliceType() == B_SLICE )
+  {
+    return ;
+  }
+  if( pcPic->getNumRefs(REF_PIC_LIST_0) == 0 && pcPic->getNumRefs(REF_PIC_LIST_1) == 0 )
+  {
+    pcPic->setSliceType(I_SLICE) ;
+    return;
+  }
+  if( pcPic->getNumRefs(REF_PIC_LIST_0) != 0 && pcPic->getNumRefs(REF_PIC_LIST_1) == 0 )
+  {
+    pcPic->setSliceType(P_SLICE) ;
+    return;
+  }
+
+  assert(0);
+}
+
+
+Void TEncTop::xSetPicProperties(TComPic* pcPic)
+{
+  pcPic->setSliceType( m_cSeqIter.getFrameDescriptor().getSliceType(m_uiViewId) );
+  pcPic->setReferenced( m_cSeqIter.getFrameDescriptor().getStoreForRef(m_uiViewId) );
+  pcPic->setColDir( m_cSeqIter.getFrameDescriptor().getColDir() ) ;
+  const Bool bQpChangePointPassed = m_iFrameNumInCodingOrder++ >= getQpChangeFrame();
+  const Int  iQpChangeOffset      = bQpChangePointPassed ? ( m_bIsDepth ? getQpChangeOffsetDepth() : getQpChangeOffsetVideo() ) : 0;
+  pcPic->setQP(max(MIN_QP,min(MAX_QP, m_iQP+ m_aiTLayerQPOffset[m_cSeqIter.getFrameDescriptor().getTEncSeqStructureLayer(m_uiViewId)] + iQpChangeOffset )) );
+  pcPic->setViewIdx( m_uiViewId );
+#if 0
+  pcPic->setNumRefs(0, REF_PIC_LIST_0);
+  pcPic->setNumRefs(0, REF_PIC_LIST_1);
+
+
+  if( m_cSeqIter.getFrameDescriptor().getSliceType(m_iViewIdx)== P_SLICE || m_cSeqIter.getFrameDescriptor().getSliceType(m_iViewIdx)== B_SLICE)
+  {
+    xSetRefPics( pcPic, REF_PIC_LIST_0 );
+  }
+  if( m_cSeqIter.getFrameDescriptor().getSliceType(m_iViewIdx)== B_SLICE)
+  {
+    xSetRefPics( pcPic, REF_PIC_LIST_1 );
+  }
+#else
+  xSetRefPics( pcPic, REF_PIC_LIST_0 );
+  xSetRefPics( pcPic, REF_PIC_LIST_1 );
+  xCheckSliceType( pcPic );
+#endif
+
+  pcPic->setScaleOffset( m_aaiCodedScale, m_aaiCodedOffset );
+}
Index: /tags/0.2r1/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/TEncTop.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/TEncTop.h	(revision 19)
@@ -0,0 +1,222 @@
+/* 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     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/TComBitStream.h"
+#include "../TLibCommon/TComDepthMapGenerator.h"
+#include "../TLibCommon/TComResidualGenerator.h"
+
+#include "../TLibVideoIO/TVideoIOYuv.h"
+#include "../TLibVideoIO/TVideoIOBits.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 "TEncSeqStructure.h"
+#include <map>
+#include "TEncAnalyze.h"
+
+
+// ====================================================================================================================
+// 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
+
+  Bool                    m_bSeqFirst ;
+  TEncSeqStructure::Iterator m_cSeqIter;
+  std::map<Int, TComPic*> m_acInputPicMap;
+  std::map<PicOrderCnt, TComPicYuv*> m_acOutputPicMap;
+
+  // 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
+#if MTK_SAO
+  TEncSampleAdaptiveOffset  m_cEncSAO;                    ///< sample adaptive offset class
+#endif
+  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
+
+  // processing unit
+  TEncPic                 m_cPicEncoder;                  ///< Pic encoder
+  TEncSlice               m_cSliceEncoder;                ///< slice encoder
+  TEncCu                  m_cCuEncoder;                   ///< CU encoder
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator   m_cDepthMapGenerator;           ///< depth map generator
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  TComResidualGenerator   m_cResidualGenerator;           ///< generator for residual pictures
+#endif
+
+  // SPS
+  TComSPS                 m_cSPS;                         ///< SPS
+  TComPPS                 m_cPPS;                         ///< PPS
+
+  // 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
+  TEncBinCABAC***         m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+  TEncBinCABAC            m_cRDGoOnBinCoderCABAC;         ///< going on bin coder CABAC for RD stage
+
+  std::vector<TEncTop*>*  m_pacTEncTopList;
+  TAppEncTop*             m_pcTAppEncTop;                 // SB better: design a new MVTop encoder class, instead of mixing lib and app
+
+  bool                    m_bPicWaitingForCoding;
+
+  PicOrderCnt             m_iFrameNumInCodingOrder;
+
+protected:
+  Void  xGetNewPicBuffer  ( TComPic*& rpcPic );           ///< get picture buffer which will be processed
+  Void  xInitSPS          ();                             ///< initialize SPS from encoder options
+#if CONSTRAINED_INTRA_PRED
+  Void  xInitPPS          ();                             ///< initialize PPS from encoder options
+#endif
+  Void  xSetPicProperties( TComPic* pcPic  ) ;
+  Void  xSetRefPics( TComPic* pcPic, RefPicList eRefPicList );
+  Void  xCheckSliceType(TComPic* pcPic);
+
+public:
+  TEncTop();
+  virtual ~TEncTop();
+
+  Void      create          ();
+  Void      destroy         ();
+  Void      init            ( TAppEncTop* pcTAppEncTop );
+  Void      deletePicBuffer ();
+
+  Void      deleteExtraPicBuffers   ( Int iPoc );
+#if AMVP_BUFFERCOMPRESS
+  Void      compressMotion          ( Int iPoc );
+#endif
+
+  UInt      getNextFrameId          ()  { return (UInt)m_cSeqIter.getPoc(); }
+  Bool      currentPocWillBeCoded   ()  { return ( m_acInputPicMap.find( (Int)m_cSeqIter.getPoc() ) != m_acInputPicMap.end() ); }
+
+  TComList<TComPic*>      getCodedPictureStore(){ return m_cListPic;}
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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;  }
+#if MTK_SAO
+  TEncSampleAdaptiveOffset* getSAO                () { return  &m_cEncSAO;              }
+#endif
+  TEncPic*                getPicEncoder         () { return  &m_cPicEncoder;          }
+  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;       }
+
+  TComBitCounter*         getBitCounter         () { return  &m_cBitCounter;          }
+  TComRdCost*             getRdCost             () { return  &m_cRdCost;              }
+  TEncSbac***             getRDSbacCoder        () { return  m_pppcRDSbacCoder;       }
+  TEncSbac*               getRDGoOnSbacCoder    () { return  &m_cRDGoOnSbacCoder;     }
+#if DEPTH_MAP_GENERATION
+  TComDepthMapGenerator*  getDepthMapGenerator  () { return  &m_cDepthMapGenerator;   }
+#endif
+#if HHI_INTER_VIEW_RESIDUAL_PRED
+  TComResidualGenerator*  getResidualGenerator  () { return  &m_cResidualGenerator;   }
+#endif
+
+  TComSPS*                getSPS                () { return  &m_cSPS;                 }
+  TComPPS*                getPPS                () { return  &m_cPPS;                 }
+
+  Void                    setTEncTopList        ( std::vector<TEncTop*>* pacTEncTopList );
+  TAppEncTop*             getEncTop             () { return m_pcTAppEncTop; }
+
+  Int                     getNumAllPicCoded     () { return m_uiNumAllPicCoded; }
+
+  Void                    printOutSummary       ( UInt uiNumAllPicCoded );
+
+  TEncAnalyze             m_cAnalyzeAll;
+  TEncAnalyze             m_cAnalyzeI;
+  TEncAnalyze             m_cAnalyzeP;
+  TEncAnalyze             m_cAnalyzeB;
+  // -------------------------------------------------------------------------------------------------------------------
+  // encoder function
+  // -------------------------------------------------------------------------------------------------------------------
+
+  /// encode several number of pictures until end-of-sequence
+
+
+//GT PRE LOAD ENC BUFFER
+  Void encode    ( bool bEos, std::map<PicOrderCnt, TComPicYuv*>& rcMapPicYuvRecOut, TComBitstream* pcBitstreamOut, Bool& bNewPicNeeded );
+  Void receivePic( bool bEos, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvRec, TComPicYuv* pcOrgPdmDepth = 0 );
+};
+
+#endif // __TENCTOP__
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 19)
@@ -0,0 +1,364 @@
+/* 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     WeightedPredAnalysis.cpp
+    \brief    encoder class
+*/
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "WeightPredAnalysis.h"
+
+#ifdef WEIGHT_PRED
+
+#define ABS(a)    ((a) < 0 ? - (a) : (a))
+
+WeightPredAnalysis::WeightPredAnalysis()
+{
+  for ( Int e=0 ; e<2 ; e++ )
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) {
+      for ( int comp=0 ; comp<3 ;comp++ ) {
+        wpScalingParam  *pwp   = &(m_wp[e][iRefIdx][comp]);
+        pwp->bPresentFlag      = false;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->iWeight           = 1;
+        pwp->iOffset           = 0;
+      }
+    }
+}
+
+Bool  WeightPredAnalysis::xCalcACDCParamSlice(TComSlice *slice)
+{
+  //===== calculate AC/DC value =====
+  //Int iPoc = slice->getPOC();
+  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);
+}
+Bool  WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *slice)
+{
+#define wpTable	m_wp //wpScalingParam	weightPredTable[2][MAX_NUM_REF][3];
+
+  //Int iPoc = slice->getPOC();
+  Int iDenom  = 6;
+  Int iDefaultWeight = ((Int)1<<iDenom);
+  Int iRealDenom = iDenom + (g_uiBitDepth+g_uiBitIncrement-8);
+  Int iRealOffset = ((Int)1<<(iRealDenom-1));
+
+  if(slice->getNumRefIdx(REF_PIC_LIST_0)>3)
+  {
+    iDenom  = 7;
+    iDefaultWeight = ((Int)1<<iDenom);
+    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);
+
+	  //Int64 iSADWP=0, iSADnoWP=0;
+      for ( Int iComp = 0; iComp < 3; iComp++ )
+      {
+        //Int irefPoc = slice->getRefPOC(eRefPicList, iRefIdxTemp);
+        // 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 (these two codes are only "Double")
+        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 );
+
+        wpTable[iRefList][iRefIdxTemp][iComp].bPresentFlag = true;
+        wpTable[iRefList][iRefIdxTemp][iComp].iWeight = (Int)iWeight;
+        wpTable[iRefList][iRefIdxTemp][iComp].iOffset = (Int)iOffset;
+        wpTable[iRefList][iRefIdxTemp][iComp].uiLog2WeightDenom = (Int)iDenom;
+      }
+    }
+  }
+
+  // selecting whether WP is used, or not
+  xSelectWP(slice, wpTable, iDenom);
+  
+  slice->setWpScaling( wpTable );
+
+  return (true);
+}
+Bool WeightPredAnalysis::xSelectWP(TComSlice *slice, wpScalingParam	weightPredTable[2][MAX_NUM_REF][3], Int iDenom)
+{
+  //Int iPoc = slice->getPOC();
+  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->xCalcSADvalueWPUV(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][1].iWeight, weightPredTable[iRefList][iRefIdxTemp][1].iOffset);
+      iSADnoWP += this->xCalcSADvalueWPUV(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->xCalcSADvalueWPUV(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][2].iWeight, weightPredTable[iRefList][iRefIdxTemp][2].iOffset);
+      iSADnoWP += this->xCalcSADvalueWPUV(pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
+
+      if(iSADWP >= iSADnoWP)
+      {
+        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);
+}
+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);
+}
+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);
+}
+
+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 = xCalcDCValueUV(pPel, iWidth, iHeight, iCStride);
+
+  return (iDC);
+}
+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 = xCalcACValueUV(pPel, iWidth, iHeight, iCStride, iDC);
+
+  return (iAC);
+}
+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);
+}
+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);
+}
+Int64 WeightPredAnalysis::xCalcDCValueUV(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);
+}
+Int64 WeightPredAnalysis::xCalcACValueUV(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);
+}
+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);
+}
+Int64 WeightPredAnalysis::xCalcSADvalueWPUV(Pel *pOrgPel, Pel *pRefPel, Int iWidth, Int iHeight, Int iOrgStride, Int iRefStride, Int iDenom, Int iWeight, Int iOffset)
+{
+  Int x, y;
+  //Int64 itmpSAD = 0;
+  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);
+}
+
+#endif	// WEIGHT_PRED
+
Index: /tags/0.2r1/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 19)
@@ -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     WeightedPredAnalysis.h
+    \brief    encoder class
+*/
+#ifndef __WEIGHTPREDANALYSIS__
+#define __WEIGHTPREDANALYSIS__
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+
+#ifdef WEIGHT_PRED
+
+#ifdef MSYS_LINUX
+  typedef long long LInt;
+#else
+  typedef __int64 LInt;
+#endif
+
+class  WeightPredAnalysis {
+
+  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   xCalcDCValueUV(Pel *pPel, Int iWidth, Int iHeight, Int iStride);
+  Int64   xCalcACValueUV(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);
+  Int64   xCalcSADvalueWPUV(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);
+};
+
+#endif	// WEIGHT_PRED
+
+#endif	// __WEIGHTPREDANALYSIS__
+
+
Index: /tags/0.2r1/source/Lib/TLibRenderer/TRenFilter.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 19)
@@ -0,0 +1,1437 @@
+/* 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 "../TLibCommon/TComPredFilter.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  )
+{
+  TComPredFilter 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, &TComPredFilter::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, &TComPredFilter::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +2, iOutputStride, 4 , 1, &TComPredFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +3, iOutputStride, 4 , 1, &TComPredFilter::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, &TComPredFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 2, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData+1                , iOutputStride, 2 , 1, &TComPredFilter::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, &TComPredFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +1, iOutputStride, 4 , 1, &TComPredFilter::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +2, iOutputStride, 4 , 1, &TComPredFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +3, iOutputStride, 4 , 1, &TComPredFilter::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, &TComPredFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +1, iOutputStride, 8 , 1, &TComPredFilter::xCTI_Filter_VP04_C_OCT0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +2, iOutputStride, 8 , 1, &TComPredFilter::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +3, iOutputStride, 8 , 1, &TComPredFilter::xCTI_Filter_VP04_C_OCT1 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +4, iOutputStride, 8 , 1, &TComPredFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +5, iOutputStride, 8 , 1, &TComPredFilter::xCTI_Filter_VP04_C_OCT2 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +6, iOutputStride, 8 , 1, &TComPredFilter::xCTI_Filter_VP04_C_QUA1 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +7, iOutputStride, 8 , 1, &TComPredFilter::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;
+
+  TComPredFilter 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;
+
+  TComPredFilter 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: /tags/0.2r1/source/Lib/TLibRenderer/TRenFilter.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenFilter.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenFilter.h	(revision 19)
@@ -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-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 "../TLibCommon/TComPredFilter.h"
+
+typedef Int (TComPredFilter::*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: /tags/0.2r1/source/Lib/TLibRenderer/TRenImage.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenImage.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenImage.cpp	(revision 19)
@@ -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-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"
+
+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>::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: /tags/0.2r1/source/Lib/TLibRenderer/TRenImage.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenImage.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenImage.h	(revision 19)
@@ -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-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;
+
+  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: /tags/0.2r1/source/Lib/TLibRenderer/TRenImagePlane.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 19)
@@ -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"
+/////// 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: /tags/0.2r1/source/Lib/TLibRenderer/TRenImagePlane.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 19)
@@ -0,0 +1,125 @@
+/* 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: /tags/0.2r1/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 19)
@@ -0,0 +1,452 @@
+/* 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"
+
+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 = -1;
+    break;
+  case 'I':
+    iBlendMode = 0;
+    break;
+  case 'L':
+    iBlendMode = 1;
+    break;
+  case 'R':
+    iBlendMode = 2;
+    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];
+}
Index: /tags/0.2r1/source/Lib/TLibRenderer/TRenModSetupStrParser.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 19)
@@ -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-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 __TRENMODSETUPSTRPARSER__
+#define __TRENMODSETUPSTRPARSER__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "../TLibCommon/TypeDef.h"
+#include "../../App/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__
Index: /tags/0.2r1/source/Lib/TLibRenderer/TRenModel.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenModel.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenModel.cpp	(revision 19)
@@ -0,0 +1,648 @@
+/* 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"
+
+///////////  TRENMODEL //////////////////////
+TRenModel::TRenModel()
+{
+  m_iPad               = 12;
+  m_iWidth             = -1;
+  m_iHeight            = -1;
+  m_iNumOfBaseViews    = -1;
+  m_iSampledWidth      = -1;
+  m_iShiftPrec         =  0;
+  m_iHoleMargin        =  1;
+
+  // 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
+TRenModel::create( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin )
+{
+  m_iNumOfBaseViews     = iNumOfBaseViews;
+  m_iNumOfRenModels     = iNumOfModels;
+  m_iWidth              = iWidth;
+  m_iHeight             = iHeight;
+  m_iShiftPrec          = iShiftPrec;
+  m_iHoleMargin         = iHoleMargin;
+
+// 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], -1);
+
+  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] = new TRenSingleModel();
+  }
+
+  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 );
+  AOF( m_apcRenModels[iModelNum] );
+  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 );
+
+  m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, iBlendMode );
+
+  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_iHeight || pcPicYuvVideoData->getWidth() == m_iWidth );
+  AOF( pcPicYuvDepthData->getHeight() == m_iHeight || pcPicYuvDepthData->getWidth() == m_iWidth );
+
+  pcPicYuvVideoData->extendPicBorder();
+  TRenFilter::sampleHorUp   ( m_iShiftPrec, pcPicYuvVideoData->getLumaAddr(), pcPicYuvVideoData->getStride() , m_iWidth,      m_iHeight,      m_aapiCurVideoPel[ iViewNum ][0], m_aaiCurVideoStrides[iViewNum][0] );
+  TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvVideoData->getCbAddr()  , pcPicYuvVideoData->getCStride(), m_iWidth >> 1, m_iHeight >> 1, m_aapiCurVideoPel[ iViewNum ][1], m_aaiCurVideoStrides[iViewNum][1] );
+  TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvVideoData->getCrAddr()  , pcPicYuvVideoData->getCStride(), m_iWidth >> 1, m_iHeight >> 1, m_aapiCurVideoPel[ iViewNum ][2], m_aaiCurVideoStrides[iViewNum][2] );
+  TRenFilter::copy          (               pcPicYuvDepthData->getLumaAddr(), pcPicYuvDepthData->getStride(),   m_iWidth,     m_iHeight,      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_iHeight || pcPicYuvOrgVideoData->getWidth() == m_iWidth );
+    pcPicYuvOrgVideoData->extendPicBorder();
+    TRenFilter::sampleHorUp   ( m_iShiftPrec, pcPicYuvOrgVideoData->getLumaAddr(), pcPicYuvOrgVideoData->getStride() , m_iWidth,      m_iHeight,      m_aapiOrgVideoPel[ iViewNum ][0], m_aaiOrgVideoStrides[iViewNum][0] );
+    TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvOrgVideoData->getCbAddr()  , pcPicYuvOrgVideoData->getCStride(), m_iWidth >> 1, m_iHeight >> 1, m_aapiOrgVideoPel[ iViewNum ][1], m_aaiOrgVideoStrides[iViewNum][1] );
+    TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvOrgVideoData->getCrAddr()  , pcPicYuvOrgVideoData->getCStride(), m_iWidth >> 1, m_iHeight >> 1, m_aapiOrgVideoPel[ iViewNum ][2], m_aaiOrgVideoStrides[iViewNum][2] );
+  }
+
+  if ( m_abSetupDepthFromOrgForView[iViewNum] )
+  {
+    AOF( pcPicYuvOrgDepthData->getHeight() == m_iHeight || pcPicYuvOrgDepthData->getWidth() == m_iWidth );
+    TRenFilter::copy          (               pcPicYuvOrgDepthData->getLumaAddr(), pcPicYuvOrgDepthData->getStride(),  m_iWidth,     m_iHeight,      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 );
+
+  // 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];
+
+    if ( ( bSetupFromOrgVideo || bSetupFromOrgDepth ) && 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 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];
+  }
+}
+
+RMDist
+TRenModel::getDist( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  AOT( iWidth  + iStartPosX > m_iWidth  );
+  AOT( iHeight + iStartPosY > m_iHeight );
+  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)
+    {
+      iDist +=  m_apcCurRenModels[iModelNum]->getDistDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY,  iWidth,  iHeight,  iStride,  piNewData );
+    }
+    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 )
+{
+  iWidth  = min(iWidth , m_iWidth  - iStartPosX );
+  iHeight = min(iHeight, m_iHeight - 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)
+    {
+      m_apcCurRenModels[iModelNum]->setDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY, iWidth, iHeight, iStride, piNewData );
+
+    }
+    else
+    {
+      m_apcCurRenModels[iModelNum]->setVideo  ( m_aiCurPosInModels[iModelNum], m_iCurrentPlane ,iStartPosX, iStartPosY,  iWidth,  iHeight,  iStride, piNewData );
+    }
+  }
+
+  if (m_iCurrentContent == 1)
+  {
+    Int iTargetStride = m_aiCurDepthStrides[ m_iCurrentView ];
+    TRenFilter::copy( piNewData, iStride, iWidth, iHeight,  m_apiCurDepthPel[ m_iCurrentView ] + iStartPosY * iTargetStride + iStartPosX, iTargetStride );
+  }
+  else
+  {
+    Int iTargetStride = m_aaiCurVideoStrides[ m_iCurrentView ][m_iCurrentPlane];
+    TRenFilter::copy( piNewData, iStride, iWidth, iHeight,  m_aapiCurVideoPel[ m_iCurrentView ][m_iCurrentPlane] + iStartPosY * iTargetStride + iStartPosX, iTargetStride);
+  }
+}
+
+Void
+TRenModel::getSynthVideo( Int iModelNum, Int iViewNum, TComPicYuv*& rpcPicYuvSynthVideo )
+{
+  Pel** ppiSynthVideoPel = NULL;
+  Pel*  ppiSynthDepthPel = NULL;
+  Int   iStride          = -1;
+  Int   aiStrides[3];
+
+  m_apcRenModels[iModelNum]->getSynthView(iViewNum, ppiSynthVideoPel, ppiSynthDepthPel, iStride );
+
+  aiStrides[0] = iStride; aiStrides[1] = iStride; aiStrides[2] = iStride;
+  xCopy2PicYuv( ppiSynthVideoPel, aiStrides, rpcPicYuvSynthVideo  );
+}
+
+Void
+TRenModel::getSynthDepth( Int iModelNum, Int iViewNum, TComPicYuv*& rpcPicYuvSynthDepth )
+{
+  Pel** ppiSynthVideoPel = NULL;
+  Pel*  piSynthDepthPel  = NULL;
+  Int   iStride          = -1;
+
+  m_apcRenModels[iModelNum]->getSynthView(iViewNum, ppiSynthVideoPel, piSynthDepthPel, iStride );
+  TRenFilter::copy( piSynthDepthPel, iStride, m_iWidth, m_iHeight, rpcPicYuvSynthDepth->getLumaAddr(), rpcPicYuvSynthDepth->getStride() );
+  rpcPicYuvSynthDepth->setChromaTo( 128 << g_uiBitIncrement );
+}
+
+
+Void
+TRenModel::getTotalSSE( Int64& riSSEY, Int64& riSSEU, Int64& riSSEV )
+{
+  TComPicYuv cPicYuvSynth;
+  cPicYuvSynth.create( m_iWidth, m_iHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+
+  TComPicYuv cPicYuvTempRef;
+  cPicYuvTempRef.create( m_iWidth, m_iHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+
+  Int64 iSSEY = 0;
+  Int64 iSSEU = 0;
+  Int64 iSSEV = 0;
+
+  for (Int iCurModel = 0; iCurModel < m_iNumOfCurRenModels; iCurModel++)
+  {
+    Pel** ppiSynthVideoPel = NULL;
+    Pel*  ppiSynthDepthPel = NULL;
+    Pel** ppiRefVideoPel   = NULL;
+    Int   iSynStride       = -1;
+    Int*  piRefStrides     = NULL;
+    Int   aiSynStrides[3];
+
+    m_apcCurRenModels[iCurModel]->getSynthView( m_aiCurPosInModels[iCurModel], ppiSynthVideoPel, ppiSynthDepthPel, iSynStride );
+    aiSynStrides[0] = iSynStride; aiSynStrides[1] = iSynStride; aiSynStrides[2] = iSynStride;
+    xCopy2PicYuv( ppiSynthVideoPel, aiSynStrides,  &cPicYuvSynth );
+
+    TComPicYuv* pcPicYuvOrgRef;
+    TComPicYuv* pcPicYuvRef;
+    m_apcCurRenModels[iCurModel]->getRefView  ( pcPicYuvOrgRef, ppiRefVideoPel, piRefStrides );
+
+    if (!pcPicYuvOrgRef )
+    {
+      xCopy2PicYuv( ppiRefVideoPel, piRefStrides,  &cPicYuvTempRef);
+      pcPicYuvRef = &cPicYuvTempRef;
+    }
+    else
+    {
+      pcPicYuvRef = pcPicYuvOrgRef;
+    }
+
+    iSSEY += TRenFilter::SSE( cPicYuvSynth.getLumaAddr(), cPicYuvSynth.getStride(),  m_iWidth,      m_iHeight     , pcPicYuvRef->getLumaAddr(), pcPicYuvRef->getStride() );
+    iSSEU += TRenFilter::SSE( cPicYuvSynth.getCbAddr()  , cPicYuvSynth.getCStride(), m_iWidth >> 1, m_iHeight >> 1, pcPicYuvRef->getCbAddr()  , pcPicYuvRef->getCStride());
+    iSSEV += TRenFilter::SSE( cPicYuvSynth.getCrAddr()  , cPicYuvSynth.getCStride(), m_iWidth >> 1, m_iHeight >> 1, pcPicYuvRef->getCrAddr()  , pcPicYuvRef->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;
+
+  m_apcRenModels[iModelNum]->setLRView( iViewPos, m_aapiCurVideoPel[iBaseViewNum], m_aaiCurVideoStrides[iBaseViewNum], m_apiCurDepthPel[iBaseViewNum], m_aiCurDepthStrides [iBaseViewNum] );
+
+  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;
+    }
+  }
+}
+
+Void
+TRenModel::xCopy2PicYuv( Pel** ppiSrcVideoPel, Int* piStrides, TComPicYuv* rpcPicYuvTarget )
+{
+  TRenFilter::copy            ( ppiSrcVideoPel[0], piStrides[0], m_iWidth, m_iHeight, rpcPicYuvTarget->getLumaAddr(), rpcPicYuvTarget->getStride() );
+  TRenFilter::sampleDown2Tap13( ppiSrcVideoPel[1], piStrides[1], m_iWidth, m_iHeight, rpcPicYuvTarget->getCbAddr  (), rpcPicYuvTarget->getCStride() );
+  TRenFilter::sampleDown2Tap13( ppiSrcVideoPel[2], piStrides[2], m_iWidth, m_iHeight, rpcPicYuvTarget->getCrAddr  (), rpcPicYuvTarget->getCStride() );
+}
Index: /tags/0.2r1/source/Lib/TLibRenderer/TRenModel.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenModel.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenModel.h	(revision 19)
@@ -0,0 +1,140 @@
+/* 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 __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
+  Void  create           ( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin );
+  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 Mode
+  Void  setErrorMode     ( Int iView, Int iContent, int iPlane );
+
+  // Get Distortion, set Data
+  Int64 getDist          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData  );
+  Void  setData          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData  );
+
+  // Get Rendered View
+  Void  getSynthVideo    ( Int iModelNum, Int iViewNum, TComPicYuv*& rpcPicYuvSynthVideo );
+  Void  getSynthDepth    ( Int iModelNum, Int iViewNum, TComPicYuv*& rpcPicYuvSynthDepth );
+
+  // 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 );
+  Void xCopy2PicYuv ( Pel** ppiSrcVideoPel, Int* piStrides, TComPicYuv* rpcPicYuvTarget );
+
+  // Settings
+  Int    m_iShiftPrec;
+  Int**  m_aaaiSubPelShiftLut[2];
+  Int    m_iHoleMargin;
+
+  /// Size of Video and Depth
+  Int m_iWidth;
+  Int m_iHeight;
+  Int m_iSampledWidth;
+  Int m_iPad;
+
+  Int m_iNumOfBaseViews;
+
+  /// 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__
Index: /tags/0.2r1/source/Lib/TLibRenderer/TRenSingleModel.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 19)
@@ -0,0 +1,1429 @@
+/* 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"
+
+////////////// TRENSINGLE MODEL ///////////////
+TRenSingleModel::TRenSingleModel()
+:  m_iDistShift ( g_uiBitIncrement << 1 )
+{
+  m_iWidth  = -1;
+  m_iHeight = -1;
+  m_iStride = -1;
+  m_iMode   = -1;
+  m_iPad    = 12;
+  m_iGapTolerance = -1;
+  m_bUseOrgRef = false;
+
+  m_pcPicYuvRef          = 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_ppiCurLUT               = NULL;
+    m_piInvZLUTLeft           = NULL;
+    m_piInvZLUTRight          = NULL;
+
+    // Cur Data
+    m_apiBaseDepthPel      [uiViewNum] = NULL;
+    m_aiBaseDepthStrides   [uiViewNum] = -1;
+
+    // State Data
+    m_apbOccluded          [uiViewNum] = NULL;
+    m_apiFilled            [uiViewNum] = NULL;
+
+    // Cur Data
+    m_aapiBaseVideoPel     [uiViewNum] = NULL;
+    m_aaiBaseVideoStrides  [uiViewNum] = NULL;
+  };
+
+  m_piError                            = NULL;
+
+  for (UInt uiViewNum = 0 ; uiViewNum < 3; uiViewNum++)
+  {
+    m_apiSynthDepthPel[uiViewNum] = NULL;
+    for (UInt uiPlaneNum = 0; uiPlaneNum < 3; uiPlaneNum++)
+    {
+      // Rendered Data
+      m_aapiSynthVideoPel[uiViewNum][uiPlaneNum] = NULL;
+    }
+  }
+}
+
+TRenSingleModel::~TRenSingleModel()
+{
+  if ( m_apbOccluded[0] ) delete[] m_apbOccluded[0];
+  if ( m_apbOccluded[1] ) delete[] m_apbOccluded[1];
+
+  if ( m_apiFilled  [0] ) delete[] m_apiFilled  [0];
+  if ( m_apiFilled  [1] ) delete[] m_apiFilled  [1];
+
+  if ( m_piError        ) delete[] m_piError      ;
+
+
+  for (UInt uiViewNum = 0 ; uiViewNum < 3; uiViewNum++)
+  {
+    for (UInt uiPlaneNum = 0; uiPlaneNum < 3; uiPlaneNum++)
+    {
+      if ( m_aapiSynthVideoPel[uiViewNum] && m_aapiSynthVideoPel[uiViewNum][uiPlaneNum] ) delete[] m_aapiSynthVideoPel[uiViewNum][uiPlaneNum];
+    }
+    if ( m_apiSynthDepthPel[uiViewNum] ) delete[] m_apiSynthDepthPel[uiViewNum];
+  }
+
+  delete[] (m_aapiRefVideoPel[0] - m_iPad * m_aiRefVideoStrides[0] - m_iPad );
+  delete[] (m_aapiRefVideoPel[1] - m_iPad * m_aiRefVideoStrides[1] - m_iPad );
+  delete[] (m_aapiRefVideoPel[2] - m_iPad * m_aiRefVideoStrides[2] - m_iPad );
+
+  if ( m_piInvZLUTLeft  ) delete[] m_piInvZLUTLeft;
+  if ( m_piInvZLUTRight ) delete[] m_piInvZLUTRight;
+}
+
+Void
+TRenSingleModel::create( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode )
+{
+  m_iBlendMode = iBlendMode;
+  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_piError               = new Int [m_iStride*m_iHeight];
+
+  // Create Buffers
+  if ( (m_iMode == 0) || (m_iMode == 2 ) )
+  {
+    m_apbOccluded        [0]  = new Bool[m_iStride*m_iHeight];
+    m_apiFilled          [0]  = new Pel [m_iStride*m_iHeight];
+
+    for (UInt uiPlaneNum = 0; uiPlaneNum < 3; uiPlaneNum++)
+    {
+      m_aapiSynthVideoPel[0][uiPlaneNum] = new Pel[m_iStride*m_iHeight];
+    }
+  }
+
+  if ( (m_iMode == 1) || (m_iMode == 2 ) )
+  {
+    m_apbOccluded        [1]  = new Bool[m_iStride*m_iHeight];
+    m_apiFilled          [1]  = new Pel [m_iStride*m_iHeight];
+
+    for (UInt uiPlaneNum = 0; uiPlaneNum < 3; uiPlaneNum++)
+    {
+      m_aapiSynthVideoPel[1][uiPlaneNum] = new Pel[m_iStride*m_iHeight];
+    }
+  }
+
+  if ( m_iMode == 2 )
+  {
+    m_apiSynthDepthPel[0] = new Pel[m_iStride*m_iHeight];
+    m_apiSynthDepthPel[1] = new Pel[m_iStride*m_iHeight];
+    m_apiSynthDepthPel[2] = new Pel[m_iStride*m_iHeight];
+
+    for (UInt uiPlaneNum = 0; uiPlaneNum < 3; uiPlaneNum++)
+    {
+      m_aapiSynthVideoPel[2][uiPlaneNum] = new Pel[m_iStride*m_iHeight];
+    }
+  }
+}
+
+Void
+TRenSingleModel::setLRView( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride )
+{
+  AOF(( iViewPos == 0) || (iViewPos == 1) );
+  m_aapiBaseVideoPel      [iViewPos] = apiCurVideoPel;
+  m_aaiBaseVideoStrides   [iViewPos] = aiCurVideoStride;
+  m_apiBaseDepthPel       [iViewPos] = piCurDepthPel;
+  m_aiBaseDepthStrides    [iViewPos] = iCurDepthStride;
+}
+
+Void
+TRenSingleModel::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) );
+  AOT( pcOrgVideo != NULL && bKeepReference );
+
+  m_appiShiftLut[0] = ppiShiftLutLeft;
+  m_appiShiftLut[1] = ppiShiftLutRight;
+
+  // Copy Reference
+  m_pcPicYuvRef = pcOrgVideo;
+
+  if ( pcOrgVideo )
+  {
+    TRenFilter::copy(             pcOrgVideo->getLumaAddr(), pcOrgVideo->getStride() , m_iWidth,      m_iHeight,      m_aapiRefVideoPel[0], m_aiRefVideoStrides[0]);
+    TRenFilter::sampleCUpHorUp(0, pcOrgVideo->getCbAddr()  , pcOrgVideo->getCStride(), m_iWidth >> 1, m_iHeight >> 1, m_aapiRefVideoPel[1], m_aiRefVideoStrides[1]);
+    TRenFilter::sampleCUpHorUp(0, pcOrgVideo->getCrAddr()  , pcOrgVideo->getCStride(), m_iWidth >> 1, m_iHeight >> 1, m_aapiRefVideoPel[2], m_aiRefVideoStrides[2]);
+  }
+
+  // Initial Rendering
+  xSetInts( m_piError                       , m_iStride, m_iWidth, m_iHeight, 0 );
+
+  switch ( m_iMode )
+  {
+  case 0:
+    xInitView( VIEWPOS_LEFT );
+    xRenderL( 0, 0, m_iWidth, m_iHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0], true );
+    break;
+  case 1:
+    xInitView( VIEWPOS_RIGHT );
+    xRenderR( 0, 0, m_iWidth, m_iHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1], true );
+    break;
+  case 2:
+    TRenFilter::setupZLUT( true, 30, iDistToLeft, ppiBaseShiftLutLeft, ppiBaseShiftLutRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight );
+    xInitView( VIEWPOS_LEFT   );
+    xInitView( VIEWPOS_RIGHT  );
+    xInitView( VIEWPOS_MERGED );
+    xRenderL( 0, 0, m_iWidth, m_iHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0], true );
+    xRenderR( 0, 0, m_iWidth, m_iHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1], true );
+    break;
+  default:
+    AOT(true);
+  }
+
+  // Get Rendered View as Reference
+  if ( !pcOrgVideo && !bKeepReference )
+  {
+    xSetInts        ( m_piError                       , m_iStride, m_iWidth, m_iHeight, 0 );
+      TRenFilter::copy( m_aapiSynthVideoPel[m_iMode ][0], m_iStride, m_iWidth, m_iHeight , m_aapiRefVideoPel[0], m_aiRefVideoStrides[0]);
+      TRenFilter::copy( m_aapiSynthVideoPel[m_iMode ][1], m_iStride, m_iWidth, m_iHeight , m_aapiRefVideoPel[1], m_aiRefVideoStrides[1]);
+      TRenFilter::copy( m_aapiSynthVideoPel[m_iMode ][2], m_iStride, m_iWidth, m_iHeight , m_aapiRefVideoPel[2], m_aiRefVideoStrides[2]);
+  }
+}
+
+RMDist
+TRenSingleModel::getDistDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  RMDist iSSE = 0;
+  switch (iViewPos )
+  {
+  case 0:
+    iSSE = xRenderL( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, false );
+    break;
+  case 1:
+    iSSE = xRenderR( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, false );
+    break;
+  default:
+    assert(0);
+  }
+  return iSSE;
+}
+
+Void
+TRenSingleModel::setDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  switch (iViewPos )
+  {
+    case 0:
+      xRenderL( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, true );
+      break;
+    case 1:
+      xRenderR( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, true );
+      break;
+    default:
+      assert(0);
+  }
+}
+
+
+Void
+TRenSingleModel::getSynthView( Int iViewPos, Pel**& rppiRenVideoPel, Pel*& rpiRenDepthPel, Int& riStride )
+{
+  rppiRenVideoPel = m_aapiSynthVideoPel[iViewPos];
+  rpiRenDepthPel  = m_apiSynthDepthPel [iViewPos];
+  riStride = m_iStride;
+}
+
+
+Void
+TRenSingleModel::getRefView( TComPicYuv*& rpcPicYuvRefView, Pel**& rppiRefVideoPel, Int*& raiStrides )
+{
+  rpcPicYuvRefView = m_pcPicYuvRef;
+  rppiRefVideoPel  = m_aapiRefVideoPel;
+  raiStrides       = m_aiRefVideoStrides;
+}
+
+
+RMDist
+TRenSingleModel::getDistVideo( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  AOF(false);
+  return 0;
+}
+
+Void
+TRenSingleModel::setVideo( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  AOF(false);
+}
+
+
+
+__inline Void
+TRenSingleModel::xSetViewRow( Int iPosY )
+{
+  m_aapiBaseVideoPelRow     [m_iCurViewPos][0] = m_aapiBaseVideoPel   [m_iCurViewPos]  [0] + m_aaiBaseVideoStrides [ m_iCurViewPos ][0] * iPosY;
+  m_aapiBaseVideoPelRow     [m_iCurViewPos][1] = m_aapiBaseVideoPel   [m_iCurViewPos]  [1] + m_aaiBaseVideoStrides [ m_iCurViewPos ][1] * iPosY;
+  m_aapiBaseVideoPelRow     [m_iCurViewPos][2] = m_aapiBaseVideoPel   [m_iCurViewPos]  [2] + m_aaiBaseVideoStrides [ m_iCurViewPos ][2] * iPosY;
+
+  m_apiBaseDepthPelRow      [m_iCurViewPos]    = m_apiBaseDepthPel    [m_iCurViewPos]      + m_aiBaseDepthStrides  [ m_iCurViewPos]     * iPosY;
+  m_apbOccludedRow          [m_iCurViewPos]    = m_apbOccluded        [m_iCurViewPos]      + m_iStride                                  * iPosY;
+  m_apiFilledRow            [m_iCurViewPos]    = m_apiFilled          [m_iCurViewPos]      + m_iStride                                  * iPosY;
+  m_apiErrorRow                                = m_piError                                 + m_iStride                                  * iPosY;
+
+  m_aapiSynthVideoPelRow    [m_iCurViewPos][0] = m_aapiSynthVideoPel  [m_iCurViewPos]  [0] + m_iStride                                  * iPosY;
+  m_aapiSynthVideoPelRow    [m_iCurViewPos][1] = m_aapiSynthVideoPel  [m_iCurViewPos]  [1] + m_iStride                                  * iPosY;
+  m_aapiSynthVideoPelRow    [m_iCurViewPos][2] = m_aapiSynthVideoPel  [m_iCurViewPos]  [2] + m_iStride                                  * iPosY;
+
+  m_aapiRefVideoPelRow                     [0] = m_aapiRefVideoPel                     [0] + m_aiRefVideoStrides                    [0] * iPosY;
+  m_aapiRefVideoPelRow                     [1] = m_aapiRefVideoPel                     [1] + m_aiRefVideoStrides                    [1] * iPosY;
+  m_aapiRefVideoPelRow                     [2] = m_aapiRefVideoPel                     [2] + m_aiRefVideoStrides                    [2] * iPosY;
+
+  if (m_iMode == 2)
+  {
+    m_apiSynthDepthPelRow [m_iCurViewPos ]     = m_apiSynthDepthPel   [m_iCurViewPos]      + m_iStride                                  * iPosY;
+    m_aapiSynthVideoPelRow[m_iOtherViewPos][0] = m_aapiSynthVideoPel  [m_iOtherViewPos][0] + m_iStride                                  * iPosY;
+    m_aapiSynthVideoPelRow[m_iOtherViewPos][1] = m_aapiSynthVideoPel  [m_iOtherViewPos][1] + m_iStride                                  * iPosY;
+    m_aapiSynthVideoPelRow[m_iOtherViewPos][2] = m_aapiSynthVideoPel  [m_iOtherViewPos][2] + m_iStride                                  * iPosY;
+
+    m_apiFilledRow        [m_iOtherViewPos]    = m_apiFilled          [m_iOtherViewPos]    + m_iStride                                  * iPosY;
+    m_apiSynthDepthPelRow [m_iOtherViewPos]    = m_apiSynthDepthPel   [m_iOtherViewPos]    + m_iStride                                  * iPosY;
+
+    m_aapiSynthVideoPelRow[2              ][0] = m_aapiSynthVideoPel[2]                [0] + m_iStride                                  * iPosY;
+    m_aapiSynthVideoPelRow[2              ][1] = m_aapiSynthVideoPel[2]                [1] + m_iStride                                  * iPosY;
+    m_aapiSynthVideoPelRow[2              ][2] = m_aapiSynthVideoPel[2]                [2] + m_iStride                                  * iPosY;
+  }
+}
+
+__inline Void
+TRenSingleModel::xIncViewRow( )
+{
+  m_aapiBaseVideoPelRow     [m_iCurViewPos][0] += m_aaiBaseVideoStrides [ m_iCurViewPos ][0];
+  m_aapiBaseVideoPelRow     [m_iCurViewPos][1] += m_aaiBaseVideoStrides [ m_iCurViewPos ][1];
+  m_aapiBaseVideoPelRow     [m_iCurViewPos][2] += m_aaiBaseVideoStrides [ m_iCurViewPos ][2];
+
+  m_apiBaseDepthPelRow      [m_iCurViewPos]    += m_aiBaseDepthStrides  [ m_iCurViewPos]    ;
+  m_apbOccludedRow          [m_iCurViewPos]    += m_iStride                                 ;
+  m_apiFilledRow            [m_iCurViewPos]    += m_iStride                                 ;
+  m_apiErrorRow                                += m_iStride                                 ;
+
+  m_aapiSynthVideoPelRow    [m_iCurViewPos][0] += m_iStride                                 ;
+  m_aapiSynthVideoPelRow    [m_iCurViewPos][1] += m_iStride                                 ;
+  m_aapiSynthVideoPelRow    [m_iCurViewPos][2] += m_iStride                                 ;
+
+  m_aapiRefVideoPelRow                     [0] += m_aiRefVideoStrides                    [0];
+  m_aapiRefVideoPelRow                     [1] += m_aiRefVideoStrides                    [1];
+  m_aapiRefVideoPelRow                     [2] += m_aiRefVideoStrides                    [2];
+
+  if (m_iMode == 2)
+  {
+    m_apiSynthDepthPelRow [m_iCurViewPos ]     += m_iStride                                 ;    // This is correct!
+
+    m_aapiSynthVideoPelRow[m_iOtherViewPos][0] += m_iStride                                 ;
+    m_aapiSynthVideoPelRow[m_iOtherViewPos][1] += m_iStride                                 ;
+    m_aapiSynthVideoPelRow[m_iOtherViewPos][2] += m_iStride                                 ;
+
+    m_apiFilledRow        [m_iOtherViewPos]    += m_iStride                                 ;
+    m_apiSynthDepthPelRow [m_iOtherViewPos]    += m_iStride                                 ;
+
+    m_aapiSynthVideoPelRow[2              ][0] += m_iStride                                 ;
+    m_aapiSynthVideoPelRow[2              ][1] += m_iStride                                 ;
+    m_aapiSynthVideoPelRow[2              ][2] += m_iStride                                 ;
+  }
+}
+
+__inline RMDist
+TRenSingleModel::xRenderL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bAdd )
+{
+  m_bSet             = bAdd;
+  m_iCurViewPos      = 0;
+  m_iOtherViewPos    = 1;
+
+  m_piNewDepthData   = piNewData;
+  m_iNewDataWidth    = iWidth;
+  m_iStartChangePosX = iStartPosX;
+
+  if ((iWidth == 0) || (iHeight == 0))
+    return 0;
+
+  //TODO: Specialize to left and right; setData and getDist
+
+  // Get Data
+  m_ppiCurLUT      = m_appiShiftLut   [m_iCurViewPos];
+
+  xSetViewRow      ( iStartPosY);
+
+  // Init Start
+  RMDist iError = 0;
+  Int   iStartChangePos;
+
+  iStartChangePos = m_iStartChangePosX;
+
+  for (Int iPosY = iStartPosY; iPosY < iStartPosY + iHeight; iPosY++ )
+  {
+    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  ( iCurSPos, iEndChangePos, iError );
+      iMinChangedSPos       = Min( iMinChangedSPos, (iEndChangePos << m_iShiftPrec) - m_ppiCurLUT[0][ RemoveBitIncrement( Max(m_apiBaseDepthPelRow[m_iCurViewPos][iEndChangePos], m_piNewDepthData[iPosXinNewData] )) ]);
+      iLastSPos             = iCurSPos;
+      m_iLastDepth          = m_iCurDepth;
+      iPosXinNewData--;
+      iEndChangePos--;
+    }
+    else
+    {
+      iLastSPos    = xShift(iEndChangePos+1);
+      m_iLastDepth = m_apiBaseDepthPelRow[m_iCurViewPos][iEndChangePos+1];
+      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][ RemoveBitIncrement( Max(m_apiBaseDepthPelRow[m_iCurViewPos][iCurPosX], m_piNewDepthData[iPosXinNewData] )) ]);
+      Int iCurSPos    = xShiftNewData(iCurPosX,iPosXinNewData);
+      m_iCurDepth     = m_piNewDepthData[iPosXinNewData];
+      xRenderRangeL(iCurSPos, iLastSPos, iCurPosX, iError );
+      iLastSPos       = iCurSPos;
+      m_iLastDepth    = m_iCurDepth;
+      iPosXinNewData--;
+    }
+
+    //// RE-RENDER DATA LEFT TO NEW DATA
+    while ( iCurPosX >= 0 )
+    {
+      Int iCurSPos = xShift(iCurPosX);
+      m_iCurDepth  = m_apiBaseDepthPelRow[m_iCurViewPos][iCurPosX];
+      xRenderRangeL( iCurSPos, iLastSPos, iCurPosX, iError );
+
+      if ( iCurSPos < iMinChangedSPos )
+      {
+          break;
+        }
+
+      iCurPosX--;
+      iLastSPos    = iCurSPos;
+      m_iLastDepth = m_iCurDepth;
+    }
+
+    xIncViewRow();
+    m_piNewDepthData += iStride;
+  }
+  return iError;
+}
+
+
+__inline RMDist
+TRenSingleModel::xRenderR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bAdd )
+{
+  m_bSet             = bAdd;
+  m_iCurViewPos      = 1;
+  m_iOtherViewPos    = 0;
+
+  m_piNewDepthData   = piNewData;
+  m_iNewDataWidth    = iWidth;
+  m_iStartChangePosX = iStartPosX;
+
+  if ((iWidth == 0) || (iHeight == 0))
+    return 0;
+
+  // Get Data
+  m_ppiCurLUT      = m_appiShiftLut   [m_iCurViewPos];
+
+  xSetViewRow      ( iStartPosY);
+
+  // Init Start
+  RMDist iError = 0;
+  Int   iEndChangePos;
+
+  iEndChangePos = m_iStartChangePosX + iWidth - 1;
+
+
+  for (Int iPosY = iStartPosY; iPosY < iStartPosY + iHeight; iPosY++ )
+  {
+    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     ( iCurSPos, iStartChangePos, iError );
+      iMaxChangedSPos       = Max( iMaxChangedSPos, (iStartChangePos << m_iShiftPrec) - m_ppiCurLUT[0][ RemoveBitIncrement( Max(m_apiBaseDepthPelRow[m_iCurViewPos][iStartChangePos], m_piNewDepthData[iPosXinNewData] )) ]);
+      iLastSPos             = iCurSPos;
+      m_iLastDepth          = m_iCurDepth;
+      iPosXinNewData++;
+      iStartChangePos++;
+    }
+    else
+    {
+      iLastSPos   = xShift(iStartChangePos-1);
+      m_iLastDepth = m_apiBaseDepthPelRow[m_iCurViewPos][iStartChangePos-1];
+      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][ RemoveBitIncrement( Max(m_apiBaseDepthPelRow[m_iCurViewPos][iCurPosX], m_piNewDepthData[iPosXinNewData] )) ]);
+      Int iCurSPos    = xShiftNewData(iCurPosX,iPosXinNewData);
+      m_iCurDepth     = m_piNewDepthData[iPosXinNewData];
+      xRenderRangeR(iCurSPos, iLastSPos, iCurPosX, iError );
+      iLastSPos      = iCurSPos;
+      m_iLastDepth    = m_iCurDepth;
+      iPosXinNewData++;
+    }
+
+    //// RE-RENDER DATA LEFT TO NEW DATA
+    while ( iCurPosX < m_iWidth )
+    {
+      Int iCurSPos = xShift(iCurPosX);
+      m_iCurDepth  = m_apiBaseDepthPelRow[m_iCurViewPos][iCurPosX];
+      xRenderRangeR( iCurSPos, iLastSPos, iCurPosX, iError );
+
+      if ( iCurSPos > iMaxChangedSPos )
+      {
+          break;
+        }
+      iCurPosX++;
+      iLastSPos    = iCurSPos;
+      m_iLastDepth = m_iCurDepth;
+    }
+    xIncViewRow();
+    m_piNewDepthData += iStride;
+  }
+  return iError;
+}
+
+
+__inline Void
+TRenSingleModel::xInitRenderPartL(  Int iEndChangePos, Int iLastSPos )
+{
+  // GET MINIMAL OCCLUDED SAMPLE POSITION
+  Int iCurPosX           = iEndChangePos;
+
+  if ( ( iCurPosX + 1 < m_iWidth ) && (m_apbOccludedRow[m_iCurViewPos][ iCurPosX + 1] ) )
+  {
+    iCurPosX++;
+    while ( (iCurPosX + 1 < m_iWidth) &&  (m_apbOccludedRow[m_iCurViewPos][ iCurPosX + 1] )  )
+      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;
+};
+
+__inline Void
+TRenSingleModel::xInitRenderPartR(  Int iStartChangePos, Int iLastSPos )
+{
+  // GET MINIMAL OCCLUDED SAMPLE POSITION
+  Int iCurPosX           = iStartChangePos;
+
+  if ( ( iCurPosX - 1 > -1 ) && (m_apbOccludedRow[m_iCurViewPos][ iCurPosX - 1] ) )
+  {
+    iCurPosX--;
+    while ( (iCurPosX - 1 > -1 ) &&  (m_apbOccludedRow[m_iCurViewPos][ iCurPosX - 1] )  )
+      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;
+};
+
+
+__inline Void
+TRenSingleModel::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( iCurSPos, iLastSPos, iCurPos, riError );
+  }
+  else
+  {
+    if (iLastSPos < 0 )
+      return;
+
+    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;
+
+      AOT( iDeltaCurSPos > iDeltaSPos );
+      AOT( iDeltaCurSPos < 0 );
+      AOT( m_aaiSubPelShiftL[iDeltaSPos][iDeltaCurSPos] == 0xdeaddead);
+
+      Int iSourcePos = (iCurPos  << m_iShiftPrec) +  m_aaiSubPelShiftL[iDeltaSPos][iDeltaCurSPos];   // GT:  = iPosX - iStep + ( iStep * iDeltaCurPos + ( iDeltaPos >> 1) ) / iDeltaPos;
+      xSetShiftedPel( iSourcePos, iFillSPos, REN_IS_FILLED, riError );
+    }
+  };
+}
+
+__inline Void
+TRenSingleModel::xRenderShiftedRangeR(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  assert( iCurSPos >= iLastSPos );
+  //assert( iRightSPos < m_iWidth );
+
+  Int iDeltaSPos = iCurSPos - iLastSPos;
+  if ( iDeltaSPos > m_iGapTolerance )
+  {
+    xFillHoleR( iCurSPos, iLastSPos, iCurPos, riError );
+  }
+  else
+  {
+    if (iLastSPos > m_iSampledWidth - 1 )
+      return;
+
+    m_iThisDepth = m_iCurDepth;
+    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;
+
+      AOT( iDeltaCurSPos > iDeltaSPos );
+      AOT( iDeltaCurSPos < 0 );
+      AOT( m_aaiSubPelShiftR[iDeltaSPos][iDeltaCurSPos] == 0xdeaddead);
+
+      Int iSourcePos = (iCurPos  << m_iShiftPrec) +  m_aaiSubPelShiftR[iDeltaSPos][iDeltaCurSPos];   // GT:  = iPosX - iStep + ( iStep * iDeltaCurPos + ( iDeltaPos >> 1) ) / iDeltaPos;
+
+      xSetShiftedPel( iSourcePos, iFillSPos, REN_IS_FILLED, riError );
+    }
+  };
+}
+
+
+
+__inline Void
+TRenSingleModel::xRenderRangeL(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  if (  !m_bInOcclusion )
+  {
+    if ( iCurSPos >= iLastSPos )
+    {
+      m_iLastOccludedSPos = iLastSPos;
+
+      Int iRightSPosFP = xRoundL( iLastSPos );
+      if ( ( iRightSPosFP == xRangeRightL(iLastSPos)) && (iRightSPosFP >= 0) )
+      {
+        m_iThisDepth = m_iLastDepth;
+        xSetShiftedPel( (iCurPos+1) << m_iShiftPrec, iRightSPosFP, REN_IS_FILLED, riError );
+      }
+      m_iLastOccludedSPosFP = iRightSPosFP;
+
+      m_bInOcclusion = true;
+
+      if ( m_bSet )
+      {
+        m_apbOccludedRow[m_iCurViewPos][ iCurPos ] = true;
+      }
+    }
+    else
+    {
+      if ( m_bSet )
+      {
+        m_apbOccludedRow[m_iCurViewPos][ iCurPos ] = false;
+      }
+
+      xRenderShiftedRangeL(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+  }
+  else
+  {
+    if ( iCurSPos < m_iLastOccludedSPos )
+    {
+      m_bInOcclusion = false;
+      if ( m_bSet )
+      {
+        m_apbOccludedRow[m_iCurViewPos][ iCurPos ] = false;
+      }
+
+      xRenderShiftedRangeL(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+    else
+    {
+      if ( m_bSet )
+      {
+        m_apbOccludedRow[m_iCurViewPos][ iCurPos ] = true;
+      }
+    }
+  }
+}
+
+__inline Void
+TRenSingleModel::xRenderRangeR(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  // 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;
+        xSetShiftedPel( (iCurPos-1) << m_iShiftPrec, iLeftSPosFP, REN_IS_FILLED, riError );
+      }
+      m_iLastOccludedSPosFP = iLeftSPosFP;
+
+      m_bInOcclusion = true;
+
+      if ( m_bSet )
+      {
+        m_apbOccludedRow[m_iCurViewPos][ iCurPos ] = true;
+      }
+    }
+    else
+    {
+      if ( m_bSet )
+      {
+        m_apbOccludedRow[m_iCurViewPos][ iCurPos ] = false;
+      }
+
+      xRenderShiftedRangeR(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+  }
+  else
+  {
+    if ( iCurSPos > m_iLastOccludedSPos )
+    {
+      m_bInOcclusion = false;
+      if ( m_bSet )
+      {
+        m_apbOccludedRow[m_iCurViewPos][ iCurPos ] = false;
+      }
+
+      xRenderShiftedRangeR(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+    else
+    {
+      if ( m_bSet )
+      {
+        m_apbOccludedRow[m_iCurViewPos][ iCurPos ] = true;
+      }
+    }
+  }
+}
+
+__inline Void
+TRenSingleModel::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;
+      xSetShiftedPel     ( iStartFillPos << m_iShiftPrec, 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++ )
+  {
+    xSetShiftedPel( iLastPos << m_iShiftPrec, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+__inline Void
+TRenSingleModel::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;
+      xSetShiftedPel( iEndFillPos << 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++ )
+  {
+    xSetShiftedPel( iLastPos << m_iShiftPrec, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+__inline Void
+TRenSingleModel::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)
+  {
+    xSetShiftedPel( iCurPos << m_iShiftPrec, iSPosFullPel, REN_IS_FILLED, riError );
+  }
+
+  for (Int iFillSPos = iSPosFullPel +1; iFillSPos < m_iWidth; iFillSPos++ )
+  {
+    xSetShiftedPel( iCurPos << m_iShiftPrec, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+__inline Void
+TRenSingleModel::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)
+  {
+    xSetShiftedPel( iCurPos << m_iShiftPrec, iSPosFullPel, REN_IS_FILLED, riError );
+  }
+
+  for (Int iFillSPos = iSPosFullPel -1; iFillSPos > -1; iFillSPos-- )
+  {
+    xSetShiftedPel( iCurPos << m_iShiftPrec, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+
+__inline Int
+TRenSingleModel::xShiftNewData( Int iPosX, Int iPosInNewData )
+{
+  AOT( iPosInNewData <               0 );
+  AOF( iPosInNewData < m_iNewDataWidth );
+
+  return (iPosX << m_iShiftPrec) - m_ppiCurLUT[0][ RemoveBitIncrement( m_piNewDepthData[iPosInNewData] )];
+}
+
+__inline Int
+TRenSingleModel::xShift( Int iPosX )
+{
+ AOT( iPosX <        0);
+ AOF( iPosX < m_iWidth);
+ return (iPosX  << m_iShiftPrec) - m_ppiCurLUT[0][ RemoveBitIncrement( m_apiBaseDepthPelRow[m_iCurViewPos][iPosX] )];
+}
+
+
+__inline Int
+TRenSingleModel::xShift( Int iPos, Int iPosInNewData )
+{
+  if ( (iPosInNewData >= 0) && (iPosInNewData < m_iNewDataWidth) )
+  {
+    return xShiftNewData(iPos ,iPosInNewData );
+  }
+  else
+  {
+    return xShift(iPos);
+  }
+}
+
+__inline Int
+TRenSingleModel::xRangeLeftL( Int iPos )
+{
+  return  ( iPos +  (1 << m_iShiftPrec) - 1) >> m_iShiftPrec;
+}
+
+
+__inline Int
+TRenSingleModel::xRangeLeftR( Int iPos )
+{
+
+  return  xRangeRightR( iPos ) + 1;
+}
+
+
+__inline Int
+TRenSingleModel::xRangeRightL( Int iPos )
+{
+  return xRangeLeftL(iPos) - 1;
+}
+
+__inline Int
+TRenSingleModel::xRangeRightR( Int iPos )
+{
+  return iPos >> m_iShiftPrec;
+}
+
+
+__inline Int
+TRenSingleModel::xRoundL( Int iPos )
+{
+  return  (iPos + (( 1 << m_iShiftPrec ) >> 1 )) >> m_iShiftPrec;
+}
+
+__inline Int
+TRenSingleModel::xRoundR( Int iPos )
+{
+  return  (m_iShiftPrec == 0) ? iPos : xRoundL(iPos - 1);
+}
+
+
+Void
+TRenSingleModel::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;
+  }
+}
+
+Void
+TRenSingleModel::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;
+  }
+}
+
+
+Void
+TRenSingleModel::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;
+  }
+}
+
+Void
+TRenSingleModel::xInitView( Int iViewPos )
+{
+  AOT( iViewPos == VIEWPOS_MERGED && ( m_iMode == 0 || m_iMode == 1 ) );
+
+  xSetPels( m_aapiSynthVideoPel[iViewPos][0], m_iStride, m_iWidth, m_iHeight, 0 );
+  xSetPels( m_aapiSynthVideoPel[iViewPos][1], m_iStride, m_iWidth, m_iHeight, 128 << g_uiBitIncrement );
+  xSetPels( m_aapiSynthVideoPel[iViewPos][2], m_iStride, m_iWidth, m_iHeight, 128 << g_uiBitIncrement );
+
+  if ( iViewPos != VIEWPOS_MERGED)
+  {
+    xSetBools( m_apbOccluded     [iViewPos],  m_iStride, m_iWidth, m_iHeight, false );
+    xSetPels ( m_apiFilled       [iViewPos],  m_iStride, m_iWidth, m_iHeight, REN_IS_HOLE);
+    if ( m_iMode == 2 )
+    {
+      xSetPels( m_apiSynthDepthPel [iViewPos],  m_iStride, m_iWidth, m_iHeight, 0);
+    }
+  }
+}
+
+__inline Void
+TRenSingleModel::xSetShiftedPel(Int iSourcePos, Int iTargetSPos, Pel iFilled, RMDist& riError )
+{
+  AOT( iSourcePos < 0         );
+  AOT( iSourcePos >= m_iSampledWidth );
+
+  AOT( iTargetSPos < 0         );
+  AOT( iTargetSPos >= m_iWidth );
+//  AOT(  m_apiFilledRow[m_iViewPos][iTargetSPos] != REN_IS_HOLE);
+
+  if ( m_iMode == 2)
+  {
+    xSetShiftedPelBlend(iSourcePos, iTargetSPos, iFilled, riError );
+    return;
+  }
+
+  if ( m_bSet )
+  {
+    m_aapiSynthVideoPelRow[m_iCurViewPos][0][iTargetSPos] = m_aapiBaseVideoPelRow[m_iCurViewPos][0][iSourcePos];
+#if HHI_VSO_COLOR_PLANES
+    m_aapiSynthVideoPelRow[m_iCurViewPos][1][iTargetSPos] = m_aapiBaseVideoPelRow[m_iCurViewPos][1][iSourcePos];
+    m_aapiSynthVideoPelRow[m_iCurViewPos][2][iTargetSPos] = m_aapiBaseVideoPelRow[m_iCurViewPos][2][iSourcePos];
+#endif
+    m_apiFilledRow        [m_iCurViewPos]   [iTargetSPos] = iFilled;
+    Int iDiffY = m_aapiRefVideoPelRow    [0][iTargetSPos] - m_aapiSynthVideoPelRow[m_iCurViewPos][0][iTargetSPos];
+#if HHI_VSO_COLOR_PLANES
+    Int iDiffU = m_aapiRefVideoPelRow    [1][iTargetSPos] - m_aapiSynthVideoPelRow[m_iCurViewPos][1][iTargetSPos];
+    Int iDiffV = m_aapiRefVideoPelRow    [2][iTargetSPos] - m_aapiSynthVideoPelRow[m_iCurViewPos][2][iTargetSPos];
+    m_apiErrorRow                           [iTargetSPos] = xGetDist( iDiffY, iDiffU, iDiffV);
+#else
+    m_apiErrorRow                           [iTargetSPos] = xGetDist(iDiffY);
+#endif
+  }
+  else
+  {
+    Int iSDOld   = m_apiErrorRow            [iTargetSPos];
+    Int iDiffY   = m_aapiRefVideoPelRow  [0][iTargetSPos] - m_aapiBaseVideoPelRow [m_iCurViewPos][0][iSourcePos];
+#if HHI_VSO_COLOR_PLANES
+    Int iDiffU   = m_aapiRefVideoPelRow  [1][iTargetSPos] - m_aapiBaseVideoPelRow [m_iCurViewPos][1][iSourcePos];
+    Int iDiffV   = m_aapiRefVideoPelRow  [2][iTargetSPos] - m_aapiBaseVideoPelRow [m_iCurViewPos][2][iSourcePos];
+    riError     += ( xGetDist(iDiffY,iDiffU,iDiffV) - iSDOld  );
+#else
+    riError     +=  ( xGetDist( iDiffY ) - iSDOld );
+#endif
+  }
+}
+
+__inline Void
+TRenSingleModel::xSetShiftedPelBlend( Int iSourcePos, Int iTargetSPos, Pel iFilled, RMDist& riError )
+{
+  AOT( iSourcePos < 0         );
+  AOT( iSourcePos >= m_iSampledWidth );
+
+  AOT( iTargetSPos < 0         );
+  AOT( iTargetSPos >= m_iWidth );
+  //  AOT(  m_apiFilledRow[m_iViewPos][iTargetSPos] != REN_IS_HOLE);
+
+  Pel piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+  Pel piBlendedValueU;
+  Pel piBlendedValueV;
+#endif
+
+
+  if (m_iCurViewPos == 0)
+  {
+    xGetBlendedValue (
+      m_aapiBaseVideoPelRow                                    [0][0][iSourcePos ]  ,
+      m_aapiSynthVideoPelRow                                   [1][0][iTargetSPos]  ,
+#if HHI_VSO_COLOR_PLANES
+      m_aapiBaseVideoPelRow                                    [0][1][iSourcePos ]  ,
+      m_aapiSynthVideoPelRow                                   [1][1][iTargetSPos]  ,
+      m_aapiBaseVideoPelRow                                    [0][2][iSourcePos ]  ,
+      m_aapiSynthVideoPelRow                                   [1][2][iTargetSPos]  ,
+#endif
+      m_piInvZLUTLeft [RemoveBitIncrement(m_iThisDepth)                            ],
+      m_piInvZLUTRight[RemoveBitIncrement(m_apiSynthDepthPelRow[1]   [iTargetSPos])],
+      iFilled,
+      m_apiFilledRow                                           [1]   [iTargetSPos]  ,
+      piBlendedValueY
+#if HHI_VSO_COLOR_PLANES
+    , piBlendedValueU,
+      piBlendedValueV
+#endif
+    );
+  }
+  else
+  {
+    xGetBlendedValue (
+      m_aapiSynthVideoPelRow                                   [0][0][iTargetSPos],
+      m_aapiBaseVideoPelRow                                    [1][0][iSourcePos ],
+#if HHI_VSO_COLOR_PLANES
+      m_aapiSynthVideoPelRow                                   [0][1][iTargetSPos],
+      m_aapiBaseVideoPelRow                                    [1][1][iSourcePos ],
+      m_aapiSynthVideoPelRow                                   [0][2][iTargetSPos],
+      m_aapiBaseVideoPelRow                                    [1][2][iSourcePos ],
+#endif
+      m_piInvZLUTLeft [RemoveBitIncrement(m_apiSynthDepthPelRow[0]   [iTargetSPos])],
+      m_piInvZLUTRight[RemoveBitIncrement(m_iThisDepth)                            ],
+      m_apiFilledRow                                           [0]   [iTargetSPos],
+      iFilled                                                                     ,
+      piBlendedValueY
+#if HHI_VSO_COLOR_PLANES
+    , piBlendedValueU,
+      piBlendedValueV
+#endif
+    );
+  }
+
+  if ( m_bSet )
+  {
+    m_apiSynthDepthPelRow [m_iCurViewPos]   [iTargetSPos] = m_iThisDepth;
+    m_aapiSynthVideoPelRow[m_iCurViewPos][0][iTargetSPos] = m_aapiBaseVideoPelRow[m_iCurViewPos][0][iSourcePos];
+    m_aapiSynthVideoPelRow[2            ][0][iTargetSPos] = piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+    m_aapiSynthVideoPelRow[m_iCurViewPos][1][iTargetSPos] = m_aapiBaseVideoPelRow[m_iCurViewPos][1][iSourcePos];
+    m_aapiSynthVideoPelRow[2            ][1][iTargetSPos] = piBlendedValueU;
+    m_aapiSynthVideoPelRow[m_iCurViewPos][2][iTargetSPos] = m_aapiBaseVideoPelRow[m_iCurViewPos][2][iSourcePos];
+    m_aapiSynthVideoPelRow[2            ][2][iTargetSPos] = piBlendedValueV;
+#endif
+    m_apiFilledRow        [m_iCurViewPos]   [iTargetSPos] = iFilled;
+
+    Int iDiffY = m_aapiRefVideoPelRow    [0][iTargetSPos] - piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+    Int iDiffU = m_aapiRefVideoPelRow    [1][iTargetSPos] - piBlendedValueU;
+    Int iDiffV = m_aapiRefVideoPelRow    [2][iTargetSPos] - piBlendedValueV;
+    m_apiErrorRow                           [iTargetSPos] = xGetDist(iDiffY, iDiffU, iDiffV );
+#else
+    m_apiErrorRow                           [iTargetSPos] = xGetDist(iDiffY);
+#endif
+  }
+  else
+  {
+    Int iSDOld   = m_apiErrorRow            [iTargetSPos];
+    Int iDiffY = m_aapiRefVideoPelRow    [0][iTargetSPos] - piBlendedValueY;
+#if HHI_VSO_COLOR_PLANES
+    Int iDiffU = m_aapiRefVideoPelRow    [1][iTargetSPos] - piBlendedValueU;
+    Int iDiffV = m_aapiRefVideoPelRow    [2][iTargetSPos] - piBlendedValueV;
+    riError   += ( xGetDist( iDiffY, iDiffU, iDiffV ) - iSDOld );
+#else
+    riError   += ( xGetDist( iDiffY )- iSDOld  );
+#endif
+  }
+}
+
+
+__inline Int
+TRenSingleModel::xGetDist( Int iDiffY, Int iDiffU, Int iDiffV )
+{
+  return (          ((iDiffY * iDiffY) >> m_iDistShift)
+             +  ((( ((iDiffU * iDiffU) >> m_iDistShift)
+                   +((iDiffV * iDiffV) >> m_iDistShift)
+                  )
+                 ) >> 2
+                )
+         );
+}
+
+__inline Int
+TRenSingleModel::xGetDist( Int iDiffY )
+{
+  return ((iDiffY * iDiffY) >> m_iDistShift);
+}
+
+#if HHI_VSO_COLOR_PLANES
+__inline Void
+TRenSingleModel::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
+Void
+TRenSingleModel::xGetBlendedValue( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY )
+#endif
+{
+  if (m_iBlendMode != 0 )
+  {
+    if (m_iBlendMode == 1 )
+    {
+#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( iYR, iYL, m_iBlendDistWeight );
+#if HHI_VSO_COLOR_PLANES
+        riU = xBlend( iUR, iUL, m_iBlendDistWeight );
+        riV = xBlend( iVR, iVL, 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
+    }
+  }
+
+}
+
+__inline Void
+#if HHI_VSO_COLOR_PLANES
+TRenSingleModel::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
+TRenSingleModel::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
+  }
+}
+
+__inline Void
+#if HHI_VSO_COLOR_PLANES
+TRenSingleModel::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
+TRenSingleModel::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
+  }
+}
+
+__inline Pel
+TRenSingleModel::xBlend( Pel pVal1, Pel pVal2, Int iWeightVal2 )
+{
+  return pVal1  +  (Pel) (  ( (Int) ( pVal2 - pVal1) * iWeightVal2 + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+}
Index: /tags/0.2r1/source/Lib/TLibRenderer/TRenSingleModel.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 19)
@@ -0,0 +1,228 @@
+/* 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 __TRENSINGLEMODEL__
+#define __TRENSINGLEMODEL__
+
+#include "TRenImage.h"
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "../TLibCommon/TypeDef.h"
+#include "../../App/TAppCommon/TAppComCamPara.h"
+
+
+#include <math.h>
+#include <errno.h>
+#include <iostream>
+
+#include <string>
+#include <cstdio>
+#include <cstring>
+
+
+using namespace std;
+
+
+class TRenSingleModel
+{
+
+public:
+  TRenSingleModel();
+  ~TRenSingleModel();
+
+  // Create Model
+  Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode );
+
+  // Set Frame dependent data
+  Void   setLRView ( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride );
+  Void   setup     ( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft, Bool bKeepReference );
+
+  // Set Data
+  Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+  Void   setVideo  ( Int iViewPos,     Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+
+  // Get Distortion
+  RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+  RMDist getDistVideo  ( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+
+  // Get Rendered Data
+  Void   getSynthView( Int iViewPos, Pel**& rppiRenVideoPel, Pel*& rpiRenDepthPel, Int& riStride );
+
+  // Get Reference Data
+  Void   getRefView  ( TComPicYuv*& rpcPicYuvRefView, Pel**& rppiRefVideoPel, Int*& raiStrides );
+
+private:
+  // Set and inc Current Row
+  __inline Void   xSetViewRow(  Int iPosY );
+  __inline Void   xIncViewRow();
+
+  /////  Rendering /////
+  // Left to Right
+  __inline RMDist xRenderL            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bSet);
+  __inline Void   xInitRenderPartL    ( Int iEndChangePos, Int iLastSPos  );
+  __inline Void   xRenderRangeL       ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  __inline Void   xRenderShiftedRangeL( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  __inline Void   xFillHoleL          ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  __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 RMDist xRenderR            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bSet );
+  __inline Void   xInitRenderPartR    ( Int iStartChangePos, Int iLastSPos );
+  __inline Void   xRenderShiftedRangeR( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  __inline Void   xRenderRangeR       ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  __inline Void   xFillHoleR          ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  __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
+  __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
+  __inline Void   xSetShiftedPel     ( Int iSourcePos, Int iTargetSPos, 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   xInitView  ( Int iViewPos );
+  __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 );
+
+private:
+
+  // Image sizes
+  Int   m_iWidth;
+  Int   m_iHeight;
+  Int   m_iStride;
+  Int   m_iPad;
+
+  Int   m_iSampledWidth;
+  Int   m_iSampledHeight;
+  Int   m_iSampledStride;
+
+  // 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
+  Pel*  m_aapiRefVideoPel      [3];    // Dim1: Plane  0-> Y, 1->U, 2->V
+  Int   m_aiRefVideoStrides    [3];    // Dim1: Plane  0-> Y, 1->U, 2->V
+
+  // Renderer State
+  Int*  m_piError                 ;
+  Pel*  m_apiFilled            [2];    // Dim1: ViewPosition
+  Bool* m_apbOccluded          [2];    // Dim1: ViewPosition
+  Pel*  m_aapiSynthVideoPel    [3][3]; // Dim1: ViewPosition 0: Left, 1:Right, 2: Merged, Dim2: Plane  0-> Y, 1->U, 2->V
+  Pel*  m_apiSynthDepthPel     [3];    // Dim1: ViewPosition 0: Left, 1:Right, 2: Merged, Dim2: 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
+
+  Bool  m_bSet;                        // Set Data, or get Error
+  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;
+  Int   m_iBlendMode;
+
+  // Derived settings
+  Int   m_iGapTolerance;
+  Int   m_iBlendZThres;
+  Int   m_iBlendDistWeight;
+
+  //// Current Pointers ////
+  Pel*  m_aapiBaseVideoPelRow  [2][3]; // Dim1: ViewPosition 0->Left, 1->Right; Dim2: Plane  0-> Y, 1->U, 2->V
+  Pel*  m_apiBaseDepthPelRow   [2];    // Dim1: ViewPosition
+  Bool* m_apbOccludedRow       [2];    // Dim1: ViewPosition
+  Pel*  m_apiFilledRow         [2];    // Dim1: ViewPosition
+  Int*  m_apiErrorRow             ;
+
+  Pel*  m_aapiRefVideoPelRow   [3];    // Dim1: Plane  0-> Y, 1->U, 2->V
+  Pel*  m_aapiSynthVideoPelRow [3][3]; // Dim1: ViewPosition 0: Left, 1:Right, 2: Merged, Dim2: Plane  0-> Y, 1->U, 2->V
+  Pel*  m_apiSynthDepthPelRow  [3];    // Dim1: ViewPosition 0: Left, 1:Right, 2: Merged
+
+
+  //// MISC ////
+  const Int m_iDistShift;                  // Shift in Distortion computation
+};
+
+#endif //__TRENSINGLEMODEL__
Index: /tags/0.2r1/source/Lib/TLibRenderer/TRenTop.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenTop.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenTop.cpp	(revision 19)
@@ -0,0 +1,2232 @@
+/* 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, 12);
+    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))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            iPrevShiftedPos = iShiftedPos;
+            continue;
+          };
+
+          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))
+          {
+            // 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::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: /tags/0.2r1/source/Lib/TLibRenderer/TRenTop.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibRenderer/TRenTop.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibRenderer/TRenTop.h	(revision 19)
@@ -0,0 +1,272 @@
+/* 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: /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOBits.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOBits.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOBits.cpp	(revision 19)
@@ -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.
+ */
+
+
+
+/** \file     TVideoIOBits.cpp
+    \brief    bitstream file I/O class
+*/
+
+#include <cstdlib>
+#include <fcntl.h>
+#include <assert.h>
+#include <sys/stat.h>
+#include <fstream>
+#include <iostream>
+
+#include "TVideoIOBits.h"
+
+using namespace std;
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ \param pchFile    file name string
+ \param bWriteMode file open mode
+ */
+Void TVideoIOBits::openBits( char* pchFile, Bool bWriteMode )
+{
+  if ( bWriteMode )
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::out );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to write Bitstream file\n");
+      exit(0);
+    }
+  }
+  else
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::in );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to read Bitstream file\n");
+      exit(0);
+    }
+  }
+  
+  return;
+}
+
+Void TVideoIOBits::closeBits()
+{
+  m_cHandle.close();
+}
+
+/**
+ \param  rpcBitstream    bitstream class pointer
+ \retval                 true if EOF is reached
+ */
+Bool TVideoIOBits::readBits( TComBitstream*& rpcBitstream )
+{
+  UInt  uiBytes = 0;
+  
+  rpcBitstream->rewindStreamPacket();
+  
+  // check end-of-file
+  if ( m_cHandle.eof() ) return true;
+  
+  // read 32-bit packet size
+  m_cHandle.read( reinterpret_cast<char*>(&uiBytes), sizeof (Int) );
+  
+  // kolya
+  if ( m_cHandle.eof() ) return true; //additional insertion to avoid over-reading, for <fstream>
+  
+  // read packet data
+  m_cHandle.read(  reinterpret_cast<char*>(rpcBitstream->getBuffer()), uiBytes );
+  
+  // initialize parsing process
+  rpcBitstream->initParsing ( uiBytes );
+  
+  assert (uiBytes >= 4);
+  
+  return false;
+}
+
+/** \param  pcBitstream   bitstream class pointer
+ */
+Void TVideoIOBits::writeBits( TComBitstream* pcBitstream )
+{
+  UInt*  plBuff  = pcBitstream->getStartStream();
+  UInt   uiBytes = pcBitstream->getNumberOfWrittenBits() >> 3;
+  
+  // write 32-bit packet size
+  m_cHandle.write( reinterpret_cast<char*>(&uiBytes ), sizeof(UInt) );
+  
+  // write packet data
+  m_cHandle.write( reinterpret_cast<char*>(plBuff   ), uiBytes      );
+}
+
+////////////////////////////////////////////////////////////////////
+
+Void TVideoIOBitsStartCode::openBits( char* pchFile, Bool bWriteMode )
+{
+  if ( bWriteMode )
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::out );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to write Bitstream file\n");
+      exit(0);
+    }
+  }
+  else
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::in );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to read Bitstream file\n");
+      exit(0);
+    }
+  }
+  
+  return;
+}
+
+Void TVideoIOBitsStartCode::closeBits()
+{
+  m_cHandle.close();
+}
+
+/**
+ \param  rpcBitstream    bitstream class pointer
+ \retval                 true if EOF is reached
+ */
+Bool TVideoIOBitsStartCode::readBits( TComBitstream*& rpcBitstream )
+{
+  rpcBitstream->rewindStreamPacket();
+  
+  // check end-of-file
+  if ( m_cHandle.eof() ) return true;
+  
+  UInt uiPacketSize = 0;
+  if( 0 != xFindNextStartCode( uiPacketSize, reinterpret_cast<UChar*>(rpcBitstream->getBuffer()) ) )
+  {
+    return true;
+  }
+  
+  // initialize parsing process
+  rpcBitstream->initParsingConvertPayloadToRBSP( uiPacketSize );
+  return false;
+}
+
+int TVideoIOBitsStartCode::xFindNextStartCode(UInt& ruiPacketSize, UChar* pucBuffer)
+{
+  UInt uiDummy = 0;
+  m_cHandle.read( reinterpret_cast<char*>(&uiDummy), 3 );
+  if ( m_cHandle.eof() ) return -1;
+  assert( 0 == uiDummy );
+  
+  m_cHandle.read( reinterpret_cast<char*>(&uiDummy), 1 );
+  if ( m_cHandle.eof() ) return -1;
+  assert( 1 == uiDummy );
+  
+  Int iNextStartCodeBytes = 0;
+  Int iBytesRead = 0;
+  UInt uiZeros = 0;
+  while( true )
+  {
+    UChar ucByte = 0;
+    m_cHandle.read( reinterpret_cast<char*>(&ucByte), 1 );
+    if ( m_cHandle.eof() )
+    {
+      iNextStartCodeBytes = 0;
+      break;
+    }
+    pucBuffer[iBytesRead++] = ucByte;
+    if( 1 < ucByte )
+    {
+      uiZeros = 0;
+    }
+    else if( 0 == ucByte )
+    {
+      uiZeros++;
+    }
+    else if( uiZeros > 2)
+    {
+      iNextStartCodeBytes = 3 + 1;
+      break;
+    }
+    else
+    {
+      uiZeros = 0;
+    }
+  }
+  
+  ruiPacketSize = iBytesRead - iNextStartCodeBytes;
+  
+  m_cHandle.seekg( -iNextStartCodeBytes, ios::cur );
+  return 0;
+}
+
+/**
+ \param  pcBitstream   bitstream class pointer
+ */
+Void TVideoIOBitsStartCode::writeBits( TComBitstream* pcBitstream )
+{
+  UInt*  plBuff  = pcBitstream->getStartStream();
+  UInt   uiBytes = pcBitstream->getNumberOfWrittenBits() >> 3;
+  Char   ucZero = 0;
+  Char   ucOne = 1;
+  
+  // write 32-bit packet size
+  m_cHandle.write( &ucZero , sizeof(Char) );
+  m_cHandle.write( &ucZero , sizeof(Char) );
+  m_cHandle.write( &ucZero , sizeof(Char) );
+  m_cHandle.write( &ucOne  , sizeof(Char) );
+  
+  // write packet data
+  m_cHandle.write( reinterpret_cast<char*>(plBuff   ), uiBytes      );
+}
+
+
Index: /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOBits.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOBits.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOBits.h	(revision 19)
@@ -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-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     TVideoIOBits.h
+    \brief    bitstream file I/O class (header)
+*/
+
+#ifndef __TVIDEOIOBITS__
+#define __TVIDEOIOBITS__
+
+#include <stdio.h>
+#include <fstream>
+#include <iostream>
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComBitStream.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// bitstream file I/O class
+class TVideoIOBits
+{
+private:
+  std::fstream   m_cHandle;                                      ///< file handle
+  
+public:
+  TVideoIOBits()            {}
+  virtual ~TVideoIOBits()   {}
+  
+  Void openBits   ( char* pchFile,  Bool bWriteMode );      ///< open or create file
+  Void closeBits  ();                                       ///< close file
+  
+  Bool readBits   ( TComBitstream*& rpcBitstream    );      ///< read  one packet from file
+  Void writeBits  ( TComBitstream*  pcBitstream     );      ///< write one packet to   file
+  
+};
+
+/// bitstream file I/O class
+class TVideoIOBitsStartCode
+{
+private:
+  std::fstream   m_cHandle;                                      ///< file handle
+  
+public:
+  TVideoIOBitsStartCode()            
+  {
+  }
+  virtual ~TVideoIOBitsStartCode()   {}
+  
+  Void openBits   ( char* pchFile,  Bool bWriteMode );      ///< open or create file
+  Void closeBits  ();                                       ///< close file
+  
+  Bool readBits   ( TComBitstream*& rpcBitstream    );      ///< read  one packet from file
+  Void writeBits  ( TComBitstream*  pcBitstream     );      ///< write one packet to   file
+  
+  std::streampos   getFileLocation      ()                          { return m_cHandle.tellg();                           }
+  Void             setFileLocation      (std::streampos uiLocation) { m_cHandle.seekg(uiLocation, std::ios_base::beg);    }
+  Void             clear                ()                          { m_cHandle.clear();                                  }
+  Bool             good                 ()                          { return m_cHandle.good();                            }
+
+private:
+  int xFindNextStartCode(UInt& ruiPacketSize, UChar* pucBuffer); ///< get packet size and number of startcode bytes and seeks to the packet's start position
+  
+};
+
+#endif // __TVIDEOIOBITS__
+
Index: /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 19)
@@ -0,0 +1,426 @@
+/* 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     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 "TVideoIOYuv.h"
+
+using namespace std;
+
+/**
+ * Perform division with rounding of all pixels in #img by
+ * \f$ 2^{#shiftbits} \f$. All pixels are clipped to [minval, maxval]
+ *
+ * @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 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 \f$ 2^{#shiftbits} \f$.
+ *
+ * @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.
+ */
+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
+ * \f$ 2^{#shiftbits} \f$.
+ *
+ * @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 \f$ 2^{#shiftbits} \f$, see scalePlane()
+ *                  if < 0, divide and round by \f$ 2^{#shiftbits} \f$ 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();
+}
+
+/**
+ * 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 \f$ #width * #height \f$ 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 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.
+ */
+static void 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 (!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 = width; x < width + pad_x; x++)
+    {
+      dst[x] = dst[x - stride];
+    }
+    dst += stride;
+  }
+  delete[] buf;
+}
+
+/**
+ * Write \f$ #width * #height \f$ pixels info #fd from #src.
+ *
+ * @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.
+ */
+static void 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);
+    src += stride;
+  }
+  delete[] buf;
+}
+
+/**
+ * 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 requried, 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 rpcPicYuv      input picture YUV buffer class pointer
+ \param aiPad[2]       source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ */
+Void TVideoIOYuv::read ( TComPicYuv*&  rpcPicYuv, Int aiPad[2], Bool bRewind /* = false */ )
+{
+  // check end-of-file
+  if ( isEof() ) return;
+  
+  Int   iStride = rpcPicYuv->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 = rpcPicYuv->getWidth();
+  unsigned int height_full = rpcPicYuv->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
+  
+  readPlane(rpcPicYuv->getLumaAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v);
+  scalePlane(rpcPicYuv->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;
+
+  readPlane(rpcPicYuv->getCbAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v);
+  scalePlane(rpcPicYuv->getCbAddr(), iStride, width_full, height_full, m_bitdepthShift, minval, maxval);
+
+  readPlane(rpcPicYuv->getCrAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v);
+  scalePlane(rpcPicYuv->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 );
+  }
+}
+
+/**
+ * Write one Y'CbCr frame. No bit-depth conversion is performed, #pcPicYuv is
+ * assumed to be at TVideoIO::m_fileBitdepth depth.
+ *
+ \param pcPicYuv     input picture YUV buffer class pointer
+ \param aiPad[2]     source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ */
+Void TVideoIOYuv::write( TComPicYuv* pcPicYuv, Int aiPad[2] )
+{
+  // compute actual YUV frame size excluding padding size
+  Int   iStride = pcPicYuv->getStride();
+  unsigned int width  = pcPicYuv->getWidth() - aiPad[0];
+  unsigned int height = pcPicYuv->getHeight() - aiPad[1];
+  bool is16bit = m_fileBitdepth > 8;
+  TComPicYuv *dstPicYuv = NULL;
+
+  if (m_bitdepthShift != 0)
+  {
+    dstPicYuv = new TComPicYuv;
+    dstPicYuv->create( pcPicYuv->getWidth(), pcPicYuv->getHeight(), 1, 1, 0 );
+    pcPicYuv->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 = pcPicYuv;
+  }
+  
+  writePlane(m_cHandle, dstPicYuv->getLumaAddr(), is16bit, iStride, width, height);
+
+  width >>= 1;
+  height >>= 1;
+  iStride >>= 1;
+  writePlane(m_cHandle, dstPicYuv->getCbAddr(), is16bit, iStride, width, height);
+  writePlane(m_cHandle, dstPicYuv->getCrAddr(), is16bit, iStride, width, height);
+  
+  if (m_bitdepthShift != 0)
+  {
+    dstPicYuv->destroy();
+    delete dstPicYuv;
+  }  
+}
+
Index: /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 19)
+++ /tags/0.2r1/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 19)
@@ -0,0 +1,80 @@
+/* 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     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);
+  
+  Void  read  ( TComPicYuv*& rpcPicYuv, Int aiPad[2], Bool bRewind = false );     ///< read  one YUV frame with padding parameter
+  Void  write ( TComPicYuv*   pcPicYuv, Int aiPad[2] );     ///< write one YUV frame with padding parameter
+  
+  Bool  isEof ();                                           ///< check end-of-file
+  
+};
+
+#endif // __TVIDEOIOYUV__
+
Index: /tags/0.2r1/source/Lib/libmd5/MD5.h
===================================================================
--- /tags/0.2r1/source/Lib/libmd5/MD5.h	(revision 19)
+++ /tags/0.2r1/source/Lib/libmd5/MD5.h	(revision 19)
@@ -0,0 +1,53 @@
+
+#pragma once
+#include "libmd5.h"
+
+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: /tags/0.2r1/source/Lib/libmd5/libmd5.c
===================================================================
--- /tags/0.2r1/source/Lib/libmd5/libmd5.c	(revision 19)
+++ /tags/0.2r1/source/Lib/libmd5/libmd5.c	(revision 19)
@@ -0,0 +1,252 @@
+/*
+ * 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"
+
+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: /tags/0.2r1/source/Lib/libmd5/libmd5.h
===================================================================
--- /tags/0.2r1/source/Lib/libmd5/libmd5.h	(revision 19)
+++ /tags/0.2r1/source/Lib/libmd5/libmd5.h	(revision 19)
@@ -0,0 +1,52 @@
+/* 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.
+ */
+
+
+#pragma once
+#include <stdint.h>
+
+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
